feedkeeper 0.45.0 → 0.46.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "feedkeeper",
3
- "version": "0.45.0",
3
+ "version": "0.46.1",
4
4
  "description": "A lightweight, self-hosted RSS reader and remote MCP server for your news, blogs, and AI workflows.",
5
5
  "keywords": [
6
6
  "rss",
@@ -2,8 +2,8 @@ import { Router } from "express";
2
2
  import { z } from "zod";
3
3
  import { requireSession } from "../auth/middleware.js";
4
4
  import { requireCapability } from "../auth/capabilities.js";
5
- import { listSubscriptionsForUser, findFeedById, isUserSubscribed, reorderSubscriptions } from "../feeds/repository.js";
6
- import { subscribeToFeed, unsubscribeFromFeed, updateFeedSettings, FeedError, MultipleFeedsFoundError } from "../feeds/service.js";
5
+ import { listSubscriptionsForUser, findFeedById, findSubscriptionForUser, isUserSubscribed, reorderSubscriptions } from "../feeds/repository.js";
6
+ import { changeFeedUrl, subscribeToFeed, unsubscribeFromFeed, updateFeedSettings, FeedError, MultipleFeedsFoundError } from "../feeds/service.js";
7
7
  import { SsrfBlockedError, normalizeUrlCandidate } from "../feeds/ssrfGuard.js";
8
8
  import { blockedUrlBody } from "../feeds/blockedHosts.js";
9
9
  import { generateOpml, importOpmlFeeds } from "../feeds/opml.js";
@@ -195,6 +195,41 @@ feedsRouter.post("/:feedId/refresh", requireSync, async (req, res) => {
195
195
  retryAt: pollResult.retryAt,
196
196
  });
197
197
  });
198
+ feedsRouter.post("/:feedId/accept-move", requireSync, async (req, res) => {
199
+ const feedId = Number(req.params.feedId);
200
+ if (!Number.isInteger(feedId) || feedId <= 0) {
201
+ res.status(400).json({ error: "invalid_feed_id" });
202
+ return;
203
+ }
204
+ const existing = findSubscriptionForUser(req.user.id, feedId);
205
+ if (!existing) {
206
+ res.status(404).json({ error: "feed_not_found" });
207
+ return;
208
+ }
209
+ if (!existing.suggested_url) {
210
+ res.status(404).json({ error: "no_suggested_url" });
211
+ return;
212
+ }
213
+ try {
214
+ const moved = await changeFeedUrl(req.user.id, feedId, existing.suggested_url);
215
+ res.json({ feed: moved.subscription });
216
+ }
217
+ catch (error) {
218
+ if (error instanceof MultipleFeedsFoundError) {
219
+ res.status(409).json({ error: "multiple_feeds_found", feeds: error.feeds });
220
+ return;
221
+ }
222
+ if (error instanceof SsrfBlockedError) {
223
+ res.status(400).json(blockedUrlBody(error));
224
+ return;
225
+ }
226
+ if (error instanceof FeedError) {
227
+ res.status(error.message === "not_subscribed" ? 404 : 400).json({ error: error.message });
228
+ return;
229
+ }
230
+ res.status(400).json({ error: "invalid_feed", message: error instanceof Error ? error.message : String(error) });
231
+ }
232
+ });
198
233
  feedsRouter.post("/refresh-all", requireSync, async (req, res) => {
199
234
  const subs = listSubscriptionsForUser(req.user.id);
200
235
  const { newItems: totalNewItems, errors: errorCount, deferred } = await pollFeeds(subs);
@@ -3,9 +3,11 @@ import { Router } from "express";
3
3
  import rateLimit from "express-rate-limit";
4
4
  import { z } from "zod";
5
5
  import { requireSession } from "../auth/middleware.js";
6
- import { listItemsForUser, markAllRead, markItemRead, markItemUnread, bookmarkItem, unbookmarkItem, findItemById, } from "../feeds/repository.js";
6
+ import { requireCapability } from "../auth/capabilities.js";
7
+ import { canAccessItem, listItemsForUser, markAllRead, markItemRead, markItemUnread, bookmarkItem, unbookmarkItem, findItemById, } from "../feeds/repository.js";
7
8
  import { loadFullText } from "../feeds/fullText.js";
8
9
  import { loadItemChapters } from "../feeds/chapters.js";
10
+ import { mediaPositions, upsertMediaPosition } from "../feeds/mediaPosition.js";
9
11
  import { readerHtml } from "../feeds/articleContent.js";
10
12
  import { cleanSnippet } from "../feeds/contentNoise.js";
11
13
  import { fetchItemImage, pruneArchive, scheduleArchive, withArchivedImages, withProxiedImages } from "../feeds/archive.js";
@@ -47,6 +49,7 @@ itemsRouter.get("/", (req, res) => {
47
49
  const archived = withArchivedImages(listItemsForUser(req.user.id, parsed.data), origin);
48
50
  // Offline copies also get the images of articles that are not archived, through this server.
49
51
  const items = parsed.data.offline ? withProxiedImages(archived, origin) : archived;
52
+ const positions = mediaPositions(req.user.id, items.map((item) => item.id));
50
53
  res.json(items.map(({ content_lead: _lead, lead_version: _leadVersion, ...item }) => ({
51
54
  ...item,
52
55
  content_snippet: cleanSnippet(item.content_snippet, item.title),
@@ -54,6 +57,7 @@ itemsRouter.get("/", (req, res) => {
54
57
  full_content_html: readerHtml(item.full_content_html, item.title, item.author, item.link),
55
58
  read: Boolean(item.read),
56
59
  bookmarked: Boolean(item.bookmarked),
60
+ media_position: positions.get(item.id) ?? null,
57
61
  })));
58
62
  });
59
63
  const imageLimiter = rateLimit({ windowMs: 60 * 1000, limit: 600, standardHeaders: true, legacyHeaders: false });
@@ -150,4 +154,24 @@ itemsRouter.get("/:itemId/chapters", async (req, res) => {
150
154
  }
151
155
  res.json({ chapters: result.chapters });
152
156
  });
157
+ const mediaPositionSchema = z.object({
158
+ positionSeconds: z.number().min(0).max(864_000),
159
+ durationSeconds: z.number().min(0).max(864_000).nullable().optional(),
160
+ completed: z.boolean().optional(),
161
+ updatedAt: z.string().datetime().optional(),
162
+ });
163
+ itemsRouter.put("/:itemId/media-position", requireCapability("sync"), (req, res) => {
164
+ const itemId = Number(req.params.itemId);
165
+ if (!Number.isInteger(itemId) || itemId <= 0 || !canAccessItem(req.user.id, itemId)) {
166
+ res.status(404).json({ error: "item_not_found" });
167
+ return;
168
+ }
169
+ const parsed = mediaPositionSchema.safeParse(req.body ?? {});
170
+ if (!parsed.success) {
171
+ res.status(400).json({ error: "invalid_input", details: parsed.error.flatten() });
172
+ return;
173
+ }
174
+ const saved = upsertMediaPosition(req.user.id, itemId, parsed.data);
175
+ res.json({ itemId, ...saved });
176
+ });
153
177
  //# sourceMappingURL=items.js.map
@@ -22,6 +22,7 @@ import { MAX_SUBSCRIPTION_BATCH, fetchStatusFor, subscribeBatch } from "../../fe
22
22
  import { buildOverview } from "../../mcp/digest.js";
23
23
  import { decodeCursor, encodeCursor } from "../../mcp/items.js";
24
24
  import { readingPositions, serializeItem, serializeSubscriptionDetail } from "./serialize.js";
25
+ import { mediaPositions, upsertMediaPosition } from "../../feeds/mediaPosition.js";
25
26
  import { dismissEdition, editionCandidates, ensureEditionSchema, getEdition, getEditionState } from "../../native/editions.js";
26
27
  import { getEditionFeedback, resetEditionFeedback, setEditionFeedback } from "../../native/editionFeedback.js";
27
28
  import { getNativePreferences, patchNativePreferences } from "../../native/preferences.js";
@@ -169,6 +170,27 @@ resourcesRouter.post("/subscriptions/:id/refresh", requireCapability("sync"), as
169
170
  return void res.status(404).json({ error: "not_found" });
170
171
  res.json(result);
171
172
  });
173
+ resourcesRouter.post("/subscriptions/:id/accept-move", requireCapability("sync"), async (req, res) => {
174
+ const id = Number(req.params.id);
175
+ const existing = findSubscriptionForUser(req.user.id, id);
176
+ if (!existing)
177
+ return void res.status(404).json({ error: "not_found" });
178
+ if (!existing.suggested_url)
179
+ return void res.status(404).json({ error: "no_suggested_url" });
180
+ try {
181
+ const moved = await changeFeedUrl(req.user.id, id, existing.suggested_url);
182
+ res.json({ subscription: subscriptionOf(req.user.id, moved.subscription.id) });
183
+ }
184
+ catch (error) {
185
+ if (error instanceof MultipleFeedsFoundError)
186
+ return void res.status(409).json({ error: "multiple_feeds_found", feeds: error.feeds });
187
+ if (error instanceof SsrfBlockedError)
188
+ return void res.status(400).json(blockedUrlBody(error));
189
+ if (error instanceof FeedError)
190
+ return void res.status(error.message === "not_subscribed" ? 404 : 400).json({ error: error.message });
191
+ res.status(400).json({ error: "invalid_feed", message: error instanceof Error ? error.message : String(error) });
192
+ }
193
+ });
172
194
  resourcesRouter.post("/refresh", requireCapability("sync"), async (req, res) => {
173
195
  const subscriptions = listSubscriptionsForUser(req.user.id);
174
196
  const { newItems, errors, deferred } = await pollFeeds(subscriptions);
@@ -367,11 +389,12 @@ resourcesRouter.get("/search", requireCapability("search.fts"), (req, res) => {
367
389
  offset: query.offset,
368
390
  });
369
391
  const progress = readingPositions(req.user.id, rows.map((row) => row.id));
392
+ const mediaProgress = mediaPositions(req.user.id, rows.map((row) => row.id));
370
393
  const hasNotes = itemsWithNotes(req.user.id, rows.map((row) => row.id));
371
394
  res.json({
372
395
  query: query.q,
373
396
  total,
374
- items: prepare(rows, req, query.images, withContent).map((row) => serializeItem(row, progress, withContent, hasNotes.has(row.id))),
397
+ items: prepare(rows, req, query.images, withContent).map((row) => serializeItem(row, progress, withContent, hasNotes.has(row.id), mediaProgress)),
375
398
  });
376
399
  });
377
400
  resourcesRouter.get("/items", (req, res) => {
@@ -403,9 +426,10 @@ resourcesRouter.get("/items", (req, res) => {
403
426
  const hasMore = rows.length > limit;
404
427
  const page = rows.slice(0, limit);
405
428
  const progress = readingPositions(req.user.id, page.map((row) => row.id));
429
+ const mediaProgress = mediaPositions(req.user.id, page.map((row) => row.id));
406
430
  const hasNotes = itemsWithNotes(req.user.id, page.map((row) => row.id));
407
431
  res.json({
408
- items: prepare(page, req, query.images, withContent).map((row) => serializeItem(row, progress, withContent, hasNotes.has(row.id))),
432
+ items: prepare(page, req, query.images, withContent).map((row) => serializeItem(row, progress, withContent, hasNotes.has(row.id), mediaProgress)),
409
433
  newestCursor: page[0] ? encodeCursor(page[0]) : null,
410
434
  nextCursor: hasMore && page.length ? encodeCursor(page[page.length - 1]) : null,
411
435
  });
@@ -419,8 +443,9 @@ resourcesRouter.get("/items/bundle", (req, res) => {
419
443
  const byId = new Map(findItemsForUser(req.user.id, ids).map((row) => [row.id, row]));
420
444
  const rows = ids.map((id) => byId.get(id)).filter((row) => Boolean(row));
421
445
  const progress = readingPositions(req.user.id, rows.map((row) => row.id));
446
+ const mediaProgress = mediaPositions(req.user.id, rows.map((row) => row.id));
422
447
  const hasNotes = itemsWithNotes(req.user.id, rows.map((row) => row.id));
423
- res.json({ items: prepare(rows, req, parsed.data.images, true).map((row) => serializeItem(row, progress, true, hasNotes.has(row.id))) });
448
+ res.json({ items: prepare(rows, req, parsed.data.images, true).map((row) => serializeItem(row, progress, true, hasNotes.has(row.id), mediaProgress)) });
424
449
  });
425
450
  // Explicit extraction side effect; read-only devices continue to consume the shared cache.
426
451
  resourcesRouter.post("/items/prepare", requireCapability("fulltext"), async (req, res) => {
@@ -444,8 +469,9 @@ resourcesRouter.get("/items/:id", (req, res) => {
444
469
  if (!row)
445
470
  return void res.status(404).json({ error: "item_not_found" });
446
471
  const progress = readingPositions(req.user.id, [row.id]);
472
+ const mediaProgress = mediaPositions(req.user.id, [row.id]);
447
473
  const hasNotes = itemsWithNotes(req.user.id, [row.id]);
448
- res.json(serializeItem(prepare([row], req, parsed.data.images)[0], progress, true, hasNotes.has(row.id)));
474
+ res.json(serializeItem(prepare([row], req, parsed.data.images)[0], progress, true, hasNotes.has(row.id), mediaProgress));
449
475
  });
450
476
  resourcesRouter.get("/items/:id/chapters", async (req, res) => {
451
477
  const id = Number(req.params.id);
@@ -458,6 +484,23 @@ resourcesRouter.get("/items/:id/chapters", async (req, res) => {
458
484
  return void res.status(502).json({ error: "chapters_unavailable" });
459
485
  res.json({ chapters: result.chapters });
460
486
  });
487
+ const mediaPositionSchema = z.object({
488
+ positionSeconds: z.number().min(0).max(864_000),
489
+ durationSeconds: z.number().min(0).max(864_000).nullable().optional(),
490
+ completed: z.boolean().optional(),
491
+ updatedAt: z.string().datetime().optional(),
492
+ });
493
+ resourcesRouter.put("/items/:id/media-position", requireCapability("sync"), (req, res) => {
494
+ const id = Number(req.params.id);
495
+ if (!Number.isInteger(id) || id <= 0 || !canAccessItem(req.user.id, id)) {
496
+ return void res.status(404).json({ error: "item_not_found" });
497
+ }
498
+ const parsed = mediaPositionSchema.safeParse(req.body ?? {});
499
+ if (!parsed.success)
500
+ return invalid(res, parsed.error.flatten());
501
+ const saved = upsertMediaPosition(req.user.id, id, parsed.data);
502
+ res.json({ itemId: id, ...saved });
503
+ });
461
504
  resourcesRouter.post("/items/:id/full-text", requireCapability("fulltext"), async (req, res) => {
462
505
  const id = Number(req.params.id);
463
506
  const result = await loadFullText(req.user.id, id, { force: req.query.force === "true" });
@@ -465,8 +508,9 @@ resourcesRouter.post("/items/:id/full-text", requireCapability("fulltext"), asyn
465
508
  return void res.status(FULL_TEXT_STATUS[result.error]).json({ error: result.error, ...(result.error === "capability_not_available" ? { capability: "fulltext" } : {}), ...(result.message ? { message: result.message } : {}) });
466
509
  }
467
510
  const row = findItemForUser(req.user.id, id);
511
+ const mediaProgress = mediaPositions(req.user.id, [id]);
468
512
  const hasNotes = itemsWithNotes(req.user.id, [id]);
469
- res.json(serializeItem(prepare([row], req, req.query.images === "proxy" ? "proxy" : "original")[0], readingPositions(req.user.id, [id]), true, hasNotes.has(id)));
513
+ res.json(serializeItem(prepare([row], req, req.query.images === "proxy" ? "proxy" : "original")[0], readingPositions(req.user.id, [id]), true, hasNotes.has(id), mediaProgress));
470
514
  });
471
515
  const readAllSchema = z.object({ subscriptionId: z.number().int().positive().optional(), folderId: z.number().int().positive().optional() });
472
516
  resourcesRouter.post("/items/read-all", requireCapability("sync"), (req, res) => {
@@ -563,11 +607,12 @@ function editionResponse(req, edition) {
563
607
  .map((id) => byId.get(id))
564
608
  .filter((row) => Boolean(row));
565
609
  const progress = readingPositions(req.user.id, rows.map((r) => r.id));
610
+ const mediaProgress = mediaPositions(req.user.id, rows.map((r) => r.id));
566
611
  const hasNotes = itemsWithNotes(req.user.id, rows.map((r) => r.id));
567
612
  const prepared = prepare(rows, req, req.query.images === "proxy" ? "proxy" : "original", false);
568
613
  return {
569
614
  ...edition,
570
- items: prepared.map((row) => serializeItem(row, progress, false, hasNotes.has(row.id))),
615
+ items: prepared.map((row) => serializeItem(row, progress, false, hasNotes.has(row.id), mediaProgress)),
571
616
  };
572
617
  }
573
618
  function nativeAction(res, action) {
@@ -676,8 +721,9 @@ resourcesRouter.post("/inbox", requireCapability("inbox"), async (req, res) => {
676
721
  try {
677
722
  const result = await saveToInbox(req.user.id, parsed.data);
678
723
  const progress = readingPositions(req.user.id, [result.itemId]);
724
+ const mediaProgress = mediaPositions(req.user.id, [result.itemId]);
679
725
  const prepared = prepare([result.item], req, "original");
680
- res.status(201).json(serializeItem(prepared[0], progress, true, result.hasNote));
726
+ res.status(201).json(serializeItem(prepared[0], progress, true, result.hasNote, mediaProgress));
681
727
  }
682
728
  catch (error) {
683
729
  if (error instanceof SsrfBlockedError) {
@@ -13,6 +13,7 @@ export function serializeSubscriptionDetail(subscription) {
13
13
  lastSuccessAt: subscription.last_success_at,
14
14
  lastError: subscription.last_error,
15
15
  consecutiveErrors: subscription.consecutive_errors,
16
+ suggestedUrl: subscription.suggested_url ?? null,
16
17
  };
17
18
  }
18
19
  export function readingPositions(userId, itemIds) {
@@ -23,7 +24,7 @@ export function readingPositions(userId, itemIds) {
23
24
  .all(userId, ...itemIds);
24
25
  return new Map(rows.map((row) => [row.item_id, row.position]));
25
26
  }
26
- export function serializeItem(row, progress, withContent, hasNote = false) {
27
+ export function serializeItem(row, progress, withContent, hasNote = false, mediaProgress) {
27
28
  return {
28
29
  id: row.id,
29
30
  subscriptionId: row.feed_id,
@@ -51,6 +52,7 @@ export function serializeItem(row, progress, withContent, hasNote = false) {
51
52
  savedAt: row.bookmarked_at ?? null,
52
53
  archivedAt: row.archived_at ?? null,
53
54
  progress: progress.get(row.id) ?? null,
55
+ mediaPosition: mediaProgress?.get(row.id) ?? null,
54
56
  hasNote,
55
57
  },
56
58
  };
@@ -0,0 +1,13 @@
1
+ CREATE TABLE IF NOT EXISTS item_media_positions (
2
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
3
+ item_id INTEGER NOT NULL REFERENCES items(id) ON DELETE CASCADE,
4
+ position_seconds INTEGER NOT NULL DEFAULT 0,
5
+ duration_seconds INTEGER,
6
+ completed INTEGER NOT NULL DEFAULT 0,
7
+ updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
8
+ PRIMARY KEY (user_id, item_id)
9
+ );
10
+ CREATE INDEX IF NOT EXISTS idx_item_media_positions_user_updated ON item_media_positions(user_id, updated_at);
11
+
12
+ ALTER TABLE feeds ADD COLUMN suggested_url TEXT;
13
+ ALTER TABLE feeds ADD COLUMN suggested_url_checked_at TEXT;
@@ -100,6 +100,8 @@ async function validateUrl(url, signal) {
100
100
  // its first slot in the shared gate, so a busy gate cannot use it up; waiting for a slot has its own limit (the poll attempt deadline).
101
101
  async function downloadPublic(url, opts) {
102
102
  let currentUrl = url;
103
+ let permanentChain = true;
104
+ let permanentRedirectUrl;
103
105
  const controller = new AbortController();
104
106
  const settings = readPollSettings();
105
107
  let timeout;
@@ -133,14 +135,27 @@ async function downloadPublic(url, opts) {
133
135
  feedRequests.defer(host, rateLimitUntil);
134
136
  if (response.status === 304) {
135
137
  await response.body?.cancel();
136
- return { notModified: true, buffer: Buffer.alloc(0), finalUrl: currentUrl, contentType: response.headers.get("content-type") ?? undefined };
138
+ return {
139
+ notModified: true,
140
+ buffer: Buffer.alloc(0),
141
+ finalUrl: currentUrl,
142
+ contentType: response.headers.get("content-type") ?? undefined,
143
+ ...(permanentRedirectUrl && permanentRedirectUrl !== url ? { permanentRedirectUrl } : {}),
144
+ };
137
145
  }
138
146
  if (response.status >= 300 && response.status < 400) {
139
147
  const location = response.headers.get("location");
140
148
  await response.body?.cancel();
141
149
  if (!location)
142
150
  throw new Error("Redirect without a Location header");
143
- currentUrl = new URL(location, validated).toString();
151
+ const nextUrl = new URL(location, validated).toString();
152
+ if (permanentChain && (response.status === 301 || response.status === 308)) {
153
+ permanentRedirectUrl = nextUrl;
154
+ }
155
+ else {
156
+ permanentChain = false;
157
+ }
158
+ currentUrl = nextUrl;
144
159
  continue;
145
160
  }
146
161
  if (!response.ok) {
@@ -179,6 +194,7 @@ async function downloadPublic(url, opts) {
179
194
  contentType: response.headers.get("content-type") ?? undefined,
180
195
  etag: response.headers.get("etag") ?? undefined,
181
196
  lastModified: response.headers.get("last-modified") ?? undefined, finalUrl: currentUrl,
197
+ ...(permanentRedirectUrl && permanentRedirectUrl !== url ? { permanentRedirectUrl } : {}),
182
198
  };
183
199
  }
184
200
  finally {
@@ -204,7 +220,13 @@ export async function fetchFeed(url, opts = {}) {
204
220
  priority: opts.priority,
205
221
  });
206
222
  if (download.notModified) {
207
- return { notModified: true, body: "", finalUrl: download.finalUrl, contentType: download.contentType };
223
+ return {
224
+ notModified: true,
225
+ body: "",
226
+ finalUrl: download.finalUrl,
227
+ contentType: download.contentType,
228
+ ...(download.permanentRedirectUrl ? { permanentRedirectUrl: download.permanentRedirectUrl } : {}),
229
+ };
208
230
  }
209
231
  return {
210
232
  body: decodeFeedBuffer(download.buffer, download.contentType),
@@ -213,6 +235,7 @@ export async function fetchFeed(url, opts = {}) {
213
235
  lastModified: download.lastModified,
214
236
  contentType: download.contentType,
215
237
  finalUrl: download.finalUrl,
238
+ ...(download.permanentRedirectUrl ? { permanentRedirectUrl: download.permanentRedirectUrl } : {}),
216
239
  };
217
240
  }
218
241
  /** Downloads an image for the archive; the caller checks the file signature. */
@@ -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