entry.go 9.4 KB

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