handler.go 16 KB

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