handler.go 14 KB

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