entry.go 13 KB

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