entry.go 12 KB

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