entry.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  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 {
  16. rows, err := s.db.Query(`SELECT status, count(*) FROM entries GROUP BY status`)
  17. if err != nil {
  18. return nil
  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
  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. query := `
  278. DELETE FROM
  279. entries
  280. WHERE
  281. feed_id=$1 AND
  282. status=$2 AND
  283. NOT (hash=ANY($3))
  284. `
  285. if _, err := s.db.Exec(query, feedID, model.EntryStatusRemoved, pq.Array(entryHashes)); err != nil {
  286. return fmt.Errorf(`store: unable to cleanup entries: %v`, err)
  287. }
  288. return nil
  289. }
  290. // DeleteRemovedEntriesEnclosures deletes enclosures associated with entries marked as "removed".
  291. func (s *Storage) DeleteRemovedEntriesEnclosures() (int64, error) {
  292. query := `
  293. DELETE FROM
  294. enclosures
  295. WHERE
  296. enclosures.entry_id IN (SELECT id FROM entries WHERE status=$1)
  297. `
  298. result, err := s.db.Exec(query, model.EntryStatusRemoved)
  299. if err != nil {
  300. return 0, fmt.Errorf(`store: unable to delete enclosures from removed entries: %v`, err)
  301. }
  302. count, err := result.RowsAffected()
  303. if err != nil {
  304. return 0, fmt.Errorf(`store: unable to get the number of rows affected while deleting enclosures from removed entries: %v`, err)
  305. }
  306. return count, nil
  307. }
  308. // ClearRemovedEntriesContent clears the content fields of entries marked as "removed", keeping only their metadata.
  309. func (s *Storage) ClearRemovedEntriesContent(limit int) (int64, error) {
  310. query := `
  311. UPDATE
  312. entries
  313. SET
  314. title='',
  315. content=NULL,
  316. url='',
  317. author=NULL,
  318. comments_url=NULL,
  319. document_vectors=NULL
  320. WHERE id IN (
  321. SELECT id
  322. FROM entries
  323. WHERE status = $1 AND content IS NOT NULL
  324. ORDER BY id ASC
  325. LIMIT $2
  326. )
  327. `
  328. result, err := s.db.Exec(query, model.EntryStatusRemoved, limit)
  329. if err != nil {
  330. return 0, fmt.Errorf(`store: unable to clear content from removed entries: %v`, err)
  331. }
  332. count, err := result.RowsAffected()
  333. if err != nil {
  334. return 0, fmt.Errorf(`store: unable to get the number of rows affected while clearing content from removed entries: %v`, err)
  335. }
  336. return count, nil
  337. }
  338. // RefreshFeedEntries updates feed entries while refreshing a feed.
  339. func (s *Storage) RefreshFeedEntries(userID, feedID int64, entries model.Entries, updateExistingEntries bool) (newEntries model.Entries, err error) {
  340. entryHashes := make([]string, 0, len(entries))
  341. for _, entry := range entries {
  342. entry.UserID = userID
  343. entry.FeedID = feedID
  344. tx, err := s.db.Begin()
  345. if err != nil {
  346. return nil, fmt.Errorf(`store: unable to start transaction: %v`, err)
  347. }
  348. entryExists, err := s.entryExists(tx, entry)
  349. if err != nil {
  350. if rollbackErr := tx.Rollback(); rollbackErr != nil {
  351. return nil, fmt.Errorf(`store: unable to rollback transaction: %v (rolled back due to: %v)`, rollbackErr, err)
  352. }
  353. return nil, err
  354. }
  355. if entryExists {
  356. if updateExistingEntries {
  357. err = s.updateEntry(tx, entry)
  358. }
  359. } else {
  360. err = s.createEntry(tx, entry)
  361. if err == nil {
  362. newEntries = append(newEntries, entry)
  363. }
  364. }
  365. if err != nil {
  366. if rollbackErr := tx.Rollback(); rollbackErr != nil {
  367. return nil, fmt.Errorf(`store: unable to rollback transaction: %v (rolled back due to: %v)`, rollbackErr, err)
  368. }
  369. return nil, err
  370. }
  371. if err := tx.Commit(); err != nil {
  372. return nil, fmt.Errorf(`store: unable to commit transaction: %v`, err)
  373. }
  374. entryHashes = append(entryHashes, entry.Hash)
  375. }
  376. go func() {
  377. if err := s.cleanupRemovedEntriesNotInFeed(feedID, entryHashes); err != nil {
  378. slog.Error("Unable to cleanup removed entries",
  379. slog.Int64("user_id", userID),
  380. slog.Int64("feed_id", feedID),
  381. slog.Any("error", err),
  382. )
  383. }
  384. }()
  385. return newEntries, nil
  386. }
  387. // ArchiveEntries changes the status of entries to "removed" after the interval (24h minimum).
  388. func (s *Storage) ArchiveEntries(status string, interval time.Duration, limit int) (int64, error) {
  389. if interval < 0 || limit <= 0 {
  390. return 0, nil
  391. }
  392. query := `
  393. UPDATE
  394. entries
  395. SET
  396. status=$1
  397. WHERE
  398. id IN (
  399. SELECT
  400. id
  401. FROM
  402. entries
  403. WHERE
  404. status=$2 AND
  405. starred is false AND
  406. share_code='' AND
  407. created_at < now () - $3::interval
  408. ORDER BY
  409. created_at ASC LIMIT $4
  410. )
  411. `
  412. days := max(int(interval/(24*time.Hour)), 1)
  413. result, err := s.db.Exec(query, model.EntryStatusRemoved, status, fmt.Sprintf("%d days", days), limit)
  414. if err != nil {
  415. return 0, fmt.Errorf(`store: unable to archive %s entries: %v`, status, err)
  416. }
  417. count, err := result.RowsAffected()
  418. if err != nil {
  419. return 0, fmt.Errorf(`store: unable to get the number of rows affected: %v`, err)
  420. }
  421. return count, nil
  422. }
  423. // SetEntriesStatus update the status of the given list of entries.
  424. func (s *Storage) SetEntriesStatus(userID int64, entryIDs []int64, status string) error {
  425. // Entries that have the model.EntryStatusRemoved status are immutable.
  426. query := `
  427. UPDATE
  428. entries
  429. SET
  430. status=$1,
  431. changed_at=now()
  432. WHERE
  433. user_id=$2 AND
  434. id=ANY($3) AND
  435. status!=$4
  436. `
  437. if _, err := s.db.Exec(query, status, userID, pq.Array(entryIDs), model.EntryStatusRemoved); err != nil {
  438. return fmt.Errorf(`store: unable to update entries statuses %v: %v`, entryIDs, err)
  439. }
  440. return nil
  441. }
  442. func (s *Storage) SetEntriesStatusCount(userID int64, entryIDs []int64, status string) (int, error) {
  443. if err := s.SetEntriesStatus(userID, entryIDs, status); err != nil {
  444. return 0, err
  445. }
  446. query := `
  447. SELECT count(*)
  448. FROM entries e
  449. JOIN feeds f ON (f.id = e.feed_id)
  450. JOIN categories c ON (c.id = f.category_id)
  451. WHERE e.user_id = $1
  452. AND e.id = ANY($2)
  453. AND NOT f.hide_globally
  454. AND NOT c.hide_globally
  455. `
  456. row := s.db.QueryRow(query, userID, pq.Array(entryIDs))
  457. visible := 0
  458. if err := row.Scan(&visible); err != nil {
  459. return 0, fmt.Errorf(`store: unable to query entries visibility %v: %v`, entryIDs, err)
  460. }
  461. return visible, nil
  462. }
  463. // SetEntriesStarredState updates the starred state for the given list of entries.
  464. func (s *Storage) SetEntriesStarredState(userID int64, entryIDs []int64, starred bool) error {
  465. query := `UPDATE entries SET starred=$1, changed_at=now() WHERE user_id=$2 AND id=ANY($3)`
  466. result, err := s.db.Exec(query, starred, userID, pq.Array(entryIDs))
  467. if err != nil {
  468. return fmt.Errorf(`store: unable to update the starred state %v: %v`, entryIDs, err)
  469. }
  470. count, err := result.RowsAffected()
  471. if err != nil {
  472. return fmt.Errorf(`store: unable to update these entries %v: %v`, entryIDs, err)
  473. }
  474. if count == 0 {
  475. return errors.New(`store: nothing has been updated`)
  476. }
  477. return nil
  478. }
  479. // ToggleStarred toggles entry starred value.
  480. func (s *Storage) ToggleStarred(userID int64, entryID int64) error {
  481. query := `UPDATE entries SET starred = NOT starred, changed_at=now() WHERE user_id=$1 AND id=$2`
  482. result, err := s.db.Exec(query, userID, entryID)
  483. if err != nil {
  484. return fmt.Errorf(`store: unable to toggle starred flag for entry #%d: %v`, entryID, err)
  485. }
  486. count, err := result.RowsAffected()
  487. if err != nil {
  488. return fmt.Errorf(`store: unable to toggle starred flag for entry #%d: %v`, entryID, err)
  489. }
  490. if count == 0 {
  491. return errors.New(`store: nothing has been updated`)
  492. }
  493. return nil
  494. }
  495. // FlushHistory changes all entries with the status "read" to "removed".
  496. func (s *Storage) FlushHistory(userID int64) error {
  497. query := `
  498. UPDATE
  499. entries
  500. SET
  501. status=$1,
  502. changed_at=now()
  503. WHERE
  504. user_id=$2 AND status=$3 AND starred is false AND share_code=''
  505. `
  506. _, err := s.db.Exec(query, model.EntryStatusRemoved, userID, model.EntryStatusRead)
  507. if err != nil {
  508. return fmt.Errorf(`store: unable to flush history: %v`, err)
  509. }
  510. return nil
  511. }
  512. // MarkAllAsRead updates all user entries to the read status.
  513. func (s *Storage) MarkAllAsRead(userID int64) error {
  514. query := `UPDATE entries SET status=$1, changed_at=now() WHERE user_id=$2 AND status=$3`
  515. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread)
  516. if err != nil {
  517. return fmt.Errorf(`store: unable to mark all entries as read: %v`, err)
  518. }
  519. count, _ := result.RowsAffected()
  520. slog.Debug("Marked all entries as read",
  521. slog.Int64("user_id", userID),
  522. slog.Int64("nb_entries", count),
  523. )
  524. return nil
  525. }
  526. // MarkAllAsReadBeforeDate updates all user entries to the read status before the given date.
  527. func (s *Storage) MarkAllAsReadBeforeDate(userID int64, before time.Time) error {
  528. query := `
  529. UPDATE
  530. entries
  531. SET
  532. status=$1,
  533. changed_at=now()
  534. WHERE
  535. user_id=$2 AND status=$3 AND published_at < $4
  536. `
  537. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread, before)
  538. if err != nil {
  539. return fmt.Errorf(`store: unable to mark all entries as read before %s: %v`, before.Format(time.RFC3339), err)
  540. }
  541. count, _ := result.RowsAffected()
  542. slog.Debug("Marked all entries as read before date",
  543. slog.Int64("user_id", userID),
  544. slog.Int64("nb_entries", count),
  545. slog.String("before", before.Format(time.RFC3339)),
  546. )
  547. return nil
  548. }
  549. // MarkGloballyVisibleFeedsAsRead updates all user entries to the read status.
  550. func (s *Storage) MarkGloballyVisibleFeedsAsRead(userID int64) error {
  551. query := `
  552. UPDATE
  553. entries
  554. SET
  555. status=$1,
  556. changed_at=now()
  557. FROM
  558. feeds
  559. WHERE
  560. entries.feed_id = feeds.id
  561. AND entries.user_id=$2
  562. AND entries.status=$3
  563. AND feeds.hide_globally=$4
  564. `
  565. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread, false)
  566. if err != nil {
  567. return fmt.Errorf(`store: unable to mark globally visible feeds as read: %v`, err)
  568. }
  569. count, _ := result.RowsAffected()
  570. slog.Debug("Marked globally visible feed entries as read",
  571. slog.Int64("user_id", userID),
  572. slog.Int64("nb_entries", count),
  573. )
  574. return nil
  575. }
  576. // MarkFeedAsRead updates all feed entries to the read status.
  577. func (s *Storage) MarkFeedAsRead(userID, feedID int64, before time.Time) error {
  578. query := `
  579. UPDATE
  580. entries
  581. SET
  582. status=$1,
  583. changed_at=now()
  584. WHERE
  585. user_id=$2 AND feed_id=$3 AND status=$4 AND published_at < $5
  586. `
  587. result, err := s.db.Exec(query, model.EntryStatusRead, userID, feedID, model.EntryStatusUnread, before)
  588. if err != nil {
  589. return fmt.Errorf(`store: unable to mark feed entries as read: %v`, err)
  590. }
  591. count, _ := result.RowsAffected()
  592. slog.Debug("Marked feed entries as read",
  593. slog.Int64("user_id", userID),
  594. slog.Int64("feed_id", feedID),
  595. slog.Int64("nb_entries", count),
  596. slog.String("before", before.Format(time.RFC3339)),
  597. )
  598. return nil
  599. }
  600. // MarkCategoryAsRead updates all category entries to the read status.
  601. func (s *Storage) MarkCategoryAsRead(userID, categoryID int64, before time.Time) error {
  602. query := `
  603. UPDATE
  604. entries
  605. SET
  606. status=$1,
  607. changed_at=now()
  608. FROM
  609. feeds
  610. WHERE
  611. feed_id=feeds.id
  612. AND
  613. feeds.user_id=$2
  614. AND
  615. status=$3
  616. AND
  617. published_at < $4
  618. AND
  619. feeds.category_id=$5
  620. `
  621. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread, before, categoryID)
  622. if err != nil {
  623. return fmt.Errorf(`store: unable to mark category entries as read: %v`, err)
  624. }
  625. count, _ := result.RowsAffected()
  626. slog.Debug("Marked category entries as read",
  627. slog.Int64("user_id", userID),
  628. slog.Int64("category_id", categoryID),
  629. slog.Int64("nb_entries", count),
  630. slog.String("before", before.Format(time.RFC3339)),
  631. )
  632. return nil
  633. }
  634. // EntryShareCode returns the share code of the provided entry.
  635. // It generates a new one if not already defined.
  636. func (s *Storage) EntryShareCode(userID int64, entryID int64) (shareCode string, err error) {
  637. query := `SELECT share_code FROM entries WHERE user_id=$1 AND id=$2`
  638. err = s.db.QueryRow(query, userID, entryID).Scan(&shareCode)
  639. if err != nil {
  640. err = fmt.Errorf(`store: unable to get share code for entry #%d: %v`, entryID, err)
  641. return
  642. }
  643. if shareCode == "" {
  644. shareCode = crypto.GenerateRandomStringHex(20)
  645. query = `UPDATE entries SET share_code = $1 WHERE user_id=$2 AND id=$3`
  646. _, err = s.db.Exec(query, shareCode, userID, entryID)
  647. if err != nil {
  648. err = fmt.Errorf(`store: unable to set share code for entry #%d: %v`, entryID, err)
  649. return
  650. }
  651. }
  652. return
  653. }
  654. // UnshareEntry removes the share code for the given entry.
  655. func (s *Storage) UnshareEntry(userID int64, entryID int64) (err error) {
  656. query := `UPDATE entries SET share_code='' WHERE user_id=$1 AND id=$2`
  657. _, err = s.db.Exec(query, userID, entryID)
  658. if err != nil {
  659. err = fmt.Errorf(`store: unable to remove share code for entry #%d: %v`, entryID, err)
  660. }
  661. return
  662. }
  663. func truncateTitleAndContentForTSVectorField(title, content string) (string, string) {
  664. // The length of a tsvector (lexemes + positions) must be less than 1 megabyte.
  665. // We don't need to index the entire content, and we need to keep a buffer for the positions.
  666. return truncateStringForTSVectorField(title, 200000), truncateStringForTSVectorField(content, 500000)
  667. }
  668. // truncateStringForTSVectorField truncates a string and don't break UTF-8 characters.
  669. func truncateStringForTSVectorField(s string, maxSize int) string {
  670. if len(s) < maxSize {
  671. return s
  672. }
  673. // Truncate to fit under the limit, ensuring we don't break UTF-8 characters
  674. truncated := s[:maxSize-1]
  675. // Walk backwards to find the last complete UTF-8 character
  676. for i := len(truncated) - 1; i >= 0; i-- {
  677. if (truncated[i] & 0x80) == 0 {
  678. // ASCII character, we can stop here
  679. return truncated[:i+1]
  680. }
  681. if (truncated[i] & 0xC0) == 0xC0 {
  682. // Start of a multi-byte UTF-8 character
  683. return truncated[:i]
  684. }
  685. }
  686. // Fallback: return empty string if we can't find a valid UTF-8 boundary
  687. return ""
  688. }