entry.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package storage // import "miniflux.app/storage"
  4. import (
  5. "database/sql"
  6. "errors"
  7. "fmt"
  8. "time"
  9. "miniflux.app/crypto"
  10. "miniflux.app/logger"
  11. "miniflux.app/model"
  12. "github.com/lib/pq"
  13. )
  14. // CountAllEntries returns the number of entries for each status in the database.
  15. func (s *Storage) CountAllEntries() map[string]int64 {
  16. rows, err := s.db.Query(`SELECT status, count(*) FROM entries GROUP BY status`)
  17. if err != nil {
  18. return nil
  19. }
  20. defer rows.Close()
  21. results := make(map[string]int64)
  22. results[model.EntryStatusUnread] = 0
  23. results[model.EntryStatusRead] = 0
  24. results[model.EntryStatusRemoved] = 0
  25. for rows.Next() {
  26. var status string
  27. var count int64
  28. if err := rows.Scan(&status, &count); err != nil {
  29. continue
  30. }
  31. results[status] = count
  32. }
  33. results["total"] = results[model.EntryStatusUnread] + results[model.EntryStatusRead] + results[model.EntryStatusRemoved]
  34. return results
  35. }
  36. // CountUnreadEntries returns the number of unread entries.
  37. func (s *Storage) CountUnreadEntries(userID int64) int {
  38. builder := s.NewEntryQueryBuilder(userID)
  39. builder.WithStatus(model.EntryStatusUnread)
  40. builder.WithGloballyVisible()
  41. n, err := builder.CountEntries()
  42. if err != nil {
  43. logger.Error(`store: unable to count unread entries for user #%d: %v`, userID, err)
  44. return 0
  45. }
  46. return n
  47. }
  48. // NewEntryQueryBuilder returns a new EntryQueryBuilder
  49. func (s *Storage) NewEntryQueryBuilder(userID int64) *EntryQueryBuilder {
  50. return NewEntryQueryBuilder(s, userID)
  51. }
  52. // UpdateEntryContent updates entry content.
  53. func (s *Storage) UpdateEntryContent(entry *model.Entry) error {
  54. tx, err := s.db.Begin()
  55. if err != nil {
  56. return err
  57. }
  58. query := `
  59. UPDATE
  60. entries
  61. SET
  62. content=$1, reading_time=$2
  63. WHERE
  64. id=$3 AND user_id=$4
  65. `
  66. _, err = tx.Exec(query, entry.Content, entry.ReadingTime, entry.ID, entry.UserID)
  67. if err != nil {
  68. tx.Rollback()
  69. return fmt.Errorf(`store: unable to update content of entry #%d: %v`, entry.ID, err)
  70. }
  71. query = `
  72. UPDATE
  73. entries
  74. SET
  75. document_vectors = setweight(to_tsvector(left(coalesce(title, ''), 500000)), 'A') || setweight(to_tsvector(left(coalesce(content, ''), 500000)), 'B')
  76. WHERE
  77. id=$1 AND user_id=$2
  78. `
  79. _, err = tx.Exec(query, entry.ID, entry.UserID)
  80. if err != nil {
  81. tx.Rollback()
  82. return fmt.Errorf(`store: unable to update content of entry #%d: %v`, entry.ID, err)
  83. }
  84. return tx.Commit()
  85. }
  86. // createEntry add a new entry.
  87. func (s *Storage) createEntry(tx *sql.Tx, entry *model.Entry) error {
  88. query := `
  89. INSERT INTO entries
  90. (
  91. title,
  92. hash,
  93. url,
  94. comments_url,
  95. published_at,
  96. content,
  97. author,
  98. user_id,
  99. feed_id,
  100. reading_time,
  101. changed_at,
  102. document_vectors,
  103. tags
  104. )
  105. VALUES
  106. (
  107. $1,
  108. $2,
  109. $3,
  110. $4,
  111. $5,
  112. $6,
  113. $7,
  114. $8,
  115. $9,
  116. $10,
  117. now(),
  118. setweight(to_tsvector(left(coalesce($1, ''), 500000)), 'A') || setweight(to_tsvector(left(coalesce($6, ''), 500000)), 'B'),
  119. $11
  120. )
  121. RETURNING
  122. id, status
  123. `
  124. err := tx.QueryRow(
  125. query,
  126. entry.Title,
  127. entry.Hash,
  128. entry.URL,
  129. entry.CommentsURL,
  130. entry.Date,
  131. entry.Content,
  132. entry.Author,
  133. entry.UserID,
  134. entry.FeedID,
  135. entry.ReadingTime,
  136. pq.Array(removeDuplicates(entry.Tags)),
  137. ).Scan(&entry.ID, &entry.Status)
  138. if err != nil {
  139. return fmt.Errorf(`store: unable to create entry %q (feed #%d): %v`, entry.URL, entry.FeedID, err)
  140. }
  141. for i := 0; i < len(entry.Enclosures); i++ {
  142. entry.Enclosures[i].EntryID = entry.ID
  143. entry.Enclosures[i].UserID = entry.UserID
  144. err := s.createEnclosure(tx, entry.Enclosures[i])
  145. if err != nil {
  146. return err
  147. }
  148. }
  149. return nil
  150. }
  151. // updateEntry updates an entry when a feed is refreshed.
  152. // Note: we do not update the published date because some feeds do not contains any date,
  153. // it default to time.Now() which could change the order of items on the history page.
  154. func (s *Storage) updateEntry(tx *sql.Tx, entry *model.Entry) error {
  155. query := `
  156. UPDATE
  157. entries
  158. SET
  159. title=$1,
  160. url=$2,
  161. comments_url=$3,
  162. content=$4,
  163. author=$5,
  164. reading_time=$6,
  165. document_vectors = setweight(to_tsvector(left(coalesce($1, ''), 500000)), 'A') || setweight(to_tsvector(left(coalesce($4, ''), 500000)), 'B'),
  166. tags=$10
  167. WHERE
  168. user_id=$7 AND feed_id=$8 AND hash=$9
  169. RETURNING
  170. id
  171. `
  172. err := tx.QueryRow(
  173. query,
  174. entry.Title,
  175. entry.URL,
  176. entry.CommentsURL,
  177. entry.Content,
  178. entry.Author,
  179. entry.ReadingTime,
  180. entry.UserID,
  181. entry.FeedID,
  182. entry.Hash,
  183. pq.Array(removeDuplicates(entry.Tags)),
  184. ).Scan(&entry.ID)
  185. if err != nil {
  186. return fmt.Errorf(`store: unable to update entry %q: %v`, entry.URL, err)
  187. }
  188. for _, enclosure := range entry.Enclosures {
  189. enclosure.UserID = entry.UserID
  190. enclosure.EntryID = entry.ID
  191. }
  192. return s.updateEnclosures(tx, entry.UserID, entry.ID, entry.Enclosures)
  193. }
  194. // entryExists checks if an entry already exists based on its hash when refreshing a feed.
  195. func (s *Storage) entryExists(tx *sql.Tx, entry *model.Entry) (bool, error) {
  196. var result bool
  197. // Note: This query uses entries_feed_id_hash_key index (filtering on user_id is not necessary).
  198. err := tx.QueryRow(`SELECT true FROM entries WHERE feed_id=$1 AND hash=$2`, entry.FeedID, entry.Hash).Scan(&result)
  199. if err != nil && err != sql.ErrNoRows {
  200. return result, fmt.Errorf(`store: unable to check if entry exists: %v`, err)
  201. }
  202. return result, nil
  203. }
  204. // GetReadTime fetches the read time of an entry based on its hash, and the feed id and user id from the feed.
  205. // It's intended to be used on entries objects created by parsing a feed as they don't contain much information.
  206. // The feed param helps to scope the search to a specific user and feed in order to avoid hash clashes.
  207. func (s *Storage) GetReadTime(entry *model.Entry, feed *model.Feed) int {
  208. var result int
  209. s.db.QueryRow(
  210. `SELECT reading_time FROM entries WHERE user_id=$1 AND feed_id=$2 AND hash=$3`,
  211. feed.UserID,
  212. feed.ID,
  213. entry.Hash,
  214. ).Scan(&result)
  215. return result
  216. }
  217. // cleanupEntries deletes from the database entries marked as "removed" and not visible anymore in the feed.
  218. func (s *Storage) cleanupEntries(feedID int64, entryHashes []string) error {
  219. query := `
  220. DELETE FROM
  221. entries
  222. WHERE
  223. feed_id=$1
  224. AND
  225. id IN (SELECT id FROM entries WHERE feed_id=$2 AND status=$3 AND NOT (hash=ANY($4)))
  226. `
  227. if _, err := s.db.Exec(query, feedID, feedID, model.EntryStatusRemoved, pq.Array(entryHashes)); err != nil {
  228. return fmt.Errorf(`store: unable to cleanup entries: %v`, err)
  229. }
  230. return nil
  231. }
  232. // RefreshFeedEntries updates feed entries while refreshing a feed.
  233. func (s *Storage) RefreshFeedEntries(userID, feedID int64, entries model.Entries, updateExistingEntries bool) (err error) {
  234. var entryHashes []string
  235. for _, entry := range entries {
  236. entry.UserID = userID
  237. entry.FeedID = feedID
  238. tx, err := s.db.Begin()
  239. if err != nil {
  240. return fmt.Errorf(`store: unable to start transaction: %v`, err)
  241. }
  242. entryExists, err := s.entryExists(tx, entry)
  243. if err != nil {
  244. if rollbackErr := tx.Rollback(); rollbackErr != nil {
  245. return fmt.Errorf(`store: unable to rollback transaction: %v (rolled back due to: %v)`, rollbackErr, err)
  246. }
  247. return err
  248. }
  249. if entryExists {
  250. if updateExistingEntries {
  251. err = s.updateEntry(tx, entry)
  252. }
  253. } else {
  254. err = s.createEntry(tx, entry)
  255. }
  256. if err != nil {
  257. if rollbackErr := tx.Rollback(); rollbackErr != nil {
  258. return fmt.Errorf(`store: unable to rollback transaction: %v (rolled back due to: %v)`, rollbackErr, err)
  259. }
  260. return err
  261. }
  262. if err := tx.Commit(); err != nil {
  263. return fmt.Errorf(`store: unable to commit transaction: %v`, err)
  264. }
  265. entryHashes = append(entryHashes, entry.Hash)
  266. }
  267. go func() {
  268. if err := s.cleanupEntries(feedID, entryHashes); err != nil {
  269. logger.Error(`store: feed #%d: %v`, feedID, err)
  270. }
  271. }()
  272. return nil
  273. }
  274. // ArchiveEntries changes the status of entries to "removed" after the given number of days.
  275. func (s *Storage) ArchiveEntries(status string, days, limit int) (int64, error) {
  276. if days < 0 || limit <= 0 {
  277. return 0, nil
  278. }
  279. query := `
  280. UPDATE
  281. entries
  282. SET
  283. status='removed'
  284. WHERE
  285. id=ANY(SELECT id FROM entries WHERE status=$1 AND starred is false AND share_code='' AND created_at < now () - '%d days'::interval ORDER BY created_at ASC LIMIT %d)
  286. `
  287. result, err := s.db.Exec(fmt.Sprintf(query, days, limit), status)
  288. if err != nil {
  289. return 0, fmt.Errorf(`store: unable to archive %s entries: %v`, status, err)
  290. }
  291. count, err := result.RowsAffected()
  292. if err != nil {
  293. return 0, fmt.Errorf(`store: unable to get the number of rows affected: %v`, err)
  294. }
  295. return count, nil
  296. }
  297. // SetEntriesStatus update the status of the given list of entries.
  298. func (s *Storage) SetEntriesStatus(userID int64, entryIDs []int64, status string) error {
  299. query := `UPDATE entries SET status=$1, changed_at=now() WHERE user_id=$2 AND id=ANY($3)`
  300. result, err := s.db.Exec(query, status, userID, pq.Array(entryIDs))
  301. if err != nil {
  302. return fmt.Errorf(`store: unable to update entries statuses %v: %v`, entryIDs, err)
  303. }
  304. count, err := result.RowsAffected()
  305. if err != nil {
  306. return fmt.Errorf(`store: unable to update these entries %v: %v`, entryIDs, err)
  307. }
  308. if count == 0 {
  309. return errors.New(`store: nothing has been updated`)
  310. }
  311. return nil
  312. }
  313. func (s *Storage) SetEntriesStatusCount(userID int64, entryIDs []int64, status string) (int, error) {
  314. if err := s.SetEntriesStatus(userID, entryIDs, status); err != nil {
  315. return 0, err
  316. }
  317. query := `
  318. SELECT count(*)
  319. FROM entries e
  320. JOIN feeds f ON (f.id = e.feed_id)
  321. JOIN categories c ON (c.id = f.category_id)
  322. WHERE e.user_id = $1
  323. AND e.id = ANY($2)
  324. AND NOT f.hide_globally
  325. AND NOT c.hide_globally
  326. `
  327. row := s.db.QueryRow(query, userID, pq.Array(entryIDs))
  328. visible := 0
  329. if err := row.Scan(&visible); err != nil {
  330. return 0, fmt.Errorf(`store: unable to query entries visibility %v: %v`, entryIDs, err)
  331. }
  332. return visible, nil
  333. }
  334. // SetEntriesBookmarked update the bookmarked state for the given list of entries.
  335. func (s *Storage) SetEntriesBookmarkedState(userID int64, entryIDs []int64, starred bool) error {
  336. query := `UPDATE entries SET starred=$1, changed_at=now() WHERE user_id=$2 AND id=ANY($3)`
  337. result, err := s.db.Exec(query, starred, userID, pq.Array(entryIDs))
  338. if err != nil {
  339. return fmt.Errorf(`store: unable to update the bookmarked state %v: %v`, entryIDs, err)
  340. }
  341. count, err := result.RowsAffected()
  342. if err != nil {
  343. return fmt.Errorf(`store: unable to update these entries %v: %v`, entryIDs, err)
  344. }
  345. if count == 0 {
  346. return errors.New(`store: nothing has been updated`)
  347. }
  348. return nil
  349. }
  350. // ToggleBookmark toggles entry bookmark value.
  351. func (s *Storage) ToggleBookmark(userID int64, entryID int64) error {
  352. query := `UPDATE entries SET starred = NOT starred, changed_at=now() WHERE user_id=$1 AND id=$2`
  353. result, err := s.db.Exec(query, userID, entryID)
  354. if err != nil {
  355. return fmt.Errorf(`store: unable to toggle bookmark flag for entry #%d: %v`, entryID, err)
  356. }
  357. count, err := result.RowsAffected()
  358. if err != nil {
  359. return fmt.Errorf(`store: unable to toggle bookmark flag for entry #%d: %v`, entryID, err)
  360. }
  361. if count == 0 {
  362. return errors.New(`store: nothing has been updated`)
  363. }
  364. return nil
  365. }
  366. // FlushHistory set all entries with the status "read" to "removed".
  367. func (s *Storage) FlushHistory(userID int64) error {
  368. query := `
  369. UPDATE
  370. entries
  371. SET
  372. status=$1,
  373. changed_at=now()
  374. WHERE
  375. user_id=$2 AND status=$3 AND starred is false AND share_code=''
  376. `
  377. _, err := s.db.Exec(query, model.EntryStatusRemoved, userID, model.EntryStatusRead)
  378. if err != nil {
  379. return fmt.Errorf(`store: unable to flush history: %v`, err)
  380. }
  381. return nil
  382. }
  383. // MarkAllAsRead updates all user entries to the read status.
  384. func (s *Storage) MarkAllAsRead(userID int64) error {
  385. query := `UPDATE entries SET status=$1, changed_at=now() WHERE user_id=$2 AND status=$3`
  386. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread)
  387. if err != nil {
  388. return fmt.Errorf(`store: unable to mark all entries as read: %v`, err)
  389. }
  390. count, _ := result.RowsAffected()
  391. logger.Debug("[Storage:MarkAllAsRead] %d items marked as read", count)
  392. return nil
  393. }
  394. // MarkGloballyVisibleFeedsAsRead updates all user entries to the read status.
  395. func (s *Storage) MarkGloballyVisibleFeedsAsRead(userID int64) error {
  396. query := `
  397. UPDATE
  398. entries
  399. SET
  400. status=$1,
  401. changed_at=now()
  402. FROM
  403. feeds
  404. WHERE
  405. entries.feed_id = feeds.id
  406. AND entries.user_id=$2
  407. AND entries.status=$3
  408. AND feeds.hide_globally=$4
  409. `
  410. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread, false)
  411. if err != nil {
  412. return fmt.Errorf(`store: unable to mark globally visible feeds as read: %v`, err)
  413. }
  414. count, _ := result.RowsAffected()
  415. logger.Debug("[Storage:MarkGloballyVisibleFeedsAsRead] %d items marked as read", count)
  416. return nil
  417. }
  418. // MarkFeedAsRead updates all feed entries to the read status.
  419. func (s *Storage) MarkFeedAsRead(userID, feedID int64, before time.Time) error {
  420. query := `
  421. UPDATE
  422. entries
  423. SET
  424. status=$1,
  425. changed_at=now()
  426. WHERE
  427. user_id=$2 AND feed_id=$3 AND status=$4 AND published_at < $5
  428. `
  429. result, err := s.db.Exec(query, model.EntryStatusRead, userID, feedID, model.EntryStatusUnread, before)
  430. if err != nil {
  431. return fmt.Errorf(`store: unable to mark feed entries as read: %v`, err)
  432. }
  433. count, _ := result.RowsAffected()
  434. logger.Debug("[Storage:MarkFeedAsRead] %d items marked as read", count)
  435. return nil
  436. }
  437. // MarkCategoryAsRead updates all category entries to the read status.
  438. func (s *Storage) MarkCategoryAsRead(userID, categoryID int64, before time.Time) error {
  439. query := `
  440. UPDATE
  441. entries
  442. SET
  443. status=$1,
  444. changed_at=now()
  445. WHERE
  446. user_id=$2
  447. AND
  448. status=$3
  449. AND
  450. published_at < $4
  451. AND
  452. feed_id IN (SELECT id FROM feeds WHERE user_id=$2 AND category_id=$5)
  453. `
  454. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread, before, categoryID)
  455. if err != nil {
  456. return fmt.Errorf(`store: unable to mark category entries as read: %v`, err)
  457. }
  458. count, _ := result.RowsAffected()
  459. logger.Debug("[Storage:MarkCategoryAsRead] %d items marked as read", count)
  460. return nil
  461. }
  462. // EntryURLExists returns true if an entry with this URL already exists.
  463. func (s *Storage) EntryURLExists(feedID int64, entryURL string) bool {
  464. var result bool
  465. query := `SELECT true FROM entries WHERE feed_id=$1 AND url=$2`
  466. s.db.QueryRow(query, feedID, entryURL).Scan(&result)
  467. return result
  468. }
  469. // EntryShareCode returns the share code of the provided entry.
  470. // It generates a new one if not already defined.
  471. func (s *Storage) EntryShareCode(userID int64, entryID int64) (shareCode string, err error) {
  472. query := `SELECT share_code FROM entries WHERE user_id=$1 AND id=$2`
  473. err = s.db.QueryRow(query, userID, entryID).Scan(&shareCode)
  474. if err != nil {
  475. err = fmt.Errorf(`store: unable to get share code for entry #%d: %v`, entryID, err)
  476. return
  477. }
  478. if shareCode == "" {
  479. shareCode = crypto.GenerateRandomStringHex(20)
  480. query = `UPDATE entries SET share_code = $1 WHERE user_id=$2 AND id=$3`
  481. _, err = s.db.Exec(query, shareCode, userID, entryID)
  482. if err != nil {
  483. err = fmt.Errorf(`store: unable to set share code for entry #%d: %v`, entryID, err)
  484. return
  485. }
  486. }
  487. return
  488. }
  489. // UnshareEntry removes the share code for the given entry.
  490. func (s *Storage) UnshareEntry(userID int64, entryID int64) (err error) {
  491. query := `UPDATE entries SET share_code='' WHERE user_id=$1 AND id=$2`
  492. _, err = s.db.Exec(query, userID, entryID)
  493. if err != nil {
  494. err = fmt.Errorf(`store: unable to remove share code for entry #%d: %v`, entryID, err)
  495. }
  496. return
  497. }
  498. // removeDuplicate removes duplicate entries from a slice
  499. func removeDuplicates[T string | int](sliceList []T) []T {
  500. allKeys := make(map[T]bool)
  501. list := []T{}
  502. for _, item := range sliceList {
  503. if _, value := allKeys[item]; !value {
  504. allKeys[item] = true
  505. list = append(list, item)
  506. }
  507. }
  508. return list
  509. }