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