entry.go 16 KB

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