entry.go 16 KB

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