entry.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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. )
  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. )
  120. RETURNING
  121. id, status
  122. `
  123. err := tx.QueryRow(
  124. query,
  125. entry.Title,
  126. entry.Hash,
  127. entry.URL,
  128. entry.CommentsURL,
  129. entry.Date,
  130. entry.Content,
  131. entry.Author,
  132. entry.UserID,
  133. entry.FeedID,
  134. entry.ReadingTime,
  135. ).Scan(&entry.ID, &entry.Status)
  136. if err != nil {
  137. return fmt.Errorf(`store: unable to create entry %q (feed #%d): %v`, entry.URL, entry.FeedID, err)
  138. }
  139. for i := 0; i < len(entry.Enclosures); i++ {
  140. entry.Enclosures[i].EntryID = entry.ID
  141. entry.Enclosures[i].UserID = entry.UserID
  142. err := s.createEnclosure(tx, entry.Enclosures[i])
  143. if err != nil {
  144. return err
  145. }
  146. }
  147. return nil
  148. }
  149. // updateEntry updates an entry when a feed is refreshed.
  150. // Note: we do not update the published date because some feeds do not contains any date,
  151. // it default to time.Now() which could change the order of items on the history page.
  152. func (s *Storage) updateEntry(tx *sql.Tx, entry *model.Entry) error {
  153. query := `
  154. UPDATE
  155. entries
  156. SET
  157. title=$1,
  158. url=$2,
  159. comments_url=$3,
  160. content=$4,
  161. author=$5,
  162. reading_time=$6,
  163. document_vectors = setweight(to_tsvector(left(coalesce($1, ''), 500000)), 'A') || setweight(to_tsvector(left(coalesce($4, ''), 500000)), 'B')
  164. WHERE
  165. user_id=$7 AND feed_id=$8 AND hash=$9
  166. RETURNING
  167. id
  168. `
  169. err := tx.QueryRow(
  170. query,
  171. entry.Title,
  172. entry.URL,
  173. entry.CommentsURL,
  174. entry.Content,
  175. entry.Author,
  176. entry.ReadingTime,
  177. entry.UserID,
  178. entry.FeedID,
  179. entry.Hash,
  180. ).Scan(&entry.ID)
  181. if err != nil {
  182. return fmt.Errorf(`store: unable to update entry %q: %v`, entry.URL, err)
  183. }
  184. for _, enclosure := range entry.Enclosures {
  185. enclosure.UserID = entry.UserID
  186. enclosure.EntryID = entry.ID
  187. }
  188. return s.updateEnclosures(tx, entry.UserID, entry.ID, entry.Enclosures)
  189. }
  190. // entryExists checks if an entry already exists based on its hash when refreshing a feed.
  191. func (s *Storage) entryExists(tx *sql.Tx, entry *model.Entry) bool {
  192. var result bool
  193. tx.QueryRow(
  194. `SELECT true FROM entries WHERE user_id=$1 AND feed_id=$2 AND hash=$3`,
  195. entry.UserID,
  196. entry.FeedID,
  197. entry.Hash,
  198. ).Scan(&result)
  199. return result
  200. }
  201. // GetReadTime fetches the read time of an entry based on its hash, and the feed id and user id from the feed.
  202. // It's intended to be used on entries objects created by parsing a feed as they don't contain much information.
  203. // The feed param helps to scope the search to a specific user and feed in order to avoid hash clashes.
  204. func (s *Storage) GetReadTime(entry *model.Entry, feed *model.Feed) int {
  205. var result int
  206. s.db.QueryRow(
  207. `SELECT reading_time FROM entries WHERE user_id=$1 AND feed_id=$2 AND hash=$3`,
  208. feed.UserID,
  209. feed.ID,
  210. entry.Hash,
  211. ).Scan(&result)
  212. return result
  213. }
  214. // cleanupEntries deletes from the database entries marked as "removed" and not visible anymore in the feed.
  215. func (s *Storage) cleanupEntries(feedID int64, entryHashes []string) error {
  216. query := `
  217. DELETE FROM
  218. entries
  219. WHERE
  220. feed_id=$1
  221. AND
  222. id IN (SELECT id FROM entries WHERE feed_id=$2 AND status=$3 AND NOT (hash=ANY($4)))
  223. `
  224. if _, err := s.db.Exec(query, feedID, feedID, model.EntryStatusRemoved, pq.Array(entryHashes)); err != nil {
  225. return fmt.Errorf(`store: unable to cleanup entries: %v`, err)
  226. }
  227. return nil
  228. }
  229. // RefreshFeedEntries updates feed entries while refreshing a feed.
  230. func (s *Storage) RefreshFeedEntries(userID, feedID int64, entries model.Entries, updateExistingEntries bool) (err error) {
  231. var entryHashes []string
  232. for _, entry := range entries {
  233. entry.UserID = userID
  234. entry.FeedID = feedID
  235. tx, err := s.db.Begin()
  236. if err != nil {
  237. return fmt.Errorf(`store: unable to start transaction: %v`, err)
  238. }
  239. if s.entryExists(tx, entry) {
  240. if updateExistingEntries {
  241. err = s.updateEntry(tx, entry)
  242. }
  243. } else {
  244. err = s.createEntry(tx, entry)
  245. }
  246. if err != nil {
  247. tx.Rollback()
  248. return err
  249. }
  250. if err := tx.Commit(); err != nil {
  251. return fmt.Errorf(`store: unable to commit transaction: %v`, err)
  252. }
  253. entryHashes = append(entryHashes, entry.Hash)
  254. }
  255. go func() {
  256. if err := s.cleanupEntries(feedID, entryHashes); err != nil {
  257. logger.Error(`store: feed #%d: %v`, feedID, err)
  258. }
  259. }()
  260. return nil
  261. }
  262. // ArchiveEntries changes the status of entries to "removed" after the given number of days.
  263. func (s *Storage) ArchiveEntries(status string, days, limit int) (int64, error) {
  264. if days < 0 || limit <= 0 {
  265. return 0, nil
  266. }
  267. query := `
  268. UPDATE
  269. entries
  270. SET
  271. status='removed'
  272. WHERE
  273. 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)
  274. `
  275. result, err := s.db.Exec(fmt.Sprintf(query, days, limit), status)
  276. if err != nil {
  277. return 0, fmt.Errorf(`store: unable to archive %s entries: %v`, status, err)
  278. }
  279. count, err := result.RowsAffected()
  280. if err != nil {
  281. return 0, fmt.Errorf(`store: unable to get the number of rows affected: %v`, err)
  282. }
  283. return count, nil
  284. }
  285. // SetEntriesStatus update the status of the given list of entries.
  286. func (s *Storage) SetEntriesStatus(userID int64, entryIDs []int64, status string) error {
  287. query := `UPDATE entries SET status=$1, changed_at=now() WHERE user_id=$2 AND id=ANY($3)`
  288. result, err := s.db.Exec(query, status, userID, pq.Array(entryIDs))
  289. if err != nil {
  290. return fmt.Errorf(`store: unable to update entries statuses %v: %v`, entryIDs, err)
  291. }
  292. count, err := result.RowsAffected()
  293. if err != nil {
  294. return fmt.Errorf(`store: unable to update these entries %v: %v`, entryIDs, err)
  295. }
  296. if count == 0 {
  297. return errors.New(`store: nothing has been updated`)
  298. }
  299. return nil
  300. }
  301. func (s *Storage) SetEntriesStatusCount(userID int64, entryIDs []int64, status string) (int, error) {
  302. if err := s.SetEntriesStatus(userID, entryIDs, status); err != nil {
  303. return 0, err
  304. }
  305. query := `
  306. SELECT count(*)
  307. FROM entries e
  308. JOIN feeds f ON (f.id = e.feed_id)
  309. JOIN categories c ON (c.id = f.category_id)
  310. WHERE e.user_id = $1
  311. AND e.id = ANY($2)
  312. AND NOT f.hide_globally
  313. AND NOT c.hide_globally
  314. `
  315. row := s.db.QueryRow(query, userID, pq.Array(entryIDs))
  316. visible := 0
  317. if err := row.Scan(&visible); err != nil {
  318. return 0, fmt.Errorf(`store: unable to query entries visibility %v: %v`, entryIDs, err)
  319. }
  320. return visible, nil
  321. }
  322. // SetEntriesBookmarked update the bookmarked state for the given list of entries.
  323. func (s *Storage) SetEntriesBookmarkedState(userID int64, entryIDs []int64, starred bool) error {
  324. query := `UPDATE entries SET starred=$1, changed_at=now() WHERE user_id=$2 AND id=ANY($3)`
  325. result, err := s.db.Exec(query, starred, userID, pq.Array(entryIDs))
  326. if err != nil {
  327. return fmt.Errorf(`store: unable to update the bookmarked state %v: %v`, entryIDs, err)
  328. }
  329. count, err := result.RowsAffected()
  330. if err != nil {
  331. return fmt.Errorf(`store: unable to update these entries %v: %v`, entryIDs, err)
  332. }
  333. if count == 0 {
  334. return errors.New(`store: nothing has been updated`)
  335. }
  336. return nil
  337. }
  338. // ToggleBookmark toggles entry bookmark value.
  339. func (s *Storage) ToggleBookmark(userID int64, entryID int64) error {
  340. query := `UPDATE entries SET starred = NOT starred, changed_at=now() WHERE user_id=$1 AND id=$2`
  341. result, err := s.db.Exec(query, userID, entryID)
  342. if err != nil {
  343. return fmt.Errorf(`store: unable to toggle bookmark flag for entry #%d: %v`, entryID, err)
  344. }
  345. count, err := result.RowsAffected()
  346. if err != nil {
  347. return fmt.Errorf(`store: unable to toggle bookmark flag for entry #%d: %v`, entryID, err)
  348. }
  349. if count == 0 {
  350. return errors.New(`store: nothing has been updated`)
  351. }
  352. return nil
  353. }
  354. // FlushHistory set all entries with the status "read" to "removed".
  355. func (s *Storage) FlushHistory(userID int64) error {
  356. query := `
  357. UPDATE
  358. entries
  359. SET
  360. status=$1,
  361. changed_at=now()
  362. WHERE
  363. user_id=$2 AND status=$3 AND starred is false AND share_code=''
  364. `
  365. _, err := s.db.Exec(query, model.EntryStatusRemoved, userID, model.EntryStatusRead)
  366. if err != nil {
  367. return fmt.Errorf(`store: unable to flush history: %v`, err)
  368. }
  369. return nil
  370. }
  371. // MarkAllAsRead updates all user entries to the read status.
  372. func (s *Storage) MarkAllAsRead(userID int64) error {
  373. query := `UPDATE entries SET status=$1, changed_at=now() WHERE user_id=$2 AND status=$3`
  374. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread)
  375. if err != nil {
  376. return fmt.Errorf(`store: unable to mark all entries as read: %v`, err)
  377. }
  378. count, _ := result.RowsAffected()
  379. logger.Debug("[Storage:MarkAllAsRead] %d items marked as read", count)
  380. return nil
  381. }
  382. // MarkFeedAsRead updates all feed entries to the read status.
  383. func (s *Storage) MarkFeedAsRead(userID, feedID int64, before time.Time) error {
  384. query := `
  385. UPDATE
  386. entries
  387. SET
  388. status=$1,
  389. changed_at=now()
  390. WHERE
  391. user_id=$2 AND feed_id=$3 AND status=$4 AND published_at < $5
  392. `
  393. result, err := s.db.Exec(query, model.EntryStatusRead, userID, feedID, model.EntryStatusUnread, before)
  394. if err != nil {
  395. return fmt.Errorf(`store: unable to mark feed entries as read: %v`, err)
  396. }
  397. count, _ := result.RowsAffected()
  398. logger.Debug("[Storage:MarkFeedAsRead] %d items marked as read", count)
  399. return nil
  400. }
  401. // MarkCategoryAsRead updates all category entries to the read status.
  402. func (s *Storage) MarkCategoryAsRead(userID, categoryID int64, before time.Time) error {
  403. query := `
  404. UPDATE
  405. entries
  406. SET
  407. status=$1,
  408. changed_at=now()
  409. WHERE
  410. user_id=$2
  411. AND
  412. status=$3
  413. AND
  414. published_at < $4
  415. AND
  416. feed_id IN (SELECT id FROM feeds WHERE user_id=$2 AND category_id=$5)
  417. `
  418. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread, before, categoryID)
  419. if err != nil {
  420. return fmt.Errorf(`store: unable to mark category entries as read: %v`, err)
  421. }
  422. count, _ := result.RowsAffected()
  423. logger.Debug("[Storage:MarkCategoryAsRead] %d items marked as read", count)
  424. return nil
  425. }
  426. // EntryURLExists returns true if an entry with this URL already exists.
  427. func (s *Storage) EntryURLExists(feedID int64, entryURL string) bool {
  428. var result bool
  429. query := `SELECT true FROM entries WHERE feed_id=$1 AND url=$2`
  430. s.db.QueryRow(query, feedID, entryURL).Scan(&result)
  431. return result
  432. }
  433. // EntryShareCode returns the share code of the provided entry.
  434. // It generates a new one if not already defined.
  435. func (s *Storage) EntryShareCode(userID int64, entryID int64) (shareCode string, err error) {
  436. query := `SELECT share_code FROM entries WHERE user_id=$1 AND id=$2`
  437. err = s.db.QueryRow(query, userID, entryID).Scan(&shareCode)
  438. if err != nil {
  439. err = fmt.Errorf(`store: unable to get share code for entry #%d: %v`, entryID, err)
  440. return
  441. }
  442. if shareCode == "" {
  443. shareCode = crypto.GenerateRandomStringHex(20)
  444. query = `UPDATE entries SET share_code = $1 WHERE user_id=$2 AND id=$3`
  445. _, err = s.db.Exec(query, shareCode, userID, entryID)
  446. if err != nil {
  447. err = fmt.Errorf(`store: unable to set share code for entry #%d: %v`, entryID, err)
  448. return
  449. }
  450. }
  451. return
  452. }
  453. // UnshareEntry removes the share code for the given entry.
  454. func (s *Storage) UnshareEntry(userID int64, entryID int64) (err error) {
  455. query := `UPDATE entries SET share_code='' WHERE user_id=$1 AND id=$2`
  456. _, err = s.db.Exec(query, userID, entryID)
  457. if err != nil {
  458. err = fmt.Errorf(`store: unable to remove share code for entry #%d: %v`, entryID, err)
  459. }
  460. return
  461. }