memos/api/v1/rss.go

202 lines
6.2 KiB
Go
Raw Normal View History

2023-07-06 22:53:38 +08:00
package v1
import (
"context"
"encoding/json"
2023-07-06 22:53:38 +08:00
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/gorilla/feeds"
"github.com/labstack/echo/v4"
2023-09-17 22:55:13 +08:00
"github.com/usememos/memos/internal/util"
2023-12-23 17:58:49 +08:00
"github.com/usememos/memos/plugin/gomark/ast"
2023-12-14 22:33:20 +08:00
"github.com/usememos/memos/plugin/gomark/parser"
"github.com/usememos/memos/plugin/gomark/parser/tokenizer"
2023-12-16 11:57:36 +08:00
"github.com/usememos/memos/plugin/gomark/renderer"
2023-05-25 21:50:37 +08:00
"github.com/usememos/memos/store"
)
2023-12-23 17:58:49 +08:00
const (
maxRSSItemCount = 100
maxRSSItemTitleLength = 128
)
2023-07-06 22:53:38 +08:00
func (s *APIV1Service) registerRSSRoutes(g *echo.Group) {
g.GET("/explore/rss.xml", s.GetExploreRSS)
g.GET("/u/:id/rss.xml", s.GetUserRSS)
}
// GetExploreRSS godoc
//
// @Summary Get RSS
// @Tags rss
// @Produce xml
// @Success 200 {object} nil "RSS"
// @Failure 500 {object} nil "Failed to get system customized profile | Failed to find memo list | Failed to generate rss"
// @Router /explore/rss.xml [GET]
func (s *APIV1Service) GetExploreRSS(c echo.Context) error {
ctx := c.Request().Context()
systemCustomizedProfile, err := s.getSystemCustomizedProfile(ctx)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get system customized profile").SetInternal(err)
}
normalStatus := store.Normal
memoFind := store.FindMemo{
RowStatus: &normalStatus,
VisibilityList: []store.Visibility{store.Public},
}
memoList, err := s.Store.ListMemos(ctx, &memoFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find memo list").SetInternal(err)
}
baseURL := c.Scheme() + "://" + c.Request().Host
rss, err := s.generateRSSFromMemoList(ctx, memoList, baseURL, systemCustomizedProfile)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate rss").SetInternal(err)
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationXMLCharsetUTF8)
return c.String(http.StatusOK, rss)
}
// GetUserRSS godoc
//
// @Summary Get RSS for a user
// @Tags rss
// @Produce xml
// @Param id path int true "User ID"
// @Success 200 {object} nil "RSS"
// @Failure 400 {object} nil "User id is not a number"
// @Failure 500 {object} nil "Failed to get system customized profile | Failed to find memo list | Failed to generate rss"
// @Router /u/{id}/rss.xml [GET]
func (s *APIV1Service) GetUserRSS(c echo.Context) error {
ctx := c.Request().Context()
id, err := util.ConvertStringToInt32(c.Param("id"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "User id is not a number").SetInternal(err)
}
systemCustomizedProfile, err := s.getSystemCustomizedProfile(ctx)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get system customized profile").SetInternal(err)
}
normalStatus := store.Normal
memoFind := store.FindMemo{
CreatorID: &id,
RowStatus: &normalStatus,
VisibilityList: []store.Visibility{store.Public},
}
memoList, err := s.Store.ListMemos(ctx, &memoFind)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find memo list").SetInternal(err)
}
baseURL := c.Scheme() + "://" + c.Request().Host
rss, err := s.generateRSSFromMemoList(ctx, memoList, baseURL, systemCustomizedProfile)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate rss").SetInternal(err)
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationXMLCharsetUTF8)
return c.String(http.StatusOK, rss)
}
2023-07-06 22:53:38 +08:00
func (s *APIV1Service) generateRSSFromMemoList(ctx context.Context, memoList []*store.Memo, baseURL string, profile *CustomizedProfile) (string, error) {
feed := &feeds.Feed{
Title: profile.Name,
Link: &feeds.Link{Href: baseURL},
Description: profile.Description,
Created: time.Now(),
}
2023-07-06 22:53:38 +08:00
var itemCountLimit = util.Min(len(memoList), maxRSSItemCount)
feed.Items = make([]*feeds.Item, itemCountLimit)
for i := 0; i < itemCountLimit; i++ {
2023-12-06 22:44:49 +08:00
memoMessage, err := s.convertMemoFromStore(ctx, memoList[i])
if err != nil {
return "", err
}
2023-12-14 22:33:20 +08:00
description, err := getRSSItemDescription(memoMessage.Content)
if err != nil {
return "", err
}
feed.Items[i] = &feeds.Item{
2023-12-06 22:44:49 +08:00
Title: getRSSItemTitle(memoMessage.Content),
Link: &feeds.Link{Href: baseURL + "/m/" + fmt.Sprintf("%d", memoMessage.ID)},
2023-12-14 22:33:20 +08:00
Description: description,
2023-12-06 22:44:49 +08:00
Created: time.Unix(memoMessage.CreatedTs, 0),
Enclosure: &feeds.Enclosure{Url: baseURL + "/m/" + fmt.Sprintf("%d", memoMessage.ID) + "/image"},
2023-04-17 23:26:56 +08:00
}
2023-12-06 22:44:49 +08:00
if len(memoMessage.ResourceList) > 0 {
resource := memoMessage.ResourceList[0]
2023-04-17 23:26:56 +08:00
enclosure := feeds.Enclosure{}
if resource.ExternalLink != "" {
enclosure.Url = resource.ExternalLink
} else {
2023-08-04 21:55:07 +08:00
enclosure.Url = baseURL + "/o/r/" + fmt.Sprintf("%d", resource.ID)
2023-04-17 23:26:56 +08:00
}
enclosure.Length = strconv.Itoa(int(resource.Size))
enclosure.Type = resource.Type
feed.Items[i].Enclosure = &enclosure
}
}
rss, err := feed.ToRss()
if err != nil {
return "", err
}
return rss, nil
}
2023-07-06 22:53:38 +08:00
func (s *APIV1Service) getSystemCustomizedProfile(ctx context.Context) (*CustomizedProfile, error) {
systemSetting, err := s.Store.GetSystemSetting(ctx, &store.FindSystemSetting{
2023-07-06 22:53:38 +08:00
Name: SystemSettingCustomizedProfileName.String(),
2023-04-16 09:51:03 +08:00
})
if err != nil {
2023-04-16 09:51:03 +08:00
return nil, err
}
2023-07-06 22:53:38 +08:00
customizedProfile := &CustomizedProfile{
2023-12-15 22:57:53 +08:00
Name: "Memos",
Locale: "en",
Appearance: "system",
}
2023-04-16 09:51:03 +08:00
if systemSetting != nil {
if err := json.Unmarshal([]byte(systemSetting.Value), customizedProfile); err != nil {
return nil, err
}
}
return customizedProfile, nil
}
func getRSSItemTitle(content string) string {
2023-12-23 17:58:49 +08:00
tokens := tokenizer.Tokenize(content)
nodes, _ := parser.Parse(tokens)
if len(nodes) > 0 {
firstNode := nodes[0]
title := renderer.NewStringRenderer().Render([]ast.Node{firstNode})
return title
}
title := strings.Split(content, "\n")[0]
var titleLengthLimit = util.Min(len(title), maxRSSItemTitleLength)
if titleLengthLimit < len(title) {
title = title[:titleLengthLimit] + "..."
}
return title
}
2023-12-14 22:33:20 +08:00
func getRSSItemDescription(content string) (string, error) {
2023-12-23 17:58:49 +08:00
tokens := tokenizer.Tokenize(content)
2023-12-14 22:33:20 +08:00
nodes, err := parser.Parse(tokens)
if err != nil {
return "", err
}
2023-12-16 11:57:36 +08:00
result := renderer.NewHTMLRenderer().Render(nodes)
2023-12-14 22:33:20 +08:00
return result, nil
}