entry.go 11 KB

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