fever.go 17 KB

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