entry.go 16 KB

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