handler.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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 userID=%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 userID=%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. logger.Debug("[Fever] Fetching items for userID=%d", userID)
  189. builder := h.store.NewEntryQueryBuilder(userID)
  190. builder.WithoutStatus(model.EntryStatusRemoved)
  191. builder.WithLimit(50)
  192. builder.WithOrder("id")
  193. builder.WithDirection(model.DefaultSortingDirection)
  194. sinceID := request.QueryIntParam(r, "since_id", 0)
  195. if sinceID > 0 {
  196. builder.AfterEntryID(int64(sinceID))
  197. }
  198. maxID := request.QueryIntParam(r, "max_id", 0)
  199. if maxID > 0 {
  200. builder.WithOffset(maxID)
  201. }
  202. csvItemIDs := request.QueryStringParam(r, "with_ids", "")
  203. if csvItemIDs != "" {
  204. var itemIDs []int64
  205. for _, strItemID := range strings.Split(csvItemIDs, ",") {
  206. strItemID = strings.TrimSpace(strItemID)
  207. itemID, _ := strconv.Atoi(strItemID)
  208. itemIDs = append(itemIDs, int64(itemID))
  209. }
  210. builder.WithEntryIDs(itemIDs)
  211. }
  212. entries, err := builder.GetEntries()
  213. if err != nil {
  214. json.ServerError(w, r, err)
  215. return
  216. }
  217. builder = h.store.NewEntryQueryBuilder(userID)
  218. builder.WithoutStatus(model.EntryStatusRemoved)
  219. result.Total, err = builder.CountEntries()
  220. if err != nil {
  221. json.ServerError(w, r, err)
  222. return
  223. }
  224. result.Items = make([]item, 0)
  225. for _, entry := range entries {
  226. isRead := 0
  227. if entry.Status == model.EntryStatusRead {
  228. isRead = 1
  229. }
  230. isSaved := 0
  231. if entry.Starred {
  232. isSaved = 1
  233. }
  234. result.Items = append(result.Items, item{
  235. ID: entry.ID,
  236. FeedID: entry.FeedID,
  237. Title: entry.Title,
  238. Author: entry.Author,
  239. HTML: entry.Content,
  240. URL: entry.URL,
  241. IsSaved: isSaved,
  242. IsRead: isRead,
  243. CreatedAt: entry.Date.Unix(),
  244. })
  245. }
  246. result.SetCommonValues()
  247. json.OK(w, r, result)
  248. }
  249. /*
  250. The unread_item_ids and saved_item_ids arguments can be used to keep your local cache synced
  251. with the remote Fever installation.
  252. A request with the unread_item_ids argument will return one additional member:
  253. unread_item_ids (string/comma-separated list of positive integers)
  254. */
  255. func (h *handler) handleUnreadItems(w http.ResponseWriter, r *http.Request) {
  256. userID := request.UserID(r)
  257. logger.Debug("[Fever] Fetching unread items for userID=%d", userID)
  258. builder := h.store.NewEntryQueryBuilder(userID)
  259. builder.WithStatus(model.EntryStatusUnread)
  260. entries, err := builder.GetEntries()
  261. if err != nil {
  262. json.ServerError(w, r, err)
  263. return
  264. }
  265. var itemIDs []string
  266. for _, entry := range entries {
  267. itemIDs = append(itemIDs, strconv.FormatInt(entry.ID, 10))
  268. }
  269. var result unreadResponse
  270. result.ItemIDs = strings.Join(itemIDs, ",")
  271. result.SetCommonValues()
  272. json.OK(w, r, result)
  273. }
  274. /*
  275. The unread_item_ids and saved_item_ids arguments can be used to keep your local cache synced
  276. with the remote Fever installation.
  277. A request with the saved_item_ids argument will return one additional member:
  278. saved_item_ids (string/comma-separated list of positive integers)
  279. */
  280. func (h *handler) handleSavedItems(w http.ResponseWriter, r *http.Request) {
  281. userID := request.UserID(r)
  282. logger.Debug("[Fever] Fetching saved items for userID=%d", userID)
  283. builder := h.store.NewEntryQueryBuilder(userID)
  284. builder.WithStarred()
  285. entryIDs, err := builder.GetEntryIDs()
  286. if err != nil {
  287. json.ServerError(w, r, err)
  288. return
  289. }
  290. var itemsIDs []string
  291. for _, entryID := range entryIDs {
  292. itemsIDs = append(itemsIDs, strconv.FormatInt(entryID, 10))
  293. }
  294. result := &savedResponse{ItemIDs: strings.Join(itemsIDs, ",")}
  295. result.SetCommonValues()
  296. json.OK(w, r, result)
  297. }
  298. /*
  299. mark=item
  300. as=? where ? is replaced with read, saved or unsaved
  301. id=? where ? is replaced with the id of the item to modify
  302. */
  303. func (h *handler) handleWriteItems(w http.ResponseWriter, r *http.Request) {
  304. userID := request.UserID(r)
  305. logger.Debug("[Fever] Receiving mark=item call for userID=%d", userID)
  306. entryID := request.FormInt64Value(r, "id")
  307. if entryID <= 0 {
  308. return
  309. }
  310. builder := h.store.NewEntryQueryBuilder(userID)
  311. builder.WithEntryID(entryID)
  312. builder.WithoutStatus(model.EntryStatusRemoved)
  313. entry, err := builder.GetEntry()
  314. if err != nil {
  315. json.ServerError(w, r, err)
  316. return
  317. }
  318. if entry == nil {
  319. return
  320. }
  321. switch r.FormValue("as") {
  322. case "read":
  323. logger.Debug("[Fever] Mark entry #%d as read", entryID)
  324. h.store.SetEntriesStatus(userID, []int64{entryID}, model.EntryStatusRead)
  325. case "unread":
  326. logger.Debug("[Fever] Mark entry #%d as unread", entryID)
  327. h.store.SetEntriesStatus(userID, []int64{entryID}, model.EntryStatusUnread)
  328. case "saved", "unsaved":
  329. logger.Debug("[Fever] Mark entry #%d as saved/unsaved", entryID)
  330. if err := h.store.ToggleBookmark(userID, entryID); err != nil {
  331. json.ServerError(w, r, err)
  332. return
  333. }
  334. settings, err := h.store.Integration(userID)
  335. if err != nil {
  336. json.ServerError(w, r, err)
  337. return
  338. }
  339. go func() {
  340. integration.SendEntry(entry, settings)
  341. }()
  342. }
  343. json.OK(w, r, newBaseResponse())
  344. }
  345. /*
  346. mark=feed
  347. as=read
  348. id=? where ? is replaced with the id of the feed or group to modify
  349. before=? where ? is replaced with the Unix timestamp of the the local client’s most recent items API request
  350. */
  351. func (h *handler) handleWriteFeeds(w http.ResponseWriter, r *http.Request) {
  352. userID := request.UserID(r)
  353. feedID := request.FormInt64Value(r, "id")
  354. before := time.Unix(request.FormInt64Value(r, "before"), 0)
  355. logger.Debug("[Fever] mark=feed, userID=%d, feedID=%d, before=%v", userID, feedID, before)
  356. if feedID <= 0 {
  357. return
  358. }
  359. go func() {
  360. if err := h.store.MarkFeedAsRead(userID, feedID, before); err != nil {
  361. logger.Error("[Fever] MarkFeedAsRead failed: %v", err)
  362. }
  363. }()
  364. json.OK(w, r, newBaseResponse())
  365. }
  366. /*
  367. mark=group
  368. as=read
  369. id=? where ? is replaced with the id of the feed or group to modify
  370. before=? where ? is replaced with the Unix timestamp of the the local client’s most recent items API request
  371. */
  372. func (h *handler) handleWriteGroups(w http.ResponseWriter, r *http.Request) {
  373. userID := request.UserID(r)
  374. groupID := request.FormInt64Value(r, "id")
  375. before := time.Unix(request.FormInt64Value(r, "before"), 0)
  376. logger.Debug("[Fever] mark=group, userID=%d, groupID=%d, before=%v", userID, groupID, before)
  377. if groupID < 0 {
  378. return
  379. }
  380. go func() {
  381. var err error
  382. if groupID == 0 {
  383. err = h.store.MarkAllAsRead(userID)
  384. } else {
  385. err = h.store.MarkCategoryAsRead(userID, groupID, before)
  386. }
  387. if err != nil {
  388. logger.Error("[Fever] MarkCategoryAsRead failed: %v", err)
  389. }
  390. }()
  391. json.OK(w, r, newBaseResponse())
  392. }
  393. /*
  394. A feeds_group object has the following members:
  395. group_id (positive integer)
  396. feed_ids (string/comma-separated list of positive integers)
  397. */
  398. func (h *handler) buildFeedGroups(feeds model.Feeds) []feedsGroups {
  399. feedsGroupedByCategory := make(map[int64][]string)
  400. for _, feed := range feeds {
  401. feedsGroupedByCategory[feed.Category.ID] = append(feedsGroupedByCategory[feed.Category.ID], strconv.FormatInt(feed.ID, 10))
  402. }
  403. result := make([]feedsGroups, 0)
  404. for categoryID, feedIDs := range feedsGroupedByCategory {
  405. result = append(result, feedsGroups{
  406. GroupID: categoryID,
  407. FeedIDs: strings.Join(feedIDs, ","),
  408. })
  409. }
  410. return result
  411. }