entry.go 16 KB

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