entry.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. query := `
  188. UPDATE
  189. entries
  190. SET
  191. status='removed'
  192. WHERE
  193. id=ANY(SELECT id FROM entries WHERE status='read' AND starred is false AND published_at < now () - '%d days'::interval LIMIT 5000)
  194. `
  195. if _, err := s.db.Exec(fmt.Sprintf(query, days)); err != nil {
  196. return fmt.Errorf(`store: unable to archive read entries: %v`, err)
  197. }
  198. return nil
  199. }
  200. // SetEntriesStatus update the status of the given list of entries.
  201. func (s *Storage) SetEntriesStatus(userID int64, entryIDs []int64, status string) error {
  202. query := `UPDATE entries SET status=$1, changed_at=now() WHERE user_id=$2 AND id=ANY($3)`
  203. result, err := s.db.Exec(query, status, userID, pq.Array(entryIDs))
  204. if err != nil {
  205. return fmt.Errorf(`store: unable to update entries statuses %v: %v`, entryIDs, err)
  206. }
  207. count, err := result.RowsAffected()
  208. if err != nil {
  209. return fmt.Errorf(`store: unable to update these entries %v: %v`, entryIDs, err)
  210. }
  211. if count == 0 {
  212. return errors.New(`store: nothing has been updated`)
  213. }
  214. return nil
  215. }
  216. // ToggleBookmark toggles entry bookmark value.
  217. func (s *Storage) ToggleBookmark(userID int64, entryID int64) error {
  218. query := `UPDATE entries SET starred = NOT starred, changed_at=now() WHERE user_id=$1 AND id=$2`
  219. result, err := s.db.Exec(query, userID, entryID)
  220. if err != nil {
  221. return fmt.Errorf(`store: unable to toggle bookmark flag for entry #%d: %v`, entryID, err)
  222. }
  223. count, err := result.RowsAffected()
  224. if err != nil {
  225. return fmt.Errorf(`store: unable to toggle bookmark flag for entry #%d: %v`, entryID, err)
  226. }
  227. if count == 0 {
  228. return errors.New(`store: nothing has been updated`)
  229. }
  230. return nil
  231. }
  232. // FlushHistory set all entries with the status "read" to "removed".
  233. func (s *Storage) FlushHistory(userID int64) error {
  234. query := `
  235. UPDATE
  236. entries
  237. SET
  238. status=$1,
  239. changed_at=now()
  240. WHERE
  241. user_id=$2 AND status=$3 AND starred='f' AND share_code=''
  242. `
  243. _, err := s.db.Exec(query, model.EntryStatusRemoved, userID, model.EntryStatusRead)
  244. if err != nil {
  245. return fmt.Errorf(`store: unable to flush history: %v`, err)
  246. }
  247. return nil
  248. }
  249. // MarkAllAsRead updates all user entries to the read status.
  250. func (s *Storage) MarkAllAsRead(userID int64) error {
  251. query := `UPDATE entries SET status=$1, changed_at=now() WHERE user_id=$2 AND status=$3`
  252. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread)
  253. if err != nil {
  254. return fmt.Errorf(`store: unable to mark all entries as read: %v`, err)
  255. }
  256. count, _ := result.RowsAffected()
  257. logger.Debug("[Storage:MarkAllAsRead] %d items marked as read", count)
  258. return nil
  259. }
  260. // MarkFeedAsRead updates all feed entries to the read status.
  261. func (s *Storage) MarkFeedAsRead(userID, feedID int64, before time.Time) error {
  262. query := `
  263. UPDATE
  264. entries
  265. SET
  266. status=$1,
  267. changed_at=now()
  268. WHERE
  269. user_id=$2 AND feed_id=$3 AND status=$4 AND published_at < $5
  270. `
  271. result, err := s.db.Exec(query, model.EntryStatusRead, userID, feedID, model.EntryStatusUnread, before)
  272. if err != nil {
  273. return fmt.Errorf(`store: unable to mark feed entries as read: %v`, err)
  274. }
  275. count, _ := result.RowsAffected()
  276. logger.Debug("[Storage:MarkFeedAsRead] %d items marked as read", count)
  277. return nil
  278. }
  279. // MarkCategoryAsRead updates all category entries to the read status.
  280. func (s *Storage) MarkCategoryAsRead(userID, categoryID int64, before time.Time) error {
  281. query := `
  282. UPDATE
  283. entries
  284. SET
  285. status=$1,
  286. changed_at=now()
  287. WHERE
  288. user_id=$2
  289. AND
  290. status=$3
  291. AND
  292. published_at < $4
  293. AND
  294. feed_id IN (SELECT id FROM feeds WHERE user_id=$2 AND category_id=$5)
  295. `
  296. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread, before, categoryID)
  297. if err != nil {
  298. return fmt.Errorf(`store: unable to mark category entries as read: %v`, err)
  299. }
  300. count, _ := result.RowsAffected()
  301. logger.Debug("[Storage:MarkCategoryAsRead] %d items marked as read", count)
  302. return nil
  303. }
  304. // EntryURLExists returns true if an entry with this URL already exists.
  305. func (s *Storage) EntryURLExists(feedID int64, entryURL string) bool {
  306. var result bool
  307. query := `SELECT true FROM entries WHERE feed_id=$1 AND url=$2`
  308. s.db.QueryRow(query, feedID, entryURL).Scan(&result)
  309. return result
  310. }
  311. // EntryShareCode returns the share code of the provided entry.
  312. // It generates a new one if not already defined.
  313. func (s *Storage) EntryShareCode(userID int64, entryID int64) (shareCode string, err error) {
  314. query := `SELECT share_code FROM entries WHERE user_id=$1 AND id=$2`
  315. err = s.db.QueryRow(query, userID, entryID).Scan(&shareCode)
  316. if err != nil {
  317. err = fmt.Errorf(`store: unable to get share code for entry #%d: %v`, entryID, err)
  318. return
  319. }
  320. if shareCode == "" {
  321. shareCode = crypto.GenerateRandomStringHex(20)
  322. query = `UPDATE entries SET share_code = $1 WHERE user_id=$2 AND id=$3`
  323. _, err = s.db.Exec(query, shareCode, userID, entryID)
  324. if err != nil {
  325. err = fmt.Errorf(`store: unable to set share code for entry #%d: %v`, entryID, err)
  326. return
  327. }
  328. }
  329. return
  330. }
  331. // UnshareEntry removes the share code for the given entry.
  332. func (s *Storage) UnshareEntry(userID int64, entryID int64) (err error) {
  333. query := `UPDATE entries SET share_code='' WHERE user_id=$1 AND id=$2`
  334. _, err = s.db.Exec(query, userID, entryID)
  335. if err != nil {
  336. err = fmt.Errorf(`store: unable to remove share code for entry #%d: %v`, entryID, err)
  337. }
  338. return
  339. }