From e8cca7c93c6e1b685e537d51c71999daa1109496 Mon Sep 17 00:00:00 2001 From: Frank Boucher <2404846+fboucher@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:05:19 -0500 Subject: [PATCH 1/3] Enhances Feed Management, Background Refresh & Resilience (#254) * fix(#173): use Id ?? RowKey for checking and opening offline post HTML (#179) * feat(#176): add sync progress bar and status updates for downloading offline post text (#180) * should have done that long ago * fix: resolve Android MAUI app crash when opening URLs (issue #177) (#181) * feat: add up/down reordering for categories and notes in summary editor (issue #92) (#183) Co-authored-by: Frank Boucher <2404846+fboucher@users.noreply.github.com> * feat: add text size slider and fix text wrapping on offline reader page (issue #178) (#182) * bumb version * feat: implement async background post content extraction to save HTML in blob storage (#185) Co-authored-by: fboucher-os * feat: improve sync html download, always display read post button, and remove ILocalHtmlCache (#186) * feat: implement async background post content extraction to save HTML in blob storage * feat: improve sync html download, always display read post button, and remove ILocalHtmlCache * feat: configure protected Azure Function Parser API and key propagation (#187) * feat: configure protected Azure Function Parser API and key propagation * bump: version to 1.4.0 --------- Co-authored-by: fboucher-os * update missing env variable * fix * chore: bump version to 1.4.1 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(#190): update actions/cache to v5 for Node.js 24 compatibility in OpenCode triage workflow (#191) * Update version to 1.4.2, add sync progress tracking, and reader page controls (#192) * chore: bump version to 1.4.2 * feat: show detailed sync progress messages and progress bar on Posts page * feat: add back button and text size slider at both top and bottom of reader page * ci: include version in android apk filename (#193) Co-authored-by: fboucher-os * Fix document sync stuck and improve sync progress and offline fallback (fixes #196) (#199) * fix: constrain reader text size slider and add step buttons (fixes #195) (#198) * feat: Add markdown saving for reading notes and bump version to 1.4.3 * feat: add MAUI storage tab (#200) * feat: add MAUI storage tab for offline posts Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix: refine MAUI storage controls Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix: highlight storage actions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * chore: bump application version to 1.4.3 (#201) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(ci): fix timeout and rate limit failures in OpenCode Daily Triage workflow (#204) (#205) * v1.4.3 - Enhances MAUI sync, local storage, and reader (#202) * fix(#173): use Id ?? RowKey for checking and opening offline post HTML (#179) * feat(#176): add sync progress bar and status updates for downloading offline post text (#180) * should have done that long ago * fix: resolve Android MAUI app crash when opening URLs (issue #177) (#181) * feat: add up/down reordering for categories and notes in summary editor (issue #92) (#183) Co-authored-by: Frank Boucher <2404846+fboucher@users.noreply.github.com> * feat: add text size slider and fix text wrapping on offline reader page (issue #178) (#182) * bumb version * feat: implement async background post content extraction to save HTML in blob storage (#185) Co-authored-by: fboucher-os * feat: improve sync html download, always display read post button, and remove ILocalHtmlCache (#186) * feat: implement async background post content extraction to save HTML in blob storage * feat: improve sync html download, always display read post button, and remove ILocalHtmlCache * feat: configure protected Azure Function Parser API and key propagation (#187) * feat: configure protected Azure Function Parser API and key propagation * bump: version to 1.4.0 --------- Co-authored-by: fboucher-os * update missing env variable * fix * chore: bump version to 1.4.1 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(#190): update actions/cache to v5 for Node.js 24 compatibility in OpenCode triage workflow (#191) * Update version to 1.4.2, add sync progress tracking, and reader page controls (#192) * chore: bump version to 1.4.2 * feat: show detailed sync progress messages and progress bar on Posts page * feat: add back button and text size slider at both top and bottom of reader page * ci: include version in android apk filename (#193) Co-authored-by: fboucher-os * Fix document sync stuck and improve sync progress and offline fallback (fixes #196) (#199) * fix: constrain reader text size slider and add step buttons (fixes #195) (#198) * feat: Add markdown saving for reading notes and bump version to 1.4.3 * feat: add MAUI storage tab (#200) * feat: add MAUI storage tab for offline posts Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix: refine MAUI storage controls Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix: highlight storage actions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * chore: bump application version to 1.4.3 (#201) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: fboucher-os Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(ci): prevent timeout and rate limits in opencode daily triage (#204) --------- Co-authored-by: Frank Boucher <2404846+fboucher@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * feat(ui): add dedicated quickadd popup and MinimalLayout for bookmarklet (#203) (#207) * v1.4.3 - Enhances MAUI sync, local storage, and reader (#202) * fix(#173): use Id ?? RowKey for checking and opening offline post HTML (#179) * feat(#176): add sync progress bar and status updates for downloading offline post text (#180) * should have done that long ago * fix: resolve Android MAUI app crash when opening URLs (issue #177) (#181) * feat: add up/down reordering for categories and notes in summary editor (issue #92) (#183) Co-authored-by: Frank Boucher <2404846+fboucher@users.noreply.github.com> * feat: add text size slider and fix text wrapping on offline reader page (issue #178) (#182) * bumb version * feat: implement async background post content extraction to save HTML in blob storage (#185) Co-authored-by: fboucher-os * feat: improve sync html download, always display read post button, and remove ILocalHtmlCache (#186) * feat: implement async background post content extraction to save HTML in blob storage * feat: improve sync html download, always display read post button, and remove ILocalHtmlCache * feat: configure protected Azure Function Parser API and key propagation (#187) * feat: configure protected Azure Function Parser API and key propagation * bump: version to 1.4.0 --------- Co-authored-by: fboucher-os * update missing env variable * fix * chore: bump version to 1.4.1 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(#190): update actions/cache to v5 for Node.js 24 compatibility in OpenCode triage workflow (#191) * Update version to 1.4.2, add sync progress tracking, and reader page controls (#192) * chore: bump version to 1.4.2 * feat: show detailed sync progress messages and progress bar on Posts page * feat: add back button and text size slider at both top and bottom of reader page * ci: include version in android apk filename (#193) Co-authored-by: fboucher-os * Fix document sync stuck and improve sync progress and offline fallback (fixes #196) (#199) * fix: constrain reader text size slider and add step buttons (fixes #195) (#198) * feat: Add markdown saving for reading notes and bump version to 1.4.3 * feat: add MAUI storage tab (#200) * feat: add MAUI storage tab for offline posts Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix: refine MAUI storage controls Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix: highlight storage actions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * chore: bump application version to 1.4.3 (#201) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: fboucher-os Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Fixes CI timeout and rate limits in triage workflow (#206) * fix(#173): use Id ?? RowKey for checking and opening offline post HTML (#179) * feat(#176): add sync progress bar and status updates for downloading offline post text (#180) * should have done that long ago * fix: resolve Android MAUI app crash when opening URLs (issue #177) (#181) * feat: add up/down reordering for categories and notes in summary editor (issue #92) (#183) Co-authored-by: Frank Boucher <2404846+fboucher@users.noreply.github.com> * feat: add text size slider and fix text wrapping on offline reader page (issue #178) (#182) * bumb version * feat: implement async background post content extraction to save HTML in blob storage (#185) Co-authored-by: fboucher-os * feat: improve sync html download, always display read post button, and remove ILocalHtmlCache (#186) * feat: implement async background post content extraction to save HTML in blob storage * feat: improve sync html download, always display read post button, and remove ILocalHtmlCache * feat: configure protected Azure Function Parser API and key propagation (#187) * feat: configure protected Azure Function Parser API and key propagation * bump: version to 1.4.0 --------- Co-authored-by: fboucher-os * update missing env variable * fix * chore: bump version to 1.4.1 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(#190): update actions/cache to v5 for Node.js 24 compatibility in OpenCode triage workflow (#191) * Update version to 1.4.2, add sync progress tracking, and reader page controls (#192) * chore: bump version to 1.4.2 * feat: show detailed sync progress messages and progress bar on Posts page * feat: add back button and text size slider at both top and bottom of reader page * ci: include version in android apk filename (#193) Co-authored-by: fboucher-os * Fix document sync stuck and improve sync progress and offline fallback (fixes #196) (#199) * fix: constrain reader text size slider and add step buttons (fixes #195) (#198) * feat: Add markdown saving for reading notes and bump version to 1.4.3 * feat: add MAUI storage tab (#200) * feat: add MAUI storage tab for offline posts Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix: refine MAUI storage controls Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix: highlight storage actions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * chore: bump application version to 1.4.3 (#201) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(ci): fix timeout and rate limit failures in OpenCode Daily Triage workflow (#204) (#205) * v1.4.3 - Enhances MAUI sync, local storage, and reader (#202) * fix(#173): use Id ?? RowKey for checking and opening offline post HTML (#179) * feat(#176): add sync progress bar and status updates for downloading offline post text (#180) * should have done that long ago * fix: resolve Android MAUI app crash when opening URLs (issue #177) (#181) * feat: add up/down reordering for categories and notes in summary editor (issue #92) (#183) Co-authored-by: Frank Boucher <2404846+fboucher@users.noreply.github.com> * feat: add text size slider and fix text wrapping on offline reader page (issue #178) (#182) * bumb version * feat: implement async background post content extraction to save HTML in blob storage (#185) Co-authored-by: fboucher-os * feat: improve sync html download, always display read post button, and remove ILocalHtmlCache (#186) * feat: implement async background post content extraction to save HTML in blob storage * feat: improve sync html download, always display read post button, and remove ILocalHtmlCache * feat: configure protected Azure Function Parser API and key propagation (#187) * feat: configure protected Azure Function Parser API and key propagation * bump: version to 1.4.0 --------- Co-authored-by: fboucher-os * update missing env variable * fix * chore: bump version to 1.4.1 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(#190): update actions/cache to v5 for Node.js 24 compatibility in OpenCode triage workflow (#191) * Update version to 1.4.2, add sync progress tracking, and reader page controls (#192) * chore: bump version to 1.4.2 * feat: show detailed sync progress messages and progress bar on Posts page * feat: add back button and text size slider at both top and bottom of reader page * ci: include version in android apk filename (#193) Co-authored-by: fboucher-os * Fix document sync stuck and improve sync progress and offline fallback (fixes #196) (#199) * fix: constrain reader text size slider and add step buttons (fixes #195) (#198) * feat: Add markdown saving for reading notes and bump version to 1.4.3 * feat: add MAUI storage tab (#200) * feat: add MAUI storage tab for offline posts Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix: refine MAUI storage controls Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix: highlight storage actions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * chore: bump application version to 1.4.3 (#201) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: fboucher-os Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(ci): prevent timeout and rate limits in opencode daily triage (#204) --------- Co-authored-by: Frank Boucher <2404846+fboucher@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: fboucher-os Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * feat(ui): add browser bookmarklet support for saving URLs (#203) * feat(ui): add dedicated quickadd popup and MinimalLayout for bookmarklet (#203) --------- Co-authored-by: Frank Boucher <2404846+fboucher@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Speed up MAUI app sync (#208) (#209) * Speed up MAUI sync: delta pull, batched saves, off-UI-thread (#208) - Pull only posts modified since the last sync; detect server deletions with a new lightweight GET api/posts/ids endpoint (falls back to the full list on first sync or on servers without the endpoint). - Save pulled posts in one SQLite transaction and remove deleted posts in one batch. - Fetch full details for unread posts with at most 5 concurrent requests. - Run sync on the thread pool and throttle progress events to ~250 ms. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Kq68qA7Jv7puAF3Kc6GSFY * Restore CRLF line endings in LocalDataService and PostNoteClient Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Kq68qA7Jv7puAF3Kc6GSFY --------- Co-authored-by: Claude * chore: bump application version to 1.4.4 Co-Authored-By: Claude Opus 5.5 * Fix bookmarklet saving the same post twice (#211) (#212) The Quick Add page is rendered with InteractiveServer and prerendering, so two component instances ran OnParametersSetAsync and each called ExtractPostDetailsAndSave, which mints a new RowKey per call. - QuickAdd skips the save while prerendering (RendererInfo.IsInteractive) and shows the progress spinner; the interactive render does the save. - The extractPostDetails endpoint returns the existing post when one is already stored for the URL, so repeat requests never add a duplicate. Claude-Session: https://claude.ai/code/session_014Yup1wuZFURs47VNTrAK7g Co-authored-by: Claude * Add offline news and updates to home page (#214) * Add offline news feed to home page Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Address review feedback on the news feed - Register NewsFeedService once as a singleton through an explicit factory, so DI no longer has to pick between two constructors and sync and the home page share a single refresh lock and cache. - Discover and rewrite images from Markdig's parse tree instead of a regex, which adds reference-style images and paths with parentheses and ignores image syntax inside code blocks. - Raise FeedUpdated after a successful refresh and reload the home page feed when it fires, so content downloaded by sync shows up without navigating away. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01HjU7ggv2Jnx9sqVXACepgC --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Claude * Add workflow to check versions match release tag (#218) * Add workflow to check versions match release tag (#217) Fails when Directory.Build.props, the Blazor csproj, or the MAUI csproj (Version and ApplicationDisplayVersion) don't match the v* tag. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01AMesZ45rYbUa63fA5MZDio * Check out the requested tag on manual version checks Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01AMesZ45rYbUa63fA5MZDio --------- Co-authored-by: Claude * Read news feed from main branch (#221) (#222) Release notes in docs/news.md and docs/assets/ are updated on main, so the app was showing only the placeholder when reading from v-next. Add a test that pins both URLs. Claude-Session: https://claude.ai/code/session_0196uTHP3Q8Gegu4SCDXV2HW Co-authored-by: Claude * doc: document AI provider configuration (#216) (#223) Add docs/ai-provider-setup.md with OpenCode, OpenRouter and Ollama examples, the /v1 Base URL rule and the settings precedence. Replace Reka examples in the Settings page, .env-sample, compose file and AppHost sample config with generic AiApiKey/AiBaseUrl/AiModelName settings (REKA_API_KEY still works). Treat empty config values as missing so unset compose variables fall back correctly. Claude-Session: https://claude.ai/code/session_01RmvEuV5wuapUH2RHeMRrWR Co-authored-by: Claude * feat(web-app): add News & Updates section to Blazor home page (#219) (#224) * chore: bump application version to 1.4.6 (#225) * Feeds tab: read RSS feeds in groups, preview and add articles as Posts (#236) * Add feeds data model, storage and API (#231) First part of the Feeds tab (#230): FeedGroup, Feed and FeedItemState domain types, Azure Table storage (FeedGroups, Feeds, FeedItemStates) and api/feeds endpoints for groups, feeds and Added/Skipped item state. Skipped records older than 60 days are pruned when states are listed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RmvEuU4c1z8w9onm9taU73 * Fetch feed items on demand with cache and per-feed errors (#232) GET api/feeds/items returns pending items, newest first, for all feeds, one group or one feed. Feeds download in parallel (max 8) with a 10 s timeout each and a 15 minute in-memory cache; refresh=true bypasses it. A failing feed reports its error while the others still load. Items older than 30 days, already Added/Skipped, already saved as Posts, or duplicated across feeds are hidden. Feed HTML is sanitized with an allow-list before it reaches the UI. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RmvEuU4c1z8w9onm9taU73 * Add Manage feeds page, feed discovery and OPML import (#233) API: GET api/feeds/discover finds the feed behind a feed or site URL (); POST api/feeds/import-opml imports a Feedly style OPML (top-level folders become groups, nested folders flatten into their top-level group, known feeds are skipped). UI: IFeedService/FeedClient in SharedUI (registered in the web app only) and a /feeds/manage page to add feeds, create/rename/delete groups, move or delete feeds and upload an OPML file. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RmvEuU4c1z8w9onm9taU73 * Add the Feeds tab layout (#234) New /feeds page in SharedUI, linked from the web app's nav menu only. Left pane: "All" and the groups with pending counts, expandable to their feeds; failing feeds show a warning icon with the error as tooltip. Right pane: items newest first with title, feed, age and a one-line excerpt. Refresh bypasses the API cache for the current selection; "Mark all as skipped" skips the selected group or feed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RmvEuU4c1z8w9onm9taU73 * Add the feed item preview dialog (#235) Clicking an item on the Feeds tab opens a FluentUI dialog with the feed-provided content (source, date, author, lead image, sanitized body). Add saves the article through ExtractPostDetailsAndSave (same path as Search suggestions and QuickAdd) and marks it Added; Skip marks it Skipped; both remove it from the list. Close leaves it, and Open original opens the real URL in a new browser tab. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RmvEuU4c1z8w9onm9taU73 * Feeds tab: fixes from first real-world test - Feed list: Add and Skip buttons on each row (no need to open the preview), "Show more" paging after 100 items. - Speed with hundreds of feeds: the page shows groups at once and loads items in batches of 10 (8 in parallel). The API answers a batch after waitMs with the feeds that are ready and marks the rest Loading; the page asks for those again and they join the same download. Failures are cached for 5 minutes, the Added/Skipped/Post URL lookup for 30 s (dropped when states or posts change), downloads are capped at 48. - Clearer warnings: FeedStatus carries ErrorKind (timeout, not-found, unreachable, invalid-feed, http), TotalCount and LastPublished. Dead feeds get a red icon, temporary failures an amber one, and working feeds with no post in 6 months a clock icon, each with a sentence explaining what it means. - Preview images: lazy-loaded images (data-src, data-lazy-src, srcset) get a real src, and images load with referrerpolicy=no-referrer to get past hotlink protection. - Manage feeds: redesigned with cards, collapsible groups (collapsed by default, which fixes the freeze after importing ~300 feeds), a filter box, inline rename, and lightweight native selects to move feeds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RmvEuU4c1z8w9onm9taU73 * Create a default "My Feeds" group GET api/feeds/groups creates "My Feeds" when no group exists, so the first feed can be added right away. OPML feeds outside any folder now go to "My Feeds" too (was "Imported"). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RmvEuU4c1z8w9onm9taU73 --------- Co-authored-by: Claude * Refresh the README demo GIFs (web app and Android) (#237) * Refresh the README demo GIF of the web app Replace the outdated 57 MB tour GIF with a new 3 MB one captured from the current web app: posts, notes, reader view, feeds, summaries, settings and dark theme. Mention the Feeds section in the README. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RmvEuURCGYvbe7P53DXeGR * Add an Android app demo GIF to the README Built from a screen recording of the Android app in the emulator: home, posts, adding a note, the reader, offline mode and offline storage. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RmvEuURCGYvbe7P53DXeGR --------- Co-authored-by: Claude * chore: bump application version to 1.5.0 (#238) Web app and Android app to 1.5.0; Android versionCode 10 -> 11. Claude-Session: https://claude.ai/code/session_01RmvEuQjrKpG4ZBaAKzUMmZ Co-authored-by: Claude * Add November Feeds tab news and condense September (#240) Claude-Session: https://claude.ai/code/session_01RmvEuT4warYoCSSnMGD33e Co-authored-by: Claude * Add inline feed editing in Manage feeds (#242) (#245) Each feed row gets an Edit button that switches it to Title and Feed URL fields with Save and Cancel, like the group rename. A changed URL goes through Discover first; the discovered feed URL is saved, SiteUrl is filled only when missing, and the typed title is kept. Errors show as toasts and leave the row in edit mode. Only one row is edited at a time. Claude-Session: https://claude.ai/code/session_01RmvEuReSejLciPkx9wycDt Co-authored-by: Claude * Validate and auto-fix feeds on OPML import, and stop the shared feed circuit breaker (#247) * Opt FeedReader's HttpClient out of the shared circuit breaker (#246) AddServiceDefaults puts the standard resilience handler on every HttpClient. Its single circuit breaker opened when many dead feeds failed and then made healthy feeds on unrelated hosts fail too. The feed client now removes the resilience handlers and relies on FeedReader's own timeout, concurrency limit and per-feed error classification. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RmvEuSbnwjBPmcYd9UzEXs * Validate and auto-fix feed URLs during OPML import (#243) Each new feed in an OPML file is checked before it is saved. When its URL fails, the import tries, in order: http -> https, discovery from the outline's site URL, and appending /feed. A working URL silently replaces the OPML one (and is skipped if it is a feed already followed). Feeds that still fail are imported with their OPML URL and returned in OpmlImportResult.FailedFeeds with their error, along with a FeedsFixed count. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RmvEuSbnwjBPmcYd9UzEXs * Show a report of feeds that still fail after OPML import (#243) When the import returns failed feeds, Manage feeds opens a dialog that lists each one with its group, address and a readable error. Each feed can be fixed by editing its address (validated with Discover, saved in its group), deleted, or kept for later. The toast now mentions fixed addresses, and the web app's feed client allows long imports (10 minute timeout). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RmvEuSbnwjBPmcYd9UzEXs --------- Co-authored-by: Claude * feat: add optional scheduled background feed refresh and blob snapshot cache (fixes #244) (#248) * feat: resolve issues #249-#252 (Aspire 13.6.5, .NET 10 badge, hide empty feeds toggle, discard all failed feeds) (#253) * chore: upgrade Aspire SDK and packages to 13.6.5 (#249) * fix: update stale .NET 9 references to .NET 10 (#250) * feat: add toggle button to show or hide feeds with zero posts (#251) * feat: add Discard all and close button to OpmlImportReportDialog (#252) * chore: bump application version to 1.5.1 --------- Co-authored-by: fboucher-os Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Claude --- Directory.Build.props | 2 +- Directory.Packages.props | 26 +- docs/maui-android-dev-setup.md | 2 +- .../Domain/SettingsTests.cs | 14 + .../Endpoints/FeedEndpointsTests.cs | 32 +++ .../Endpoints/FeedImportEndpointTests.cs | 123 +++++++++ .../Endpoints/FeedItemsEndpointTests.cs | 26 ++ .../Endpoints/SettingEndpointsTests.cs | 31 +++ .../Feeds/FeedReaderResilienceTests.cs | 48 ++++ .../Feeds/FeedReaderTests.cs | 154 +++++++++++ .../Feeds/FeedRefreshBackgroundWorkerTests.cs | 159 ++++++++++++ .../Feeds/FeedUrlValidatorTests.cs | 139 ++++++++++ .../Services/DataStorageServiceTests.cs | 69 +++++ src/NoteBookmark.Api/DataStorageService.cs | 76 +++++- src/NoteBookmark.Api/FeedEndpoints.cs | 87 ++++++- src/NoteBookmark.Api/FeedReader.cs | 244 ++++++++++++++++-- .../FeedReaderServiceCollectionExtensions.cs | 23 ++ .../FeedRefreshBackgroundWorker.cs | 152 +++++++++++ src/NoteBookmark.Api/FeedUrlValidator.cs | 110 ++++++++ src/NoteBookmark.Api/IDataStorageService.cs | 6 + src/NoteBookmark.Api/Program.cs | 9 +- src/NoteBookmark.Api/SettingEndpoints.cs | 28 +- .../NoteBookmark.AppHost.csproj | 3 +- .../OpmlImportReportDialogTestWrapper.razor | 12 + .../Tests/FeedsPageTests.cs | 92 +++++++ .../Tests/ManageFeedsTests.cs | 172 ++++++++++++ .../Tests/NewsFeedServiceTests.cs | 14 + .../Tests/OpmlImportReportDialogTests.cs | 206 +++++++++++++++ .../Tests/SettingsPageTests.cs | 65 +++++ .../Components/Pages/Home.razor | 2 +- .../NoteBookmark.BlazorApp.csproj | 2 +- src/NoteBookmark.BlazorApp/Program.cs | 2 + src/NoteBookmark.Domain/FeedItem.cs | 53 ++++ src/NoteBookmark.Domain/Settings.cs | 11 + src/NoteBookmark.MauiApp/Data/LocalModels.cs | 8 +- .../NoteBookmark.MauiApp.csproj | 6 +- .../Components/Pages/Feeds.razor | 54 +++- .../Components/Pages/ManageFeeds.razor | 164 ++++++++++-- .../Components/Pages/Settings.razor | 56 +++- .../Shared/OpmlImportReportDialog.razor | 214 +++++++++++++++ src/NoteBookmark.SharedUI/OpmlImportReport.cs | 12 + 41 files changed, 2617 insertions(+), 91 deletions(-) create mode 100644 src/NoteBookmark.Api.Tests/Feeds/FeedReaderResilienceTests.cs create mode 100644 src/NoteBookmark.Api.Tests/Feeds/FeedRefreshBackgroundWorkerTests.cs create mode 100644 src/NoteBookmark.Api.Tests/Feeds/FeedUrlValidatorTests.cs create mode 100644 src/NoteBookmark.Api/FeedReaderServiceCollectionExtensions.cs create mode 100644 src/NoteBookmark.Api/FeedRefreshBackgroundWorker.cs create mode 100644 src/NoteBookmark.Api/FeedUrlValidator.cs create mode 100644 src/NoteBookmark.BlazorApp.Tests/Helpers/OpmlImportReportDialogTestWrapper.razor create mode 100644 src/NoteBookmark.BlazorApp.Tests/Tests/OpmlImportReportDialogTests.cs create mode 100644 src/NoteBookmark.BlazorApp.Tests/Tests/SettingsPageTests.cs create mode 100644 src/NoteBookmark.SharedUI/Components/Shared/OpmlImportReportDialog.razor create mode 100644 src/NoteBookmark.SharedUI/OpmlImportReport.cs diff --git a/Directory.Build.props b/Directory.Build.props index ec61f2c..953407f 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,6 +1,6 @@ - 1.5.0 + 1.5.1 net10.0 enable enable diff --git a/Directory.Packages.props b/Directory.Packages.props index 4d8d8d3..15e467e 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -1,25 +1,25 @@ - - - - - - + + + + + + - - + + - - + + - - + + @@ -41,7 +41,7 @@ - + diff --git a/docs/maui-android-dev-setup.md b/docs/maui-android-dev-setup.md index c213bee..611e467 100644 --- a/docs/maui-android-dev-setup.md +++ b/docs/maui-android-dev-setup.md @@ -25,7 +25,7 @@ java -version ## Step 2 — Install .NET MAUI Android workload -.NET 9 or 10 must already be installed. Then: +.NET 10 must already be installed. Then: ```bash dotnet workload install maui-android diff --git a/src/NoteBookmark.Api.Tests/Domain/SettingsTests.cs b/src/NoteBookmark.Api.Tests/Domain/SettingsTests.cs index b547c11..6502ae5 100644 --- a/src/NoteBookmark.Api.Tests/Domain/SettingsTests.cs +++ b/src/NoteBookmark.Api.Tests/Domain/SettingsTests.cs @@ -226,4 +226,18 @@ public void FontSize_CanBeSetAndRetrieved(string fontSize) settings.FontSize.Should().Be(fontSize); } + + [Fact] + public void FeedRefreshSettings_HaveExpectedDefaultsAndPresets() + { + var settings = new Settings + { + PartitionKey = "setting", + RowKey = "setting" + }; + + settings.FeedRefreshEnabled.Should().BeFalse(); + settings.FeedRefreshIntervalMinutes.Should().Be(60); + Settings.AllowedFeedRefreshIntervals.Should().Equal(30, 60, 180, 360, 720, 1440); + } } diff --git a/src/NoteBookmark.Api.Tests/Endpoints/FeedEndpointsTests.cs b/src/NoteBookmark.Api.Tests/Endpoints/FeedEndpointsTests.cs index 079f305..7eb648f 100644 --- a/src/NoteBookmark.Api.Tests/Endpoints/FeedEndpointsTests.cs +++ b/src/NoteBookmark.Api.Tests/Endpoints/FeedEndpointsTests.cs @@ -185,6 +185,38 @@ public async Task SaveFeed_WithExistingId_MovesFeedToAnotherGroup() feeds!.Where(f => f.RowKey == feed.RowKey).Should().ContainSingle().Which.GroupId.Should().Be(second.RowKey); } + [Fact] + public async Task SaveFeed_WithExistingId_UpdatesTitleAndUrl_WithoutDuplicating() + { + var group = await CreateGroup(); + var feed = await CreateFeed(group.RowKey); + var newUrl = $"https://example.com/{Guid.NewGuid():N}/atom"; + feed.Title = " Renamed feed "; + feed.FeedUrl = newUrl; + + var response = await _client.PostAsJsonAsync("/api/feeds/", feed); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + var feeds = await _client.GetFromJsonAsync>("/api/feeds/"); + var saved = feeds!.Where(f => f.RowKey == feed.RowKey).Should().ContainSingle().Which; + saved.Title.Should().Be("Renamed feed"); + saved.FeedUrl.Should().Be(newUrl); + saved.GroupId.Should().Be(group.RowKey); + } + + [Fact] + public async Task SaveFeed_WithExistingId_ToAnotherFeedsUrl_ReturnsConflict() + { + var group = await CreateGroup(); + var first = await CreateFeed(group.RowKey); + var second = await CreateFeed(group.RowKey); + second.FeedUrl = first.FeedUrl; + + var response = await _client.PostAsJsonAsync("/api/feeds/", second); + + response.StatusCode.Should().Be(HttpStatusCode.Conflict); + } + [Theory] [InlineData("")] [InlineData("not a url")] diff --git a/src/NoteBookmark.Api.Tests/Endpoints/FeedImportEndpointTests.cs b/src/NoteBookmark.Api.Tests/Endpoints/FeedImportEndpointTests.cs index f2f2624..82d93ef 100644 --- a/src/NoteBookmark.Api.Tests/Endpoints/FeedImportEndpointTests.cs +++ b/src/NoteBookmark.Api.Tests/Endpoints/FeedImportEndpointTests.cs @@ -37,6 +37,7 @@ public async Task ImportOpml_CreatesGroupsAndFeeds_ThenSkipsThemOnSecondImport() firstResult!.FeedsCreated.Should().Be(4); firstResult.FeedsSkipped.Should().Be(0); firstResult.GroupsCreated.Should().BeInRange(2, 3); // "My Feeds" may already exist from another test + firstResult.FailedFeeds.Should().HaveCount(4); // nothing answers at these URLs: imported and reported var secondResult = await second.Content.ReadFromJsonAsync(); secondResult!.FeedsCreated.Should().Be(0); @@ -65,6 +66,128 @@ public async Task ImportOpml_ReusesExistingGroupByName() feeds!.Should().Contain(f => f.GroupId == created!.RowKey && f.Title == "X"); } + private void Feed(string url) => _factory.Feeds.Respond(url, FeedSamples.Rss(($"{url}/1", "One", DateTimeOffset.UtcNow))); + + private async Task Import(string outlines) + { + var response = await _client.PostAsJsonAsync("/api/feeds/import-opml", + new OpmlImportRequest { Opml = $"""{outlines}""" }); + response.StatusCode.Should().Be(HttpStatusCode.OK); + return (await response.Content.ReadFromJsonAsync())!; + } + + private async Task FeedByTitle(string title) => + (await _client.GetFromJsonAsync>("/api/feeds/"))!.SingleOrDefault(f => f.Title == title); + + [Fact] + public async Task ImportOpml_HealthyFeeds_AreImportedAsIs() + { + var host = $"{Guid.NewGuid():N}.example.com"; + Feed($"https://{host}/a"); + Feed($"https://{host}/b"); + + var result = await Import($""""""); + + result.FeedsCreated.Should().Be(2); + result.FeedsFixed.Should().Be(0); + result.FailedFeeds.Should().BeEmpty(); + (await FeedByTitle($"A {host}"))!.FeedUrl.Should().Be($"https://{host}/a"); + } + + [Fact] + public async Task ImportOpml_HttpFeed_IsSavedWithHttpsUrl() + { + var host = $"{Guid.NewGuid():N}.example.com"; + Feed($"https://{host}/rss"); + + var result = await Import($""""""); + + result.FeedsCreated.Should().Be(1); + result.FeedsFixed.Should().Be(1); + result.FailedFeeds.Should().BeEmpty(); + (await FeedByTitle($"Https {host}"))!.FeedUrl.Should().Be($"https://{host}/rss"); + } + + [Fact] + public async Task ImportOpml_MovedFeed_IsFoundFromSiteUrl() + { + var host = $"{Guid.NewGuid():N}.example.com"; + _factory.Feeds.Respond($"https://{host}/", $"""""", "text/html"); + _factory.Feeds.Respond($"https://{host}/atom", FeedSamples.Atom()); + + var result = await Import($""""""); + + result.FeedsFixed.Should().Be(1); + var feed = await FeedByTitle($"Moved {host}"); + feed!.FeedUrl.Should().Be($"https://{host}/atom"); + feed.SiteUrl.Should().Be($"https://{host}/"); + } + + [Fact] + public async Task ImportOpml_SiteLikeUrl_IsFixedWithFeedSuffix() + { + var host = $"{Guid.NewGuid():N}.example.com"; + Feed($"https://{host}/dotnet/feed"); + + var result = await Import($""""""); + + result.FeedsFixed.Should().Be(1); + (await FeedByTitle($"Suffix {host}"))!.FeedUrl.Should().Be($"https://{host}/dotnet/feed"); + } + + [Fact] + public async Task ImportOpml_FixedUrlOfAFeedAlreadyFollowed_IsSkipped() + { + var host = $"{Guid.NewGuid():N}.example.com"; + Feed($"https://{host}/rss"); + var groups = await _client.GetFromJsonAsync>("/api/feeds/groups"); + var group = groups!.FirstOrDefault() ?? (await (await _client.PostAsJsonAsync("/api/feeds/groups", new FeedGroup { Name = "Any" })).Content.ReadFromJsonAsync())!; + (await _client.PostAsJsonAsync("/api/feeds/", new Feed { Title = $"Existing {host}", FeedUrl = $"https://{host}/rss", GroupId = group.RowKey })) + .StatusCode.Should().Be(HttpStatusCode.OK); + + // The http URL doesn't answer; its https fix is the feed already followed. + var result = await Import($""""""); + + result.FeedsCreated.Should().Be(0); + result.FeedsSkipped.Should().Be(1); + (await FeedByTitle($"Dup {host}")).Should().BeNull(); + } + + [Fact] + public async Task ImportOpml_TwoEntriesFixedToTheSameFeed_AreImportedOnce() + { + var host = $"{Guid.NewGuid():N}.example.com"; + Feed($"https://{host}/rss"); + + var result = await Import($""""""); + + result.FeedsCreated.Should().Be(1); + result.FeedsSkipped.Should().Be(1); + (await FeedByTitle($"First {host}"))!.FeedUrl.Should().Be($"https://{host}/rss"); + (await FeedByTitle($"Second {host}")).Should().BeNull(); + } + + [Fact] + public async Task ImportOpml_UnrecoverableFeed_IsImportedAndReported() + { + var host = $"{Guid.NewGuid():N}.example.com"; + Feed($"https://{host}/ok"); + + var result = await Import($""""""); + + result.FeedsCreated.Should().Be(2); + var failed = result.FailedFeeds.Should().ContainSingle().Which; + var saved = await FeedByTitle($"Gone {host}"); + saved!.FeedUrl.Should().Be($"https://{host}/gone"); + failed.FeedId.Should().Be(saved.RowKey); + failed.Title.Should().Be($"Gone {host}"); + failed.FeedUrl.Should().Be($"https://{host}/gone"); + failed.SiteUrl.Should().Be($"https://{host}/"); + failed.GroupName.Should().Be($"Report {host}"); + failed.ErrorKind.Should().Be(FeedErrorKind.NotFound); + failed.Error.Should().Contain("404"); + } + [Fact] public async Task ImportOpml_InvalidFile_ReturnsBadRequest() { diff --git a/src/NoteBookmark.Api.Tests/Endpoints/FeedItemsEndpointTests.cs b/src/NoteBookmark.Api.Tests/Endpoints/FeedItemsEndpointTests.cs index 37798c6..346210d 100644 --- a/src/NoteBookmark.Api.Tests/Endpoints/FeedItemsEndpointTests.cs +++ b/src/NoteBookmark.Api.Tests/Endpoints/FeedItemsEndpointTests.cs @@ -1,4 +1,5 @@ using FluentAssertions; +using Microsoft.Extensions.DependencyInjection; using NoteBookmark.Api.Tests.Feeds; using NoteBookmark.Api.Tests.Fixtures; using NoteBookmark.Domain; @@ -223,4 +224,29 @@ public async Task GetItems_UnknownGroup_ReturnsEmpty() body!.Items.Should().BeEmpty(); body.Feeds.Should().BeEmpty(); } + + [Fact] + public async Task GetItems_PersistsSnapshotInBlob_AndReturnsLastRefreshedTimestamp() + { + var group = await CreateGroup(); + var host = UniqueHost(); + var now = DateTimeOffset.UtcNow; + _factory.Feeds.Respond($"{host}/rss", FeedSamples.Rss(($"{host}/1", "Persisted item", now))); + var feed = await CreateFeed(group, $"{host}/rss"); + + var response = await GetItems($"?feedId={feed.RowKey}"); + + response!.LastRefreshed.Should().NotBeNull(); + response.Feeds.Single().FetchedAt.Should().NotBeNull(); + + using var scope = _factory.Services.CreateScope(); + var storage = scope.ServiceProvider.GetRequiredService(); + var snapshot = await storage.GetFeedSnapshot(feed.RowKey); + snapshot.Should().NotBeNull(); + snapshot!.Items.Should().ContainSingle().Which.Title.Should().Be("Persisted item"); + + // Deleting the feed removes the snapshot blob. + (await _client.DeleteAsync($"/api/feeds/{feed.RowKey}")).EnsureSuccessStatusCode(); + (await storage.GetFeedSnapshot(feed.RowKey)).Should().BeNull(); + } } diff --git a/src/NoteBookmark.Api.Tests/Endpoints/SettingEndpointsTests.cs b/src/NoteBookmark.Api.Tests/Endpoints/SettingEndpointsTests.cs index 6f7e6fd..4942752 100644 --- a/src/NoteBookmark.Api.Tests/Endpoints/SettingEndpointsTests.cs +++ b/src/NoteBookmark.Api.Tests/Endpoints/SettingEndpointsTests.cs @@ -226,6 +226,37 @@ public async Task SaveSettings_WithEmptyPartitionKey_ReturnsBadRequest() response.StatusCode.Should().Be(HttpStatusCode.BadRequest); } + [Fact] + public async Task SaveSettings_PersistsFeedRefreshSettings() + { + var settings = CreateTestSettings(); + settings.FeedRefreshEnabled = true; + settings.FeedRefreshIntervalMinutes = 180; + + var saveResponse = await _client.PostAsJsonAsync("/api/settings/SaveSettings", settings); + saveResponse.StatusCode.Should().Be(HttpStatusCode.OK); + + var saved = await _client.GetFromJsonAsync("/api/settings/"); + saved!.FeedRefreshEnabled.Should().BeTrue(); + saved.FeedRefreshIntervalMinutes.Should().Be(180); + + // Reset so other tests using the shared fixture observe the default disabled state. + settings.FeedRefreshEnabled = false; + settings.FeedRefreshIntervalMinutes = 60; + (await _client.PostAsJsonAsync("/api/settings/SaveSettings", settings)).EnsureSuccessStatusCode(); + } + + [Fact] + public async Task SaveSettings_WithInvalidFeedRefreshInterval_ReturnsBadRequest() + { + var settings = CreateTestSettings(); + settings.FeedRefreshIntervalMinutes = 15; + + var response = await _client.PostAsJsonAsync("/api/settings/SaveSettings", settings); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + } + // Helper methods private static Settings CreateTestSettings() { diff --git a/src/NoteBookmark.Api.Tests/Feeds/FeedReaderResilienceTests.cs b/src/NoteBookmark.Api.Tests/Feeds/FeedReaderResilienceTests.cs new file mode 100644 index 0000000..e68abd0 --- /dev/null +++ b/src/NoteBookmark.Api.Tests/Feeds/FeedReaderResilienceTests.cs @@ -0,0 +1,48 @@ +using System.Net; +using FluentAssertions; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using NoteBookmark.Api; +using NoteBookmark.Api.Tests.Fixtures; +using NoteBookmark.Domain; +using Xunit; + +namespace NoteBookmark.Api.Tests.Feeds; + +/// Regression tests for #246: dead feeds must not trip a circuit breaker shared with healthy feeds. +public class FeedReaderResilienceTests +{ + [Fact] + public async Task ManyFailingFeeds_DoNotBreakHealthyFeeds_WithServiceDefaults() + { + var handler = new StubFeedHandler(); + var builder = Host.CreateApplicationBuilder(); + builder.AddServiceDefaults(); // puts the standard resilience handler on every HttpClient + builder.Services.AddMemoryCache(); + builder.Services.AddFeedReader().ConfigurePrimaryHttpMessageHandler(() => handler); + using var host = builder.Build(); + var reader = (FeedReader)host.Services.GetRequiredService(); + reader.Timeout = TimeSpan.FromSeconds(2); + + // Well over the standard circuit breaker's minimum throughput (100) and failure ratio (10%). + var tag = Guid.NewGuid().ToString("N"); + var dead = Enumerable.Range(0, 150).Select(i => $"https://dead{i}-{tag}.example.com/rss").ToList(); + foreach (var url in dead) + { + handler.Respond(url, "boom", "text/plain", HttpStatusCode.InternalServerError); + } + var healthy = Enumerable.Range(0, 20).Select(i => $"https://ok{i}-{tag}.example.org/rss").ToList(); + foreach (var url in healthy) + { + handler.Respond(url, FeedSamples.Rss(($"{url}/1", "One", DateTimeOffset.UtcNow))); + } + + var failed = await Task.WhenAll(dead.Select(u => reader.FetchAsync(new Feed { FeedUrl = u }, refresh: true))); + var ok = await Task.WhenAll(healthy.Select(u => reader.FetchAsync(new Feed { FeedUrl = u }, refresh: true))); + + failed.Should().OnlyContain(r => r.ErrorKind == FeedErrorKind.Http); + ok.Should().OnlyContain(r => r.Error == null && r.Items.Count == 1); + // No retries either: the reader classifies each failure itself. + dead.Should().OnlyContain(u => handler.Hits(u) == 1); + } +} diff --git a/src/NoteBookmark.Api.Tests/Feeds/FeedReaderTests.cs b/src/NoteBookmark.Api.Tests/Feeds/FeedReaderTests.cs index f72fa5f..dea5c67 100644 --- a/src/NoteBookmark.Api.Tests/Feeds/FeedReaderTests.cs +++ b/src/NoteBookmark.Api.Tests/Feeds/FeedReaderTests.cs @@ -1,6 +1,7 @@ using FluentAssertions; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging.Abstractions; +using Moq; using NoteBookmark.Api; using NoteBookmark.Api.Tests.Fixtures; using NoteBookmark.Domain; @@ -8,6 +9,15 @@ namespace NoteBookmark.Api.Tests.Feeds; +public sealed class AdjustableTimeProvider(DateTimeOffset? start = null) : TimeProvider +{ + private DateTimeOffset _now = start ?? DateTimeOffset.UtcNow; + + public override DateTimeOffset GetUtcNow() => _now; + + public void Advance(TimeSpan delta) => _now = _now.Add(delta); +} + public class FeedReaderTests { private readonly StubFeedHandler _handler = new(); @@ -205,4 +215,148 @@ public async Task DiscoverAsync_BadOrUnreachableUrl_ReturnsNull(string url) { (await _reader.DiscoverAsync(url)).Should().BeNull(); } + + [Fact] + public async Task FetchAsync_PersistsSnapshotToStorage_OnlyWithRecentItems_AndPreservesTotalAndLastPublished() + { + const string url = "https://persist.example.com/rss"; + var now = DateTimeOffset.UtcNow; + _handler.Respond(url, FeedSamples.Rss( + ("https://persist.example.com/recent", "Recent", now.AddDays(-2)), + ("https://persist.example.com/old", "Old", now.AddDays(-45)))); + var storage = new Mock(); + FeedSnapshot? savedSnapshot = null; + storage.Setup(s => s.SaveFeedSnapshot(It.IsAny())) + .Callback(s => savedSnapshot = s) + .Returns(Task.CompletedTask); + storage.Setup(s => s.GetSettings()).ReturnsAsync(new Settings { PartitionKey = "setting", RowKey = "setting" }); + + var clock = new AdjustableTimeProvider(now); + var reader = new FeedReader(new HttpClient(_handler), new MemoryCache(new MemoryCacheOptions()), NullLogger.Instance, storage.Object, clock); + var feed = MakeFeed(url); + + var result = await reader.FetchAsync(feed, refresh: false); + + result.Items.Select(i => i.Title).Should().Equal("Recent"); + result.TotalCount.Should().Be(2); + result.NewestPublished.Should().BeCloseTo(now.AddDays(-2), TimeSpan.FromSeconds(1)); + result.FetchedAt.Should().Be(now); + + savedSnapshot.Should().NotBeNull(); + savedSnapshot!.FeedId.Should().Be(feed.RowKey); + savedSnapshot.TotalCount.Should().Be(2); + savedSnapshot.LastPublished.Should().BeCloseTo(now.AddDays(-2), TimeSpan.FromSeconds(1)); + savedSnapshot.Items.Select(i => i.Title).Should().Equal("Recent"); + } + + [Fact] + public async Task FetchAsync_TransientFailureDuringRefresh_PreservesPreviouslyStoredItems_WhileRecordingError() + { + const string url = "https://transient.example.com/rss"; + var now = DateTimeOffset.UtcNow; + _handler.Respond(url, FeedSamples.Rss(("https://transient.example.com/1", "Keep me", now.AddHours(-1)))); + + var snapshots = new Dictionary(); + var storage = new Mock(); + storage.Setup(s => s.SaveFeedSnapshot(It.IsAny())) + .Callback(s => snapshots[s.FeedId] = s) + .Returns(Task.CompletedTask); + storage.Setup(s => s.GetFeedSnapshot(It.IsAny())) + .ReturnsAsync((string id) => snapshots.GetValueOrDefault(id)); + storage.Setup(s => s.GetSettings()).ReturnsAsync(new Settings { PartitionKey = "setting", RowKey = "setting" }); + + var clock = new AdjustableTimeProvider(now); + var reader = new FeedReader(new HttpClient(_handler), new MemoryCache(new MemoryCacheOptions()), NullLogger.Instance, storage.Object, clock); + var feed = MakeFeed(url); + + var initial = await reader.FetchAsync(feed, refresh: false); + initial.Error.Should().BeNull(); + initial.Items.Should().ContainSingle().Which.Title.Should().Be("Keep me"); + + // Next refresh fails with HTTP 500 (even with a fresh memory cache simulating a restart). + _handler.Respond(url, "boom", "text/plain", System.Net.HttpStatusCode.InternalServerError); + clock.Advance(TimeSpan.FromMinutes(30)); + var readerAfterRestart = new FeedReader(new HttpClient(_handler), new MemoryCache(new MemoryCacheOptions()), NullLogger.Instance, storage.Object, clock); + + var afterFailure = await readerAfterRestart.FetchAsync(feed, refresh: true); + + afterFailure.ErrorKind.Should().Be(FeedErrorKind.Http); + afterFailure.Error.Should().Contain("500"); + afterFailure.Items.Should().ContainSingle().Which.Title.Should().Be("Keep me"); + afterFailure.TotalCount.Should().Be(1); + afterFailure.FetchedAt.Should().Be(clock.GetUtcNow()); + snapshots[feed.RowKey].Items.Should().ContainSingle().Which.Title.Should().Be("Keep me"); + snapshots[feed.RowKey].ErrorKind.Should().Be(FeedErrorKind.Http); + } + + [Fact] + public async Task FetchAsync_BackgroundRefreshEnabled_ServesSnapshotFromBlobRegardlessOfAge() + { + const string url = "https://warm.example.com/rss"; + var now = DateTimeOffset.UtcNow; + var feed = MakeFeed(url); + var storedSnapshot = new FeedSnapshot + { + FeedId = feed.RowKey, + FeedUrl = url, + FetchedAt = now.AddHours(-3), + TotalCount = 1, + LastPublished = now.AddHours(-4), + Items = [new FeedItem { Url = "https://warm.example.com/1", Title = "Cached in blob", Published = now.AddHours(-4) }] + }; + + var storage = new Mock(); + storage.Setup(s => s.GetFeedSnapshot(feed.RowKey)).ReturnsAsync(storedSnapshot); + storage.Setup(s => s.GetSettings()).ReturnsAsync(new Settings + { + PartitionKey = "setting", + RowKey = "setting", + FeedRefreshEnabled = true, + FeedRefreshIntervalMinutes = 360 + }); + + var clock = new AdjustableTimeProvider(now); + var reader = new FeedReader(new HttpClient(_handler), new MemoryCache(new MemoryCacheOptions()), NullLogger.Instance, storage.Object, clock); + + var result = await reader.FetchAsync(feed, refresh: false); + + _handler.Hits(url).Should().Be(0); + result.Items.Should().ContainSingle().Which.Title.Should().Be("Cached in blob"); + result.FetchedAt.Should().Be(now.AddHours(-3)); + } + + [Fact] + public async Task FetchAsync_BackgroundRefreshDisabled_RefreshesSnapshotOlderThan15Minutes() + { + const string url = "https://stale.example.com/rss"; + var now = DateTimeOffset.UtcNow; + _handler.Respond(url, FeedSamples.Rss(("https://stale.example.com/2", "Fresh download", now))); + var feed = MakeFeed(url); + var storedSnapshot = new FeedSnapshot + { + FeedId = feed.RowKey, + FeedUrl = url, + FetchedAt = now.AddMinutes(-16), + TotalCount = 1, + LastPublished = now.AddHours(-1), + Items = [new FeedItem { Url = "https://stale.example.com/1", Title = "Stale snapshot", Published = now.AddHours(-1) }] + }; + + var storage = new Mock(); + storage.Setup(s => s.GetFeedSnapshot(feed.RowKey)).ReturnsAsync(storedSnapshot); + storage.Setup(s => s.GetSettings()).ReturnsAsync(new Settings + { + PartitionKey = "setting", + RowKey = "setting", + FeedRefreshEnabled = false + }); + + var clock = new AdjustableTimeProvider(now); + var reader = new FeedReader(new HttpClient(_handler), new MemoryCache(new MemoryCacheOptions()), NullLogger.Instance, storage.Object, clock); + + var result = await reader.FetchAsync(feed, refresh: false); + + _handler.Hits(url).Should().Be(1); + result.Items.Should().ContainSingle().Which.Title.Should().Be("Fresh download"); + } } diff --git a/src/NoteBookmark.Api.Tests/Feeds/FeedRefreshBackgroundWorkerTests.cs b/src/NoteBookmark.Api.Tests/Feeds/FeedRefreshBackgroundWorkerTests.cs new file mode 100644 index 0000000..a4eeae7 --- /dev/null +++ b/src/NoteBookmark.Api.Tests/Feeds/FeedRefreshBackgroundWorkerTests.cs @@ -0,0 +1,159 @@ +using FluentAssertions; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using NoteBookmark.Api; +using NoteBookmark.Domain; +using Xunit; + +namespace NoteBookmark.Api.Tests.Feeds; + +public class FeedRefreshBackgroundWorkerTests +{ + private readonly Mock _storage = new(); + private readonly Mock _reader = new(); + private readonly FeedRefreshNotifier _notifier = new(); + private readonly AdjustableTimeProvider _clock = new(new DateTimeOffset(2026, 11, 14, 12, 0, 0, TimeSpan.Zero)); + private readonly IServiceProvider _serviceProvider; + private readonly FeedRefreshBackgroundWorker _worker; + + private Settings _settings = new() + { + PartitionKey = "setting", + RowKey = "setting", + FeedRefreshEnabled = false, + FeedRefreshIntervalMinutes = 60 + }; + + private readonly List _feeds = + [ + new() { RowKey = "f-1", Title = "Feed 1", FeedUrl = "https://one.example.com/rss", GroupId = "g-1" }, + new() { RowKey = "f-2", Title = "Feed 2", FeedUrl = "https://two.example.com/rss", GroupId = "g-1" } + ]; + + public FeedRefreshBackgroundWorkerTests() + { + _storage.Setup(s => s.GetSettings()).ReturnsAsync(() => _settings); + _storage.Setup(s => s.GetFeeds()).ReturnsAsync(() => _feeds); + _reader.Setup(r => r.FetchAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(new FeedFetchResult([], null)); + + var services = new ServiceCollection(); + services.AddScoped(_ => _storage.Object); + services.AddScoped(_ => _reader.Object); + _serviceProvider = services.BuildServiceProvider(); + + _worker = new FeedRefreshBackgroundWorker( + _serviceProvider, + _notifier, + NullLogger.Instance, + _clock); + } + + [Fact] + public async Task RunCycleAsync_WhenDisabled_DoesNotFetchFeeds_AndWaitsIndefinitely() + { + _settings.FeedRefreshEnabled = false; + + var delay = await _worker.RunCycleAsync(); + + delay.Should().Be(Timeout.InfiniteTimeSpan); + _reader.Verify(r => r.FetchAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task RunCycleAsync_WhenEnabledAndNeverRefreshed_RefreshesAllFeedsImmediately() + { + _settings.FeedRefreshEnabled = true; + _settings.FeedRefreshIntervalMinutes = 180; + + var delay = await _worker.RunCycleAsync(); + + delay.Should().Be(TimeSpan.FromMinutes(180)); + _reader.Verify(r => r.FetchAsync(It.Is(f => f.RowKey == "f-1"), true, It.IsAny()), Times.Once); + _reader.Verify(r => r.FetchAsync(It.Is(f => f.RowKey == "f-2"), true, It.IsAny()), Times.Once); + } + + [Fact] + public async Task RunCycleAsync_WhenFeedsRecentlyRefreshed_WaitsUntilNextDueTime() + { + _settings.FeedRefreshEnabled = true; + _settings.FeedRefreshIntervalMinutes = 60; + var fetchedAt = _clock.GetUtcNow().AddMinutes(-20); + + _storage.Setup(s => s.GetFeedSnapshot("f-1")).ReturnsAsync(new FeedSnapshot + { + FeedId = "f-1", + FeedUrl = "https://one.example.com/rss", + FetchedAt = fetchedAt + }); + _storage.Setup(s => s.GetFeedSnapshot("f-2")).ReturnsAsync(new FeedSnapshot + { + FeedId = "f-2", + FeedUrl = "https://two.example.com/rss", + FetchedAt = fetchedAt.AddMinutes(5) + }); + + var delay = await _worker.RunCycleAsync(); + + delay.Should().Be(TimeSpan.FromMinutes(40)); + _reader.Verify(r => r.FetchAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task RunCycleAsync_WhenSnapshotIsOlderThanInterval_RefreshesImmediately() + { + _settings.FeedRefreshEnabled = true; + _settings.FeedRefreshIntervalMinutes = 30; + var fetchedAt = _clock.GetUtcNow().AddMinutes(-35); + + _storage.Setup(s => s.GetFeedSnapshot(It.IsAny())).ReturnsAsync((string id) => new FeedSnapshot + { + FeedId = id, + FeedUrl = _feeds.Single(f => f.RowKey == id).FeedUrl, + FetchedAt = fetchedAt + }); + + var delay = await _worker.RunCycleAsync(); + + delay.Should().Be(TimeSpan.FromMinutes(30)); + _reader.Verify(r => r.FetchAsync(It.IsAny(), true, It.IsAny()), Times.Exactly(2)); + } + + [Fact] + public async Task BackgroundService_WakesUpImmediatelyWhenSettingsChange() + { + _settings.FeedRefreshEnabled = false; + var refreshedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var refreshCount = 0; + _reader.Setup(r => r.FetchAsync(It.IsAny(), true, It.IsAny())) + .Callback(() => + { + if (Interlocked.Increment(ref refreshCount) >= _feeds.Count) + { + refreshedTcs.TrySetResult(); + } + }) + .ReturnsAsync(new FeedFetchResult([], null)); + + await _worker.StartAsync(CancellationToken.None); + try + { + // Initially disabled: no refresh occurs. + await Task.Delay(50); + refreshCount.Should().Be(0); + + // Enable background refresh and notify the worker without restarting it. + _settings.FeedRefreshEnabled = true; + _settings.FeedRefreshIntervalMinutes = 60; + _notifier.NotifySettingsChanged(); + + await refreshedTcs.Task.WaitAsync(TimeSpan.FromSeconds(2)); + refreshCount.Should().Be(2); + } + finally + { + await _worker.StopAsync(CancellationToken.None); + } + } +} diff --git a/src/NoteBookmark.Api.Tests/Feeds/FeedUrlValidatorTests.cs b/src/NoteBookmark.Api.Tests/Feeds/FeedUrlValidatorTests.cs new file mode 100644 index 0000000..a03295d --- /dev/null +++ b/src/NoteBookmark.Api.Tests/Feeds/FeedUrlValidatorTests.cs @@ -0,0 +1,139 @@ +using System.Net; +using FluentAssertions; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Logging.Abstractions; +using NoteBookmark.Api; +using NoteBookmark.Api.Tests.Fixtures; +using NoteBookmark.Domain; +using Xunit; + +namespace NoteBookmark.Api.Tests.Feeds; + +public class FeedUrlValidatorTests +{ + private readonly StubFeedHandler _handler = new(); + private readonly FeedUrlValidator _validator; + private readonly string _host = $"{Guid.NewGuid():N}.example.com"; + + public FeedUrlValidatorTests() + { + var reader = new FeedReader(new HttpClient(_handler), new MemoryCache(new MemoryCacheOptions()), NullLogger.Instance) + { + Timeout = TimeSpan.FromSeconds(2) + }; + _validator = new FeedUrlValidator(reader); + } + + private void Feed(string url) => _handler.Respond(url, FeedSamples.Rss(($"{url}/1", "One", DateTimeOffset.UtcNow))); + + [Fact] + public async Task WorkingUrl_IsKept() + { + var url = $"https://{_host}/rss"; + Feed(url); + + var result = await _validator.ValidateAsync(url, null); + + result.Should().BeEquivalentTo(new FeedValidationResult(url, null, null, false, null, null)); + } + + [Fact] + public async Task HttpUrl_IsFixedWithHttps() + { + Feed($"https://{_host}/rss"); + + var result = await _validator.ValidateAsync($"http://{_host}/rss", null); + + result.Success.Should().BeTrue(); + result.Fixed.Should().BeTrue(); + result.FeedUrl.Should().Be($"https://{_host}/rss"); + } + + [Fact] + public async Task DeadUrl_IsFixedByDiscoveryFromSiteUrl_BeforeTryingFeedSuffix() + { + var site = $"https://{_host}/"; + _handler.Respond(site, $"""Blog""", "text/html"); + Feed($"https://{_host}/new/rss"); + Feed($"https://{_host}/old/rss/feed"); + + var result = await _validator.ValidateAsync($"https://{_host}/old/rss", site); + + result.Fixed.Should().BeTrue(); + result.FeedUrl.Should().Be($"https://{_host}/new/rss"); + result.SiteUrl.Should().Be(site); + _handler.Hits($"https://{_host}/old/rss/feed").Should().Be(0); + } + + [Fact] + public async Task SiteLikeUrl_IsFixedByAppendingFeed() + { + // The example from the issue: https://devblogs.microsoft.com/dotnet/ -> .../dotnet/feed + Feed($"https://{_host}/dotnet/feed"); + + var result = await _validator.ValidateAsync($"https://{_host}/dotnet/", null); + + result.Fixed.Should().BeTrue(); + result.FeedUrl.Should().Be($"https://{_host}/dotnet/feed"); + } + + [Fact] + public async Task HttpSiteLikeUrl_TriesFeedSuffixOverHttpsToo() + { + Feed($"https://{_host}/blog/feed"); + + var result = await _validator.ValidateAsync($"http://{_host}/blog", null); + + result.FeedUrl.Should().Be($"https://{_host}/blog/feed"); + } + + [Fact] + public async Task Unrecoverable_ReturnsOriginalUrlAndError() + { + var url = $"https://{_host}/gone"; + + var result = await _validator.ValidateAsync(url, $"https://{_host}/"); + + result.Success.Should().BeFalse(); + result.Fixed.Should().BeFalse(); + result.FeedUrl.Should().Be(url); + result.ErrorKind.Should().Be(FeedErrorKind.NotFound); + _handler.Hits($"https://{_host}/gone/feed").Should().Be(1); // every step was tried + } + + [Fact] + public async Task UnreachableHost_IsNotTriedAgainWithFeedSuffix() + { + var url = $"https://{_host}/rss"; + _handler.Throwing[url] = new HttpRequestException("No such host is known."); + _handler.Throwing[$"https://{_host}/rss/feed"] = new HttpRequestException("No such host is known."); + + var result = await _validator.ValidateAsync(url, null); + + result.ErrorKind.Should().Be(FeedErrorKind.Unreachable); + _handler.Hits($"https://{_host}/rss/feed").Should().Be(0); + } + + [Fact] + public async Task HostThatTimesOut_IsNotTriedAgainWithFeedSuffix() + { + var url = $"https://{_host}/slow"; + _handler.Hanging[url] = true; + + var result = await _validator.ValidateAsync(url, null); + + result.ErrorKind.Should().Be(FeedErrorKind.Timeout); + _handler.Hits($"https://{_host}/slow/feed").Should().Be(0); + } + + [Theory] + [InlineData("https://a.example.com/dotnet/", "https://a.example.com/dotnet/feed")] + [InlineData("https://a.example.com/blog?x=1", "https://a.example.com/blog/feed")] + [InlineData("https://a.example.com", "https://a.example.com/feed")] + [InlineData("http://a.example.com/blog", "http://a.example.com/blog/feed", "https://a.example.com/blog/feed")] + [InlineData("https://a.example.com/feed/")] + public void FeedSuffixCandidates_AppendFeed(string url, params string[] expected) + { + FeedUrlValidator.FeedSuffixCandidates(new Uri(url)).Should().Equal(expected); + } +} diff --git a/src/NoteBookmark.Api.Tests/Services/DataStorageServiceTests.cs b/src/NoteBookmark.Api.Tests/Services/DataStorageServiceTests.cs index 1802d66..aab317e 100644 --- a/src/NoteBookmark.Api.Tests/Services/DataStorageServiceTests.cs +++ b/src/NoteBookmark.Api.Tests/Services/DataStorageServiceTests.cs @@ -393,6 +393,75 @@ public async Task UpdatePostReadStatus_UpdatesAllPostsWithNotes() updatedPost2!.is_read.Should().BeFalse(); // No note, should remain unread } + [Fact] + public async Task SaveAndGetFeedSnapshot_RoundTripsJsonInFeedCacheContainer() + { + var feedId = Guid.NewGuid().ToString("N"); + var now = DateTimeOffset.UtcNow; + var snapshot = new FeedSnapshot + { + FeedId = feedId, + FeedUrl = "https://example.com/feed.xml", + FetchedAt = now, + TotalCount = 5, + LastPublished = now.AddHours(-2), + Items = + [ + new FeedItem + { + Url = "https://example.com/1", + Title = "Article 1", + Published = now.AddHours(-2), + Author = "Alice", + Excerpt = "Short excerpt", + Body = "

Hello

" + } + ] + }; + + await _dataStorageService.SaveFeedSnapshot(snapshot); + var loaded = await _dataStorageService.GetFeedSnapshot(feedId); + + loaded.Should().NotBeNull(); + loaded!.FeedId.Should().Be(feedId); + loaded.FeedUrl.Should().Be("https://example.com/feed.xml"); + loaded.FetchedAt.Should().BeCloseTo(now, TimeSpan.FromMilliseconds(10)); + loaded.TotalCount.Should().Be(5); + loaded.LastPublished.Should().BeCloseTo(now.AddHours(-2), TimeSpan.FromMilliseconds(10)); + loaded.Items.Should().ContainSingle().Which.Title.Should().Be("Article 1"); + + var blob = _fixture.BlobServiceClient! + .GetBlobContainerClient(DataStorageService.FeedCacheContainerName) + .GetBlobClient($"{feedId}.json"); + (await blob.ExistsAsync()).Value.Should().BeTrue(); + } + + [Fact] + public async Task DeleteFeed_DeletesFeedCacheSnapshotBlob() + { + var group = new FeedGroup { Name = "Group-" + Guid.NewGuid().ToString("N") }; + await _dataStorageService.SaveFeedGroup(group); + var feed = new Feed + { + Title = "Feed to delete", + FeedUrl = $"https://example.com/{Guid.NewGuid():N}/rss", + GroupId = group.RowKey + }; + await _dataStorageService.SaveFeed(feed); + await _dataStorageService.SaveFeedSnapshot(new FeedSnapshot + { + FeedId = feed.RowKey, + FeedUrl = feed.FeedUrl, + FetchedAt = DateTimeOffset.UtcNow, + TotalCount = 1 + }); + + var deleted = await _dataStorageService.DeleteFeed(feed.RowKey); + + deleted.Should().BeTrue(); + (await _dataStorageService.GetFeedSnapshot(feed.RowKey)).Should().BeNull(); + } + // Helper methods for creating test data private static Post CreateTestPost() { diff --git a/src/NoteBookmark.Api/DataStorageService.cs b/src/NoteBookmark.Api/DataStorageService.cs index 01d787b..24a3bea 100644 --- a/src/NoteBookmark.Api/DataStorageService.cs +++ b/src/NoteBookmark.Api/DataStorageService.cs @@ -231,6 +231,10 @@ public async Task GetSettings() if (result.HasValue) { settings = result.Value!; + if (settings.FeedRefreshIntervalMinutes <= 0) + { + settings.FeedRefreshIntervalMinutes = Settings.DefaultFeedRefreshIntervalMinutes; + } } else { @@ -238,7 +242,9 @@ public async Task GetSettings() PartitionKey = "setting", RowKey = "setting", LastBookmarkDate = "2023-04-06T07:31:44", - ReadingNotesCounter = "623" + ReadingNotesCounter = "623", + FeedRefreshEnabled = false, + FeedRefreshIntervalMinutes = Settings.DefaultFeedRefreshIntervalMinutes }; await tblSettings.AddEntityAsync(settings); @@ -449,13 +455,81 @@ public async Task SaveFeed(Feed feed) await table.UpsertEntityAsync(feed, TableUpdateMode.Replace); } + public const string FeedCacheContainerName = "feed-cache"; + + private static readonly JsonSerializerOptions FeedSnapshotJsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + PropertyNameCaseInsensitive = true + }; + public async Task DeleteFeed(string id) { var table = await GetFeedTable(); var response = await table.DeleteEntityAsync(Feed.Partition, id); + await DeleteFeedSnapshot(id); return response.Status != 404; } + public async Task GetFeedSnapshot(string feedId) + { + if (string.IsNullOrWhiteSpace(feedId)) + { + return null; + } + + try + { + var container = blobClient.GetBlobContainerClient(FeedCacheContainerName); + var blob = container.GetBlobClient($"{feedId}.json"); + if (!await blob.ExistsAsync()) + { + return null; + } + + var response = await blob.DownloadContentAsync(); + return response.Value.Content.ToObjectFromJson(FeedSnapshotJsonOptions); + } + catch (RequestFailedException ex) when (ex.Status == 404) + { + return null; + } + } + + public async Task SaveFeedSnapshot(FeedSnapshot snapshot) + { + if (string.IsNullOrWhiteSpace(snapshot.FeedId)) + { + return; + } + + var container = blobClient.GetBlobContainerClient(FeedCacheContainerName); + await container.CreateIfNotExistsAsync(); + var blob = container.GetBlobClient($"{snapshot.FeedId}.json"); + var bytes = JsonSerializer.SerializeToUtf8Bytes(snapshot, FeedSnapshotJsonOptions); + using var stream = new MemoryStream(bytes); + await blob.UploadAsync(stream, overwrite: true); + } + + public async Task DeleteFeedSnapshot(string feedId) + { + if (string.IsNullOrWhiteSpace(feedId)) + { + return false; + } + + try + { + var container = blobClient.GetBlobContainerClient(FeedCacheContainerName); + var response = await container.DeleteBlobIfExistsAsync($"{feedId}.json"); + return response.Value; + } + catch (RequestFailedException ex) when (ex.Status == 404) + { + return false; + } + } + public async Task> GetFeedItemStates() => await QueryAllAsync(await GetFeedItemStateTable(), FeedItemState.Partition); diff --git a/src/NoteBookmark.Api/FeedEndpoints.cs b/src/NoteBookmark.Api/FeedEndpoints.cs index 113f717..f5cdfd0 100644 --- a/src/NoteBookmark.Api/FeedEndpoints.cs +++ b/src/NoteBookmark.Api/FeedEndpoints.cs @@ -43,7 +43,7 @@ public static void MapFeedEndpoints(this IEndpointRouteBuilder app) endpoints.MapGet("/discover", Discover) .WithDescription("Find the RSS/Atom feed for a feed URL or a site URL"); endpoints.MapPost("/import-opml", ImportOpml) - .WithDescription("Import an OPML subscription list (e.g. a Feedly export); folders become groups"); + .WithDescription("Import an OPML subscription list (e.g. a Feedly export); folders become groups. Each new feed is checked, broken URLs are fixed when possible (https, site discovery, /feed), and feeds that still fail are imported and listed in FailedFeeds"); endpoints.MapGet("/items", GetItems) .WithDescription("Pending items (newest first) for all feeds, one group (groupId), one feed (feedId) or a comma-separated list (feedIds); refresh=true bypasses the cache; waitMs answers early with still-loading feeds marked Loading"); @@ -148,8 +148,16 @@ static async Task, BadRequest, Conflict>> SaveF return TypedResults.Ok(feed); } - static async Task> DeleteFeed(string id, IDataStorageService storage) => - await storage.DeleteFeed(id) ? TypedResults.Ok() : TypedResults.NotFound(); + static async Task> DeleteFeed(string id, IDataStorageService storage, IMemoryCache cache) + { + var existing = await storage.GetFeed(id); + if (!await storage.DeleteFeed(id)) + { + return TypedResults.NotFound(); + } + FeedReader.EvictCache(cache, id, existing?.FeedUrl); + return TypedResults.Ok(); + } // ----- Discovery and import ----- @@ -167,7 +175,8 @@ static async Task, BadRequest, NotFound< : TypedResults.Ok(result); } - static async Task, BadRequest>> ImportOpml(OpmlImportRequest request, IDataStorageService storage) + static async Task, BadRequest>> ImportOpml(OpmlImportRequest request, IDataStorageService storage, + FeedUrlValidator validator, CancellationToken cancellationToken) { List entries; try @@ -183,11 +192,38 @@ static async Task, BadRequest>> ImportOpml( var groups = (await storage.GetFeedGroups()) .GroupBy(g => g.Name, StringComparer.OrdinalIgnoreCase) .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase); - var knownFeeds = new HashSet((await storage.GetFeeds()).Select(f => FeedItemState.NormalizeUrl(f.FeedUrl))); + var existing = (await storage.GetFeeds()).Select(f => FeedItemState.NormalizeUrl(f.FeedUrl)).ToList(); + // Feeds already followed (or listed twice in the file) are skipped without being checked. + var seen = new HashSet(existing); + var candidates = new List(); foreach (var entry in entries) { - if (!knownFeeds.Add(FeedItemState.NormalizeUrl(entry.FeedUrl))) + if (seen.Add(FeedItemState.NormalizeUrl(entry.FeedUrl))) + { + candidates.Add(entry); + } + else + { + result.FeedsSkipped++; + } + } + + // Check every new feed, and try to fix the broken ones, before saving anything. The reader limits + // concurrent downloads and times each one out, so a few hundred feeds take well under a minute. + var validations = new FeedValidationResult[candidates.Count]; + await Parallel.ForEachAsync(Enumerable.Range(0, candidates.Count), + new ParallelOptions { MaxDegreeOfParallelism = FeedReader.MaxConcurrentDownloads, CancellationToken = cancellationToken }, + async (i, ct) => validations[i] = await validator.ValidateAsync(candidates[i].FeedUrl, candidates[i].SiteUrl, ct)); + + // A fixed URL can point to a feed that is already followed, or to another entry of the same file. + var saved = new HashSet(existing); + for (var i = 0; i < candidates.Count; i++) + { + var entry = candidates[i]; + var validation = validations[i]; + var feedUrl = validation.Success ? validation.FeedUrl : entry.FeedUrl; + if (!saved.Add(FeedItemState.NormalizeUrl(feedUrl))) { result.FeedsSkipped++; continue; @@ -201,14 +237,36 @@ static async Task, BadRequest>> ImportOpml( result.GroupsCreated++; } - await storage.SaveFeed(new Feed + // The OPML parser uses the URL as the title when the outline has none; a discovered title is better. + var title = entry.Title == entry.FeedUrl && !string.IsNullOrWhiteSpace(validation.Title) ? validation.Title : entry.Title; + var feed = new Feed { - Title = entry.Title, - FeedUrl = entry.FeedUrl, - SiteUrl = entry.SiteUrl, + Title = title, + FeedUrl = feedUrl, + SiteUrl = entry.SiteUrl ?? validation.SiteUrl, GroupId = group.RowKey - }); + }; + await storage.SaveFeed(feed); result.FeedsCreated++; + + if (validation.Fixed) + { + result.FeedsFixed++; + } + else if (!validation.Success) + { + // Imported anyway so the subscription isn't lost; the user can edit or delete it from the report. + result.FailedFeeds.Add(new OpmlFailedFeed + { + FeedId = feed.RowKey, + Title = feed.Title, + FeedUrl = feed.FeedUrl, + SiteUrl = feed.SiteUrl, + GroupName = group.Name, + Error = validation.Error, + ErrorKind = validation.ErrorKind + }); + } } return TypedResults.Ok(result); @@ -269,12 +327,17 @@ static async Task> GetItems(IDataStorageService storage, I GroupId = feed.GroupId, PendingCount = pending.Count, TotalCount = result.TotalCount, - LastPublished = result.Items.Max(i => i.Published), + LastPublished = result.NewestPublished, + FetchedAt = result.FetchedAt, Error = result.Error, ErrorKind = result.ErrorKind }); } + response.LastRefreshed = response.Feeds + .Where(f => !f.Loading && f.FetchedAt is not null) + .Select(f => f.FetchedAt) + .Max(); response.Items = response.Items .OrderByDescending(i => i.Published ?? DateTimeOffset.MinValue) .ToList(); diff --git a/src/NoteBookmark.Api/FeedReader.cs b/src/NoteBookmark.Api/FeedReader.cs index 74b6403..e6bd6d1 100644 --- a/src/NoteBookmark.Api/FeedReader.cs +++ b/src/NoteBookmark.Api/FeedReader.cs @@ -5,23 +5,37 @@ namespace NoteBookmark.Api; -public record FeedFetchResult(List Items, string? Error, string? ErrorKind = null) +public record FeedFetchResult( + List Items, + string? Error, + string? ErrorKind = null, + int? TotalItemCount = null, + DateTimeOffset? LastPublished = null, + DateTimeOffset? FetchedAt = null) { /// Items in the feed document before any filtering. - public int TotalCount => Items.Count; + public int TotalCount => TotalItemCount ?? Items.Count; + + /// Date of the newest item in the feed document before any filtering. + public DateTimeOffset? NewestPublished => LastPublished ?? (Items.Count > 0 ? Items.Max(i => i.Published) : null); } public interface IFeedReader { - /// Items of one feed, from a ~15 minute cache unless is set. Never throws for feed errors. + /// Items of one feed, from cache/storage unless is set. Never throws for feed errors. Task FetchAsync(Feed feed, bool refresh, CancellationToken cancellationToken = default); /// Finds the feed for a feed URL or a site URL (via <link rel="alternate">). Null when there is none. Task DiscoverAsync(string url, CancellationToken cancellationToken = default); } -/// Downloads and parses feeds on demand. There is no background polling. -public class FeedReader(HttpClient httpClient, IMemoryCache cache, ILogger logger) : IFeedReader +/// Downloads, parses, and caches feeds in memory and Azure Blob Storage (feed-cache). +public class FeedReader( + HttpClient httpClient, + IMemoryCache cache, + ILogger logger, + IDataStorageService? storage = null, + TimeProvider? timeProvider = null) : IFeedReader { public static readonly TimeSpan CacheDuration = TimeSpan.FromMinutes(15); public static readonly TimeSpan FetchTimeout = TimeSpan.FromSeconds(10); @@ -31,6 +45,7 @@ public class FeedReader(HttpClient httpClient, IMemoryCache cache, ILogger public static readonly TimeSpan FailureCacheDuration = TimeSpan.FromMinutes(5); + private static readonly TimeSpan MemoryCacheEntryLifetime = TimeSpan.FromHours(25); private const long MaxDocumentBytes = 10 * 1024 * 1024; /// Per-download timeout; settable so tests don't wait 10 seconds. @@ -41,62 +56,243 @@ public class FeedReader(HttpClient httpClient, IMemoryCache cache, ILogger (timeProvider ?? TimeProvider.System).GetUtcNow(); + + private static string SnapshotCacheKey(string feedId) => "feed-snapshot:" + feedId; + private static string UrlCacheKey(string normalizedUrl) => "feed:" + normalizedUrl; + + public static void EvictCache(IMemoryCache cache, string feedId, string? feedUrl = null) + { + if (!string.IsNullOrWhiteSpace(feedId)) + { + if (cache.TryGetValue(SnapshotCacheKey(feedId), out FeedSnapshot? existing) && existing is not null) + { + cache.Remove(UrlCacheKey(FeedItemState.NormalizeUrl(existing.FeedUrl))); + } + cache.Remove(SnapshotCacheKey(feedId)); + } + + if (!string.IsNullOrWhiteSpace(feedUrl)) + { + cache.Remove(UrlCacheKey(FeedItemState.NormalizeUrl(feedUrl))); + } + } + public async Task FetchAsync(Feed feed, bool refresh, CancellationToken cancellationToken = default) { - var cacheKey = "feed:" + FeedItemState.NormalizeUrl(feed.FeedUrl); - if (!refresh && cache.TryGetValue(cacheKey, out FeedFetchResult? cached) && cached is not null) + var normalizedUrl = FeedItemState.NormalizeUrl(feed.FeedUrl); + if (!refresh) { - return cached with { Items = Stamp(cached.Items, feed) }; + var existing = await GetExistingSnapshotAsync(feed, normalizedUrl); + if (existing is not null) + { + var backgroundRefreshEnabled = await IsBackgroundRefreshEnabledAsync(); + if (IsSnapshotFresh(existing, backgroundRefreshEnabled)) + { + return ToFetchResult(existing, feed); + } + } } // One download per feed at a time: a second request for the same feed (another batch, or // the UI asking again for a feed that was still loading) waits for the same download. // The download isn't tied to the request, so it finishes and fills the cache even when the // request that started it has already answered. - Task download; - var inFlightKey = "feed-inflight:" + cacheKey; + Task download; + var inFlightKey = "feed-inflight:" + normalizedUrl; lock (InFlightLock) { // A completed task can linger when the download finished before it was registered; ignore it. - if (!cache.TryGetValue(inFlightKey, out Task? running) || running is null || running.IsCompleted) + if (!cache.TryGetValue(inFlightKey, out Task? running) || running is null || running.IsCompleted) { - running = DownloadAndCacheAsync(feed.FeedUrl, cacheKey, inFlightKey); + running = DownloadAndCacheAsync(feed, normalizedUrl, inFlightKey); cache.Set(inFlightKey, running, TimeSpan.FromMinutes(2)); } download = running; } - var result = await download.WaitAsync(cancellationToken); - return result with { Items = Stamp(result.Items, feed) }; + var snapshot = await download.WaitAsync(cancellationToken); + if (!string.IsNullOrWhiteSpace(feed.RowKey) && snapshot.FeedId != feed.RowKey) + { + var boundSnapshot = new FeedSnapshot + { + FeedId = feed.RowKey, + FeedUrl = snapshot.FeedUrl, + FetchedAt = snapshot.FetchedAt, + TotalCount = snapshot.TotalCount, + LastPublished = snapshot.LastPublished, + Error = snapshot.Error, + ErrorKind = snapshot.ErrorKind, + Items = snapshot.Items + }; + CacheInMemory(feed.RowKey, normalizedUrl, boundSnapshot); + if (storage is not null) + { + await storage.SaveFeedSnapshot(boundSnapshot); + } + snapshot = boundSnapshot; + } + + return ToFetchResult(snapshot, feed); } - private async Task DownloadAndCacheAsync(string feedUrl, string cacheKey, string inFlightKey) + private async Task DownloadAndCacheAsync(Feed feed, string normalizedUrl, string inFlightKey) { await Task.Yield(); // run outside the caller's lock - FeedFetchResult result; + var previous = await GetExistingSnapshotAsync(feed, normalizedUrl); + FeedSnapshot snapshot; await DownloadSlots.WaitAsync(); try { - var content = await DownloadAsync(feedUrl, CancellationToken.None); - var parsed = FeedParser.Parse(content, new Uri(feedUrl)); - result = new FeedFetchResult(parsed.Items, null); - cache.Set(cacheKey, result, CacheDuration); + var content = await DownloadAsync(feed.FeedUrl, CancellationToken.None); + var parsed = FeedParser.Parse(content, new Uri(feed.FeedUrl)); + var now = GetUtcNow(); + var cutoff = now - FeedEndpoints.ItemMaxAge; + var totalCount = parsed.Items.Count; + var lastPublished = parsed.Items.Count > 0 ? parsed.Items.Max(i => i.Published) : null; + var recentItems = parsed.Items + .Where(i => i.Published is null || i.Published >= cutoff) + .ToList(); + + snapshot = new FeedSnapshot + { + FeedId = feed.RowKey, + FeedUrl = normalizedUrl, + FetchedAt = now, + TotalCount = totalCount, + LastPublished = lastPublished, + Error = null, + ErrorKind = null, + Items = recentItems + }; } catch (Exception ex) { var (kind, message) = Classify(ex); - logger.LogWarning("Feed {FeedUrl} failed ({Kind}): {Error}", feedUrl, kind, message); - result = new FeedFetchResult([], message, kind); - cache.Set(cacheKey, result, FailureCacheDuration); + logger.LogWarning("Feed {FeedUrl} failed ({Kind}): {Error}", feed.FeedUrl, kind, message); + var now = GetUtcNow(); + if (previous is not null && FeedItemState.NormalizeUrl(previous.FeedUrl) == normalizedUrl) + { + var cutoff = now - FeedEndpoints.ItemMaxAge; + var preservedItems = previous.Items + .Where(i => i.Published is null || i.Published >= cutoff) + .ToList(); + snapshot = new FeedSnapshot + { + FeedId = feed.RowKey, + FeedUrl = normalizedUrl, + FetchedAt = now, + TotalCount = previous.TotalCount, + LastPublished = previous.LastPublished, + Error = message, + ErrorKind = kind, + Items = preservedItems + }; + } + else + { + snapshot = new FeedSnapshot + { + FeedId = feed.RowKey, + FeedUrl = normalizedUrl, + FetchedAt = now, + TotalCount = 0, + LastPublished = null, + Error = message, + ErrorKind = kind, + Items = [] + }; + } } finally { DownloadSlots.Release(); cache.Remove(inFlightKey); } - return result; + + CacheInMemory(feed.RowKey, normalizedUrl, snapshot); + if (storage is not null && !string.IsNullOrWhiteSpace(feed.RowKey)) + { + await storage.SaveFeedSnapshot(snapshot); + } + + return snapshot; } + private async Task GetExistingSnapshotAsync(Feed feed, string normalizedUrl) + { + if (!string.IsNullOrWhiteSpace(feed.RowKey) && + cache.TryGetValue(SnapshotCacheKey(feed.RowKey), out FeedSnapshot? byId) && + byId is not null && + FeedItemState.NormalizeUrl(byId.FeedUrl) == normalizedUrl) + { + return byId; + } + + if (storage is not null && !string.IsNullOrWhiteSpace(feed.RowKey)) + { + var stored = await storage.GetFeedSnapshot(feed.RowKey); + if (stored is not null && FeedItemState.NormalizeUrl(stored.FeedUrl) == normalizedUrl) + { + CacheInMemory(feed.RowKey, normalizedUrl, stored); + return stored; + } + } + + if (cache.TryGetValue(UrlCacheKey(normalizedUrl), out FeedSnapshot? byUrl) && + byUrl is not null && + FeedItemState.NormalizeUrl(byUrl.FeedUrl) == normalizedUrl && + (storage is null || string.IsNullOrWhiteSpace(feed.RowKey) || string.IsNullOrWhiteSpace(byUrl.FeedId) || byUrl.FeedId == feed.RowKey)) + { + return byUrl; + } + + return null; + } + + private void CacheInMemory(string feedId, string normalizedUrl, FeedSnapshot snapshot) + { + if (!string.IsNullOrWhiteSpace(feedId)) + { + cache.Set(SnapshotCacheKey(feedId), snapshot, MemoryCacheEntryLifetime); + } + cache.Set(UrlCacheKey(normalizedUrl), snapshot, MemoryCacheEntryLifetime); + } + + private async Task IsBackgroundRefreshEnabledAsync() + { + if (storage is null) + { + return false; + } + + var settings = await storage.GetSettings(); + return settings?.FeedRefreshEnabled == true; + } + + private bool IsSnapshotFresh(FeedSnapshot snapshot, bool backgroundRefreshEnabled) + { + if (backgroundRefreshEnabled) + { + return true; + } + + var age = GetUtcNow() - snapshot.FetchedAt; + var ttl = snapshot.Error is not null && snapshot.Items.Count == 0 + ? FailureCacheDuration + : CacheDuration; + return age < ttl; + } + + private static FeedFetchResult ToFetchResult(FeedSnapshot snapshot, Feed feed) => + new( + Stamp(snapshot.Items, feed), + snapshot.Error, + snapshot.ErrorKind, + snapshot.TotalCount, + snapshot.LastPublished, + snapshot.FetchedAt); + public async Task DiscoverAsync(string url, CancellationToken cancellationToken = default) { if (!Uri.TryCreate(url.Trim(), UriKind.Absolute, out var uri) || (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)) diff --git a/src/NoteBookmark.Api/FeedReaderServiceCollectionExtensions.cs b/src/NoteBookmark.Api/FeedReaderServiceCollectionExtensions.cs new file mode 100644 index 0000000..02e51ff --- /dev/null +++ b/src/NoteBookmark.Api/FeedReaderServiceCollectionExtensions.cs @@ -0,0 +1,23 @@ +namespace NoteBookmark.Api; + +public static class FeedReaderServiceCollectionExtensions +{ + public const string UserAgent = "NoteBookmark/1.0 (+https://github.com/fboucher/NoteBookmark)"; + + /// + /// Registers (and ) with its own . + /// The client opts out of the standard resilience handler that AddServiceDefaults puts on every client: + /// that handler has one circuit breaker per client, so with feeds on hundreds of unrelated hosts a batch of + /// dead feeds would open it and make healthy feeds fail too. has its own timeout, + /// concurrency limit and per-feed error classification instead. + /// + public static IHttpClientBuilder AddFeedReader(this IServiceCollection services) + { + services.AddTransient(); + var builder = services.AddHttpClient(client => client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent)); +#pragma warning disable EXTEXP0001 // RemoveAllResilienceHandlers is marked experimental; it is the documented way to opt one client out. + builder.RemoveAllResilienceHandlers(); +#pragma warning restore EXTEXP0001 + return builder; + } +} diff --git a/src/NoteBookmark.Api/FeedRefreshBackgroundWorker.cs b/src/NoteBookmark.Api/FeedRefreshBackgroundWorker.cs new file mode 100644 index 0000000..8651c41 --- /dev/null +++ b/src/NoteBookmark.Api/FeedRefreshBackgroundWorker.cs @@ -0,0 +1,152 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using NoteBookmark.Domain; + +namespace NoteBookmark.Api; + +/// Signals when feed refresh settings are updated. +public class FeedRefreshNotifier +{ + private readonly SemaphoreSlim _signal = new(0, 1); + + public void NotifySettingsChanged() + { + try + { + if (_signal.CurrentCount == 0) + { + _signal.Release(); + } + } + catch (SemaphoreFullException) + { + } + } + + public async Task WaitAsync(TimeSpan delay, TimeProvider timeProvider, CancellationToken cancellationToken) + { + if (_signal.Wait(0)) + { + return true; + } + + using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var signalTask = _signal.WaitAsync(linkedCts.Token); + var delayTask = Task.Delay(delay, timeProvider, linkedCts.Token); + + var completed = await Task.WhenAny(signalTask, delayTask).ConfigureAwait(false); + await linkedCts.CancelAsync().ConfigureAwait(false); + + if (cancellationToken.IsCancellationRequested) + { + cancellationToken.ThrowIfCancellationRequested(); + } + + return completed == signalTask && signalTask.IsCompletedSuccessfully; + } +} + +/// Optional scheduled background worker that refreshes all feeds on the configured interval. +public class FeedRefreshBackgroundWorker( + IServiceProvider serviceProvider, + FeedRefreshNotifier notifier, + ILogger logger, + TimeProvider? timeProvider = null) : BackgroundService +{ + private readonly TimeProvider _timeProvider = timeProvider ?? TimeProvider.System; + private DateTimeOffset? _lastSweepAt; + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + logger.LogInformation("Feed Refresh Background Worker started."); + + while (!stoppingToken.IsCancellationRequested) + { + try + { + var delay = await RunCycleAsync(stoppingToken); + await notifier.WaitAsync(delay, _timeProvider, stoppingToken); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + break; + } + catch (Exception ex) + { + logger.LogError(ex, "Error occurred in Feed Refresh Background Worker."); + try + { + await notifier.WaitAsync(TimeSpan.FromMinutes(1), _timeProvider, stoppingToken); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + break; + } + } + } + + logger.LogInformation("Feed Refresh Background Worker stopped."); + } + + public async Task RunCycleAsync(CancellationToken cancellationToken = default) + { + using var scope = serviceProvider.CreateScope(); + var storage = scope.ServiceProvider.GetRequiredService(); + var settings = await storage.GetSettings(); + if (settings is null || !settings.FeedRefreshEnabled) + { + return Timeout.InfiniteTimeSpan; + } + + var intervalMinutes = settings.FeedRefreshIntervalMinutes >= 30 + ? settings.FeedRefreshIntervalMinutes + : Settings.DefaultFeedRefreshIntervalMinutes; + var interval = TimeSpan.FromMinutes(intervalMinutes); + + var feeds = await storage.GetFeeds(); + if (feeds.Count == 0) + { + return interval; + } + + var now = _timeProvider.GetUtcNow(); + DateTimeOffset? oldestRefresh = null; + var needsImmediateRefresh = false; + + foreach (var feed in feeds) + { + var snapshot = await storage.GetFeedSnapshot(feed.RowKey); + DateTimeOffset? feedRefreshedAt = snapshot is not null && + FeedItemState.NormalizeUrl(snapshot.FeedUrl) == FeedItemState.NormalizeUrl(feed.FeedUrl) + ? snapshot.FetchedAt + : _lastSweepAt; + + if (feedRefreshedAt is null) + { + needsImmediateRefresh = true; + break; + } + + if (oldestRefresh is null || feedRefreshedAt.Value < oldestRefresh.Value) + { + oldestRefresh = feedRefreshedAt.Value; + } + } + + if (!needsImmediateRefresh && oldestRefresh is not null) + { + var nextDueAt = oldestRefresh.Value + interval; + if (nextDueAt > now) + { + return nextDueAt - now; + } + } + + var reader = scope.ServiceProvider.GetRequiredService(); + logger.LogInformation("Running scheduled background feed refresh for {FeedCount} feed(s).", feeds.Count); + await Task.WhenAll(feeds.Select(f => reader.FetchAsync(f, refresh: true, cancellationToken))); + _lastSweepAt = _timeProvider.GetUtcNow(); + return interval; + } +} diff --git a/src/NoteBookmark.Api/FeedUrlValidator.cs b/src/NoteBookmark.Api/FeedUrlValidator.cs new file mode 100644 index 0000000..2051673 --- /dev/null +++ b/src/NoteBookmark.Api/FeedUrlValidator.cs @@ -0,0 +1,110 @@ +using NoteBookmark.Domain; + +namespace NoteBookmark.Api; + +/// Outcome of . +public record FeedValidationResult(string FeedUrl, string? SiteUrl, string? Title, bool Fixed, string? Error, string? ErrorKind) +{ + public bool Success => Error is null; +} + +/// +/// Checks that a feed URL works and, when it doesn't, tries to find a working one. Used by OPML import (#243). +/// Steps, stopping at the first that gives a valid RSS/Atom feed: +/// (a) the URL as given, (b) http → https, (c) discovery from the site URL, (d) the URL with /feed appended. +/// +public class FeedUrlValidator(IFeedReader reader) +{ + public async Task ValidateAsync(string feedUrl, string? siteUrl, CancellationToken cancellationToken = default) + { + // (a) The URL as given. Successes also fill the reader's cache, so the Feeds tab loads instantly afterwards. + var original = await reader.FetchAsync(new Feed { RowKey = string.Empty, FeedUrl = feedUrl }, refresh: false, cancellationToken); + if (original.Error is null) + { + return new FeedValidationResult(feedUrl, siteUrl, null, Fixed: false, null, null); + } + + // Hosts that couldn't be reached (DNS or connection error) or didn't answer in time: another path on them + // won't do better, and skipping them keeps a file full of dead feeds from taking minutes to import. + var unreachable = new HashSet(StringComparer.OrdinalIgnoreCase); + if (IsHostDown(original.ErrorKind)) + { + unreachable.Add(Authority(feedUrl)); + } + + // (b) http → https. + var uri = new Uri(feedUrl); + if (uri.Scheme == Uri.UriSchemeHttp) + { + var https = ToHttps(uri); + var result = await TryAsync(https, unreachable, cancellationToken); + if (result) + { + return Fixed(https, siteUrl, null); + } + } + + // (c) Discover the current feed from the site's . This fixes moved feeds, such as old blog platforms. + if (!string.IsNullOrEmpty(siteUrl)) + { + var discovered = await reader.DiscoverAsync(siteUrl, cancellationToken); + if (discovered is not null) + { + return Fixed(discovered.FeedUrl, siteUrl, discovered.Title); + } + } + + // (d) Append /feed (WordPress and many blog engines), also over https when the URL is http. + foreach (var candidate in FeedSuffixCandidates(uri)) + { + if (await TryAsync(candidate, unreachable, cancellationToken)) + { + return Fixed(candidate, siteUrl, null); + } + } + + return new FeedValidationResult(feedUrl, siteUrl, null, Fixed: false, original.Error, original.ErrorKind); + + FeedValidationResult Fixed(string url, string? site, string? title) => + new(url, site, title, Fixed: FeedItemState.NormalizeUrl(url) != FeedItemState.NormalizeUrl(feedUrl), null, null); + } + + private async Task TryAsync(string url, HashSet unreachable, CancellationToken cancellationToken) + { + if (unreachable.Contains(Authority(url))) + { + return false; + } + var result = await reader.FetchAsync(new Feed { RowKey = string.Empty, FeedUrl = url }, refresh: false, cancellationToken); + if (IsHostDown(result.ErrorKind)) + { + unreachable.Add(Authority(url)); + } + return result.Error is null; + } + + private static bool IsHostDown(string? kind) => kind is FeedErrorKind.Unreachable or FeedErrorKind.Timeout; + + /// https://example.com/blog/ → https://example.com/blog/feed; an http URL also gets its https form. + public static List FeedSuffixCandidates(Uri uri) + { + if (uri.AbsolutePath.TrimEnd('/').EndsWith("/feed", StringComparison.OrdinalIgnoreCase)) + { + return []; + } + var builder = new UriBuilder(uri) { Query = string.Empty, Fragment = string.Empty }; + builder.Path = builder.Path.EndsWith('/') ? builder.Path + "feed" : builder.Path + "/feed"; + var withSuffix = builder.Uri; + var candidates = new List { withSuffix.AbsoluteUri }; + if (withSuffix.Scheme == Uri.UriSchemeHttp) + { + candidates.Add(ToHttps(withSuffix)); + } + return candidates; + } + + private static string ToHttps(Uri uri) => + new UriBuilder(uri) { Scheme = Uri.UriSchemeHttps, Port = uri.IsDefaultPort ? -1 : uri.Port }.Uri.AbsoluteUri; + + private static string Authority(string url) => Uri.TryCreate(url, UriKind.Absolute, out var u) ? u.GetLeftPart(UriPartial.Authority) : url; +} diff --git a/src/NoteBookmark.Api/IDataStorageService.cs b/src/NoteBookmark.Api/IDataStorageService.cs index 8a1d9a6..650450a 100644 --- a/src/NoteBookmark.Api/IDataStorageService.cs +++ b/src/NoteBookmark.Api/IDataStorageService.cs @@ -63,4 +63,10 @@ public interface IDataStorageService public Task SaveFeedItemStates(IEnumerable states); public Task PruneSkippedFeedItemStates(DateTime olderThan); + + public Task GetFeedSnapshot(string feedId); + + public Task SaveFeedSnapshot(FeedSnapshot snapshot); + + public Task DeleteFeedSnapshot(string feedId); } diff --git a/src/NoteBookmark.Api/Program.cs b/src/NoteBookmark.Api/Program.cs index c816d98..46d0043 100644 --- a/src/NoteBookmark.Api/Program.cs +++ b/src/NoteBookmark.Api/Program.cs @@ -23,12 +23,11 @@ // Register AI settings provider builder.Services.AddScoped(); -// Feeds tab: on-demand RSS/Atom fetching with an in-memory cache +// Feeds tab: RSS/Atom fetching with in-memory + blob snapshot cache and optional background refresh worker builder.Services.AddMemoryCache(); -builder.Services.AddHttpClient(client => -{ - client.DefaultRequestHeaders.UserAgent.ParseAdd("NoteBookmark/1.0 (+https://github.com/fboucher/NoteBookmark)"); -}); +builder.Services.AddFeedReader(); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(); var app = builder.Build(); diff --git a/src/NoteBookmark.Api/SettingEndpoints.cs b/src/NoteBookmark.Api/SettingEndpoints.cs index d7a40aa..95ff701 100644 --- a/src/NoteBookmark.Api/SettingEndpoints.cs +++ b/src/NoteBookmark.Api/SettingEndpoints.cs @@ -33,7 +33,11 @@ static async Task GetNextReadingNotesCounter(TableServiceClient tblClien return counter; } - static async Task> SaveSettings(Settings settings, TableServiceClient tblClient, BlobServiceClient blobClient) + static async Task> SaveSettings( + Settings settings, + TableServiceClient tblClient, + BlobServiceClient blobClient, + FeedRefreshNotifier? feedRefreshNotifier = null) { try { @@ -45,6 +49,15 @@ static async Task> SaveSettings(Settings settings, Table return TypedResults.BadRequest(); } + if (settings.FeedRefreshIntervalMinutes == 0) + { + settings.FeedRefreshIntervalMinutes = Settings.DefaultFeedRefreshIntervalMinutes; + } + else if (!Settings.AllowedFeedRefreshIntervals.Contains(settings.FeedRefreshIntervalMinutes)) + { + return TypedResults.BadRequest(); + } + var dataStorageService = new DataStorageService(tblClient, blobClient); // If API key is masked, preserve the existing value from database @@ -55,7 +68,13 @@ static async Task> SaveSettings(Settings settings, Table } var result = await dataStorageService.SaveSettings(settings); - return result ? TypedResults.Ok() : TypedResults.BadRequest(); + if (!result) + { + return TypedResults.BadRequest(); + } + + feedRefreshNotifier?.NotifySettingsChanged(); + return TypedResults.Ok(); } catch (Exception ex) { @@ -79,6 +98,11 @@ static async Task, BadRequest>> GetSettings(TableServiceCli settings.SummaryPrompt = "write a short introduction paragraph, without using '—', for the blog post: {content}"; } + if (settings.FeedRefreshIntervalMinutes <= 0) + { + settings.FeedRefreshIntervalMinutes = Settings.DefaultFeedRefreshIntervalMinutes; + } + // Security: Do not expose the API key to clients - return masked value if (!string.IsNullOrWhiteSpace(settings.AiApiKey)) { diff --git a/src/NoteBookmark.AppHost/NoteBookmark.AppHost.csproj b/src/NoteBookmark.AppHost/NoteBookmark.AppHost.csproj index 7d76b2d..49ae839 100644 --- a/src/NoteBookmark.AppHost/NoteBookmark.AppHost.csproj +++ b/src/NoteBookmark.AppHost/NoteBookmark.AppHost.csproj @@ -1,8 +1,9 @@ - + Exe true 0784f0a9-b1e6-4e65-8d31-00f1369f6d75 + $(NoWarn);ASPIRE010 diff --git a/src/NoteBookmark.BlazorApp.Tests/Helpers/OpmlImportReportDialogTestWrapper.razor b/src/NoteBookmark.BlazorApp.Tests/Helpers/OpmlImportReportDialogTestWrapper.razor new file mode 100644 index 0000000..a829df4 --- /dev/null +++ b/src/NoteBookmark.BlazorApp.Tests/Helpers/OpmlImportReportDialogTestWrapper.razor @@ -0,0 +1,12 @@ +@using NoteBookmark.SharedUI +@using NoteBookmark.SharedUI.Components.Shared +@using Microsoft.FluentUI.AspNetCore.Components + + + + + +@code { + [Parameter] + public OpmlImportReport Content { get; set; } = default!; +} diff --git a/src/NoteBookmark.BlazorApp.Tests/Tests/FeedsPageTests.cs b/src/NoteBookmark.BlazorApp.Tests/Tests/FeedsPageTests.cs index 00dc9cb..f90348c 100644 --- a/src/NoteBookmark.BlazorApp.Tests/Tests/FeedsPageTests.cs +++ b/src/NoteBookmark.BlazorApp.Tests/Tests/FeedsPageTests.cs @@ -191,6 +191,7 @@ public void ExpandingGroup_ExplainsWhyAFeedFailed() cut.FindAll(".feeds-nav-row.feed").Should().BeEmpty(); cut.Find("[data-group-id='g-dev'] .feeds-warning").GetAttribute("title").Should().Contain("1 feed(s)"); + cut.Find("#toggle-empty-feeds").Click(); cut.Find("[data-group-id='g-dev'] .feeds-expand").Click(); cut.FindAll(".feeds-nav-row.feed").Should().HaveCount(2); @@ -206,6 +207,7 @@ public void Timeout_IsShownAsTemporary() _server["f-b"] = ([], new FeedStatus { FeedId = "f-b", GroupId = "g-dev", Error = "Timed out after 10 seconds.", ErrorKind = FeedErrorKind.Timeout }); var cut = RenderLoaded(); + cut.Find("#toggle-empty-feeds").Click(); cut.Find("[data-group-id='g-dev'] .feeds-expand").Click(); var warning = cut.Find("[data-feed-id='f-b'] .feeds-warning"); @@ -219,6 +221,7 @@ public void InactiveOrEmptyFeed_GetsClockHint() _server["f-b"] = ([], new FeedStatus { FeedId = "f-b", GroupId = "g-dev", TotalCount = 5, LastPublished = Now.AddYears(-2) }); var cut = RenderLoaded(); + cut.Find("#toggle-empty-feeds").Click(); cut.Find("[data-group-id='g-dev'] .feeds-expand").Click(); cut.Find("[data-feed-id='f-b'] .feeds-inactive").GetAttribute("title").Should().Contain("may no longer be updated"); @@ -229,6 +232,7 @@ public void InactiveOrEmptyFeed_GetsClockHint() public void SelectingFeed_FiltersItems() { var cut = RenderLoaded(); + cut.Find("#toggle-empty-feeds").Click(); cut.Find("[data-group-id='g-dev'] .feeds-expand").Click(); cut.Find("[data-feed-id='f-b']").Click(); @@ -237,6 +241,56 @@ public void SelectingFeed_FiltersItems() cut.Markup.Should().Contain("All caught up"); } + [Fact] + public void ExpandingGroup_HidesZeroPostFeedsByDefault_AndTogglesToShowThem() + { + var cut = RenderLoaded(); + var toggle = cut.Find("#nav-all #toggle-empty-feeds"); + toggle.GetAttribute("title").Should().Be("Show feeds with no posts"); + toggle.GetAttribute("aria-label").Should().Be("Show feeds with no posts"); + toggle.GetAttribute("aria-pressed").Should().Be("true"); + + cut.Find("[data-group-id='g-dev'] .feeds-expand").Click(); + + cut.FindAll(".feeds-nav-row.feed").Select(e => e.GetAttribute("data-feed-id")).Should().Equal("f-a"); + + cut.Find("#toggle-empty-feeds").Click(); + + toggle = cut.Find("#nav-all #toggle-empty-feeds"); + toggle.GetAttribute("title").Should().Be("Hide feeds with no posts"); + toggle.GetAttribute("aria-label").Should().Be("Hide feeds with no posts"); + toggle.GetAttribute("aria-pressed").Should().Be("false"); + cut.FindAll(".feeds-nav-row.feed").Select(e => e.GetAttribute("data-feed-id")).Should().Equal("f-a", "f-b"); + + cut.Find("#toggle-empty-feeds").Click(); + + cut.FindAll(".feeds-nav-row.feed").Select(e => e.GetAttribute("data-feed-id")).Should().Equal("f-a"); + } + + [Fact] + public void ToggleEmptyFeeds_PreservesSelection_AndKeepsSelectedZeroPostFeedVisible() + { + var cut = RenderLoaded(); + cut.Find("[data-group-id='g-news']").Click(); + cut.Find("[data-group-id='g-news']").ClassList.Should().Contain("selected"); + Titles(cut).Should().Equal("News item"); + + cut.Find("#toggle-empty-feeds").Click(); + + cut.Find("#nav-all").ClassList.Should().NotContain("selected"); + cut.Find("[data-group-id='g-news']").ClassList.Should().Contain("selected"); + Titles(cut).Should().Equal("News item"); + + cut.Find("[data-group-id='g-dev'] .feeds-expand").Click(); + cut.Find("[data-feed-id='f-b']").Click(); + cut.Find("[data-feed-id='f-b']").ClassList.Should().Contain("selected"); + + cut.Find("#toggle-empty-feeds").Click(); + + cut.Find("[data-feed-id='f-b']").ClassList.Should().Contain("selected"); + cut.FindAll(".feeds-nav-row.feed").Select(e => e.GetAttribute("data-feed-id")).Should().Equal("f-a", "f-b"); + } + [Fact] public void ManyItems_ArePaged() { @@ -338,4 +392,42 @@ public void Age_Undated() { Feeds.Age(null).Should().Be("undated"); } + + [Theory] + [InlineData(0.2, "Updated just now")] + [InlineData(12, "Updated 12m ago")] + [InlineData(3 * 60, "Updated 3h ago")] + [InlineData(2 * 24 * 60, "Updated 2d ago")] + public void FormatLastUpdated_FormatsRelativeTime(double minutesAgo, string expected) + { + var now = DateTimeOffset.UtcNow; + + Feeds.FormatLastUpdated(now.AddMinutes(-minutesAgo), now).Should().Be(expected); + } + + [Fact] + public async Task LastUpdatedIndicator_DisplaysNextToRefreshButton_AndUpdatesAfterRefresh() + { + var initialFetchTime = DateTimeOffset.UtcNow.AddMinutes(-12); + _server["f-a"] = ([Item("f-a", "g-dev", "Dev newest", 1)], + new FeedStatus { FeedId = "f-a", GroupId = "g-dev", PendingCount = 1, TotalCount = 1, FetchedAt = initialFetchTime }); + _server["f-n"] = ([Item("f-n", "g-news", "News item", 2)], + new FeedStatus { FeedId = "f-n", GroupId = "g-news", PendingCount = 1, TotalCount = 1, FetchedAt = initialFetchTime }); + + var cut = RenderLoaded(); + + var indicator = cut.Find("#feeds-last-updated"); + indicator.TextContent.Trim().Should().Be("Updated 12m ago"); + indicator.GetAttribute("title").Should().StartWith("Last updated:"); + + var refreshedTime = DateTimeOffset.UtcNow; + _server["f-a"] = ([Item("f-a", "g-dev", "Dev newest", 1)], + new FeedStatus { FeedId = "f-a", GroupId = "g-dev", PendingCount = 1, TotalCount = 1, FetchedAt = refreshedTime }); + _server["f-n"] = ([Item("f-n", "g-news", "News item", 2)], + new FeedStatus { FeedId = "f-n", GroupId = "g-news", PendingCount = 1, TotalCount = 1, FetchedAt = refreshedTime }); + + await cut.InvokeAsync(() => cut.Find("fluent-button#refresh-feeds").Click()); + + cut.WaitForAssertion(() => cut.Find("#feeds-last-updated").TextContent.Trim().Should().Be("Updated just now")); + } } diff --git a/src/NoteBookmark.BlazorApp.Tests/Tests/ManageFeedsTests.cs b/src/NoteBookmark.BlazorApp.Tests/Tests/ManageFeedsTests.cs index c6469fa..5affa32 100644 --- a/src/NoteBookmark.BlazorApp.Tests/Tests/ManageFeedsTests.cs +++ b/src/NoteBookmark.BlazorApp.Tests/Tests/ManageFeedsTests.cs @@ -1,8 +1,10 @@ using Bunit; +using Microsoft.AspNetCore.Components; using Microsoft.Extensions.DependencyInjection; using Microsoft.FluentUI.AspNetCore.Components; using NoteBookmark.BlazorApp.Tests.Helpers; using NoteBookmark.SharedUI.Components.Pages; +using NoteBookmark.SharedUI.Components.Shared; namespace NoteBookmark.BlazorApp.Tests.Tests; @@ -195,6 +197,136 @@ public async Task MoveFeed_SavesFeedWithNewGroup() cut.Find(".mf-group[data-group-id='g-news'] .feed-count").TextContent.Should().Be("2"); } + private async Task> StartEditingBlog() + { + var cut = Render(); + Expand(cut, "g-dev"); + await Click(cut, "[data-feed-id='f-1'] fluent-button.edit-feed"); + return cut; + } + + [Fact] + public async Task EditFeed_ShowsFieldsWithCurrentValues_AndSaveDisabledUntilChanged() + { + var cut = await StartEditingBlog(); + + var fields = cut.FindComponents(); + fields.Single(t => t.Instance.Id == "edit-title-f-1").Instance.Value.Should().Be("Some blog"); + fields.Single(t => t.Instance.Id == "edit-url-f-1").Instance.Value.Should().Be("https://blog.example.com/rss"); + cut.FindComponents().Single(b => b.Instance.Class == "save-feed").Instance.Disabled.Should().BeTrue(); + cut.FindAll("[data-feed-id='f-1'] fluent-button.delete-feed").Should().BeEmpty(); + } + + [Fact] + public async Task EditFeed_TitleOnly_SavesWithoutDiscovery() + { + _feeds.Setup(f => f.SaveFeed(It.IsAny())).ReturnsAsync((Feed f) => new FeedResult(f, null)); + var cut = await StartEditingBlog(); + + await SetText(cut, "edit-title-f-1", " A better name "); + await Click(cut, "[data-feed-id='f-1'] fluent-button.save-feed"); + + _feeds.Verify(f => f.Discover(It.IsAny()), Times.Never); + _feeds.Verify(f => f.SaveFeed(It.Is(x => x.RowKey == "f-1" && x.GroupId == "g-dev" + && x.Title == "A better name" && x.FeedUrl == "https://blog.example.com/rss")), Times.Once); + cut.Find("[data-feed-id='f-1'] .feed-row-title").TextContent.Should().Be("A better name"); + cut.FindAll("[data-feed-id='f-1'] fluent-button.save-feed").Should().BeEmpty(); + _toasts.Verify(t => t.ShowSuccess(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny?>()), Times.Once); + } + + [Fact] + public async Task EditFeed_UrlChanged_SavesDiscoveredUrl_AndKeepsTypedTitle() + { + var feedWithoutSite = new Feed { RowKey = "f-3", Title = "Old", FeedUrl = "https://old.example.com/rss", GroupId = "g-dev" }; + _feeds.Setup(f => f.GetFeeds()).ReturnsAsync(() => [_blog, _other, feedWithoutSite]); + _feeds.Setup(f => f.Discover("https://new.example.com")) + .ReturnsAsync(new FeedResult(new FeedDiscoveryResult { FeedUrl = "https://new.example.com/feed.xml", Title = "Discovered title", SiteUrl = "https://new.example.com/" }, null)); + _feeds.Setup(f => f.SaveFeed(It.IsAny())).ReturnsAsync((Feed f) => new FeedResult(f, null)); + var cut = Render(); + Expand(cut, "g-dev"); + await Click(cut, "[data-feed-id='f-3'] fluent-button.edit-feed"); + + await SetText(cut, "edit-title-f-3", "My title"); + await SetText(cut, "edit-url-f-3", " https://new.example.com "); + await Click(cut, "[data-feed-id='f-3'] fluent-button.save-feed"); + + _feeds.Verify(f => f.SaveFeed(It.Is(x => x.RowKey == "f-3" && x.GroupId == "g-dev" && x.Title == "My title" + && x.FeedUrl == "https://new.example.com/feed.xml" && x.SiteUrl == "https://new.example.com/")), Times.Once); + var row = cut.Find("[data-feed-id='f-3']"); + row.QuerySelector(".feed-row-title")!.TextContent.Should().Be("My title"); + row.QuerySelector(".feed-row-url")!.TextContent.Should().Be("https://new.example.com/feed.xml"); + } + + [Fact] + public async Task EditFeed_UrlChanged_KeepsExistingSiteUrl() + { + _feeds.Setup(f => f.Discover(It.IsAny())) + .ReturnsAsync(new FeedResult(new FeedDiscoveryResult { FeedUrl = "https://blog.example.com/atom", Title = "Blog", SiteUrl = "https://elsewhere.example.com/" }, null)); + _feeds.Setup(f => f.SaveFeed(It.IsAny())).ReturnsAsync((Feed f) => new FeedResult(f, null)); + var cut = await StartEditingBlog(); + + await SetText(cut, "edit-url-f-1", "https://blog.example.com/atom"); + await Click(cut, "[data-feed-id='f-1'] fluent-button.save-feed"); + + _feeds.Verify(f => f.SaveFeed(It.Is(x => x.SiteUrl == "https://blog.example.com/" && x.Title == "Some blog")), Times.Once); + } + + [Fact] + public async Task EditFeed_UrlNotDiscovered_ShowsError_StaysInEditMode() + { + _feeds.Setup(f => f.Discover(It.IsAny())) + .ReturnsAsync(new FeedResult(null, "No RSS or Atom feed was found at this address.")); + var cut = await StartEditingBlog(); + + await SetText(cut, "edit-url-f-1", "https://nofeed.example.com"); + await Click(cut, "[data-feed-id='f-1'] fluent-button.save-feed"); + + _feeds.Verify(f => f.SaveFeed(It.IsAny()), Times.Never); + _toasts.Verify(t => t.ShowError("No RSS or Atom feed was found at this address.", It.IsAny(), It.IsAny(), It.IsAny?>()), Times.Once); + cut.FindComponents().Single(t => t.Instance.Id == "edit-url-f-1").Instance.Value.Should().Be("https://nofeed.example.com"); + _blog.FeedUrl.Should().Be("https://blog.example.com/rss"); + } + + [Fact] + public async Task EditFeed_Conflict_ShowsError_KeepsOriginalValues() + { + _feeds.Setup(f => f.Discover(It.IsAny())) + .ReturnsAsync(new FeedResult(new FeedDiscoveryResult { FeedUrl = "https://kayak.example.com/rss", Title = "Kayak" }, null)); + _feeds.Setup(f => f.SaveFeed(It.IsAny())).ReturnsAsync(new FeedResult(null, "This feed is already in your list.")); + var cut = await StartEditingBlog(); + + await SetText(cut, "edit-url-f-1", "https://kayak.example.com/rss"); + await Click(cut, "[data-feed-id='f-1'] fluent-button.save-feed"); + + _toasts.Verify(t => t.ShowError("This feed is already in your list.", It.IsAny(), It.IsAny(), It.IsAny?>()), Times.Once); + cut.FindAll("[data-feed-id='f-1'] fluent-button.save-feed").Should().ContainSingle(); + _blog.FeedUrl.Should().Be("https://blog.example.com/rss"); + } + + [Fact] + public async Task EditFeed_Cancel_RestoresValues_WithoutCallingApi() + { + var cut = await StartEditingBlog(); + + await SetText(cut, "edit-title-f-1", "Changed"); + await Click(cut, "[data-feed-id='f-1'] fluent-button.cancel-feed"); + + _feeds.Verify(f => f.SaveFeed(It.IsAny()), Times.Never); + _feeds.Verify(f => f.Discover(It.IsAny()), Times.Never); + cut.Find("[data-feed-id='f-1'] .feed-row-title").TextContent.Should().Be("Some blog"); + } + + [Fact] + public async Task EditFeed_And_RenameGroup_AreExclusive() + { + var cut = await StartEditingBlog(); + + await Click(cut, ".mf-group[data-group-id='g-dev'] fluent-button.rename-group"); + + cut.FindAll("[data-feed-id='f-1'] fluent-button.save-feed").Should().BeEmpty(); + cut.FindAll(".mf-group[data-group-id='g-dev'] fluent-button.save-rename").Should().ContainSingle(); + } + [Fact] public async Task DeleteFeed_RemovesRow() { @@ -242,4 +374,44 @@ public async Task ImportOpml_ThreeHundredFeeds_RendersCollapsed() cut.FindAll(".feed-row").Should().BeEmpty(); cut.Find("#mf-summary").TextContent.Should().Be("309 feed(s) in 35 group(s)"); } + [Fact] + public async Task ImportOpml_WithoutFailures_ShowsToastOnly() + { + var dialogs = new Mock(); + Services.AddSingleton(dialogs.Object); + _feeds.Setup(f => f.ImportOpml(It.IsAny())) + .ReturnsAsync(new FeedResult(new OpmlImportResult { FeedsCreated = 3, GroupsCreated = 1, FeedsFixed = 2 }, null)); + var cut = Render(); + + var input = cut.FindComponent(); + await cut.InvokeAsync(() => input.UploadFiles(InputFileContent.CreateFromText("", "feedly.opml"))); + + _toasts.Verify(t => t.ShowSuccess(It.Is(m => m.Contains("Imported 3 feed(s)") && m.Contains("2 address(es) fixed")), + It.IsAny(), It.IsAny(), It.IsAny?>()), Times.Once); + dialogs.VerifyNoOtherCalls(); + } + + [Fact] + public async Task ImportOpml_WithFailures_OpensReport_ThenReloads() + { + var failed = new OpmlFailedFeed { FeedId = "f-1", Title = "Some blog", FeedUrl = _blog.FeedUrl, GroupName = "Dev", ErrorKind = FeedErrorKind.NotFound }; + var dialogs = new Mock(); + var reference = new Mock(); + reference.Setup(r => r.Result).ReturnsAsync(DialogResult.Ok(null)); + dialogs.Setup(d => d.ShowDialogAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(reference.Object); + Services.AddSingleton(dialogs.Object); + _feeds.Setup(f => f.ImportOpml(It.IsAny())) + .ReturnsAsync(new FeedResult(new OpmlImportResult { FeedsCreated = 1, FailedFeeds = [failed] }, null)); + var cut = Render(); + + var input = cut.FindComponent(); + await cut.InvokeAsync(() => input.UploadFiles(InputFileContent.CreateFromText("", "feedly.opml"))); + + dialogs.Verify(d => d.ShowDialogAsync( + It.Is(o => ((OpmlImportReport)o).FailedFeeds.Single().FeedId == "f-1" && ((OpmlImportReport)o).Feeds.Any(f => f.RowKey == "f-1")), + It.Is(p => p.Title == "1 feed(s) need attention")), Times.Once); + _feeds.Verify(f => f.GetGroups(), Times.Exactly(3)); // initial load, after import, after the report closes + cut.FindAll("#importing").Should().BeEmpty(); + } } diff --git a/src/NoteBookmark.BlazorApp.Tests/Tests/NewsFeedServiceTests.cs b/src/NoteBookmark.BlazorApp.Tests/Tests/NewsFeedServiceTests.cs index 7b7fbe5..9f3bcf8 100644 --- a/src/NoteBookmark.BlazorApp.Tests/Tests/NewsFeedServiceTests.cs +++ b/src/NoteBookmark.BlazorApp.Tests/Tests/NewsFeedServiceTests.cs @@ -138,6 +138,20 @@ public void Home_WhenNewsFeedReturnsFallback_DisplaysWelcomeMessage() cut.Find(".news-content").TextContent.Should().Contain("Welcome to NoteBookmark! Check back here for product updates."); } + [Fact] + public void Home_RendersDotNet10Badge() + { + this.AddFluentUI(); + var newsFeedMock = new Mock(); + newsFeedMock.Setup(s => s.GetHtmlAsync()).ReturnsAsync("

News

"); + Services.AddSingleton(newsFeedMock.Object); + + var cut = Render(); + + cut.Markup.Should().Contain(".NET 10"); + cut.Markup.Should().NotContain(".NET 9"); + } + private static NewsFeedService CreateService(HttpMessageHandler handler) { var logger = new Mock>(); diff --git a/src/NoteBookmark.BlazorApp.Tests/Tests/OpmlImportReportDialogTests.cs b/src/NoteBookmark.BlazorApp.Tests/Tests/OpmlImportReportDialogTests.cs new file mode 100644 index 0000000..f279ccb --- /dev/null +++ b/src/NoteBookmark.BlazorApp.Tests/Tests/OpmlImportReportDialogTests.cs @@ -0,0 +1,206 @@ +using Bunit; +using Microsoft.AspNetCore.Components; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.FluentUI.AspNetCore.Components; +using NoteBookmark.BlazorApp.Tests.Helpers; + +namespace NoteBookmark.BlazorApp.Tests.Tests; + +public sealed class OpmlImportReportDialogTests : BunitContext +{ + private readonly Mock _feeds = new(); + private readonly Mock _toasts = new(); + private readonly Feed _dead = new() { RowKey = "f-dead", Title = "Old blog", FeedUrl = "https://old.example.com/rss", GroupId = "g-dev", ETag = new Azure.ETag("e1") }; + private readonly Feed _gone = new() { RowKey = "f-gone", Title = "Gone blog", FeedUrl = "https://gone.example.com/rss", GroupId = "g-dev" }; + private readonly OpmlImportReport _report; + + public OpmlImportReportDialogTests() + { + this.AddFluentUI(); + Services.AddSingleton(_feeds.Object); + Services.AddSingleton(_toasts.Object); + _report = new OpmlImportReport + { + Feeds = [_dead, _gone], + FailedFeeds = + [ + new() { FeedId = "f-dead", Title = "Old blog", FeedUrl = "https://old.example.com/rss", GroupName = "Dev", ErrorKind = FeedErrorKind.NotFound, Error = "HTTP 404 Not Found" }, + new() { FeedId = "f-gone", Title = "Gone blog", FeedUrl = "https://gone.example.com/rss", GroupName = "Dev", ErrorKind = FeedErrorKind.Unreachable, Error = "No such host is known." } + ] + }; + } + + private IRenderedComponent RenderDialog() => + Render(p => p.Add(x => x.Content, _report)); + + private static Task Click(IRenderedComponent cut, string selector) => + cut.InvokeAsync(() => cut.Find(selector).Click()); + + [Fact] + public void Lists_EachFailedFeed_WithItsReason() + { + var cut = RenderDialog(); + + cut.FindAll(".oir-row").Should().HaveCount(2); + var row = cut.Find(".oir-row[data-feed-id='f-dead']"); + row.TextContent.Should().Contain("Old blog").And.Contain("Dev").And.Contain("https://old.example.com/rss") + .And.Contain(FeedErrorKind.Describe(FeedErrorKind.NotFound)).And.Contain("HTTP 404 Not Found"); + cut.Find("#oir-intro").TextContent.Should().Contain("2 feed(s)"); + } + + [Fact] + public async Task Delete_RemovesTheFeed_AndTheRow() + { + _feeds.Setup(f => f.DeleteFeed("f-gone")).ReturnsAsync(new FeedResult(true, null)); + var cut = RenderDialog(); + + await Click(cut, ".oir-row[data-feed-id='f-gone'] fluent-button.oir-delete"); + + _feeds.Verify(f => f.DeleteFeed("f-gone"), Times.Once); + cut.FindAll(".oir-row").Select(r => r.GetAttribute("data-feed-id")).Should().Equal("f-dead"); + } + + [Fact] + public async Task Delete_Failure_KeepsTheRow() + { + _feeds.Setup(f => f.DeleteFeed("f-gone")).ReturnsAsync(new FeedResult(false, "Boom")); + var cut = RenderDialog(); + + await Click(cut, ".oir-row[data-feed-id='f-gone'] fluent-button.oir-delete"); + + cut.FindAll(".oir-row").Should().HaveCount(2); + _toasts.Verify(t => t.ShowError("Boom", It.IsAny(), It.IsAny(), It.IsAny?>()), Times.Once); + } + + [Fact] + public async Task Edit_DiscoversTheNewAddress_AndSavesTheFeedInItsGroup() + { + _feeds.Setup(f => f.Discover("https://new.example.com/")) + .ReturnsAsync(new FeedResult(new FeedDiscoveryResult { FeedUrl = "https://new.example.com/feed", Title = "New", SiteUrl = "https://new.example.com/" }, null)); + _feeds.Setup(f => f.SaveFeed(It.IsAny())).ReturnsAsync((Feed f) => new FeedResult(f, null)); + var cut = RenderDialog(); + + await Click(cut, ".oir-row[data-feed-id='f-dead'] fluent-button.oir-edit-button"); + await cut.InvokeAsync(() => cut.FindComponents().Single(t => t.Instance.Id == "oir-url-f-dead").Instance.ValueChanged.InvokeAsync("https://new.example.com/")); + await Click(cut, ".oir-row[data-feed-id='f-dead'] fluent-button.oir-save"); + + _feeds.Verify(f => f.SaveFeed(It.Is(x => + x.RowKey == "f-dead" && x.GroupId == "g-dev" && x.Title == "Old blog" && + x.FeedUrl == "https://new.example.com/feed" && x.SiteUrl == "https://new.example.com/" && x.ETag == new Azure.ETag("e1"))), Times.Once); + cut.FindAll(".oir-row").Select(r => r.GetAttribute("data-feed-id")).Should().Equal("f-gone"); + } + + [Fact] + public async Task Edit_AddressWithoutFeed_KeepsEditing() + { + _feeds.Setup(f => f.Discover(It.IsAny())).ReturnsAsync(new FeedResult(null, "No RSS or Atom feed was found at this address.")); + var cut = RenderDialog(); + + await Click(cut, ".oir-row[data-feed-id='f-dead'] fluent-button.oir-edit-button"); + await Click(cut, ".oir-row[data-feed-id='f-dead'] fluent-button.oir-save"); + + _feeds.Verify(f => f.SaveFeed(It.IsAny()), Times.Never); + cut.FindAll(".oir-row").Should().HaveCount(2); + cut.FindAll(".oir-row[data-feed-id='f-dead'] fluent-button.oir-save").Should().ContainSingle(); + } + + [Fact] + public async Task HandlingEveryFeed_SaysSo() + { + _feeds.Setup(f => f.DeleteFeed(It.IsAny())).ReturnsAsync(new FeedResult(true, null)); + var cut = RenderDialog(); + + await Click(cut, ".oir-row[data-feed-id='f-gone'] fluent-button.oir-delete"); + await Click(cut, ".oir-row[data-feed-id='f-dead'] fluent-button.oir-delete"); + + cut.Find("#oir-done").Should().NotBeNull(); + cut.FindAll("fluent-button#oir-discard-all").Should().BeEmpty(); + cut.Find("fluent-button#oir-close").TextContent.Should().Be("Close"); + } + + [Fact] + public async Task Close_KeepsTheRemainingFeeds() + { + var cut = RenderDialog(); + + cut.Find("fluent-button#oir-discard-all").TextContent.Should().Be("Discard all and close"); + cut.Find("fluent-button#oir-close").TextContent.Should().Be("Keep the rest and close"); + await Click(cut, "fluent-button#oir-close"); + + _feeds.Verify(f => f.DeleteFeed(It.IsAny()), Times.Never); + _feeds.Verify(f => f.SaveFeed(It.IsAny()), Times.Never); + } + + [Fact] + public async Task DiscardAllAndClose_DeletesAllRemainingFeeds_AndShowsSummaryToast() + { + _feeds.Setup(f => f.DeleteFeed(It.IsAny())).ReturnsAsync(new FeedResult(true, null)); + var cut = RenderDialog(); + + await Click(cut, "fluent-button#oir-discard-all"); + + _feeds.Verify(f => f.DeleteFeed("f-dead"), Times.Once); + _feeds.Verify(f => f.DeleteFeed("f-gone"), Times.Once); + cut.Find("#oir-done").Should().NotBeNull(); + cut.FindAll("fluent-button#oir-discard-all").Should().BeEmpty(); + _toasts.Verify(t => t.ShowSuccess("Removed 2 feed(s).", It.IsAny(), It.IsAny(), It.IsAny?>()), Times.Once); + } + + [Fact] + public async Task DiscardAllAndClose_AfterEditingOneFeed_OnlyDeletesRemainingFeeds() + { + _feeds.Setup(f => f.Discover("https://new.example.com/")) + .ReturnsAsync(new FeedResult(new FeedDiscoveryResult { FeedUrl = "https://new.example.com/feed", Title = "New", SiteUrl = "https://new.example.com/" }, null)); + _feeds.Setup(f => f.SaveFeed(It.IsAny())).ReturnsAsync((Feed f) => new FeedResult(f, null)); + _feeds.Setup(f => f.DeleteFeed("f-gone")).ReturnsAsync(new FeedResult(true, null)); + var cut = RenderDialog(); + + await Click(cut, ".oir-row[data-feed-id='f-dead'] fluent-button.oir-edit-button"); + await cut.InvokeAsync(() => cut.FindComponents().Single(t => t.Instance.Id == "oir-url-f-dead").Instance.ValueChanged.InvokeAsync("https://new.example.com/")); + await Click(cut, ".oir-row[data-feed-id='f-dead'] fluent-button.oir-save"); + + await Click(cut, "fluent-button#oir-discard-all"); + + _feeds.Verify(f => f.DeleteFeed("f-dead"), Times.Never); + _feeds.Verify(f => f.DeleteFeed("f-gone"), Times.Once); + _toasts.Verify(t => t.ShowSuccess("Removed 1 feed(s).", It.IsAny(), It.IsAny(), It.IsAny?>()), Times.Once); + } + + [Fact] + public async Task DiscardAllAndClose_WhenSomeDeletionsFail_RemovesSucceededAndKeepsFailed() + { + _feeds.Setup(f => f.DeleteFeed("f-dead")).ReturnsAsync(new FeedResult(true, null)); + _feeds.Setup(f => f.DeleteFeed("f-gone")).ReturnsAsync(new FeedResult(false, "Could not delete Gone blog")); + var cut = RenderDialog(); + + await Click(cut, "fluent-button#oir-discard-all"); + + cut.FindAll(".oir-row").Select(r => r.GetAttribute("data-feed-id")).Should().Equal("f-gone"); + cut.FindAll("fluent-button#oir-discard-all").Should().ContainSingle(); + _toasts.Verify(t => t.ShowError("Could not delete Gone blog", It.IsAny(), It.IsAny(), It.IsAny?>()), Times.Once); + _toasts.Verify(t => t.ShowSuccess(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny?>()), Times.Never); + } + + [Fact] + public async Task DiscardAllAndClose_DisablesActionButtonsWhileInProgress() + { + var tcs = new TaskCompletionSource>(); + _feeds.Setup(f => f.DeleteFeed("f-dead")).Returns(tcs.Task); + _feeds.Setup(f => f.DeleteFeed("f-gone")).ReturnsAsync(new FeedResult(true, null)); + var cut = RenderDialog(); + + var clickTask = Click(cut, "fluent-button#oir-discard-all"); + + var discardBtn = cut.FindComponents().Single(b => b.Instance.Id == "oir-discard-all").Instance; + var closeBtn = cut.FindComponents().Single(b => b.Instance.Id == "oir-close").Instance; + discardBtn.Disabled.Should().BeTrue(); + discardBtn.Loading.Should().BeTrue(); + closeBtn.Disabled.Should().BeTrue(); + cut.FindComponents() + .Where(b => b.Instance.Class is "oir-edit-button" or "oir-delete") + .Should().OnlyContain(b => b.Instance.Disabled); + + tcs.SetResult(new FeedResult(true, null)); + await clickTask; + } +} diff --git a/src/NoteBookmark.BlazorApp.Tests/Tests/SettingsPageTests.cs b/src/NoteBookmark.BlazorApp.Tests/Tests/SettingsPageTests.cs new file mode 100644 index 0000000..45e9b5e --- /dev/null +++ b/src/NoteBookmark.BlazorApp.Tests/Tests/SettingsPageTests.cs @@ -0,0 +1,65 @@ +using Bunit; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.FluentUI.AspNetCore.Components; +using NoteBookmark.BlazorApp.Tests.Helpers; +using NoteBookmark.SharedUI.Components.Pages; + +namespace NoteBookmark.BlazorApp.Tests.Tests; + +public sealed class SettingsPageTests : BunitContext +{ + private readonly Mock _data = new(); + private Domain.Settings _settings = new() + { + PartitionKey = "setting", + RowKey = "setting", + LastBookmarkDate = "2026-01-01T00:00:00", + ReadingNotesCounter = "650", + SummaryPrompt = "Summarize {content}", + SearchPrompt = "Search {topic}" + }; + + public SettingsPageTests() + { + this.AddFluentUI(); + Services.AddSingleton(_data.Object); + + _data.Setup(d => d.GetSettings()).ReturnsAsync(() => _settings); + _data.Setup(d => d.SaveSettings(It.IsAny())) + .Callback(s => _settings = s) + .ReturnsAsync(true); + } + + [Fact] + public void RendersFeedRefreshToggleOffByDefault_AndPresetIntervalDropdown() + { + var cut = Render< NoteBookmark.SharedUI.Components.Pages.Settings >(); + + var toggle = cut.FindComponents().Single(s => s.Instance.Id == "feed-refresh-enabled"); + toggle.Instance.Value.Should().BeFalse(); + + var intervalSelect = cut.FindComponents>().FirstOrDefault(s => s.Instance.Id == "feed-refresh-interval"); + cut.Find("#feed-refresh-interval").Should().NotBeNull(); + _settings.FeedRefreshIntervalMinutes.Should().Be(60); + + var optionValues = cut.FindAll("#feed-refresh-interval fluent-option").Select(o => o.GetAttribute("value")).ToList(); + optionValues.Should().Equal("30", "60", "180", "360", "720", "1440"); + } + + [Fact] + public async Task SavingSettings_PersistsBackgroundFeedRefreshAndSelectedInterval() + { + var cut = Render< NoteBookmark.SharedUI.Components.Pages.Settings >(); + + var toggle = cut.FindComponents().Single(s => s.Instance.Id == "feed-refresh-enabled"); + await cut.InvokeAsync(() => toggle.Instance.ValueChanged.InvokeAsync(true)); + + var intervalElement = cut.Find("#feed-refresh-interval"); + await cut.InvokeAsync(() => intervalElement.Change("180")); + + await cut.InvokeAsync(() => cut.Find("form").Submit()); + + _data.Verify(d => d.SaveSettings(It.Is(s => + s.FeedRefreshEnabled && s.FeedRefreshIntervalMinutes == 180)), Times.Once); + } +} diff --git a/src/NoteBookmark.BlazorApp/Components/Pages/Home.razor b/src/NoteBookmark.BlazorApp/Components/Pages/Home.razor index 6a3ac83..0905b5c 100644 --- a/src/NoteBookmark.BlazorApp/Components/Pages/Home.razor +++ b/src/NoteBookmark.BlazorApp/Components/Pages/Home.razor @@ -54,7 +54,7 @@

Built with Modern Tech

- .NET 9 + .NET 10 Blazor diff --git a/src/NoteBookmark.BlazorApp/NoteBookmark.BlazorApp.csproj b/src/NoteBookmark.BlazorApp/NoteBookmark.BlazorApp.csproj index c01c9b4..9ba8921 100644 --- a/src/NoteBookmark.BlazorApp/NoteBookmark.BlazorApp.csproj +++ b/src/NoteBookmark.BlazorApp/NoteBookmark.BlazorApp.csproj @@ -1,7 +1,7 @@ - 1.5.0 + 1.5.1 diff --git a/src/NoteBookmark.BlazorApp/Program.cs b/src/NoteBookmark.BlazorApp/Program.cs index 29f7f46..173dcd7 100644 --- a/src/NoteBookmark.BlazorApp/Program.cs +++ b/src/NoteBookmark.BlazorApp/Program.cs @@ -22,6 +22,8 @@ builder.Services.AddHttpClient(client => { client.BaseAddress = new Uri("https+http://api"); + // OPML import checks every new feed before answering; a few hundred feeds can take a few minutes. + client.Timeout = TimeSpan.FromMinutes(10); }); builder.Services.AddScoped(); builder.Services.AddHttpClient(nameof(NewsFeedService)); diff --git a/src/NoteBookmark.Domain/FeedItem.cs b/src/NoteBookmark.Domain/FeedItem.cs index df77a81..1dfda7c 100644 --- a/src/NoteBookmark.Domain/FeedItem.cs +++ b/src/NoteBookmark.Domain/FeedItem.cs @@ -43,6 +43,9 @@ public class FeedStatus /// Date of the newest item in the feed, to spot feeds that stopped publishing. public DateTimeOffset? LastPublished { get; set; } + /// When this feed snapshot was last fetched (UTC). + public DateTimeOffset? FetchedAt { get; set; } + /// True when the feed was still downloading when the API answered; ask for it again. public bool Loading { get; set; } @@ -53,6 +56,26 @@ public class FeedStatus public string? ErrorKind { get; set; } } +/// Persisted snapshot of one feed stored in the feed-cache blob container. +public class FeedSnapshot +{ + public string FeedId { get; set; } = string.Empty; + + public string FeedUrl { get; set; } = string.Empty; + + public DateTimeOffset FetchedAt { get; set; } + + public int TotalCount { get; set; } + + public DateTimeOffset? LastPublished { get; set; } + + public string? Error { get; set; } + + public string? ErrorKind { get; set; } + + public List Items { get; set; } = []; +} + /// Why a feed failed to load, so the UI can tell a dead feed from a slow one. public static class FeedErrorKind { @@ -94,6 +117,9 @@ public class FeedItemsResponse /// One entry per requested feed, including failed ones. public List Feeds { get; set; } = []; + + /// Most recent fetch time across the returned feeds. + public DateTimeOffset? LastRefreshed { get; set; } } /// Response of GET api/feeds/discover. @@ -121,4 +147,31 @@ public class OpmlImportResult /// Feeds already in the list (same URL), left untouched. public int FeedsSkipped { get; set; } + + /// Imported feeds whose OPML URL didn't work and was replaced by a working one. + public int FeedsFixed { get; set; } + + /// Imported feeds that still don't work after every recovery attempt. They are saved with their OPML URL. + public List FailedFeeds { get; set; } = []; +} + +/// A feed imported from OPML that could not be loaded, even after trying to fix its URL. +public class OpmlFailedFeed +{ + /// RowKey of the saved . + public string FeedId { get; set; } = string.Empty; + + public string Title { get; set; } = string.Empty; + + public string FeedUrl { get; set; } = string.Empty; + + public string? SiteUrl { get; set; } + + public string GroupName { get; set; } = string.Empty; + + /// Technical error message of the OPML URL. + public string? Error { get; set; } + + /// One of . + public string? ErrorKind { get; set; } } diff --git a/src/NoteBookmark.Domain/Settings.cs b/src/NoteBookmark.Domain/Settings.cs index 7c029fd..055b125 100644 --- a/src/NoteBookmark.Domain/Settings.cs +++ b/src/NoteBookmark.Domain/Settings.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using Azure; @@ -8,6 +9,10 @@ namespace NoteBookmark.Domain; public class Settings: ITableEntity { + public const int DefaultFeedRefreshIntervalMinutes = 60; + + public static readonly IReadOnlyList AllowedFeedRefreshIntervals = [30, 60, 180, 360, 720, 1440]; + [DataMember(Name="last_bookmark_date")] public string? LastBookmarkDate { get; set; } @@ -47,6 +52,12 @@ public class Settings: ITableEntity [DataMember(Name="font_size")] public string? FontSize { get; set; } + + [DataMember(Name="feed_refresh_enabled")] + public bool FeedRefreshEnabled { get; set; } + + [DataMember(Name="feed_refresh_interval_minutes")] + public int FeedRefreshIntervalMinutes { get; set; } = DefaultFeedRefreshIntervalMinutes; public required string PartitionKey { get ; set; } public required string RowKey { get ; set; } diff --git a/src/NoteBookmark.MauiApp/Data/LocalModels.cs b/src/NoteBookmark.MauiApp/Data/LocalModels.cs index 681dd48..6d0da24 100644 --- a/src/NoteBookmark.MauiApp/Data/LocalModels.cs +++ b/src/NoteBookmark.MauiApp/Data/LocalModels.cs @@ -180,6 +180,8 @@ public class LocalSettings public string? AiBaseUrl { get; set; } public string? AiModelName { get; set; } public string? FontSize { get; set; } + public bool FeedRefreshEnabled { get; set; } + public int FeedRefreshIntervalMinutes { get; set; } = Settings.DefaultFeedRefreshIntervalMinutes; public bool IsPendingSync { get; set; } public Settings ToDomain() => new Settings @@ -195,7 +197,9 @@ public class LocalSettings AiApiKey = AiApiKey, AiBaseUrl = AiBaseUrl, AiModelName = AiModelName, - FontSize = FontSize + FontSize = FontSize, + FeedRefreshEnabled = FeedRefreshEnabled, + FeedRefreshIntervalMinutes = FeedRefreshIntervalMinutes > 0 ? FeedRefreshIntervalMinutes : Settings.DefaultFeedRefreshIntervalMinutes }; public static LocalSettings FromDomain(Settings s, bool isPendingSync = false) => new LocalSettings @@ -212,6 +216,8 @@ public class LocalSettings AiBaseUrl = s.AiBaseUrl, AiModelName = s.AiModelName, FontSize = s.FontSize, + FeedRefreshEnabled = s.FeedRefreshEnabled, + FeedRefreshIntervalMinutes = s.FeedRefreshIntervalMinutes > 0 ? s.FeedRefreshIntervalMinutes : Settings.DefaultFeedRefreshIntervalMinutes, IsPendingSync = isPendingSync }; } diff --git a/src/NoteBookmark.MauiApp/NoteBookmark.MauiApp.csproj b/src/NoteBookmark.MauiApp/NoteBookmark.MauiApp.csproj index c12c755..17908f3 100644 --- a/src/NoteBookmark.MauiApp/NoteBookmark.MauiApp.csproj +++ b/src/NoteBookmark.MauiApp/NoteBookmark.MauiApp.csproj @@ -44,9 +44,9 @@ c5m.notebookmark.mauiapp - 1.5.0 - 11 - 1.5.0 + 1.5.1 + 12 + 1.5.1 None diff --git a/src/NoteBookmark.SharedUI/Components/Pages/Feeds.razor b/src/NoteBookmark.SharedUI/Components/Pages/Feeds.razor index 0c3506f..04af123 100644 --- a/src/NoteBookmark.SharedUI/Components/Pages/Feeds.razor +++ b/src/NoteBookmark.SharedUI/Components/Pages/Feeds.razor @@ -12,6 +12,12 @@

Feeds

+ @if (LastRefreshed is { } refreshedAt) + { + + @FormatLastUpdated(refreshedAt) + + } Refresh @foreach (var group in groups) @@ -57,7 +70,7 @@ else @if (expanded) { - @foreach (var feed in groupFeeds) + @foreach (var feed in groupFeeds.Where(f => !hideEmptyFeeds || CountFor(null, f.RowKey) > 0 || selection.FeedId == f.RowKey)) { var status = StatusFor(feed.RowKey);
feeds = []; private List items = []; private Dictionary statuses = []; + private DateTimeOffset? lastResponseRefreshed; private readonly HashSet expandedGroups = []; private readonly HashSet busyUrls = []; private Selection selection = Selection.All; + private bool hideEmptyFeeds = true; private bool IsFetching => feedsLoaded < feedsToLoad; + private DateTimeOffset? LastRefreshed + { + get + { + var statusTimes = statuses.Values + .Where(s => selection.FeedId is null || s.FeedId == selection.FeedId) + .Where(s => selection.GroupId is null || s.GroupId == selection.GroupId) + .Where(s => s.FetchedAt is not null) + .Select(s => s.FetchedAt!.Value) + .ToList(); + if (statusTimes.Count > 0) + { + return statusTimes.Max(); + } + return lastResponseRefreshed; + } + } + private List VisibleItems => items .Where(i => selection.FeedId is null || i.FeedId == selection.FeedId) .Where(i => selection.GroupId is null || i.GroupId == selection.GroupId) @@ -314,6 +350,11 @@ else { statuses[status.FeedId] = status; } + if (response.LastRefreshed is { } responseRefreshed && + (lastResponseRefreshed is null || responseRefreshed > lastResponseRefreshed)) + { + lastResponseRefreshed = responseRefreshed; + } } private async Task Refresh() @@ -420,6 +461,8 @@ else } } + private void ToggleEmptyFeeds() => hideEmptyFeeds = !hideEmptyFeeds; + private int CountFor(string? groupId, string? feedId) => items.Count(i => (groupId is null || i.GroupId == groupId) && (feedId is null || i.FeedId == feedId)); @@ -494,6 +537,15 @@ else : $"{(int)span.TotalDays}d"; } + public static string FormatLastUpdated(DateTimeOffset refreshedAt, DateTimeOffset? now = null) + { + var age = Age(refreshedAt, now); + return age == "just now" ? "Updated just now" : $"Updated {age} ago"; + } + + public static string FormatLastUpdatedTooltip(DateTimeOffset refreshedAt) => + $"Last updated: {refreshedAt.ToLocalTime():f}"; + public void Dispose() { // Not disposed: batches still awaiting the throttle observe the cancellation. diff --git a/src/NoteBookmark.SharedUI/Components/Pages/ManageFeeds.razor b/src/NoteBookmark.SharedUI/Components/Pages/ManageFeeds.razor index 3d78517..9bce5fe 100644 --- a/src/NoteBookmark.SharedUI/Components/Pages/ManageFeeds.razor +++ b/src/NoteBookmark.SharedUI/Components/Pages/ManageFeeds.razor @@ -3,6 +3,7 @@ @using Microsoft.AspNetCore.Authorization @inject IFeedService feedService @inject IToastService toastService +@inject IDialogService dialogService Manage feeds @@ -41,7 +42,7 @@ else

Import OPML

-

Import a subscription list, such as a Feedly export. Folders become groups; feeds you already follow are skipped.

+

Import a subscription list, such as a Feedly export. Folders become groups; feeds you already follow are skipped. Each new feed is checked, and broken addresses are fixed when possible.

@@ -114,25 +115,40 @@ else @foreach (var feed in shown.OrderBy(f => f.Title, StringComparer.OrdinalIgnoreCase)) {
-
- @if (!string.IsNullOrEmpty(feed.SiteUrl)) - { - @feed.Title - } - else - { - @feed.Title - } -
@feed.FeedUrl
-
- - + @if (editingFeedId == feed.RowKey) + { +
+ + +
+ Save + Cancel + } + else + { +
+ @if (!string.IsNullOrEmpty(feed.SiteUrl)) + { + @feed.Title + } + else + { + @feed.Title + } +
@feed.FeedUrl
+
+ + + + }
} } @@ -164,6 +180,7 @@ else .feed-row:hover { background: var(--neutral-fill-stealth-hover); } .feed-row-text { flex: 1; min-width: 0; } .feed-row-title { font-weight: 500; } + .feed-row-edit { flex: 1; min-width: 0; display: flex; flex-wrap: wrap; gap: 0.5rem; } .feed-row-url { font-size: 0.8em; color: var(--neutral-foreground-hint); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } @@ -183,6 +200,10 @@ else private string filter = string.Empty; private string? editingGroupId; private string renameText = string.Empty; + private string? editingFeedId; + private string editTitle = string.Empty; + private string editUrl = string.Empty; + private bool savingFeed; private bool Filtering => !string.IsNullOrWhiteSpace(filter); @@ -279,6 +300,8 @@ else private void StartRename(FeedGroup group) { + // Only one row (group or feed) is edited at a time. + editingFeedId = null; editingGroupId = group.RowKey; renameText = group.Name; } @@ -340,6 +363,80 @@ else toastService.ShowSuccess($"Moved \"{feed.Title}\" to {group.Name}."); } + private void StartFeedEdit(Feed feed) + { + // Only one row (group or feed) is edited at a time. + editingGroupId = null; + editingFeedId = feed.RowKey; + editTitle = feed.Title; + editUrl = feed.FeedUrl; + } + + private void CancelFeedEdit() => editingFeedId = null; + + private bool FeedUrlChanged(Feed feed) => editUrl.Trim() != feed.FeedUrl; + + private bool FeedEditChanged(Feed feed) => + !string.IsNullOrWhiteSpace(editUrl) && (editTitle.Trim() != feed.Title || FeedUrlChanged(feed)); + + private async Task SaveFeedEdit(Feed feed) + { + if (!FeedEditChanged(feed)) + { + return; + } + + savingFeed = true; + try + { + // Work on a copy so the row keeps its values when anything fails. + var updated = new Feed + { + RowKey = feed.RowKey, + GroupId = feed.GroupId, + Title = editTitle.Trim(), + FeedUrl = feed.FeedUrl, + SiteUrl = feed.SiteUrl, + ETag = feed.ETag + }; + + if (FeedUrlChanged(feed)) + { + var discovered = await feedService.Discover(editUrl.Trim()); + if (!discovered.Success || discovered.Value is null) + { + toastService.ShowError(discovered.Error ?? "No feed found at this address."); + return; + } + + // The discovered feed URL may differ from what was typed (e.g. a site URL); the typed title is kept. + updated.FeedUrl = discovered.Value.FeedUrl; + if (string.IsNullOrWhiteSpace(updated.SiteUrl)) + { + updated.SiteUrl = discovered.Value.SiteUrl; + } + } + + var result = await feedService.SaveFeed(updated); + if (!result.Success || result.Value is null) + { + toastService.ShowError(result.Error ?? "The feed could not be saved."); + return; + } + + feed.Title = result.Value.Title; + feed.FeedUrl = result.Value.FeedUrl; + feed.SiteUrl = result.Value.SiteUrl; + feed.ETag = result.Value.ETag; + editingFeedId = null; + toastService.ShowSuccess($"Updated \"{feed.Title}\"."); + } + finally + { + savingFeed = false; + } + } + private async Task DeleteFeed(Feed feed) { var result = await feedService.DeleteFeed(feed.RowKey); @@ -380,11 +477,34 @@ else // Groups stay collapsed, so even a few hundred imported feeds render instantly. await Reload(); var r = result.Value; - toastService.ShowSuccess($"Imported {r.FeedsCreated} feed(s) in {r.GroupsCreated} new group(s); {r.FeedsSkipped} already followed."); + var fixedText = r.FeedsFixed > 0 ? $" {r.FeedsFixed} address(es) fixed automatically." : string.Empty; + toastService.ShowSuccess($"Imported {r.FeedsCreated} feed(s) in {r.GroupsCreated} new group(s); {r.FeedsSkipped} already followed.{fixedText}"); + + if (r.FailedFeeds.Count > 0) + { + importing = false; + await ShowImportReport(r); + } } finally { importing = false; } } + + /// Lists the imported feeds that still fail, to edit or delete them now or keep them for later. + private async Task ShowImportReport(OpmlImportResult result) + { + var dialog = await dialogService.ShowDialogAsync( + new OpmlImportReport { FailedFeeds = result.FailedFeeds, Feeds = feeds }, + new DialogParameters + { + Title = $"{result.FailedFeeds.Count} feed(s) need attention", + Width = "min(760px, 95vw)", + PreventScroll = true, + TrapFocus = true + }); + await dialog.Result; + await Reload(); // the dialog may have edited or deleted feeds + } } diff --git a/src/NoteBookmark.SharedUI/Components/Pages/Settings.razor b/src/NoteBookmark.SharedUI/Components/Pages/Settings.razor index 2563185..d07c0a8 100644 --- a/src/NoteBookmark.SharedUI/Components/Pages/Settings.razor +++ b/src/NoteBookmark.SharedUI/Components/Pages/Settings.razor @@ -102,6 +102,26 @@ + + + Feeds + + + + + + + + + Save @@ -139,6 +159,7 @@ private Domain.Settings? settings; private record FontSizeOption(string Text, string Value); + private record FeedRefreshIntervalOption(string Text, string Value); private static readonly List fontSizeOptions = new() { @@ -147,12 +168,43 @@ new("Large", "large") }; + private static readonly List feedRefreshIntervalOptions = new() + { + new("30 min", "30"), + new("1 h", "60"), + new("3 h", "180"), + new("6 h", "360"), + new("12 h", "720"), + new("24 h", "1440") + }; + + private string FeedRefreshIntervalValue + { + get => (settings?.FeedRefreshIntervalMinutes is > 0 + ? settings.FeedRefreshIntervalMinutes + : Domain.Settings.DefaultFeedRefreshIntervalMinutes).ToString(); + set + { + if (settings != null && int.TryParse(value, out var minutes)) + { + settings.FeedRefreshIntervalMinutes = minutes; + } + } + } + protected override async Task OnInitializedAsync() { settings = await client.GetSettings(); - if (settings != null && string.IsNullOrWhiteSpace(settings.FontSize)) + if (settings != null) { - settings.FontSize = FontSizeHelper.DefaultFontSize; + if (string.IsNullOrWhiteSpace(settings.FontSize)) + { + settings.FontSize = FontSizeHelper.DefaultFontSize; + } + if (settings.FeedRefreshIntervalMinutes <= 0) + { + settings.FeedRefreshIntervalMinutes = Domain.Settings.DefaultFeedRefreshIntervalMinutes; + } } } diff --git a/src/NoteBookmark.SharedUI/Components/Shared/OpmlImportReportDialog.razor b/src/NoteBookmark.SharedUI/Components/Shared/OpmlImportReportDialog.razor new file mode 100644 index 0000000..afa1a6e --- /dev/null +++ b/src/NoteBookmark.SharedUI/Components/Shared/OpmlImportReportDialog.razor @@ -0,0 +1,214 @@ +@implements IDialogContentComponent +@inject IFeedService feedService +@inject IToastService toastService + +
+ @if (remaining.Count == 0) + { +

All failed feeds have been handled.

+ } + else + { +

+ @remaining.Count feed(s) could not be loaded, even after trying https, the site's own feed link, and adding /feed. + They were imported anyway. Edit the address, delete the feed, or keep it to deal with later. +

+ @foreach (var failed in remaining) + { +
+
+
@failed.Title · @failed.GroupName
+ @if (editingId == failed.FeedId) + { +
+ + Save + Cancel +
+ } + else + { +
@failed.FeedUrl
+ } +
@FeedErrorKind.Describe(failed.ErrorKind) @if (!string.IsNullOrEmpty(failed.Error)) { (@failed.Error) }
+
+ @if (editingId != failed.FeedId) + { + + + } +
+ } + } +
+ + + + @if (remaining.Count > 0) + { + Discard all and close + } + @(remaining.Count == 0 ? "Close" : "Keep the rest and close") + + + + +@code { + [Parameter] + public OpmlImportReport Content { get; set; } = default!; + + [CascadingParameter] + public FluentDialog? Dialog { get; set; } + + private List remaining = []; + private string? editingId; + private string editUrl = string.Empty; + private bool saving; + private bool deleting; + private bool discardingAll; + private bool busy => saving || deleting || discardingAll; + + protected override void OnInitialized() => remaining = Content.FailedFeeds.ToList(); + + private void StartEdit(OpmlFailedFeed failed) + { + editingId = failed.FeedId; + editUrl = failed.FeedUrl; + } + + private void CancelEdit() => editingId = null; + + private async Task SaveEdit(OpmlFailedFeed failed) + { + var feed = Content.Feeds.FirstOrDefault(f => f.RowKey == failed.FeedId); + if (feed is null) + { + toastService.ShowError("This feed is no longer in your list."); + remaining.Remove(failed); + editingId = null; + return; + } + + saving = true; + try + { + // Same rules as editing a feed in Manage feeds: the address must lead to a working feed. + var discovered = await feedService.Discover(editUrl.Trim()); + if (!discovered.Success || discovered.Value is null) + { + toastService.ShowError(discovered.Error ?? "No feed found at this address."); + return; + } + + var updated = new Feed + { + RowKey = feed.RowKey, + GroupId = feed.GroupId, + Title = feed.Title, + FeedUrl = discovered.Value.FeedUrl, + SiteUrl = string.IsNullOrWhiteSpace(feed.SiteUrl) ? discovered.Value.SiteUrl : feed.SiteUrl, + ETag = feed.ETag + }; + var result = await feedService.SaveFeed(updated); + if (!result.Success || result.Value is null) + { + toastService.ShowError(result.Error ?? "The feed could not be saved."); + return; + } + + feed.FeedUrl = result.Value.FeedUrl; + feed.SiteUrl = result.Value.SiteUrl; + feed.ETag = result.Value.ETag; + remaining.Remove(failed); + editingId = null; + toastService.ShowSuccess($"Updated \"{feed.Title}\"."); + } + finally + { + saving = false; + } + } + + private async Task Delete(OpmlFailedFeed failed) + { + deleting = true; + try + { + var result = await feedService.DeleteFeed(failed.FeedId); + if (!result.Success) + { + toastService.ShowError(result.Error ?? "The feed could not be deleted."); + return; + } + + remaining.Remove(failed); + toastService.ShowSuccess($"Removed \"{failed.Title}\"."); + } + finally + { + deleting = false; + } + } + + private async Task DiscardAllAndClose() + { + if (remaining.Count == 0) + { + return; + } + + discardingAll = true; + try + { + var targets = remaining.ToList(); + var removedCount = 0; + string? firstError = null; + + foreach (var failed in targets) + { + var result = await feedService.DeleteFeed(failed.FeedId); + if (result.Success) + { + remaining.Remove(failed); + removedCount++; + } + else + { + firstError ??= result.Error ?? "Some feeds could not be deleted."; + } + } + + if (remaining.Count == 0) + { + toastService.ShowSuccess($"Removed {removedCount} feed(s)."); + await Close(); + } + else + { + toastService.ShowError(firstError ?? "Some feeds could not be deleted."); + } + } + finally + { + discardingAll = false; + } + } + + private Task Close() => Dialog?.CloseAsync() ?? Task.CompletedTask; +} diff --git a/src/NoteBookmark.SharedUI/OpmlImportReport.cs b/src/NoteBookmark.SharedUI/OpmlImportReport.cs new file mode 100644 index 0000000..b75df86 --- /dev/null +++ b/src/NoteBookmark.SharedUI/OpmlImportReport.cs @@ -0,0 +1,12 @@ +using NoteBookmark.Domain; + +namespace NoteBookmark.SharedUI; + +/// Content of the OPML import report dialog: the feeds that still fail and the saved feeds they map to. +public class OpmlImportReport +{ + public List FailedFeeds { get; set; } = []; + + /// The user's feeds after the import, to edit a failed feed without losing its group or ETag. + public List Feeds { get; set; } = []; +} From 5a41372121b04389c884faa6bad54ae65379cd37 Mon Sep 17 00:00:00 2001 From: fboucher <2404846+fboucher@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:05:15 +0000 Subject: [PATCH 2/3] Initial plan From 2f9ccd623aa03fc292e9eaef3e3830cd50a569d3 Mon Sep 17 00:00:00 2001 From: fboucher <2404846+fboucher@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:06:51 +0000 Subject: [PATCH 3/3] Decode HTML entities and normalize whitespace in extracted post metadata Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- .../Endpoints/PostHtmlExtractionTests.cs | 63 +++++++++++++++++++ src/NoteBookmark.Api/PostEndpoints.cs | 20 +++++- 2 files changed, 80 insertions(+), 3 deletions(-) create mode 100644 src/NoteBookmark.Api.Tests/Endpoints/PostHtmlExtractionTests.cs diff --git a/src/NoteBookmark.Api.Tests/Endpoints/PostHtmlExtractionTests.cs b/src/NoteBookmark.Api.Tests/Endpoints/PostHtmlExtractionTests.cs new file mode 100644 index 0000000..24015f7 --- /dev/null +++ b/src/NoteBookmark.Api.Tests/Endpoints/PostHtmlExtractionTests.cs @@ -0,0 +1,63 @@ +using FluentAssertions; +using HtmlAgilityPack; +using Xunit; + +namespace NoteBookmark.Api.Tests.Endpoints; + +public class PostHtmlExtractionTests +{ + private static NoteBookmark.Domain.Post Extract(string html) + { + var doc = new HtmlDocument(); + doc.LoadHtml(html); + return PostEndpoints.BuildPostFromHtml(doc, "https://example.com/a"); + } + + [Fact] + public void Title_DecodesNumericEntities() + { + var post = Extract("Your Skills Don't Count If Agents Can't Find Them"); + post.Title.Should().Be("Your Skills Don't Count If Agents Can't Find Them"); + } + + [Fact] + public void Metadata_DecodesNamedDecimalAndHexEntities() + { + var post = Extract("A & B "q" 'x' ’ — ’ ' ’" + + ""); + post.Title.Should().Be("A & B \"q\" 'x' ’ — ’ ' ’"); + post.Author.Should().Be("Tom & Jerry 's"); + post.Excerpt.Should().Be("It’s 'ok'"); + } + + [Fact] + public void Metadata_CollapsesWhitespace() + { + var post = Extract("\n Hello   \t World \n"); + post.Title.Should().Be("Hello World"); + } + + [Fact] + public void Metadata_PreservesAngleBrackets() + { + var post = Extract("Using <T> here and <T>\">"); + post.Title.Should().Be("Using here"); + post.Excerpt.Should().Contain("<T>".Replace("<", "<").Replace(">", ">")); + } + + [Fact] + public void Title_DecodesOnlyOnce() + { + var post = Extract("a &#39; b"); + post.Title.Should().Be("a ' b"); + } + + [Fact] + public void MissingNodes_ProduceNull() + { + var post = Extract(""); + post.Title.Should().BeNull(); + post.Author.Should().BeNull(); + post.Excerpt.Should().BeNull(); + } +} diff --git a/src/NoteBookmark.Api/PostEndpoints.cs b/src/NoteBookmark.Api/PostEndpoints.cs index 4126aac..57fe970 100644 --- a/src/NoteBookmark.Api/PostEndpoints.cs +++ b/src/NoteBookmark.Api/PostEndpoints.cs @@ -187,7 +187,11 @@ static Results, NotFound, BadRequest> PatchPost(string id, Post post, T Console.WriteLine($"An error Loading the page URL={url} /n Error: {docloadEx.Message}"); } + return BuildPostFromHtml(doc, url); + } + public static Post BuildPostFromHtml(HtmlDocument doc, string url) + { var titleNode = doc.DocumentNode.SelectSingleNode("//head/title"); var authorNode = doc.DocumentNode.SelectSingleNode("//meta[@name='author']"); var descriptionNode = doc.DocumentNode.SelectSingleNode("//meta[@name='description']"); @@ -214,9 +218,9 @@ static Results, NotFound, BadRequest> PatchPost(string id, Post post, T { Url = url, Domain = new Uri(url).Host, - Title = titleNode?.InnerText, - Author = authorNode?.GetAttributeValue("content", string.Empty), - Excerpt = descriptionNode?.GetAttributeValue("content", string.Empty), + Title = NormalizeText(titleNode?.InnerText), + Author = NormalizeText(authorNode?.GetAttributeValue("content", string.Empty)), + Excerpt = NormalizeText(descriptionNode?.GetAttributeValue("content", string.Empty)), PartitionKey = DateTime.UtcNow.ToString("yyyy-MM"), Date_published = publicationDate.ToString("yyyy-MM-ddTHH:mm:ssZ"), is_read = false, @@ -226,6 +230,16 @@ static Results, NotFound, BadRequest> PatchPost(string id, Post post, T }; return post; } + + private static string? NormalizeText(string? text) + { + if (text is null) + { + return null; + } + var decoded = System.Net.WebUtility.HtmlDecode(text); + return System.Text.RegularExpressions.Regex.Replace(decoded, @"\s+", " ").Trim(); + } } public record ExtractPostRequest(string url, string? tags = null, string? category = null);