1// Copyright 2018 The Gitea Authors. All rights reserved.
2// Use of this source code is governed by a MIT-style
3// license that can be found in the LICENSE file.
4
5package repo
6
7import (
8	"net/http"
9	"strings"
10
11	repo_model "code.gitea.io/gitea/models/repo"
12	"code.gitea.io/gitea/modules/context"
13	"code.gitea.io/gitea/modules/log"
14)
15
16// TopicsPost response for creating repository
17func TopicsPost(ctx *context.Context) {
18	if ctx.User == nil {
19		ctx.JSON(http.StatusForbidden, map[string]interface{}{
20			"message": "Only owners could change the topics.",
21		})
22		return
23	}
24
25	var topics = make([]string, 0)
26	var topicsStr = ctx.FormTrim("topics")
27	if len(topicsStr) > 0 {
28		topics = strings.Split(topicsStr, ",")
29	}
30
31	validTopics, invalidTopics := repo_model.SanitizeAndValidateTopics(topics)
32
33	if len(validTopics) > 25 {
34		ctx.JSON(http.StatusUnprocessableEntity, map[string]interface{}{
35			"invalidTopics": nil,
36			"message":       ctx.Tr("repo.topic.count_prompt"),
37		})
38		return
39	}
40
41	if len(invalidTopics) > 0 {
42		ctx.JSON(http.StatusUnprocessableEntity, map[string]interface{}{
43			"invalidTopics": invalidTopics,
44			"message":       ctx.Tr("repo.topic.format_prompt"),
45		})
46		return
47	}
48
49	err := repo_model.SaveTopics(ctx.Repo.Repository.ID, validTopics...)
50	if err != nil {
51		log.Error("SaveTopics failed: %v", err)
52		ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
53			"message": "Save topics failed.",
54		})
55		return
56	}
57
58	ctx.JSON(http.StatusOK, map[string]interface{}{
59		"status": "ok",
60	})
61}
62