handler.go 13 KB

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