handler.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package fever // import "miniflux.app/v2/internal/fever"
  4. import (
  5. "log/slog"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "miniflux.app/v2/internal/http/request"
  11. "miniflux.app/v2/internal/http/response"
  12. "miniflux.app/v2/internal/integration"
  13. "miniflux.app/v2/internal/mediaproxy"
  14. "miniflux.app/v2/internal/model"
  15. "miniflux.app/v2/internal/storage"
  16. )
  17. // NewHandler returns an http.Handler for Fever API calls.
  18. func NewHandler(store *storage.Storage) http.Handler {
  19. h := &feverHandler{store: store}
  20. return http.HandlerFunc(h.serve)
  21. }
  22. type feverHandler struct {
  23. store *storage.Storage
  24. }
  25. func (h *feverHandler) serve(w http.ResponseWriter, r *http.Request) {
  26. switch {
  27. case request.HasQueryParam(r, "groups"):
  28. h.handleGroups(w, r)
  29. case request.HasQueryParam(r, "feeds"):
  30. h.handleFeeds(w, r)
  31. case request.HasQueryParam(r, "favicons"):
  32. h.handleFavicons(w, r)
  33. case request.HasQueryParam(r, "unread_item_ids"):
  34. h.handleUnreadItems(w, r)
  35. case request.HasQueryParam(r, "saved_item_ids"):
  36. h.handleSavedItems(w, r)
  37. case request.HasQueryParam(r, "items"):
  38. h.handleItems(w, r)
  39. case r.FormValue("mark") == "item":
  40. h.handleWriteItems(w, r)
  41. case r.FormValue("mark") == "feed":
  42. h.handleWriteFeeds(w, r)
  43. case r.FormValue("mark") == "group":
  44. h.handleWriteGroups(w, r)
  45. default:
  46. response.JSON(w, r, newBaseResponse())
  47. }
  48. }
  49. /*
  50. A request with the groups argument will return two additional members:
  51. groups contains an array of group objects
  52. feeds_groups contains an array of feeds_group objects
  53. A group object has the following members:
  54. id (positive integer)
  55. title (utf-8 string)
  56. The feeds_group object is documented under “Feeds/Groups Relationships.”
  57. The “Kindling” super group is not included in this response and is composed of all feeds with
  58. an is_spark equal to 0.
  59. The “Sparks” super group is not included in this response and is composed of all feeds with an
  60. is_spark equal to 1.
  61. */
  62. func (h *feverHandler) handleGroups(w http.ResponseWriter, r *http.Request) {
  63. userID := request.UserID(r)
  64. slog.Debug("[Fever] Fetching groups",
  65. slog.Int64("user_id", userID),
  66. )
  67. categories, err := h.store.Categories(userID)
  68. if err != nil {
  69. response.JSONServerError(w, r, err)
  70. return
  71. }
  72. feeds, err := h.store.Feeds(userID)
  73. if err != nil {
  74. response.JSONServerError(w, r, err)
  75. return
  76. }
  77. var result groupsResponse
  78. for _, category := range categories {
  79. result.Groups = append(result.Groups, group{ID: category.ID, Title: category.Title})
  80. }
  81. result.FeedsGroups = buildFeedGroups(feeds)
  82. result.SetCommonValues()
  83. response.JSON(w, r, result)
  84. }
  85. /*
  86. A request with the feeds argument will return two additional members:
  87. feeds contains an array of group objects
  88. feeds_groups contains an array of feeds_group objects
  89. A feed object has the following members:
  90. id (positive integer)
  91. favicon_id (positive integer)
  92. title (utf-8 string)
  93. url (utf-8 string)
  94. site_url (utf-8 string)
  95. is_spark (boolean integer)
  96. last_updated_on_time (Unix timestamp/integer)
  97. The feeds_group object is documented under “Feeds/Groups Relationships.”
  98. The “All Items” super feed is not included in this response and is composed of all items from all feeds
  99. that belong to a given group. For the “Kindling” super group and all user created groups the items
  100. should be limited to feeds with an is_spark equal to 0.
  101. For the “Sparks” super group the items should be limited to feeds with an is_spark equal to 1.
  102. */
  103. func (h *feverHandler) handleFeeds(w http.ResponseWriter, r *http.Request) {
  104. userID := request.UserID(r)
  105. slog.Debug("[Fever] Fetching feeds",
  106. slog.Int64("user_id", userID),
  107. )
  108. feeds, err := h.store.Feeds(userID)
  109. if err != nil {
  110. response.JSONServerError(w, r, err)
  111. return
  112. }
  113. var result feedsResponse
  114. result.Feeds = make([]feed, 0, len(feeds))
  115. for _, f := range feeds {
  116. subscription := feed{
  117. ID: f.ID,
  118. Title: f.Title,
  119. URL: f.FeedURL,
  120. SiteURL: f.SiteURL,
  121. IsSpark: 0,
  122. LastUpdated: f.CheckedAt.Unix(),
  123. }
  124. if f.Icon != nil {
  125. subscription.FaviconID = f.Icon.IconID
  126. }
  127. result.Feeds = append(result.Feeds, subscription)
  128. }
  129. result.FeedsGroups = buildFeedGroups(feeds)
  130. result.SetCommonValues()
  131. response.JSON(w, r, result)
  132. }
  133. /*
  134. A request with the favicons argument will return one additional member:
  135. favicons contains an array of favicon objects
  136. A favicon object has the following members:
  137. id (positive integer)
  138. data (base64 encoded image data; prefixed by image type)
  139. An example data value:
  140. image/gif;base64,R0lGODlhAQABAIAAAObm5gAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==
  141. The data member of a favicon object can be used with the data: protocol to embed an image in CSS or HTML.
  142. A PHP/HTML example:
  143. echo '<img src="data:'.$favicon['data'].'">';
  144. */
  145. func (h *feverHandler) handleFavicons(w http.ResponseWriter, r *http.Request) {
  146. userID := request.UserID(r)
  147. slog.Debug("[Fever] Fetching favicons",
  148. slog.Int64("user_id", userID),
  149. )
  150. icons, err := h.store.Icons(userID)
  151. if err != nil {
  152. response.JSONServerError(w, r, err)
  153. return
  154. }
  155. var result faviconsResponse
  156. for _, i := range icons {
  157. result.Favicons = append(result.Favicons, favicon{
  158. ID: i.ID,
  159. Data: i.DataURL(),
  160. })
  161. }
  162. result.SetCommonValues()
  163. response.JSON(w, r, result)
  164. }
  165. /*
  166. A request with the items argument will return two additional members:
  167. items contains an array of item objects
  168. total_items contains the total number of items stored in the database (added in API version 2)
  169. An item object has the following members:
  170. id (positive integer)
  171. feed_id (positive integer)
  172. title (utf-8 string)
  173. author (utf-8 string)
  174. html (utf-8 string)
  175. url (utf-8 string)
  176. is_saved (boolean integer)
  177. is_read (boolean integer)
  178. created_on_time (Unix timestamp/integer)
  179. Most servers won’t have enough memory allocated to PHP to dump all items at once.
  180. Three optional arguments control determine the items included in the response.
  181. Use the since_id argument with the highest id of locally cached items to request 50 additional items.
  182. Repeat until the items array in the response is empty.
  183. Use the max_id argument with the lowest id of locally cached items (or 0 initially) to request 50 previous items.
  184. Repeat until the items array in the response is empty. (added in API version 2)
  185. Use the with_ids argument with a comma-separated list of item ids to request (a maximum of 50) specific items.
  186. (added in API version 2)
  187. */
  188. func (h *feverHandler) handleItems(w http.ResponseWriter, r *http.Request) {
  189. var result itemsResponse
  190. userID := request.UserID(r)
  191. builder := h.store.NewEntryQueryBuilder(userID)
  192. builder.WithLimit(50)
  193. switch {
  194. case request.HasQueryParam(r, "since_id"):
  195. sinceID := request.QueryInt64Param(r, "since_id", 0)
  196. if sinceID > 0 {
  197. slog.Debug("[Fever] Fetching items since a given date",
  198. slog.Int64("user_id", userID),
  199. slog.Int64("since_id", sinceID),
  200. )
  201. builder.AfterEntryID(sinceID)
  202. builder.WithSorting("id", "ASC")
  203. }
  204. case request.HasQueryParam(r, "max_id"):
  205. maxID := request.QueryInt64Param(r, "max_id", 0)
  206. if maxID == 0 {
  207. slog.Debug("[Fever] Fetching most recent items",
  208. slog.Int64("user_id", userID),
  209. )
  210. builder.WithSorting("id", "DESC")
  211. } else if maxID > 0 {
  212. slog.Debug("[Fever] Fetching items before a given item ID",
  213. slog.Int64("user_id", userID),
  214. slog.Int64("max_id", maxID),
  215. )
  216. builder.BeforeEntryID(maxID)
  217. builder.WithSorting("id", "DESC")
  218. }
  219. case request.HasQueryParam(r, "with_ids"):
  220. csvItemIDs := request.QueryStringParam(r, "with_ids", "")
  221. if csvItemIDs != "" {
  222. var itemIDs []int64
  223. for strItemID := range strings.SplitSeq(csvItemIDs, ",") {
  224. strItemID = strings.TrimSpace(strItemID)
  225. itemID, _ := strconv.ParseInt(strItemID, 10, 64)
  226. itemIDs = append(itemIDs, itemID)
  227. }
  228. builder.WithEntryIDs(itemIDs)
  229. }
  230. default:
  231. slog.Debug("[Fever] Fetching oldest items",
  232. slog.Int64("user_id", userID),
  233. )
  234. }
  235. entries, err := builder.GetEntries()
  236. if err != nil {
  237. response.JSONServerError(w, r, err)
  238. return
  239. }
  240. builder = h.store.NewEntryQueryBuilder(userID)
  241. result.Total, err = builder.CountEntries()
  242. if err != nil {
  243. response.JSONServerError(w, r, err)
  244. return
  245. }
  246. result.Items = make([]item, 0, len(entries))
  247. for _, entry := range entries {
  248. isRead := 0
  249. if entry.Status == model.EntryStatusRead {
  250. isRead = 1
  251. }
  252. isSaved := 0
  253. if entry.Starred {
  254. isSaved = 1
  255. }
  256. result.Items = append(result.Items, item{
  257. ID: entry.ID,
  258. FeedID: entry.FeedID,
  259. Title: entry.Title,
  260. Author: entry.Author,
  261. HTML: mediaproxy.RewriteDocumentWithAbsoluteProxyURL(entry.Content),
  262. URL: entry.URL,
  263. IsSaved: isSaved,
  264. IsRead: isRead,
  265. CreatedAt: entry.Date.Unix(),
  266. })
  267. }
  268. result.SetCommonValues()
  269. response.JSON(w, r, result)
  270. }
  271. /*
  272. The unread_item_ids and saved_item_ids arguments can be used to keep your local cache synced
  273. with the remote Fever installation.
  274. A request with the unread_item_ids argument will return one additional member:
  275. unread_item_ids (string/comma-separated list of positive integers)
  276. */
  277. func (h *feverHandler) handleUnreadItems(w http.ResponseWriter, r *http.Request) {
  278. userID := request.UserID(r)
  279. slog.Debug("[Fever] Fetching unread items",
  280. slog.Int64("user_id", userID),
  281. )
  282. builder := h.store.NewEntryQueryBuilder(userID)
  283. builder.WithStatus(model.EntryStatusUnread)
  284. rawEntryIDs, err := builder.GetEntryIDs()
  285. if err != nil {
  286. response.JSONServerError(w, r, err)
  287. return
  288. }
  289. itemIDs := make([]string, 0, len(rawEntryIDs))
  290. for _, entryID := range rawEntryIDs {
  291. itemIDs = append(itemIDs, strconv.FormatInt(entryID, 10))
  292. }
  293. var result unreadResponse
  294. result.ItemIDs = strings.Join(itemIDs, ",")
  295. result.SetCommonValues()
  296. response.JSON(w, r, result)
  297. }
  298. /*
  299. The unread_item_ids and saved_item_ids arguments can be used to keep your local cache synced
  300. with the remote Fever installation.
  301. A request with the saved_item_ids argument will return one additional member:
  302. saved_item_ids (string/comma-separated list of positive integers)
  303. */
  304. func (h *feverHandler) handleSavedItems(w http.ResponseWriter, r *http.Request) {
  305. userID := request.UserID(r)
  306. slog.Debug("[Fever] Fetching saved items",
  307. slog.Int64("user_id", userID),
  308. )
  309. builder := h.store.NewEntryQueryBuilder(userID)
  310. builder.WithStarred(true)
  311. entryIDs, err := builder.GetEntryIDs()
  312. if err != nil {
  313. response.JSONServerError(w, r, err)
  314. return
  315. }
  316. itemsIDs := make([]string, 0, len(entryIDs))
  317. for _, entryID := range entryIDs {
  318. itemsIDs = append(itemsIDs, strconv.FormatInt(entryID, 10))
  319. }
  320. result := &savedResponse{ItemIDs: strings.Join(itemsIDs, ",")}
  321. result.SetCommonValues()
  322. response.JSON(w, r, result)
  323. }
  324. /*
  325. mark=item
  326. as=? where ? is replaced with read, saved or unsaved
  327. id=? where ? is replaced with the id of the item to modify
  328. */
  329. func (h *feverHandler) handleWriteItems(w http.ResponseWriter, r *http.Request) {
  330. userID := request.UserID(r)
  331. slog.Debug("[Fever] Receiving mark=item call",
  332. slog.Int64("user_id", userID),
  333. )
  334. entryID := request.FormInt64Value(r, "id")
  335. if entryID <= 0 {
  336. return
  337. }
  338. builder := h.store.NewEntryQueryBuilder(userID)
  339. builder.WithEntryID(entryID)
  340. entry, err := builder.GetEntry()
  341. if err != nil {
  342. response.JSONServerError(w, r, err)
  343. return
  344. }
  345. if entry == nil {
  346. slog.Debug("[Fever] Entry not found",
  347. slog.Int64("user_id", userID),
  348. slog.Int64("entry_id", entryID),
  349. )
  350. response.JSON(w, r, newBaseResponse())
  351. return
  352. }
  353. switch r.FormValue("as") {
  354. case "read":
  355. slog.Debug("[Fever] Mark entry as read",
  356. slog.Int64("user_id", userID),
  357. slog.Int64("entry_id", entryID),
  358. )
  359. h.store.SetEntriesStatus(userID, []int64{entryID}, model.EntryStatusRead)
  360. case "unread":
  361. slog.Debug("[Fever] Mark entry as unread",
  362. slog.Int64("user_id", userID),
  363. slog.Int64("entry_id", entryID),
  364. )
  365. h.store.SetEntriesStatus(userID, []int64{entryID}, model.EntryStatusUnread)
  366. case "saved":
  367. slog.Debug("[Fever] Mark entry as saved",
  368. slog.Int64("user_id", userID),
  369. slog.Int64("entry_id", entryID),
  370. )
  371. if err := h.store.ToggleStarred(userID, entryID); err != nil {
  372. response.JSONServerError(w, r, err)
  373. return
  374. }
  375. settings, err := h.store.Integration(userID)
  376. if err != nil {
  377. response.JSONServerError(w, r, err)
  378. return
  379. }
  380. go func() {
  381. integration.SendEntry(entry, settings)
  382. }()
  383. case "unsaved":
  384. slog.Debug("[Fever] Mark entry as unsaved",
  385. slog.Int64("user_id", userID),
  386. slog.Int64("entry_id", entryID),
  387. )
  388. if err := h.store.ToggleStarred(userID, entryID); err != nil {
  389. response.JSONServerError(w, r, err)
  390. return
  391. }
  392. }
  393. response.JSON(w, r, newBaseResponse())
  394. }
  395. /*
  396. mark=feed
  397. as=read
  398. id=? where ? is replaced with the id of the feed or group to modify
  399. before=? where ? is replaced with the Unix timestamp of the the local client’s most recent items API request
  400. */
  401. func (h *feverHandler) handleWriteFeeds(w http.ResponseWriter, r *http.Request) {
  402. userID := request.UserID(r)
  403. feedID := request.FormInt64Value(r, "id")
  404. before := time.Unix(request.FormInt64Value(r, "before"), 0)
  405. slog.Debug("[Fever] Mark feed as read before a given date",
  406. slog.Int64("user_id", userID),
  407. slog.Int64("feed_id", feedID),
  408. slog.Time("before_ts", before),
  409. )
  410. if feedID <= 0 {
  411. return
  412. }
  413. if err := h.store.MarkFeedAsRead(userID, feedID, before); err != nil {
  414. response.JSONServerError(w, r, err)
  415. return
  416. }
  417. response.JSON(w, r, newBaseResponse())
  418. }
  419. /*
  420. mark=group
  421. as=read
  422. id=? where ? is replaced with the id of the feed or group to modify
  423. before=? where ? is replaced with the Unix timestamp of the the local client’s most recent items API request
  424. */
  425. func (h *feverHandler) handleWriteGroups(w http.ResponseWriter, r *http.Request) {
  426. userID := request.UserID(r)
  427. groupID := request.FormInt64Value(r, "id")
  428. if groupID < 0 {
  429. return
  430. }
  431. var err error
  432. if groupID == 0 {
  433. err = h.store.MarkAllAsRead(userID)
  434. slog.Debug("[Fever] Mark all items as read",
  435. slog.Int64("user_id", userID),
  436. )
  437. } else {
  438. before := time.Unix(request.FormInt64Value(r, "before"), 0)
  439. err = h.store.MarkCategoryAsRead(userID, groupID, before)
  440. slog.Debug("[Fever] Mark group as read before a given date",
  441. slog.Int64("user_id", userID),
  442. slog.Int64("group_id", groupID),
  443. slog.Time("before_ts", before),
  444. )
  445. }
  446. if err != nil {
  447. response.JSONServerError(w, r, err)
  448. return
  449. }
  450. response.JSON(w, r, newBaseResponse())
  451. }
  452. /*
  453. A feeds_group object has the following members:
  454. group_id (positive integer)
  455. feed_ids (string/comma-separated list of positive integers)
  456. */
  457. func buildFeedGroups(feeds model.Feeds) []feedsGroups {
  458. feedsGroupedByCategory := make(map[int64][]string, len(feeds))
  459. for _, feed := range feeds {
  460. feedsGroupedByCategory[feed.Category.ID] = append(feedsGroupedByCategory[feed.Category.ID], strconv.FormatInt(feed.ID, 10))
  461. }
  462. result := make([]feedsGroups, 0, len(feedsGroupedByCategory))
  463. for categoryID, feedIDs := range feedsGroupedByCategory {
  464. result = append(result, feedsGroups{
  465. GroupID: categoryID,
  466. FeedIDs: strings.Join(feedIDs, ","),
  467. })
  468. }
  469. return result
  470. }