feed.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. // FeedsByCategoryWithCounters returns all feeds of the given user/category with counters of read and unread entries.
  138. func (s *Storage) FeedsByCategoryWithCounters(userID, categoryID int64) (model.Feeds, error) {
  139. builder := NewFeedQueryBuilder(s, userID)
  140. builder.WithCategoryID(categoryID)
  141. builder.WithCounters()
  142. builder.WithOrder(model.DefaultFeedSorting)
  143. builder.WithDirection(model.DefaultFeedSortingDirection)
  144. return getFeedsSorted(builder)
  145. }
  146. // WeeklyFeedEntryCount returns the weekly entry count for a feed.
  147. func (s *Storage) WeeklyFeedEntryCount(userID, feedID int64) (int, error) {
  148. query := `
  149. SELECT
  150. count(*)
  151. FROM
  152. entries
  153. WHERE
  154. entries.user_id=$1 AND
  155. entries.feed_id=$2 AND
  156. entries.published_at BETWEEN (now() - interval '1 week') AND now();
  157. `
  158. var weeklyCount int
  159. err := s.db.QueryRow(query, userID, feedID).Scan(&weeklyCount)
  160. switch {
  161. case errors.Is(err, sql.ErrNoRows):
  162. return 0, nil
  163. case err != nil:
  164. return 0, fmt.Errorf(`store: unable to fetch weekly count for feed #%d: %v`, feedID, err)
  165. }
  166. return weeklyCount, nil
  167. }
  168. // FeedByID returns a feed by the ID.
  169. func (s *Storage) FeedByID(userID, feedID int64) (*model.Feed, error) {
  170. builder := NewFeedQueryBuilder(s, userID)
  171. builder.WithFeedID(feedID)
  172. feed, err := builder.GetFeed()
  173. switch {
  174. case errors.Is(err, sql.ErrNoRows):
  175. return nil, nil
  176. case err != nil:
  177. return nil, fmt.Errorf(`store: unable to fetch feed #%d: %v`, feedID, err)
  178. }
  179. return feed, nil
  180. }
  181. // CreateFeed creates a new feed.
  182. func (s *Storage) CreateFeed(feed *model.Feed) error {
  183. sql := `
  184. INSERT INTO feeds (
  185. feed_url,
  186. site_url,
  187. title,
  188. category_id,
  189. user_id,
  190. etag_header,
  191. last_modified_header,
  192. crawler,
  193. user_agent,
  194. cookie,
  195. username,
  196. password,
  197. disabled,
  198. scraper_rules,
  199. rewrite_rules,
  200. blocklist_rules,
  201. keeplist_rules,
  202. ignore_http_cache,
  203. allow_self_signed_certificates,
  204. fetch_via_proxy,
  205. hide_globally
  206. )
  207. VALUES
  208. ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21)
  209. RETURNING
  210. id
  211. `
  212. err := s.db.QueryRow(
  213. sql,
  214. feed.FeedURL,
  215. feed.SiteURL,
  216. feed.Title,
  217. feed.Category.ID,
  218. feed.UserID,
  219. feed.EtagHeader,
  220. feed.LastModifiedHeader,
  221. feed.Crawler,
  222. feed.UserAgent,
  223. feed.Cookie,
  224. feed.Username,
  225. feed.Password,
  226. feed.Disabled,
  227. feed.ScraperRules,
  228. feed.RewriteRules,
  229. feed.BlocklistRules,
  230. feed.KeeplistRules,
  231. feed.IgnoreHTTPCache,
  232. feed.AllowSelfSignedCertificates,
  233. feed.FetchViaProxy,
  234. feed.HideGlobally,
  235. ).Scan(&feed.ID)
  236. if err != nil {
  237. return fmt.Errorf(`store: unable to create feed %q: %v`, feed.FeedURL, err)
  238. }
  239. for i := 0; i < len(feed.Entries); i++ {
  240. feed.Entries[i].FeedID = feed.ID
  241. feed.Entries[i].UserID = feed.UserID
  242. tx, err := s.db.Begin()
  243. if err != nil {
  244. return fmt.Errorf(`store: unable to start transaction: %v`, err)
  245. }
  246. if !s.entryExists(tx, feed.Entries[i]) {
  247. if err := s.createEntry(tx, feed.Entries[i]); err != nil {
  248. tx.Rollback()
  249. return err
  250. }
  251. }
  252. if err := tx.Commit(); err != nil {
  253. return fmt.Errorf(`store: unable to commit transaction: %v`, err)
  254. }
  255. }
  256. return nil
  257. }
  258. // UpdateFeed updates an existing feed.
  259. func (s *Storage) UpdateFeed(feed *model.Feed) (err error) {
  260. query := `
  261. UPDATE
  262. feeds
  263. SET
  264. feed_url=$1,
  265. site_url=$2,
  266. title=$3,
  267. category_id=$4,
  268. etag_header=$5,
  269. last_modified_header=$6,
  270. checked_at=$7,
  271. parsing_error_msg=$8,
  272. parsing_error_count=$9,
  273. scraper_rules=$10,
  274. rewrite_rules=$11,
  275. blocklist_rules=$12,
  276. keeplist_rules=$13,
  277. crawler=$14,
  278. user_agent=$15,
  279. cookie=$16,
  280. username=$17,
  281. password=$18,
  282. disabled=$19,
  283. next_check_at=$20,
  284. ignore_http_cache=$21,
  285. allow_self_signed_certificates=$22,
  286. fetch_via_proxy=$23,
  287. hide_globally=$24
  288. WHERE
  289. id=$25 AND user_id=$26
  290. `
  291. _, err = s.db.Exec(query,
  292. feed.FeedURL,
  293. feed.SiteURL,
  294. feed.Title,
  295. feed.Category.ID,
  296. feed.EtagHeader,
  297. feed.LastModifiedHeader,
  298. feed.CheckedAt,
  299. feed.ParsingErrorMsg,
  300. feed.ParsingErrorCount,
  301. feed.ScraperRules,
  302. feed.RewriteRules,
  303. feed.BlocklistRules,
  304. feed.KeeplistRules,
  305. feed.Crawler,
  306. feed.UserAgent,
  307. feed.Cookie,
  308. feed.Username,
  309. feed.Password,
  310. feed.Disabled,
  311. feed.NextCheckAt,
  312. feed.IgnoreHTTPCache,
  313. feed.AllowSelfSignedCertificates,
  314. feed.FetchViaProxy,
  315. feed.HideGlobally,
  316. feed.ID,
  317. feed.UserID,
  318. )
  319. if err != nil {
  320. return fmt.Errorf(`store: unable to update feed #%d (%s): %v`, feed.ID, feed.FeedURL, err)
  321. }
  322. return nil
  323. }
  324. // UpdateFeedError updates feed errors.
  325. func (s *Storage) UpdateFeedError(feed *model.Feed) (err error) {
  326. query := `
  327. UPDATE
  328. feeds
  329. SET
  330. parsing_error_msg=$1,
  331. parsing_error_count=$2,
  332. checked_at=$3,
  333. next_check_at=$4
  334. WHERE
  335. id=$5 AND user_id=$6
  336. `
  337. _, err = s.db.Exec(query,
  338. feed.ParsingErrorMsg,
  339. feed.ParsingErrorCount,
  340. feed.CheckedAt,
  341. feed.NextCheckAt,
  342. feed.ID,
  343. feed.UserID,
  344. )
  345. if err != nil {
  346. return fmt.Errorf(`store: unable to update feed error #%d (%s): %v`, feed.ID, feed.FeedURL, err)
  347. }
  348. return nil
  349. }
  350. // RemoveFeed removes a feed and all entries.
  351. // This operation can takes time if the feed has lot of entries.
  352. func (s *Storage) RemoveFeed(userID, feedID int64) error {
  353. rows, err := s.db.Query(`SELECT id FROM entries WHERE user_id=$1 AND feed_id=$2`, userID, feedID)
  354. if err != nil {
  355. return fmt.Errorf(`store: unable to get user feed entries: %v`, err)
  356. }
  357. defer rows.Close()
  358. for rows.Next() {
  359. var entryID int64
  360. if err := rows.Scan(&entryID); err != nil {
  361. return fmt.Errorf(`store: unable to read user feed entry ID: %v`, err)
  362. }
  363. logger.Debug(`[FEED DELETION] Deleting entry #%d of feed #%d for user #%d (%d GoRoutines)`, entryID, feedID, userID, runtime.NumGoroutine())
  364. if _, err := s.db.Exec(`DELETE FROM entries WHERE id=$1 AND user_id=$2`, entryID, userID); err != nil {
  365. return fmt.Errorf(`store: unable to delete user feed entries #%d: %v`, entryID, err)
  366. }
  367. }
  368. if _, err := s.db.Exec(`DELETE FROM feeds WHERE id=$1 AND user_id=$2`, feedID, userID); err != nil {
  369. return fmt.Errorf(`store: unable to delete feed #%d: %v`, feedID, err)
  370. }
  371. return nil
  372. }
  373. // ResetFeedErrors removes all feed errors.
  374. func (s *Storage) ResetFeedErrors() error {
  375. _, err := s.db.Exec(`UPDATE feeds SET parsing_error_count=0, parsing_error_msg=''`)
  376. return err
  377. }