entry.go 16 KB

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