entry.go 19 KB

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