entry.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package storage // import "miniflux.app/v2/internal/storage"
  4. import (
  5. "database/sql"
  6. "errors"
  7. "fmt"
  8. "log/slog"
  9. "time"
  10. "miniflux.app/v2/internal/crypto"
  11. "miniflux.app/v2/internal/model"
  12. "github.com/lib/pq"
  13. )
  14. // CountAllEntries returns the number of entries for each status in the database.
  15. func (s *Storage) CountAllEntries() (map[string]int64, error) {
  16. rows, err := s.db.Query(`SELECT status, count(*) FROM entries GROUP BY status`)
  17. if err != nil {
  18. return nil, fmt.Errorf("storage: unable to count entries: %w", err)
  19. }
  20. defer rows.Close()
  21. results := make(map[string]int64)
  22. results[model.EntryStatusUnread] = 0
  23. results[model.EntryStatusRead] = 0
  24. results[model.EntryStatusRemoved] = 0
  25. for rows.Next() {
  26. var status string
  27. var count int64
  28. if err := rows.Scan(&status, &count); err != nil {
  29. continue
  30. }
  31. results[status] = count
  32. }
  33. results["total"] = results[model.EntryStatusUnread] + results[model.EntryStatusRead] + results[model.EntryStatusRemoved]
  34. return results, nil
  35. }
  36. // CountUnreadEntries returns the number of unread entries.
  37. func (s *Storage) CountUnreadEntries(userID int64) int {
  38. builder := s.NewEntryQueryBuilder(userID)
  39. builder.WithStatus(model.EntryStatusUnread)
  40. builder.WithGloballyVisible()
  41. n, err := builder.CountEntries()
  42. if err != nil {
  43. slog.Error("Unable to count unread entries",
  44. slog.Int64("user_id", userID),
  45. slog.Any("error", err),
  46. )
  47. return 0
  48. }
  49. return n
  50. }
  51. // NewEntryQueryBuilder returns a new EntryQueryBuilder
  52. func (s *Storage) NewEntryQueryBuilder(userID int64) *EntryQueryBuilder {
  53. return NewEntryQueryBuilder(s, userID)
  54. }
  55. // UpdateEntryTitleAndContent updates entry title and content.
  56. func (s *Storage) UpdateEntryTitleAndContent(entry *model.Entry) error {
  57. truncatedTitle, truncatedContent := truncateTitleAndContentForTSVectorField(entry.Title, entry.Content)
  58. query := `
  59. UPDATE
  60. entries
  61. SET
  62. title=$1,
  63. content=$2,
  64. reading_time=$3,
  65. document_vectors = setweight(to_tsvector($4), 'A') || setweight(to_tsvector($5), 'B')
  66. WHERE
  67. id=$6 AND user_id=$7
  68. `
  69. if _, err := s.db.Exec(
  70. query,
  71. entry.Title,
  72. entry.Content,
  73. entry.ReadingTime,
  74. truncatedTitle,
  75. truncatedContent,
  76. entry.ID,
  77. entry.UserID); err != nil {
  78. return fmt.Errorf(`store: unable to update entry #%d: %v`, entry.ID, err)
  79. }
  80. return nil
  81. }
  82. // createEntry add a new entry.
  83. func (s *Storage) createEntry(tx *sql.Tx, entry *model.Entry) error {
  84. truncatedTitle, truncatedContent := truncateTitleAndContentForTSVectorField(entry.Title, entry.Content)
  85. query := `
  86. INSERT INTO entries
  87. (
  88. title,
  89. hash,
  90. url,
  91. comments_url,
  92. published_at,
  93. content,
  94. author,
  95. user_id,
  96. feed_id,
  97. reading_time,
  98. changed_at,
  99. document_vectors,
  100. tags
  101. )
  102. VALUES
  103. (
  104. $1,
  105. $2,
  106. $3,
  107. $4,
  108. $5,
  109. $6,
  110. $7,
  111. $8,
  112. $9,
  113. $10,
  114. now(),
  115. setweight(to_tsvector($11), 'A') || setweight(to_tsvector($12), 'B'),
  116. $13
  117. )
  118. RETURNING
  119. id, status, created_at, changed_at
  120. `
  121. err := tx.QueryRow(
  122. query,
  123. entry.Title,
  124. entry.Hash,
  125. entry.URL,
  126. entry.CommentsURL,
  127. entry.Date,
  128. entry.Content,
  129. entry.Author,
  130. entry.UserID,
  131. entry.FeedID,
  132. entry.ReadingTime,
  133. truncatedTitle,
  134. truncatedContent,
  135. pq.Array(entry.Tags),
  136. ).Scan(
  137. &entry.ID,
  138. &entry.Status,
  139. &entry.CreatedAt,
  140. &entry.ChangedAt,
  141. )
  142. if err != nil {
  143. return fmt.Errorf(`store: unable to create entry %q (feed #%d): %v`, entry.URL, entry.FeedID, err)
  144. }
  145. for _, enclosure := range entry.Enclosures {
  146. enclosure.EntryID = entry.ID
  147. enclosure.UserID = entry.UserID
  148. err := s.createEnclosure(tx, enclosure)
  149. if err != nil {
  150. return err
  151. }
  152. }
  153. return nil
  154. }
  155. // updateEntry updates an entry when a feed is refreshed.
  156. // Note: we do not update the published date because some feeds do not contains any date,
  157. // it default to time.Now() which could change the order of items on the history page.
  158. func (s *Storage) updateEntry(tx *sql.Tx, entry *model.Entry) error {
  159. truncatedTitle, truncatedContent := truncateTitleAndContentForTSVectorField(entry.Title, entry.Content)
  160. query := `
  161. UPDATE
  162. entries
  163. SET
  164. title=$1,
  165. url=$2,
  166. comments_url=$3,
  167. content=$4,
  168. author=$5,
  169. reading_time=$6,
  170. document_vectors = setweight(to_tsvector($7), 'A') || setweight(to_tsvector($8), 'B'),
  171. tags=$12
  172. WHERE
  173. user_id=$9 AND feed_id=$10 AND hash=$11
  174. RETURNING
  175. id
  176. `
  177. err := tx.QueryRow(
  178. query,
  179. entry.Title,
  180. entry.URL,
  181. entry.CommentsURL,
  182. entry.Content,
  183. entry.Author,
  184. entry.ReadingTime,
  185. truncatedTitle,
  186. truncatedContent,
  187. entry.UserID,
  188. entry.FeedID,
  189. entry.Hash,
  190. pq.Array(entry.Tags),
  191. ).Scan(&entry.ID)
  192. if err != nil {
  193. return fmt.Errorf(`store: unable to update entry %q: %v`, entry.URL, err)
  194. }
  195. for _, enclosure := range entry.Enclosures {
  196. enclosure.UserID = entry.UserID
  197. enclosure.EntryID = entry.ID
  198. }
  199. return s.updateEnclosures(tx, entry)
  200. }
  201. // entryExists checks if an entry already exists based on its hash when refreshing a feed.
  202. func (s *Storage) entryExists(tx *sql.Tx, entry *model.Entry) (bool, error) {
  203. var result bool
  204. // Note: This query uses entries_feed_id_hash_key index (filtering on user_id is not necessary).
  205. err := tx.QueryRow(`SELECT true FROM entries WHERE feed_id=$1 AND hash=$2 LIMIT 1`, entry.FeedID, entry.Hash).Scan(&result)
  206. if err != nil && err != sql.ErrNoRows {
  207. return result, fmt.Errorf(`store: unable to check if entry exists: %v`, err)
  208. }
  209. return result, nil
  210. }
  211. func (s *Storage) getEntryIDByHash(tx *sql.Tx, feedID int64, entryHash string) (int64, error) {
  212. var entryID int64
  213. err := tx.QueryRow(
  214. `SELECT id FROM entries WHERE feed_id=$1 AND hash=$2 LIMIT 1`,
  215. feedID,
  216. entryHash,
  217. ).Scan(&entryID)
  218. if err != nil {
  219. return 0, fmt.Errorf(`store: unable to fetch entry ID: %v`, err)
  220. }
  221. return entryID, nil
  222. }
  223. // InsertEntryForFeed inserts a single entry into a feed, optionally updating if it already exists.
  224. // Returns true if a new entry was created, false if an existing one was reused.
  225. func (s *Storage) InsertEntryForFeed(userID, feedID int64, entry *model.Entry) (bool, error) {
  226. entry.UserID = userID
  227. entry.FeedID = feedID
  228. tx, err := s.db.Begin()
  229. if err != nil {
  230. return false, fmt.Errorf("store: unable to start transaction: %v", err)
  231. }
  232. defer tx.Rollback()
  233. exists, err := s.entryExists(tx, entry)
  234. if err != nil {
  235. return false, err
  236. }
  237. if exists {
  238. entryID, err := s.getEntryIDByHash(tx, entry.FeedID, entry.Hash)
  239. if err != nil {
  240. return false, err
  241. }
  242. entry.ID = entryID
  243. } else {
  244. if err := s.createEntry(tx, entry); err != nil {
  245. return false, err
  246. }
  247. }
  248. if err := tx.Commit(); err != nil {
  249. return false, err
  250. }
  251. return !exists, nil
  252. }
  253. func (s *Storage) IsNewEntry(feedID int64, entryHash string) bool {
  254. var result bool
  255. s.db.QueryRow(`SELECT true FROM entries WHERE feed_id=$1 AND hash=$2 LIMIT 1`, feedID, entryHash).Scan(&result)
  256. return !result
  257. }
  258. func (s *Storage) GetReadTime(feedID int64, entryHash string) int {
  259. var result int
  260. // Note: This query uses entries_feed_id_hash_key index
  261. s.db.QueryRow(
  262. `SELECT
  263. reading_time
  264. FROM
  265. entries
  266. WHERE
  267. feed_id=$1 AND
  268. hash=$2
  269. `,
  270. feedID,
  271. entryHash,
  272. ).Scan(&result)
  273. return result
  274. }
  275. // cleanupRemovedEntriesNotInFeed deletes from the database entries marked as "removed" and not visible anymore in the feed.
  276. func (s *Storage) cleanupRemovedEntriesNotInFeed(feedID int64, entryHashes []string) error {
  277. // Acquire locks in id order and skip already-locked rows to avoid deadlocks with
  278. // ClearRemovedEntriesContent, which also updates removed entries concurrently.
  279. query := `
  280. WITH to_delete AS (
  281. SELECT id
  282. FROM entries
  283. WHERE
  284. feed_id=$1 AND
  285. status=$2 AND
  286. NOT (hash=ANY($3))
  287. ORDER BY id
  288. FOR UPDATE SKIP LOCKED
  289. )
  290. DELETE FROM entries
  291. USING to_delete
  292. WHERE entries.id = to_delete.id
  293. `
  294. if _, err := s.db.Exec(query, feedID, model.EntryStatusRemoved, pq.Array(entryHashes)); err != nil {
  295. return fmt.Errorf(`store: unable to remove entries not in feed: %v`, err)
  296. }
  297. return nil
  298. }
  299. // ClearRemovedEntriesContent clears the content fields of entries marked as "removed", keeping only their metadata.
  300. func (s *Storage) ClearRemovedEntriesContent(limit int) (int64, error) {
  301. // Skip locked rows so this batch scrubber doesn't block or deadlock with the
  302. // concurrent cleanup that deletes removed entries in the same table.
  303. query := `
  304. UPDATE
  305. entries
  306. SET
  307. title='',
  308. content=NULL,
  309. url='',
  310. author=NULL,
  311. comments_url=NULL,
  312. document_vectors=NULL
  313. WHERE id IN (
  314. SELECT id
  315. FROM entries
  316. WHERE status = $1 AND content IS NOT NULL
  317. ORDER BY id ASC
  318. FOR UPDATE SKIP LOCKED
  319. LIMIT $2
  320. )
  321. `
  322. result, err := s.db.Exec(query, model.EntryStatusRemoved, limit)
  323. if err != nil {
  324. return 0, fmt.Errorf(`store: unable to clear content from removed entries: %v`, err)
  325. }
  326. count, err := result.RowsAffected()
  327. if err != nil {
  328. return 0, fmt.Errorf(`store: unable to get the number of rows affected while clearing content from removed entries: %v`, err)
  329. }
  330. return count, nil
  331. }
  332. // RefreshFeedEntries updates feed entries while refreshing a feed.
  333. func (s *Storage) RefreshFeedEntries(userID, feedID int64, entries model.Entries, updateExistingEntries bool) (newEntries model.Entries, err error) {
  334. entryHashes := make([]string, 0, len(entries))
  335. for _, entry := range entries {
  336. entry.UserID = userID
  337. entry.FeedID = feedID
  338. tx, err := s.db.Begin()
  339. if err != nil {
  340. return nil, fmt.Errorf(`store: unable to start transaction: %v`, err)
  341. }
  342. entryExists, err := s.entryExists(tx, entry)
  343. if err != nil {
  344. if rollbackErr := tx.Rollback(); rollbackErr != nil {
  345. return nil, fmt.Errorf(`store: unable to rollback transaction: %v (rolled back due to: %v)`, rollbackErr, err)
  346. }
  347. return nil, err
  348. }
  349. if entryExists {
  350. if updateExistingEntries {
  351. err = s.updateEntry(tx, entry)
  352. }
  353. } else {
  354. err = s.createEntry(tx, entry)
  355. if err == nil {
  356. newEntries = append(newEntries, entry)
  357. }
  358. }
  359. if err != nil {
  360. if rollbackErr := tx.Rollback(); rollbackErr != nil {
  361. return nil, fmt.Errorf(`store: unable to rollback transaction: %v (rolled back due to: %v)`, rollbackErr, err)
  362. }
  363. return nil, err
  364. }
  365. if err := tx.Commit(); err != nil {
  366. return nil, fmt.Errorf(`store: unable to commit transaction: %v`, err)
  367. }
  368. entryHashes = append(entryHashes, entry.Hash)
  369. }
  370. go func() {
  371. if err := s.cleanupRemovedEntriesNotInFeed(feedID, entryHashes); err != nil {
  372. slog.Error("Unable to cleanup removed entries",
  373. slog.Int64("user_id", userID),
  374. slog.Int64("feed_id", feedID),
  375. slog.Any("error", err),
  376. )
  377. }
  378. }()
  379. return newEntries, nil
  380. }
  381. // ArchiveEntries changes the status of entries to "removed" after the interval (24h minimum).
  382. func (s *Storage) ArchiveEntries(status string, interval time.Duration, limit int) (int64, error) {
  383. if interval < 0 || limit <= 0 {
  384. return 0, nil
  385. }
  386. query := `
  387. UPDATE
  388. entries
  389. SET
  390. status=$1
  391. WHERE
  392. id IN (
  393. SELECT
  394. id
  395. FROM
  396. entries
  397. WHERE
  398. status=$2 AND
  399. starred is false AND
  400. share_code='' AND
  401. created_at < now () - $3::interval
  402. ORDER BY
  403. created_at ASC
  404. FOR UPDATE SKIP LOCKED
  405. LIMIT $4
  406. )
  407. `
  408. days := max(int(interval/(24*time.Hour)), 1)
  409. result, err := s.db.Exec(query, model.EntryStatusRemoved, status, fmt.Sprintf("%d days", days), limit)
  410. if err != nil {
  411. return 0, fmt.Errorf(`store: unable to archive %s entries: %v`, status, err)
  412. }
  413. count, err := result.RowsAffected()
  414. if err != nil {
  415. return 0, fmt.Errorf(`store: unable to get the number of rows affected: %v`, err)
  416. }
  417. return count, nil
  418. }
  419. // SetEntriesStatus update the status of the given list of entries.
  420. func (s *Storage) SetEntriesStatus(userID int64, entryIDs []int64, status string) error {
  421. // Entries that have the model.EntryStatusRemoved status are immutable.
  422. query := `
  423. UPDATE
  424. entries
  425. SET
  426. status=$1,
  427. changed_at=now()
  428. WHERE
  429. user_id=$2 AND
  430. id=ANY($3) AND
  431. status!=$4
  432. `
  433. if _, err := s.db.Exec(query, status, userID, pq.Array(entryIDs), model.EntryStatusRemoved); err != nil {
  434. return fmt.Errorf(`store: unable to update entries statuses %v: %v`, entryIDs, err)
  435. }
  436. return nil
  437. }
  438. func (s *Storage) SetEntriesStatusCount(userID int64, entryIDs []int64, status string) (int, error) {
  439. if err := s.SetEntriesStatus(userID, entryIDs, status); err != nil {
  440. return 0, err
  441. }
  442. query := `
  443. SELECT count(*)
  444. FROM entries e
  445. JOIN feeds f ON (f.id = e.feed_id)
  446. JOIN categories c ON (c.id = f.category_id)
  447. WHERE e.user_id = $1
  448. AND e.id = ANY($2)
  449. AND NOT f.hide_globally
  450. AND NOT c.hide_globally
  451. `
  452. row := s.db.QueryRow(query, userID, pq.Array(entryIDs))
  453. visible := 0
  454. if err := row.Scan(&visible); err != nil {
  455. return 0, fmt.Errorf(`store: unable to query entries visibility %v: %v`, entryIDs, err)
  456. }
  457. return visible, nil
  458. }
  459. // SetEntriesStarredState updates the starred state for the given list of entries.
  460. func (s *Storage) SetEntriesStarredState(userID int64, entryIDs []int64, starred bool) error {
  461. query := `UPDATE entries SET starred=$1, changed_at=now() WHERE user_id=$2 AND id=ANY($3)`
  462. result, err := s.db.Exec(query, starred, userID, pq.Array(entryIDs))
  463. if err != nil {
  464. return fmt.Errorf(`store: unable to update the starred state %v: %v`, entryIDs, err)
  465. }
  466. count, err := result.RowsAffected()
  467. if err != nil {
  468. return fmt.Errorf(`store: unable to update these entries %v: %v`, entryIDs, err)
  469. }
  470. if count == 0 {
  471. return errors.New(`store: nothing has been updated`)
  472. }
  473. return nil
  474. }
  475. // ToggleStarred toggles entry starred value.
  476. func (s *Storage) ToggleStarred(userID int64, entryID int64) error {
  477. query := `UPDATE entries SET starred = NOT starred, changed_at=now() WHERE user_id=$1 AND id=$2`
  478. result, err := s.db.Exec(query, userID, entryID)
  479. if err != nil {
  480. return fmt.Errorf(`store: unable to toggle starred flag for entry #%d: %v`, entryID, err)
  481. }
  482. count, err := result.RowsAffected()
  483. if err != nil {
  484. return fmt.Errorf(`store: unable to toggle starred flag for entry #%d: %v`, entryID, err)
  485. }
  486. if count == 0 {
  487. return errors.New(`store: nothing has been updated`)
  488. }
  489. return nil
  490. }
  491. // FlushHistory changes all entries with the status "read" to "removed".
  492. func (s *Storage) FlushHistory(userID int64) error {
  493. query := `
  494. UPDATE
  495. entries
  496. SET
  497. status=$1,
  498. changed_at=now()
  499. WHERE
  500. user_id=$2 AND status=$3 AND starred is false AND share_code=''
  501. `
  502. _, err := s.db.Exec(query, model.EntryStatusRemoved, userID, model.EntryStatusRead)
  503. if err != nil {
  504. return fmt.Errorf(`store: unable to flush history: %v`, err)
  505. }
  506. return nil
  507. }
  508. // MarkAllAsRead updates all user entries to the read status.
  509. func (s *Storage) MarkAllAsRead(userID int64) error {
  510. query := `UPDATE entries SET status=$1, changed_at=now() WHERE user_id=$2 AND status=$3`
  511. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread)
  512. if err != nil {
  513. return fmt.Errorf(`store: unable to mark all entries as read: %v`, err)
  514. }
  515. count, _ := result.RowsAffected()
  516. slog.Debug("Marked all entries as read",
  517. slog.Int64("user_id", userID),
  518. slog.Int64("nb_entries", count),
  519. )
  520. return nil
  521. }
  522. // MarkAllAsReadBeforeDate updates all user entries to the read status before the given date.
  523. func (s *Storage) MarkAllAsReadBeforeDate(userID int64, before time.Time) error {
  524. query := `
  525. UPDATE
  526. entries
  527. SET
  528. status=$1,
  529. changed_at=now()
  530. WHERE
  531. user_id=$2 AND status=$3 AND published_at < $4
  532. `
  533. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread, before)
  534. if err != nil {
  535. return fmt.Errorf(`store: unable to mark all entries as read before %s: %v`, before.Format(time.RFC3339), err)
  536. }
  537. count, _ := result.RowsAffected()
  538. slog.Debug("Marked all entries as read before date",
  539. slog.Int64("user_id", userID),
  540. slog.Int64("nb_entries", count),
  541. slog.String("before", before.Format(time.RFC3339)),
  542. )
  543. return nil
  544. }
  545. // MarkGloballyVisibleFeedsAsRead updates all user entries to the read status.
  546. func (s *Storage) MarkGloballyVisibleFeedsAsRead(userID int64) error {
  547. query := `
  548. UPDATE
  549. entries
  550. SET
  551. status=$1,
  552. changed_at=now()
  553. FROM
  554. feeds
  555. WHERE
  556. entries.feed_id = feeds.id
  557. AND entries.user_id=$2
  558. AND entries.status=$3
  559. AND feeds.hide_globally=$4
  560. `
  561. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread, false)
  562. if err != nil {
  563. return fmt.Errorf(`store: unable to mark globally visible feeds as read: %v`, err)
  564. }
  565. count, _ := result.RowsAffected()
  566. slog.Debug("Marked globally visible feed entries as read",
  567. slog.Int64("user_id", userID),
  568. slog.Int64("nb_entries", count),
  569. )
  570. return nil
  571. }
  572. // MarkFeedAsRead updates all feed entries to the read status.
  573. func (s *Storage) MarkFeedAsRead(userID, feedID int64, before time.Time) error {
  574. query := `
  575. UPDATE
  576. entries
  577. SET
  578. status=$1,
  579. changed_at=now()
  580. WHERE
  581. user_id=$2 AND feed_id=$3 AND status=$4 AND published_at < $5
  582. `
  583. result, err := s.db.Exec(query, model.EntryStatusRead, userID, feedID, model.EntryStatusUnread, before)
  584. if err != nil {
  585. return fmt.Errorf(`store: unable to mark feed entries as read: %v`, err)
  586. }
  587. count, _ := result.RowsAffected()
  588. slog.Debug("Marked feed entries as read",
  589. slog.Int64("user_id", userID),
  590. slog.Int64("feed_id", feedID),
  591. slog.Int64("nb_entries", count),
  592. slog.String("before", before.Format(time.RFC3339)),
  593. )
  594. return nil
  595. }
  596. // MarkCategoryAsRead updates all category entries to the read status.
  597. func (s *Storage) MarkCategoryAsRead(userID, categoryID int64, before time.Time) error {
  598. query := `
  599. UPDATE
  600. entries
  601. SET
  602. status=$1,
  603. changed_at=now()
  604. FROM
  605. feeds
  606. WHERE
  607. feed_id=feeds.id
  608. AND
  609. feeds.user_id=$2
  610. AND
  611. status=$3
  612. AND
  613. published_at < $4
  614. AND
  615. feeds.category_id=$5
  616. `
  617. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread, before, categoryID)
  618. if err != nil {
  619. return fmt.Errorf(`store: unable to mark category entries as read: %v`, err)
  620. }
  621. count, _ := result.RowsAffected()
  622. slog.Debug("Marked category entries as read",
  623. slog.Int64("user_id", userID),
  624. slog.Int64("category_id", categoryID),
  625. slog.Int64("nb_entries", count),
  626. slog.String("before", before.Format(time.RFC3339)),
  627. )
  628. return nil
  629. }
  630. // EntryShareCode returns the share code of the provided entry.
  631. // It generates a new one if not already defined.
  632. func (s *Storage) EntryShareCode(userID int64, entryID int64) (shareCode string, err error) {
  633. query := `SELECT share_code FROM entries WHERE user_id=$1 AND id=$2`
  634. err = s.db.QueryRow(query, userID, entryID).Scan(&shareCode)
  635. if err != nil {
  636. err = fmt.Errorf(`store: unable to get share code for entry #%d: %v`, entryID, err)
  637. return
  638. }
  639. if shareCode == "" {
  640. shareCode = crypto.GenerateRandomStringHex(20)
  641. query = `UPDATE entries SET share_code = $1 WHERE user_id=$2 AND id=$3`
  642. _, err = s.db.Exec(query, shareCode, userID, entryID)
  643. if err != nil {
  644. err = fmt.Errorf(`store: unable to set share code for entry #%d: %v`, entryID, err)
  645. return
  646. }
  647. }
  648. return
  649. }
  650. // UnshareEntry removes the share code for the given entry.
  651. func (s *Storage) UnshareEntry(userID int64, entryID int64) (err error) {
  652. query := `UPDATE entries SET share_code='' WHERE user_id=$1 AND id=$2`
  653. _, err = s.db.Exec(query, userID, entryID)
  654. if err != nil {
  655. err = fmt.Errorf(`store: unable to remove share code for entry #%d: %v`, entryID, err)
  656. }
  657. return
  658. }
  659. func truncateTitleAndContentForTSVectorField(title, content string) (string, string) {
  660. // The length of a tsvector (lexemes + positions) must be less than 1 megabyte.
  661. // We don't need to index the entire content, and we need to keep a buffer for the positions.
  662. return truncateStringForTSVectorField(title, 200000), truncateStringForTSVectorField(content, 500000)
  663. }
  664. // truncateStringForTSVectorField truncates a string and don't break UTF-8 characters.
  665. func truncateStringForTSVectorField(s string, maxSize int) string {
  666. if len(s) < maxSize {
  667. return s
  668. }
  669. // Truncate to fit under the limit, ensuring we don't break UTF-8 characters
  670. truncated := s[:maxSize-1]
  671. // Walk backwards to find the last complete UTF-8 character
  672. for i := len(truncated) - 1; i >= 0; i-- {
  673. if (truncated[i] & 0x80) == 0 {
  674. // ASCII character, we can stop here
  675. return truncated[:i+1]
  676. }
  677. if (truncated[i] & 0xC0) == 0xC0 {
  678. // Start of a multi-byte UTF-8 character
  679. return truncated[:i]
  680. }
  681. }
  682. // Fallback: return empty string if we can't find a valid UTF-8 boundary
  683. return ""
  684. }