entry.go 16 KB

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