fever.go 16 KB

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