entry.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. "errors"
  7. "fmt"
  8. "time"
  9. "miniflux.app/logger"
  10. "miniflux.app/model"
  11. "github.com/lib/pq"
  12. )
  13. // CountUnreadEntries returns the number of unread entries.
  14. func (s *Storage) CountUnreadEntries(userID int64) int {
  15. builder := s.NewEntryQueryBuilder(userID)
  16. builder.WithStatus(model.EntryStatusUnread)
  17. n, err := builder.CountEntries()
  18. if err != nil {
  19. logger.Error("unable to count unread entries for user #%d: %v", userID, err)
  20. return 0
  21. }
  22. return n
  23. }
  24. // NewEntryQueryBuilder returns a new EntryQueryBuilder
  25. func (s *Storage) NewEntryQueryBuilder(userID int64) *EntryQueryBuilder {
  26. return NewEntryQueryBuilder(s, userID)
  27. }
  28. // UpdateEntryContent updates entry content.
  29. func (s *Storage) UpdateEntryContent(entry *model.Entry) error {
  30. tx, err := s.db.Begin()
  31. if err != nil {
  32. return err
  33. }
  34. _, err = tx.Exec(`UPDATE entries SET content=$1 WHERE id=$2 AND user_id=$3`, entry.Content, entry.ID, entry.UserID)
  35. if err != nil {
  36. tx.Rollback()
  37. return fmt.Errorf(`unable to update content of entry #%d: %v`, entry.ID, err)
  38. }
  39. query := `
  40. UPDATE entries
  41. SET document_vectors = setweight(to_tsvector(substring(coalesce(title, '') for 1000000)), 'A') || setweight(to_tsvector(substring(coalesce(content, '') for 1000000)), 'B')
  42. WHERE id=$1 AND user_id=$2
  43. `
  44. _, err = tx.Exec(query, entry.ID, entry.UserID)
  45. if err != nil {
  46. tx.Rollback()
  47. return fmt.Errorf(`unable to update content of entry #%d: %v`, entry.ID, err)
  48. }
  49. return tx.Commit()
  50. }
  51. // createEntry add a new entry.
  52. func (s *Storage) createEntry(entry *model.Entry) error {
  53. query := `
  54. INSERT INTO entries
  55. (title, hash, url, comments_url, published_at, content, author, user_id, feed_id, document_vectors)
  56. VALUES
  57. ($1, $2, $3, $4, $5, $6, $7, $8, $9, setweight(to_tsvector(substring(coalesce($1, '') for 1000000)), 'A') || setweight(to_tsvector(substring(coalesce($6, '') for 1000000)), 'B'))
  58. RETURNING id, status
  59. `
  60. err := s.db.QueryRow(
  61. query,
  62. entry.Title,
  63. entry.Hash,
  64. entry.URL,
  65. entry.CommentsURL,
  66. entry.Date,
  67. entry.Content,
  68. entry.Author,
  69. entry.UserID,
  70. entry.FeedID,
  71. ).Scan(&entry.ID, &entry.Status)
  72. if err != nil {
  73. return fmt.Errorf("unable to create entry %q (feed #%d): %v", entry.URL, entry.FeedID, err)
  74. }
  75. for i := 0; i < len(entry.Enclosures); i++ {
  76. entry.Enclosures[i].EntryID = entry.ID
  77. entry.Enclosures[i].UserID = entry.UserID
  78. err := s.CreateEnclosure(entry.Enclosures[i])
  79. if err != nil {
  80. return err
  81. }
  82. }
  83. return nil
  84. }
  85. // updateEntry updates an entry when a feed is refreshed.
  86. // Note: we do not update the published date because some feeds do not contains any date,
  87. // it default to time.Now() which could change the order of items on the history page.
  88. func (s *Storage) updateEntry(entry *model.Entry) error {
  89. query := `
  90. UPDATE entries SET
  91. title=$1, url=$2, comments_url=$3, content=$4, author=$5,
  92. document_vectors = setweight(to_tsvector(substring(coalesce($1, '') for 1000000)), 'A') || setweight(to_tsvector(substring(coalesce($4, '') for 1000000)), 'B')
  93. WHERE user_id=$6 AND feed_id=$7 AND hash=$8
  94. RETURNING id
  95. `
  96. err := s.db.QueryRow(
  97. query,
  98. entry.Title,
  99. entry.URL,
  100. entry.CommentsURL,
  101. entry.Content,
  102. entry.Author,
  103. entry.UserID,
  104. entry.FeedID,
  105. entry.Hash,
  106. ).Scan(&entry.ID)
  107. if err != nil {
  108. return fmt.Errorf(`unable to update entry %q: %v`, entry.URL, err)
  109. }
  110. for _, enclosure := range entry.Enclosures {
  111. enclosure.UserID = entry.UserID
  112. enclosure.EntryID = entry.ID
  113. }
  114. return s.UpdateEnclosures(entry.Enclosures)
  115. }
  116. // entryExists checks if an entry already exists based on its hash when refreshing a feed.
  117. func (s *Storage) entryExists(entry *model.Entry) bool {
  118. var result int
  119. query := `SELECT count(*) as c FROM entries WHERE user_id=$1 AND feed_id=$2 AND hash=$3`
  120. s.db.QueryRow(query, entry.UserID, entry.FeedID, entry.Hash).Scan(&result)
  121. return result >= 1
  122. }
  123. // cleanupEntries deletes from the database entries marked as "removed" and not visible anymore in the feed.
  124. func (s *Storage) cleanupEntries(feedID int64, entryHashes []string) error {
  125. query := `
  126. DELETE FROM entries
  127. WHERE feed_id=$1 AND
  128. id IN (SELECT id FROM entries WHERE feed_id=$2 AND status=$3 AND NOT (hash=ANY($4)))
  129. `
  130. if _, err := s.db.Exec(query, feedID, feedID, model.EntryStatusRemoved, pq.Array(entryHashes)); err != nil {
  131. return fmt.Errorf("unable to cleanup entries: %v", err)
  132. }
  133. return nil
  134. }
  135. // UpdateEntries updates a list of entries while refreshing a feed.
  136. func (s *Storage) UpdateEntries(userID, feedID int64, entries model.Entries, updateExistingEntries bool) (err error) {
  137. var entryHashes []string
  138. for _, entry := range entries {
  139. entry.UserID = userID
  140. entry.FeedID = feedID
  141. if s.entryExists(entry) {
  142. if updateExistingEntries {
  143. err = s.updateEntry(entry)
  144. }
  145. } else {
  146. err = s.createEntry(entry)
  147. }
  148. if err != nil {
  149. return err
  150. }
  151. entryHashes = append(entryHashes, entry.Hash)
  152. }
  153. if err := s.cleanupEntries(feedID, entryHashes); err != nil {
  154. logger.Error("[Storage:CleanupEntries] feed #%d: %v", feedID, err)
  155. }
  156. return nil
  157. }
  158. // ArchiveEntries changes the status of read items to "removed" after specified days.
  159. func (s *Storage) ArchiveEntries(days int) error {
  160. if days < 0 {
  161. return nil
  162. }
  163. query := fmt.Sprintf(`
  164. UPDATE entries SET status='removed'
  165. WHERE id=ANY(SELECT id FROM entries WHERE status='read' AND starred is false AND published_at < now () - '%d days'::interval LIMIT 5000)
  166. `, days)
  167. if _, err := s.db.Exec(query); err != nil {
  168. return fmt.Errorf("unable to archive read entries: %v", err)
  169. }
  170. return nil
  171. }
  172. // SetEntriesStatus update the status of the given list of entries.
  173. func (s *Storage) SetEntriesStatus(userID int64, entryIDs []int64, status string) error {
  174. query := `UPDATE entries SET status=$1 WHERE user_id=$2 AND id=ANY($3)`
  175. result, err := s.db.Exec(query, status, userID, pq.Array(entryIDs))
  176. if err != nil {
  177. return fmt.Errorf("unable to update entries statuses %v: %v", entryIDs, err)
  178. }
  179. count, err := result.RowsAffected()
  180. if err != nil {
  181. return fmt.Errorf("unable to update these entries %v: %v", entryIDs, err)
  182. }
  183. if count == 0 {
  184. return errors.New("nothing has been updated")
  185. }
  186. return nil
  187. }
  188. // ToggleBookmark toggles entry bookmark value.
  189. func (s *Storage) ToggleBookmark(userID int64, entryID int64) error {
  190. query := `UPDATE entries SET starred = NOT starred WHERE user_id=$1 AND id=$2`
  191. result, err := s.db.Exec(query, userID, entryID)
  192. if err != nil {
  193. return fmt.Errorf("unable to toggle bookmark flag for entry #%d: %v", entryID, err)
  194. }
  195. count, err := result.RowsAffected()
  196. if err != nil {
  197. return fmt.Errorf("unable to toogle bookmark flag for entry #%d: %v", entryID, err)
  198. }
  199. if count == 0 {
  200. return errors.New("nothing has been updated")
  201. }
  202. return nil
  203. }
  204. // FlushHistory set all entries with the status "read" to "removed".
  205. func (s *Storage) FlushHistory(userID int64) error {
  206. query := `UPDATE entries SET status=$1 WHERE user_id=$2 AND status=$3 AND starred='f'`
  207. _, err := s.db.Exec(query, model.EntryStatusRemoved, userID, model.EntryStatusRead)
  208. if err != nil {
  209. return fmt.Errorf("unable to flush history: %v", err)
  210. }
  211. return nil
  212. }
  213. // MarkAllAsRead updates all user entries to the read status.
  214. func (s *Storage) MarkAllAsRead(userID int64) error {
  215. query := `UPDATE entries SET status=$1 WHERE user_id=$2 AND status=$3`
  216. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread)
  217. if err != nil {
  218. return fmt.Errorf("unable to mark all entries as read: %v", err)
  219. }
  220. count, _ := result.RowsAffected()
  221. logger.Debug("[Storage:MarkAllAsRead] %d items marked as read", count)
  222. return nil
  223. }
  224. // MarkFeedAsRead updates all feed entries to the read status.
  225. func (s *Storage) MarkFeedAsRead(userID, feedID int64, before time.Time) error {
  226. query := `
  227. UPDATE entries
  228. SET status=$1
  229. WHERE user_id=$2 AND feed_id=$3 AND status=$4 AND published_at < $5
  230. `
  231. result, err := s.db.Exec(query, model.EntryStatusRead, userID, feedID, model.EntryStatusUnread, before)
  232. if err != nil {
  233. return fmt.Errorf("unable to mark feed entries as read: %v", err)
  234. }
  235. count, _ := result.RowsAffected()
  236. logger.Debug("[Storage:MarkFeedAsRead] %d items marked as read", count)
  237. return nil
  238. }
  239. // MarkCategoryAsRead updates all category entries to the read status.
  240. func (s *Storage) MarkCategoryAsRead(userID, categoryID int64, before time.Time) error {
  241. query := `
  242. UPDATE entries
  243. SET status=$1
  244. WHERE
  245. user_id=$2 AND status=$3 AND published_at < $4 AND feed_id IN (SELECT id FROM feeds WHERE user_id=$2 AND category_id=$5)
  246. `
  247. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread, before, categoryID)
  248. if err != nil {
  249. return fmt.Errorf("unable to mark category entries as read: %v", err)
  250. }
  251. count, _ := result.RowsAffected()
  252. logger.Debug("[Storage:MarkCategoryAsRead] %d items marked as read", count)
  253. return nil
  254. }
  255. // EntryURLExists returns true if an entry with this URL already exists.
  256. func (s *Storage) EntryURLExists(feedID int64, entryURL string) bool {
  257. var result int
  258. query := `SELECT count(*) as c FROM entries WHERE feed_id=$1 AND url=$2`
  259. s.db.QueryRow(query, feedID, entryURL).Scan(&result)
  260. return result >= 1
  261. }