feed.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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 storage // import "miniflux.app/storage"
  5. import (
  6. "database/sql"
  7. "errors"
  8. "fmt"
  9. "runtime"
  10. "sort"
  11. "miniflux.app/config"
  12. "miniflux.app/logger"
  13. "miniflux.app/model"
  14. )
  15. type byStateAndName struct{ f model.Feeds }
  16. func (l byStateAndName) Len() int { return len(l.f) }
  17. func (l byStateAndName) Swap(i, j int) { l.f[i], l.f[j] = l.f[j], l.f[i] }
  18. func (l byStateAndName) Less(i, j int) bool {
  19. // disabled test first, since we don't care about errors if disabled
  20. if l.f[i].Disabled != l.f[j].Disabled {
  21. return l.f[j].Disabled
  22. }
  23. if l.f[i].ParsingErrorCount != l.f[j].ParsingErrorCount {
  24. return l.f[i].ParsingErrorCount > l.f[j].ParsingErrorCount
  25. }
  26. if l.f[i].UnreadCount != l.f[j].UnreadCount {
  27. return l.f[i].UnreadCount > l.f[j].UnreadCount
  28. }
  29. return l.f[i].Title < l.f[j].Title
  30. }
  31. // FeedExists checks if the given feed exists.
  32. func (s *Storage) FeedExists(userID, feedID int64) bool {
  33. var result bool
  34. query := `SELECT true FROM feeds WHERE user_id=$1 AND id=$2`
  35. s.db.QueryRow(query, userID, feedID).Scan(&result)
  36. return result
  37. }
  38. // FeedURLExists checks if feed URL already exists.
  39. func (s *Storage) FeedURLExists(userID int64, feedURL string) bool {
  40. var result bool
  41. query := `SELECT true FROM feeds WHERE user_id=$1 AND feed_url=$2`
  42. s.db.QueryRow(query, userID, feedURL).Scan(&result)
  43. return result
  44. }
  45. // AnotherFeedURLExists checks if the user a duplicated feed.
  46. func (s *Storage) AnotherFeedURLExists(userID, feedID int64, feedURL string) bool {
  47. var result bool
  48. query := `SELECT true FROM feeds WHERE id <> $1 AND user_id=$2 AND feed_url=$3`
  49. s.db.QueryRow(query, feedID, userID, feedURL).Scan(&result)
  50. return result
  51. }
  52. // CountAllFeeds returns the number of feeds in the database.
  53. func (s *Storage) CountAllFeeds() map[string]int64 {
  54. rows, err := s.db.Query(`SELECT disabled, count(*) FROM feeds GROUP BY disabled`)
  55. if err != nil {
  56. return nil
  57. }
  58. defer rows.Close()
  59. results := make(map[string]int64)
  60. results["enabled"] = 0
  61. results["disabled"] = 0
  62. for rows.Next() {
  63. var disabled bool
  64. var count int64
  65. if err := rows.Scan(&disabled, &count); err != nil {
  66. continue
  67. }
  68. if disabled {
  69. results["disabled"] = count
  70. } else {
  71. results["enabled"] = count
  72. }
  73. }
  74. results["total"] = results["disabled"] + results["enabled"]
  75. return results
  76. }
  77. // CountFeeds returns the number of feeds that belongs to the given user.
  78. func (s *Storage) CountFeeds(userID int64) int {
  79. var result int
  80. err := s.db.QueryRow(`SELECT count(*) FROM feeds WHERE user_id=$1`, userID).Scan(&result)
  81. if err != nil {
  82. return 0
  83. }
  84. return result
  85. }
  86. // CountUserFeedsWithErrors returns the number of feeds with parsing errors that belong to the given user.
  87. func (s *Storage) CountUserFeedsWithErrors(userID int64) int {
  88. pollingParsingErrorLimit := config.Opts.PollingParsingErrorLimit()
  89. if pollingParsingErrorLimit <= 0 {
  90. pollingParsingErrorLimit = 1
  91. }
  92. query := `SELECT count(*) FROM feeds WHERE user_id=$1 AND parsing_error_count >= $2`
  93. var result int
  94. err := s.db.QueryRow(query, userID, pollingParsingErrorLimit).Scan(&result)
  95. if err != nil {
  96. return 0
  97. }
  98. return result
  99. }
  100. // CountAllFeedsWithErrors returns the number of feeds with parsing errors.
  101. func (s *Storage) CountAllFeedsWithErrors() int {
  102. pollingParsingErrorLimit := config.Opts.PollingParsingErrorLimit()
  103. if pollingParsingErrorLimit <= 0 {
  104. pollingParsingErrorLimit = 1
  105. }
  106. query := `SELECT count(*) FROM feeds WHERE parsing_error_count >= $1`
  107. var result int
  108. err := s.db.QueryRow(query, pollingParsingErrorLimit).Scan(&result)
  109. if err != nil {
  110. return 0
  111. }
  112. return result
  113. }
  114. // Feeds returns all feeds that belongs to the given user.
  115. func (s *Storage) Feeds(userID int64) (model.Feeds, error) {
  116. builder := NewFeedQueryBuilder(s, userID)
  117. builder.WithOrder(model.DefaultFeedSorting)
  118. builder.WithDirection(model.DefaultFeedSortingDirection)
  119. return builder.GetFeeds()
  120. }
  121. func getFeedsSorted(builder *FeedQueryBuilder) (model.Feeds, error) {
  122. result, err := builder.GetFeeds()
  123. if err == nil {
  124. sort.Sort(byStateAndName{result})
  125. return result, nil
  126. }
  127. return result, err
  128. }
  129. // FeedsWithCounters returns all feeds of the given user with counters of read and unread entries.
  130. func (s *Storage) FeedsWithCounters(userID int64) (model.Feeds, error) {
  131. builder := NewFeedQueryBuilder(s, userID)
  132. builder.WithCounters()
  133. builder.WithOrder(model.DefaultFeedSorting)
  134. builder.WithDirection(model.DefaultFeedSortingDirection)
  135. return getFeedsSorted(builder)
  136. }
  137. // Return read and unread count.
  138. func (s *Storage) FetchCounters(userID int64) (model.FeedCounters, error) {
  139. builder := NewFeedQueryBuilder(s, userID)
  140. builder.WithCounters()
  141. reads, unreads, err := builder.fetchFeedCounter()
  142. return model.FeedCounters{ReadCounters: reads, UnreadCounters: unreads}, err
  143. }
  144. // FeedsByCategoryWithCounters returns all feeds of the given user/category with counters of read and unread entries.
  145. func (s *Storage) FeedsByCategoryWithCounters(userID, categoryID int64) (model.Feeds, error) {
  146. builder := NewFeedQueryBuilder(s, userID)
  147. builder.WithCategoryID(categoryID)
  148. builder.WithCounters()
  149. builder.WithOrder(model.DefaultFeedSorting)
  150. builder.WithDirection(model.DefaultFeedSortingDirection)
  151. return getFeedsSorted(builder)
  152. }
  153. // WeeklyFeedEntryCount returns the weekly entry count for a feed.
  154. func (s *Storage) WeeklyFeedEntryCount(userID, feedID int64) (int, error) {
  155. query := `
  156. SELECT
  157. count(*)
  158. FROM
  159. entries
  160. WHERE
  161. entries.user_id=$1 AND
  162. entries.feed_id=$2 AND
  163. entries.published_at BETWEEN (now() - interval '1 week') AND now();
  164. `
  165. var weeklyCount int
  166. err := s.db.QueryRow(query, userID, feedID).Scan(&weeklyCount)
  167. switch {
  168. case errors.Is(err, sql.ErrNoRows):
  169. return 0, nil
  170. case err != nil:
  171. return 0, fmt.Errorf(`store: unable to fetch weekly count for feed #%d: %v`, feedID, err)
  172. }
  173. return weeklyCount, nil
  174. }
  175. // FeedByID returns a feed by the ID.
  176. func (s *Storage) FeedByID(userID, feedID int64) (*model.Feed, error) {
  177. builder := NewFeedQueryBuilder(s, userID)
  178. builder.WithFeedID(feedID)
  179. feed, err := builder.GetFeed()
  180. switch {
  181. case errors.Is(err, sql.ErrNoRows):
  182. return nil, nil
  183. case err != nil:
  184. return nil, fmt.Errorf(`store: unable to fetch feed #%d: %v`, feedID, err)
  185. }
  186. return feed, nil
  187. }
  188. // CreateFeed creates a new feed.
  189. func (s *Storage) CreateFeed(feed *model.Feed) error {
  190. sql := `
  191. INSERT INTO feeds (
  192. feed_url,
  193. site_url,
  194. title,
  195. category_id,
  196. user_id,
  197. etag_header,
  198. last_modified_header,
  199. crawler,
  200. user_agent,
  201. cookie,
  202. username,
  203. password,
  204. disabled,
  205. scraper_rules,
  206. rewrite_rules,
  207. blocklist_rules,
  208. keeplist_rules,
  209. ignore_http_cache,
  210. allow_self_signed_certificates,
  211. fetch_via_proxy,
  212. hide_globally
  213. )
  214. VALUES
  215. ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21)
  216. RETURNING
  217. id
  218. `
  219. err := s.db.QueryRow(
  220. sql,
  221. feed.FeedURL,
  222. feed.SiteURL,
  223. feed.Title,
  224. feed.Category.ID,
  225. feed.UserID,
  226. feed.EtagHeader,
  227. feed.LastModifiedHeader,
  228. feed.Crawler,
  229. feed.UserAgent,
  230. feed.Cookie,
  231. feed.Username,
  232. feed.Password,
  233. feed.Disabled,
  234. feed.ScraperRules,
  235. feed.RewriteRules,
  236. feed.BlocklistRules,
  237. feed.KeeplistRules,
  238. feed.IgnoreHTTPCache,
  239. feed.AllowSelfSignedCertificates,
  240. feed.FetchViaProxy,
  241. feed.HideGlobally,
  242. ).Scan(&feed.ID)
  243. if err != nil {
  244. return fmt.Errorf(`store: unable to create feed %q: %v`, feed.FeedURL, err)
  245. }
  246. for i := 0; i < len(feed.Entries); i++ {
  247. feed.Entries[i].FeedID = feed.ID
  248. feed.Entries[i].UserID = feed.UserID
  249. tx, err := s.db.Begin()
  250. if err != nil {
  251. return fmt.Errorf(`store: unable to start transaction: %v`, err)
  252. }
  253. if !s.entryExists(tx, feed.Entries[i]) {
  254. if err := s.createEntry(tx, feed.Entries[i]); err != nil {
  255. tx.Rollback()
  256. return err
  257. }
  258. }
  259. if err := tx.Commit(); err != nil {
  260. return fmt.Errorf(`store: unable to commit transaction: %v`, err)
  261. }
  262. }
  263. return nil
  264. }
  265. // UpdateFeed updates an existing feed.
  266. func (s *Storage) UpdateFeed(feed *model.Feed) (err error) {
  267. query := `
  268. UPDATE
  269. feeds
  270. SET
  271. feed_url=$1,
  272. site_url=$2,
  273. title=$3,
  274. category_id=$4,
  275. etag_header=$5,
  276. last_modified_header=$6,
  277. checked_at=$7,
  278. parsing_error_msg=$8,
  279. parsing_error_count=$9,
  280. scraper_rules=$10,
  281. rewrite_rules=$11,
  282. blocklist_rules=$12,
  283. keeplist_rules=$13,
  284. crawler=$14,
  285. user_agent=$15,
  286. cookie=$16,
  287. username=$17,
  288. password=$18,
  289. disabled=$19,
  290. next_check_at=$20,
  291. ignore_http_cache=$21,
  292. allow_self_signed_certificates=$22,
  293. fetch_via_proxy=$23,
  294. hide_globally=$24
  295. WHERE
  296. id=$25 AND user_id=$26
  297. `
  298. _, err = s.db.Exec(query,
  299. feed.FeedURL,
  300. feed.SiteURL,
  301. feed.Title,
  302. feed.Category.ID,
  303. feed.EtagHeader,
  304. feed.LastModifiedHeader,
  305. feed.CheckedAt,
  306. feed.ParsingErrorMsg,
  307. feed.ParsingErrorCount,
  308. feed.ScraperRules,
  309. feed.RewriteRules,
  310. feed.BlocklistRules,
  311. feed.KeeplistRules,
  312. feed.Crawler,
  313. feed.UserAgent,
  314. feed.Cookie,
  315. feed.Username,
  316. feed.Password,
  317. feed.Disabled,
  318. feed.NextCheckAt,
  319. feed.IgnoreHTTPCache,
  320. feed.AllowSelfSignedCertificates,
  321. feed.FetchViaProxy,
  322. feed.HideGlobally,
  323. feed.ID,
  324. feed.UserID,
  325. )
  326. if err != nil {
  327. return fmt.Errorf(`store: unable to update feed #%d (%s): %v`, feed.ID, feed.FeedURL, err)
  328. }
  329. return nil
  330. }
  331. // UpdateFeedError updates feed errors.
  332. func (s *Storage) UpdateFeedError(feed *model.Feed) (err error) {
  333. query := `
  334. UPDATE
  335. feeds
  336. SET
  337. parsing_error_msg=$1,
  338. parsing_error_count=$2,
  339. checked_at=$3,
  340. next_check_at=$4
  341. WHERE
  342. id=$5 AND user_id=$6
  343. `
  344. _, err = s.db.Exec(query,
  345. feed.ParsingErrorMsg,
  346. feed.ParsingErrorCount,
  347. feed.CheckedAt,
  348. feed.NextCheckAt,
  349. feed.ID,
  350. feed.UserID,
  351. )
  352. if err != nil {
  353. return fmt.Errorf(`store: unable to update feed error #%d (%s): %v`, feed.ID, feed.FeedURL, err)
  354. }
  355. return nil
  356. }
  357. // RemoveFeed removes a feed and all entries.
  358. // This operation can takes time if the feed has lot of entries.
  359. func (s *Storage) RemoveFeed(userID, feedID int64) error {
  360. rows, err := s.db.Query(`SELECT id FROM entries WHERE user_id=$1 AND feed_id=$2`, userID, feedID)
  361. if err != nil {
  362. return fmt.Errorf(`store: unable to get user feed entries: %v`, err)
  363. }
  364. defer rows.Close()
  365. for rows.Next() {
  366. var entryID int64
  367. if err := rows.Scan(&entryID); err != nil {
  368. return fmt.Errorf(`store: unable to read user feed entry ID: %v`, err)
  369. }
  370. logger.Debug(`[FEED DELETION] Deleting entry #%d of feed #%d for user #%d (%d GoRoutines)`, entryID, feedID, userID, runtime.NumGoroutine())
  371. if _, err := s.db.Exec(`DELETE FROM entries WHERE id=$1 AND user_id=$2`, entryID, userID); err != nil {
  372. return fmt.Errorf(`store: unable to delete user feed entries #%d: %v`, entryID, err)
  373. }
  374. }
  375. if _, err := s.db.Exec(`DELETE FROM feeds WHERE id=$1 AND user_id=$2`, feedID, userID); err != nil {
  376. return fmt.Errorf(`store: unable to delete feed #%d: %v`, feedID, err)
  377. }
  378. return nil
  379. }
  380. // ResetFeedErrors removes all feed errors.
  381. func (s *Storage) ResetFeedErrors() error {
  382. _, err := s.db.Exec(`UPDATE feeds SET parsing_error_count=0, parsing_error_msg=''`)
  383. return err
  384. }