entry.go 12 KB

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