entry.go 16 KB

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