entry.go 15 KB

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