memos/server/tag.go

81 lines
2.1 KiB
Go
Raw Normal View History

2022-06-21 16:58:33 +03:00
package server
import (
"encoding/json"
"fmt"
2022-06-21 16:58:33 +03:00
"net/http"
"regexp"
2022-07-02 10:01:59 +03:00
"sort"
"strconv"
2022-06-21 16:58:33 +03:00
2022-06-27 17:09:06 +03:00
"github.com/usememos/memos/api"
2022-06-21 16:58:33 +03:00
"github.com/labstack/echo/v4"
)
func (s *Server) registerTagRoutes(g *echo.Group) {
g.GET("/tag", func(c echo.Context) error {
userID, ok := c.Get(getUserIDContextKey()).(int)
if !ok {
if c.QueryParam("userID") != "" {
var err error
userID, err = strconv.Atoi(c.QueryParam("userID"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.QueryParam("userID")))
}
} else {
ownerUserType := api.Owner
ownerUser, err := s.Store.FindUser(&api.UserFind{
Role: &ownerUserType,
})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find owner user").SetInternal(err)
}
if ownerUser == nil {
return echo.NewHTTPError(http.StatusNotFound, "Owner user do not exist")
}
userID = ownerUser.ID
}
}
2022-06-21 16:58:33 +03:00
contentSearch := "#"
2022-06-21 18:29:07 +03:00
normalRowStatus := api.Normal
2022-06-21 16:58:33 +03:00
memoFind := api.MemoFind{
CreatorID: &userID,
ContentSearch: &contentSearch,
2022-06-21 18:29:07 +03:00
RowStatus: &normalRowStatus,
2022-06-21 16:58:33 +03:00
}
memoList, err := s.Store.FindMemoList(&memoFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find memo list").SetInternal(err)
}
tagMapSet := make(map[string]bool)
r, err := regexp.Compile("#(.+?) ")
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to compile regexp").SetInternal(err)
}
for _, memo := range memoList {
for _, rawTag := range r.FindAllString(memo.Content, -1) {
tag := r.ReplaceAllString(rawTag, "$1")
tagMapSet[tag] = true
}
}
tagList := []string{}
for tag := range tagMapSet {
tagList = append(tagList, tag)
}
2022-07-02 10:01:59 +03:00
sort.Strings(tagList)
2022-06-21 16:58:33 +03:00
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
2022-06-21 17:29:06 +03:00
if err := json.NewEncoder(c.Response().Writer).Encode(composeResponse(tagList)); err != nil {
2022-06-21 16:58:33 +03:00
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to encode tags response").SetInternal(err)
}
return nil
})
}