entry.go 17 KB

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