entry.go 7.2 KB

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