feedkeeper 0.44.3 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,56 @@
1
+ import { db } from "../db/index.js";
2
+ function toEntry(row) {
3
+ return {
4
+ positionSeconds: row.position_seconds,
5
+ durationSeconds: row.duration_seconds,
6
+ completed: Boolean(row.completed),
7
+ updatedAt: row.updated_at,
8
+ };
9
+ }
10
+ /** Loads per-user playback positions for a batch of item IDs. */
11
+ export function mediaPositions(userId, itemIds) {
12
+ if (itemIds.length === 0)
13
+ return new Map();
14
+ const rows = db
15
+ .prepare(`SELECT item_id, position_seconds, duration_seconds, completed, updated_at
16
+ FROM item_media_positions
17
+ WHERE user_id = ? AND item_id IN (${itemIds.map(() => "?").join(",")})`)
18
+ .all(userId, ...itemIds);
19
+ return new Map(rows.map((row) => [row.item_id, toEntry(row)]));
20
+ }
21
+ /**
22
+ * Stores a user's playback position for an item using last-write-wins timestamp resolution.
23
+ * Reaching the end of an episode resets the saved position to 0 and marks it completed.
24
+ */
25
+ export function upsertMediaPosition(userId, itemId, input) {
26
+ const duration = input.durationSeconds != null && Number.isFinite(input.durationSeconds) && input.durationSeconds > 0
27
+ ? Math.round(input.durationSeconds)
28
+ : null;
29
+ const rawPos = Number.isFinite(input.positionSeconds) ? Math.max(0, Math.round(input.positionSeconds)) : 0;
30
+ const completed = Boolean(input.completed) || (duration !== null && duration >= 15 && rawPos >= duration - 5);
31
+ const storedPos = completed ? 0 : rawPos;
32
+ const parsedTs = input.updatedAt ? Date.parse(input.updatedAt) : Number.NaN;
33
+ const clientTs = Number.isFinite(parsedTs) ? new Date(parsedTs).toISOString() : new Date().toISOString();
34
+ const existing = db
35
+ .prepare(`SELECT item_id, position_seconds, duration_seconds, completed, updated_at
36
+ FROM item_media_positions
37
+ WHERE user_id = ? AND item_id = ?`)
38
+ .get(userId, itemId);
39
+ if (existing && Date.parse(existing.updated_at) > Date.parse(clientTs)) {
40
+ return toEntry(existing);
41
+ }
42
+ db.prepare(`INSERT INTO item_media_positions (user_id, item_id, position_seconds, duration_seconds, completed, updated_at)
43
+ VALUES (?, ?, ?, ?, ?, ?)
44
+ ON CONFLICT(user_id, item_id) DO UPDATE SET
45
+ position_seconds = excluded.position_seconds,
46
+ duration_seconds = COALESCE(excluded.duration_seconds, item_media_positions.duration_seconds),
47
+ completed = excluded.completed,
48
+ updated_at = excluded.updated_at`).run(userId, itemId, storedPos, duration, completed ? 1 : 0, clientTs);
49
+ const saved = db
50
+ .prepare(`SELECT item_id, position_seconds, duration_seconds, completed, updated_at
51
+ FROM item_media_positions
52
+ WHERE user_id = ? AND item_id = ?`)
53
+ .get(userId, itemId);
54
+ return toEntry(saved);
55
+ }
56
+ //# sourceMappingURL=mediaPosition.js.map
@@ -1,9 +1,11 @@
1
- import { fetchFeed } from "./fetcher.js";
1
+ import { FeedHttpError, fetchFeed } from "./fetcher.js";
2
+ import { discoverFeeds } from "./discovery.js";
3
+ import { isHostBlocked } from "./blockedHosts.js";
2
4
  import { discoverIconUrls, iconCheckDue } from "./icon.js";
3
5
  import { refreshFeedIcon } from "./feedIcon.js";
4
6
  import { enqueueNewItemNotifications, startPushOutbox, stopPushOutbox } from "../pushOutbox.js";
5
7
  import { hasUserCapability } from "../auth/capabilities.js";
6
- import { findFeedById, listSubscriberIds, updateFeedAfterPoll, updateFeedIcon, upsertItems } from "./repository.js";
8
+ import { findFeedById, findFeedByUrl, listSubscriberIds, replaceFeedUrl, setFeedSuggestedUrl, updateFeedAfterPoll, updateFeedIcon, upsertItems, } from "./repository.js";
7
9
  import { db } from "../db/index.js";
8
10
  import { configurePollHostCooldowns, PollQueue } from "./pollQueue.js";
9
11
  import { feedRequests, PollDeferredError, sourceHost } from "./requestGate.js";
@@ -39,14 +41,47 @@ export async function settleIconChecks() {
39
41
  while (iconChecks.size)
40
42
  await Promise.allSettled([...iconChecks]);
41
43
  }
44
+ const GONE_SUGGESTION_TTL_MS = 24 * 60 * 60 * 1000;
45
+ function isUrlBlocked(url) {
46
+ try {
47
+ return isHostBlocked(new URL(url).hostname);
48
+ }
49
+ catch {
50
+ return true;
51
+ }
52
+ }
53
+ async function trySuggestReplacementForGoneFeed(feed) {
54
+ const checkedAt = feed.suggested_url_checked_at ? Date.parse(feed.suggested_url_checked_at) : Number.NaN;
55
+ if (Number.isFinite(checkedAt) && Date.now() - checkedAt < GONE_SUGGESTION_TTL_MS)
56
+ return;
57
+ try {
58
+ const originUrl = new URL(feed.url).origin;
59
+ const candidateSite = feed.site_url || originUrl;
60
+ const discovered = await discoverFeeds(candidateSite);
61
+ const match = discovered.find((entry) => entry.url !== feed.url && !isUrlBlocked(entry.url));
62
+ setFeedSuggestedUrl(feed.id, match ? match.url : null);
63
+ }
64
+ catch {
65
+ setFeedSuggestedUrl(feed.id, null);
66
+ }
67
+ }
42
68
  /** One attempt; the queue owns retries, admission, single-flight and the total deadline. */
43
69
  async function pollAttempt(feed, signal, interactive) {
44
- const fetched = await fetchFeed(feed.url, {
45
- etag: feed.etag ?? undefined,
46
- lastModified: feed.last_modified ?? undefined,
47
- signal,
48
- priority: interactive ? "interactive" : "background",
49
- });
70
+ let fetched;
71
+ try {
72
+ fetched = await fetchFeed(feed.url, {
73
+ etag: feed.etag ?? undefined,
74
+ lastModified: feed.last_modified ?? undefined,
75
+ signal,
76
+ priority: interactive ? "interactive" : "background",
77
+ });
78
+ }
79
+ catch (error) {
80
+ if (error instanceof FeedHttpError && error.status === 410) {
81
+ await trySuggestReplacementForGoneFeed(feed);
82
+ }
83
+ throw error;
84
+ }
50
85
  const parsed = fetched.notModified ? null : await parseFeedBody(fetched.body);
51
86
  signal.throwIfAborted();
52
87
  const current = findFeedById(feed.id);
@@ -69,8 +104,22 @@ async function pollAttempt(feed, signal, interactive) {
69
104
  enclosureDurationSeconds: item.enclosureDurationSeconds,
70
105
  chaptersUrl: item.chaptersUrl,
71
106
  }));
107
+ const permanentRedirect = fetched.permanentRedirectUrl && !isUrlBlocked(fetched.permanentRedirectUrl)
108
+ ? fetched.permanentRedirectUrl
109
+ : undefined;
72
110
  // No await in this transaction. Items, health/validators and job completion become visible together.
73
111
  const newItems = db.transaction(() => {
112
+ let effectiveFeed = current;
113
+ if (permanentRedirect) {
114
+ const collision = findFeedByUrl(permanentRedirect);
115
+ if (!collision) {
116
+ replaceFeedUrl(feed.id, permanentRedirect);
117
+ effectiveFeed = { ...current, url: permanentRedirect };
118
+ }
119
+ else if (collision.id !== feed.id) {
120
+ setFeedSuggestedUrl(feed.id, permanentRedirect);
121
+ }
122
+ }
74
123
  const count = items ? upsertItems(feed.id, items) : 0;
75
124
  updateFeedAfterPoll(feed.id, {
76
125
  ...(parsed ? { title: parsed.title, siteUrl: parsed.link, etag: fetched.etag, lastModified: fetched.lastModified } : {}),
@@ -79,14 +128,14 @@ async function pollAttempt(feed, signal, interactive) {
79
128
  if (count > 0 && feed.last_success_at)
80
129
  enqueueNewItemNotifications(feed.id, count);
81
130
  db.prepare("DELETE FROM feed_poll_jobs WHERE feed_id = ?").run(feed.id);
82
- return count;
131
+ return { count, effectiveFeed };
83
132
  })();
84
133
  // Push is committed above and dispatched independently of the feed deadline.
85
134
  startPushOutbox();
86
135
  // Icon upkeep is best effort. It runs after this result is returned: the poll slot is free again, and a new subscription that is
87
136
  // waiting for the first fetch is answered as soon as the feed is stored, not after the publisher's home page and icons.
88
- scheduleIconMaintenance(feed, parsed);
89
- return { newItems, error: null };
137
+ scheduleIconMaintenance(newItems.effectiveFeed, parsed);
138
+ return { newItems: newItems.count, error: null };
90
139
  }
91
140
  let queue;
92
141
  function pollingQueue() {
@@ -7,6 +7,7 @@ import { largerHeroImage } from "./heroImage.js";
7
7
  import { refreshGalleryClassification, refreshLead } from "./lead.js";
8
8
  import { decodeEntities, plainTitle } from "./text.js";
9
9
  import { unwrapRedirectLink } from "./redirectLinks.js";
10
+ import { appendSearchOperatorConditions, parseSearchQuery } from "./searchQuery.js";
10
11
  export function findFeedByUrl(url) {
11
12
  return db.prepare("SELECT * FROM feeds WHERE url = ?").get(url);
12
13
  }
@@ -293,10 +294,14 @@ export function listItemsForUser(userId, opts = {}) {
293
294
  params.push(userId);
294
295
  }
295
296
  if (opts.search) {
296
- // Saved articles are searched in their archived full text too.
297
- const fields = ["i.title", "i.content_snippet", ...(opts.bookmarkedOnly ? ["i.full_content_html", "i.content_html"] : [])];
298
- conditions.push(`(${fields.map((field) => `INSTR(LOWER(COALESCE(${field}, '')), LOWER(?)) > 0`).join(" OR ")} OR i.id IN (SELECT item_id FROM item_notes WHERE user_id = ? AND INSTR(LOWER(content), LOWER(?)) > 0))`);
299
- params.push(...fields.map(() => opts.search), userId, opts.search);
297
+ const parsedSearch = parseSearchQuery(opts.search);
298
+ appendSearchOperatorConditions(parsedSearch, userId, conditions, params);
299
+ if (parsedSearch.textQuery) {
300
+ // Saved articles are searched in their archived full text too.
301
+ const fields = ["i.title", "i.content_snippet", ...(opts.bookmarkedOnly ? ["i.full_content_html", "i.content_html"] : [])];
302
+ conditions.push(`(${fields.map((field) => `INSTR(LOWER(COALESCE(${field}, '')), LOWER(?)) > 0`).join(" OR ")} OR i.id IN (SELECT item_id FROM item_notes WHERE user_id = ? AND INSTR(LOWER(content), LOWER(?)) > 0))`);
303
+ params.push(...fields.map(() => parsedSearch.textQuery), userId, parsedSearch.textQuery);
304
+ }
300
305
  }
301
306
  if (opts.since) {
302
307
  conditions.push("i.created_at > ?");
@@ -605,9 +610,13 @@ export function countFeedSubscribers(feedId) {
605
610
  /** Point a feed at a new URL in place, keeping its items; resets fetch state so the next poll starts fresh. */
606
611
  export function replaceFeedUrl(feedId, url) {
607
612
  db.prepare(`UPDATE feeds SET url = ?, etag = NULL, last_modified = NULL, last_error = NULL, consecutive_errors = 0,
608
- full_text_blocks = 0, full_text_blocked_at = NULL
613
+ full_text_blocks = 0, full_text_blocked_at = NULL, suggested_url = NULL, suggested_url_checked_at = NULL
609
614
  WHERE id = ?`).run(url, feedId);
610
615
  }
616
+ /** Records a replacement feed suggestion (e.g. from 410 Gone auto-discovery or a colliding permanent redirect). */
617
+ export function setFeedSuggestedUrl(feedId, suggestedUrl) {
618
+ db.prepare(`UPDATE feeds SET suggested_url = ?, suggested_url_checked_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') WHERE id = ?`).run(suggestedUrl, feedId);
619
+ }
611
620
  /** Move a user's subscription to another feed, keeping label, folder, order and full-text mode. */
612
621
  export function moveSubscription(userId, fromFeedId, toFeedId) {
613
622
  db.transaction(() => {
@@ -760,7 +769,8 @@ export function needsSubstringSearch(raw) {
760
769
  return /(?![a-zA-Z0-9_\u00C0-\u024F\u1E00-\u1EFF])[\p{L}\p{N}]/u.test(outsideQuotes);
761
770
  }
762
771
  export function searchItemsForUser(userId, opts) {
763
- const fts = needsSubstringSearch(opts.query) ? "" : formatFtsQuery(opts.query);
772
+ const parsedQuery = parseSearchQuery(opts.query);
773
+ const fts = parsedQuery.textQuery && !needsSubstringSearch(parsedQuery.textQuery) ? formatFtsQuery(parsedQuery.textQuery) : "";
764
774
  const conditions = ["(s.id IS NOT NULL OR b.item_id IS NOT NULL OR n.user_id IS NOT NULL)",
765
775
  "(i.is_empty_gallery = 0 OR b.item_id IS NOT NULL OR n.user_id IS NOT NULL)"];
766
776
  const params = [];
@@ -778,17 +788,18 @@ export function searchItemsForUser(userId, opts) {
778
788
  if (opts.bookmarkedOnly) {
779
789
  conditions.push("b.item_id IS NOT NULL");
780
790
  }
791
+ appendSearchOperatorConditions(parsedQuery, userId, conditions, params);
781
792
  // Search filter (FTS on items + user notes)
782
793
  if (fts) {
783
794
  conditions.push(`(
784
795
  i.id IN (SELECT rowid FROM items_fts WHERE items_fts MATCH ?)
785
796
  OR i.id IN (SELECT item_id FROM item_notes WHERE user_id = ? AND INSTR(LOWER(content), LOWER(?)) > 0)
786
797
  )`);
787
- params.push(fts, userId, opts.query);
798
+ params.push(fts, userId, parsedQuery.textQuery);
788
799
  }
789
- else {
800
+ else if (parsedQuery.textQuery) {
790
801
  // Every word has to occur somewhere in the article or in the person's note.
791
- const words = opts.query.trim().split(/\s+/).filter(Boolean).slice(0, 8);
802
+ const words = parsedQuery.textQuery.trim().split(/\s+/).filter(Boolean).slice(0, 8);
792
803
  for (const word of words) {
793
804
  conditions.push(`(
794
805
  INSTR(LOWER(COALESCE(i.title, '')), LOWER(?)) > 0
@@ -0,0 +1,101 @@
1
+ const TOKEN_RE = /(\w+:"[^"]*"|\w+:[^\s]+|\S+)/g;
2
+ /**
3
+ * Splits a search query into structured filter operators (`has:audio`, `has:video`,
4
+ * `has:notes`, `has:media`, `is:unread`, `is:read`, `is:starred`, `feed:...`)
5
+ * and the remaining free-text search string.
6
+ */
7
+ export function parseSearchQuery(raw) {
8
+ const result = {
9
+ textQuery: "",
10
+ hasAudio: false,
11
+ hasVideo: false,
12
+ hasMedia: false,
13
+ hasNotes: false,
14
+ readState: null,
15
+ starredOnly: false,
16
+ feedTerms: [],
17
+ hasOperators: false,
18
+ };
19
+ const textParts = [];
20
+ const tokens = raw.trim().match(TOKEN_RE) ?? [];
21
+ for (const token of tokens) {
22
+ const lower = token.toLowerCase();
23
+ if (lower === "has:audio") {
24
+ result.hasAudio = true;
25
+ result.hasOperators = true;
26
+ }
27
+ else if (lower === "has:video") {
28
+ result.hasVideo = true;
29
+ result.hasOperators = true;
30
+ }
31
+ else if (lower === "has:media") {
32
+ result.hasMedia = true;
33
+ result.hasOperators = true;
34
+ }
35
+ else if (lower === "has:notes" || lower === "has:note") {
36
+ result.hasNotes = true;
37
+ result.hasOperators = true;
38
+ }
39
+ else if (lower === "is:unread") {
40
+ result.readState = "unread";
41
+ result.hasOperators = true;
42
+ }
43
+ else if (lower === "is:read") {
44
+ result.readState = "read";
45
+ result.hasOperators = true;
46
+ }
47
+ else if (lower === "is:starred" || lower === "is:bookmarked" || lower === "is:saved") {
48
+ result.starredOnly = true;
49
+ result.hasOperators = true;
50
+ }
51
+ else if (lower.startsWith("feed:")) {
52
+ const value = token.slice(5).replace(/^"(.*)"$/, "$1").trim();
53
+ if (value) {
54
+ result.feedTerms.push(value);
55
+ result.hasOperators = true;
56
+ }
57
+ else {
58
+ textParts.push(token);
59
+ }
60
+ }
61
+ else {
62
+ textParts.push(token);
63
+ }
64
+ }
65
+ result.textQuery = textParts.join(" ").trim();
66
+ return result;
67
+ }
68
+ /** Appends SQL WHERE conditions for parsed search operators (expects `items i`, `subscriptions s`, `item_reads r`, `item_bookmarks b`). */
69
+ export function appendSearchOperatorConditions(parsed, userId, conditions, params) {
70
+ if (parsed.hasAudio && parsed.hasVideo) {
71
+ conditions.push("i.enclosure_url IS NOT NULL");
72
+ }
73
+ else if (parsed.hasAudio) {
74
+ conditions.push("(i.enclosure_url IS NOT NULL AND (i.enclosure_type IS NULL OR LOWER(i.enclosure_type) NOT LIKE 'video/%'))");
75
+ }
76
+ else if (parsed.hasVideo) {
77
+ conditions.push("(i.enclosure_url IS NOT NULL AND LOWER(i.enclosure_type) LIKE 'video/%')");
78
+ }
79
+ else if (parsed.hasMedia) {
80
+ conditions.push("i.enclosure_url IS NOT NULL");
81
+ }
82
+ if (parsed.hasNotes) {
83
+ conditions.push("i.id IN (SELECT item_id FROM item_notes WHERE user_id = ?)");
84
+ params.push(userId);
85
+ }
86
+ if (parsed.readState === "unread") {
87
+ conditions.push("r.item_id IS NULL");
88
+ }
89
+ else if (parsed.readState === "read") {
90
+ conditions.push("r.item_id IS NOT NULL");
91
+ }
92
+ if (parsed.starredOnly) {
93
+ conditions.push("b.item_id IS NOT NULL");
94
+ }
95
+ for (const term of parsed.feedTerms.slice(0, 3)) {
96
+ const pattern = `%${term.toLowerCase()}%`;
97
+ conditions.push("EXISTS (SELECT 1 FROM feeds f_op WHERE f_op.id = i.feed_id AND (LOWER(COALESCE(NULLIF(TRIM(s.label), ''), NULLIF(TRIM(f_op.title), ''), f_op.url)) LIKE ? OR LOWER(f_op.url) LIKE ?))");
98
+ params.push(pattern, pattern);
99
+ }
100
+ }
101
+ //# sourceMappingURL=searchQuery.js.map
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feedkeeper/server",
3
- "version": "0.44.3",
3
+ "version": "0.46.0",
4
4
  "private": true,
5
5
  "type": "module"
6
6
  }