news: new sitemap-driven reader app (com.vayunmathur.news)
- Commit
45f3c295d805c9a085e02331c2272999af655f88- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-23 16:59 UTC (12 days ago)
- Parents
9b6c115
Everything on device: verified publisher news sitemaps (BBC, Al Jazeera, TechCrunch, ProPublica, El Pais, Guardian) plus RSS for sources without sitemaps; JS- overlay/metered sources verified to carry full article text in raw HTML, server-walled sources excluded (Reuters, AP, NYT et al.). Parsing, feed merge (URL-normalised dedupe), and Readability-style extraction are pure domain code; Room caches feed + bodies offline; sources, feed, saved, reader screens with Route-carried article URLs; one Networking entry with the SYSTEM trust bundle (narrowest that reaches arbitrary publishers). Reader mode is first-class: adjustable text size, serif/sans, inline images, bookmark, web-view toggle. Verified: 12 tests (parsers, extraction, merge, repo) green; compile, lint, detekt green. Guardian articles 403 from datacentre IPs (badged; device fetch pending).
Diff
AGENTS.md
diff --git a/AGENTS.md b/AGENTS.mdindex 8ef8fd4856..132b28fd70 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -46,7 +46,7 @@ Monorepo: ~100 Gradle modules + Rust workspace. Do scoped work only. ### Apps (Gradle key → dir) Reference: `backup/` satisfies every rule; `notes/` second + `intents/` demo. `camera` + `games/voxels` hand-commit screenshots. Full canonical index (Gradle key → dir + group + notes): `.llms/repo-map.md`.-`appstore→appstore/` `astronomy→astronomy/` `auto→auto/,auto/protocol/` `backup→backup/` `calculator→calculator/` `calendar→calendar/` `camera→camera/` `cast→cast/,cast/protocol/,cast/tv/` `clock→clock/` `code→code/` `communicate→communicate/` `contacts→contacts/` `education→education/` `email→email/` `emergency→emergency/` `euicc→euicc/` `everysync→everysync/` `files→files/` `findfamily→findfamily/` `findfamily-ios→apple/FindFamily/` (SwiftPM/xtool, not Gradle) `flashcards→flashcards/` `fooddelivery→fooddelivery/` `health→health/` `keyboard→keyboard/` `launcher→launcher/` `logviewer→logviewer/` `maps→maps/` `measure→measure/` `music→music/` `networklocation→networklocation/` `notes→notes/` `office→office/` `openassistant→openassistant/` `passwords→passwords/` `pdf→pdf/` `photos→photos/` `parentalcontrols→parentalcontrols/` `screentime→screentime/` `setupwizard→setupwizard/` `share→share/` `speech→speech/` `taxi→taxi/` `things→things/` `todo→todo/` `translate→translate/` `travel→travel/` `tuner→tuner/` `updater→updater/` `vpn→vpn/` `weather→weather/` `web→web/` `youpipe→youpipe/,youpipe/extractor/` `games-hub→games/hub/` `games-arrows→games/arrows/` `games-chess→games/chess/` `games-logicgate→games/logicgate/` `games-minesweeper→games/minesweeper/` `games-nonogram→games/nonogram/` `games-pipes→games/pipes/` `games-solitaire→games/solitaire/` `games-sudoku→games/sudoku/` `games-unblockjam→games/unblockjam/` `games-voxels→games/voxels/` `games-wordmaker→games/wordmaker/`+`appstore→appstore/` `astronomy→astronomy/` `auto→auto/,auto/protocol/` `backup→backup/` `calculator→calculator/` `calendar→calendar/` `camera→camera/` `cast→cast/,cast/protocol/,cast/tv/` `clock→clock/` `code→code/` `communicate→communicate/` `contacts→contacts/` `education→education/` `email→email/` `emergency→emergency/` `euicc→euicc/` `everysync→everysync/` `files→files/` `findfamily→findfamily/` `findfamily-ios→apple/FindFamily/` (SwiftPM/xtool, not Gradle) `flashcards→flashcards/` `fooddelivery→fooddelivery/` `health→health/` `keyboard→keyboard/` `launcher→launcher/` `logviewer→logviewer/` `maps→maps/` `measure→measure/` `music→music/` `networklocation→networklocation/` `news→news/` `notes→notes/` `office→office/` `openassistant→openassistant/` `passwords→passwords/` `pdf→pdf/` `photos→photos/` `parentalcontrols→parentalcontrols/` `screentime→screentime/` `setupwizard→setupwizard/` `share→share/` `speech→speech/` `taxi→taxi/` `things→things/` `todo→todo/` `translate→translate/` `travel→travel/` `tuner→tuner/` `updater→updater/` `vpn→vpn/` `weather→weather/` `web→web/` `youpipe→youpipe/,youpipe/extractor/` `games-hub→games/hub/` `games-arrows→games/arrows/` `games-chess→games/chess/` `games-logicgate→games/logicgate/` `games-minesweeper→games/minesweeper/` `games-nonogram→games/nonogram/` `games-pipes→games/pipes/` `games-solitaire→games/solitaire/` `games-sudoku→games/sudoku/` `games-unblockjam→games/unblockjam/` `games-voxels→games/voxels/` `games-wordmaker→games/wordmaker/` Slash == colon for Gradle (`games/voxels` == `games:voxels`). ### Never scan
library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.ktindex a5b6451881..25cd4a0fbe 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -227,6 +227,10 @@ import androidx.compose.material.icons.filled.PhotoLibrary import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material.icons.filled.PlayCircle import androidx.compose.material.icons.filled.Public+import androidx.compose.material.icons.filled.Bookmark+import androidx.compose.material.icons.filled.BookmarkBorder+import androidx.compose.material.icons.filled.Newspaper+import androidx.compose.material.icons.filled.OpenInNew import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.RemoveCircleOutline import androidx.compose.material.icons.filled.Repeat@@ -1978,3 +1982,19 @@ fun IconBugReport(modifier: Modifier = Modifier, tint: Color = LocalContentColor @Composable fun IconInstall(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) = AppIcon(Icons.Filled.SystemUpdateAlt, "Install", modifier, tint)++@Composable+fun IconBookmark(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.Bookmark, "Saved", modifier, tint)++@Composable+fun IconBookmarkBorder(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.BookmarkBorder, "Save for later", modifier, tint)++@Composable+fun IconNewspaper(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.Newspaper, "News", modifier, tint)++@Composable+fun IconOpenInNew(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+ AppIcon(Icons.Filled.OpenInNew, "Open in browser", modifier, tint)
metadata_data/news.md
diff --git a/metadata_data/news.md b/metadata_data/news.mdnew file mode 100644index 0000000000..56b300c768--- /dev/null+++ b/metadata_data/news.md@@ -0,0 +1,10 @@+A news reader that fetches articles directly from publishers - no account, no server of ours++Features:+- News from built-in sources (BBC, The Guardian, Al Jazeera, TechCrunch, ProPublica, El País, NPR, DW, Ars Technica, The Verge, Hacker News), each fetched from its own sitemap or feed+- Enable or disable sources; filter the merged, newest-first feed by source+- Clean reader view extracted on your device (no tracking, no external service), with adjustable text size and serif/sans choice+- Toggle to the original web page, or open the article in your browser+- Save articles for later; feed and read articles are cached for offline reading++Internet only used for: fetching publisher sitemaps, articles and article images directly from the publisher sites
news/AGENTS.md
diff --git a/news/AGENTS.md b/news/AGENTS.mdnew file mode 100644index 0000000000..5f2d368725--- /dev/null+++ b/news/AGENTS.md@@ -0,0 +1,70 @@+# AGENTS.md — news/ (':news')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside `news/` + allowed shared modules. Do not root-scan.++_Install: ./install news_+- Gradle: :news / dir: news/+- Package roots present: ui, data, domain, platform, network+- Entry files: MainActivity.kt, Route.kt, Navigation.kt+- Deps: :library:network, :library:room, :library:image+- Metadata: metadata_data/news.md (present)+- Rust: no / screenshotTest: no++## Overview+**Purpose:** Sitemap-driven news reader. Everything is on-device: feeds and+articles are fetched directly from publisher sites, parsed and extracted+locally. There is no backend and no account.+**Key features:**+- Built-in source catalog (`domain/SourceCatalog`) — Google News sitemaps+ where a verified one exists, RSS only where no sitemap verifies (NPR, DW,+ Ars, The Verge, Hacker News)+- Room-cached feed + extracted article bodies (offline reading), bookmarks+- Readability-style extraction in `domain/ArticleExtractor` over a small+ tolerant HTML DOM (`domain/HtmlDom`); reader with text size, serif/sans,+ and a toggle to the original web page++## Source verification (2026-11-23, via the dev box's proxied network)+Verified = sitemap/RSS fetched 200 and parsed + one article's raw HTML+contained the full body (paragraph text measured, tail checked):+- BBC `bbc.com/sitemaps/https-sitemap-com-news-1.xml` — full (no paywall)+- The Guardian `theguardian.com/sitemaps/news.xml` — sitemap verified;+ article pages returned 403 to the datacentre verification IP (no+ paywall exists), badged in the catalog+- Al Jazeera `aljazeera.com/news-sitemap.xml` — full+- TechCrunch `techcrunch.com/news-sitemap.xml` — full+- ProPublica `propublica.org/news-sitemap.xml` (index → daily urlsets) — full+- El País `elpais.com/sitemaps/news.xml` — full text present in raw HTML+ despite meter markers; badged as metered+- NPR (RSS), DW (RSS), Ars Technica (RSS), The Verge (RSS),+ Hacker News (RSS) — full article HTML verified on linked articles+Excluded after verification (body absent from raw HTML or fetch blocked):+Reuters (401), AP (403), NYT (bot wall + server-side paywall), WSJ/WaPo+(403), Axios (JS-only shell, no body in HTML), France 24 (403),+Japan Times (sitemap URL serves HTML, not XML).++## Architecture / data-flow+`ui/` feed/reader/sources/saved → `platform/NewsViewModel` →+`data/NewsRepository` (Room via `library/room`) + `data/NewsPrefs`+(DataStore owner) → `network/Networking` (the single networking entry+point, `NetworkClient` with `TrustBundle.SYSTEM` — publisher hosts are+arbitrary, so no reduced bundle can cover them) → `domain/` parsers and+extractor (pure, no Android imports).++## Entry points + reading order+`Route` (`Feed` / `Reader(url)` / `Sources` / `Saved`) → `MainActivity.kt`+→ `Navigation.kt` → `platform/NewsViewModel.kt` → `data/NewsRepository.kt`+→ `domain/SitemapParser.kt` + `domain/ArticleExtractor.kt`.++## Gotchas+- Selection is navigation: the article URL lives in `Route.Reader`, never+ in ViewModel state that swaps list→detail.+- A failing source never fails a refresh; the cached feed stays visible.+- Extraction quality is judged by `ExtractedArticle.bodyChars`; truncated+ extractions usually mean the source changed its markup or paywall.++## Verify (this module only)+```+./gradlew :news:compileDevKotlin+./gradlew :news:testDevUnitTest+./gradlew :news:lint+```
news/build.gradle.kts
diff --git a/news/build.gradle.kts b/news/build.gradle.ktsnew file mode 100644index 0000000000..9164f39b91--- /dev/null+++ b/news/build.gradle.kts@@ -0,0 +1,23 @@+plugins {+ id("common-conventions-app")+ alias(libs.plugins.ksp)+}++launcherIcon {+ symbol = "newspaper"+}++android {+ defaultConfig {+ applicationId = "com.vayunmathur.news"+ }+}++dependencies {+ implementation(project(":library:network"))+ implementation(project(":library:image"))+ implementRoom(libs)+ implementation(project(":library:room"))+ implementation(libs.androidx.datastore.preferences)+ testImplementation(libs.androidx.sqlite.bundled.jvm)+}
news/schemas/com.vayunmathur.news.data.NewsDatabase/1.json
diff --git a/news/schemas/com.vayunmathur.news.data.NewsDatabase/1.json b/news/schemas/com.vayunmathur.news.data.NewsDatabase/1.jsonnew file mode 100644index 0000000000..5459332629--- /dev/null+++ b/news/schemas/com.vayunmathur.news.data.NewsDatabase/1.json@@ -0,0 +1,123 @@+{+ "formatVersion": 1,+ "database": {+ "version": 1,+ "identityHash": "a64be95919611487f7656821da5e0f91",+ "entities": [+ {+ "tableName": "CachedArticle",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`url` TEXT NOT NULL, `sourceId` TEXT NOT NULL, `title` TEXT NOT NULL, `publishedAtMillis` INTEGER NOT NULL, `imageUrl` TEXT, `keywords` TEXT NOT NULL, `fetchedAtMillis` INTEGER NOT NULL, `bookmarked` INTEGER NOT NULL, PRIMARY KEY(`url`))",+ "fields": [+ {+ "fieldPath": "url",+ "columnName": "url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceId",+ "columnName": "sourceId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "publishedAtMillis",+ "columnName": "publishedAtMillis",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "imageUrl",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "keywords",+ "columnName": "keywords",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "fetchedAtMillis",+ "columnName": "fetchedAtMillis",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "bookmarked",+ "columnName": "bookmarked",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "url"+ ]+ }+ },+ {+ "tableName": "CachedBody",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`url` TEXT NOT NULL, `title` TEXT NOT NULL, `byline` TEXT, `publishedAtMillis` INTEGER, `heroImageUrl` TEXT, `blocksJson` TEXT NOT NULL, `fetchedAtMillis` INTEGER NOT NULL, PRIMARY KEY(`url`))",+ "fields": [+ {+ "fieldPath": "url",+ "columnName": "url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "byline",+ "columnName": "byline",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "publishedAtMillis",+ "columnName": "publishedAtMillis",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "heroImageUrl",+ "columnName": "heroImageUrl",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "blocksJson",+ "columnName": "blocksJson",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "fetchedAtMillis",+ "columnName": "fetchedAtMillis",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "url"+ ]+ }+ }+ ],+ "setupQueries": [+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'a64be95919611487f7656821da5e0f91')"+ ]+ }+}\ No newline at end of file
news/src/main/AndroidManifest.xml
diff --git a/news/src/main/AndroidManifest.xml b/news/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..fdb5564c76--- /dev/null+++ b/news/src/main/AndroidManifest.xml@@ -0,0 +1,29 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <!-- MAOS: opt out of the GrapheneOS Sensors permission (OTHER_SENSORS). -->+ <uses-permission android:name="com.vayunmathur.permission.SENSORS_OPTOUT" />+ <!-- Direct fetches from publisher sites only; no backend of ours. -->+ <uses-permission android:name="android.permission.INTERNET" />+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />++ <application+ android:allowBackup="true"+ android:dataExtractionRules="@xml/data_extraction_rules"+ android:icon="@mipmap/ic_launcher"+ android:label="@string/app_name"+ android:roundIcon="@mipmap/ic_launcher"+ android:supportsRtl="true"+ android:theme="@style/Theme.General">+ <activity+ android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+ android:name=".MainActivity"+ android:exported="true"+ android:theme="@style/Theme.General">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ </activity>+ </application>+</manifest>
news/src/main/java/com/vayunmathur/news/MainActivity.kt
diff --git a/news/src/main/java/com/vayunmathur/news/MainActivity.kt b/news/src/main/java/com/vayunmathur/news/MainActivity.ktnew file mode 100644index 0000000000..5ef2829c1b--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/MainActivity.kt@@ -0,0 +1,39 @@+package com.vayunmathur.news++import androidx.activity.viewModels+import androidx.compose.runtime.Composable+import com.vayunmathur.library.image.ImageLoader+import com.vayunmathur.library.image.fetchers.HttpImageFetcher+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.TrustBundle+import com.vayunmathur.library.ui.MaActivity+import com.vayunmathur.library.util.OfflineAware+import com.vayunmathur.news.data.NewsRepository+import com.vayunmathur.news.platform.NewsViewModel+import com.vayunmathur.news.platform.NewsViewModelFactory++/** Entry activity hosting the news feed, reader, sources and saved screens. */+class MainActivity : MaActivity() {+ private val viewModel: NewsViewModel by viewModels {+ NewsViewModelFactory(application, NewsRepository.get(application))+ }++ override fun onCreateBeforeContent() {+ // Publisher hosts are arbitrary public sites, so SYSTEM (platform+ // trust) is the narrowest TrustBundle that can reach them; the+ // reduced bundles only cover our own / well-known roots.+ NetworkClient.init(this, TrustBundle.SYSTEM)+ ImageLoader.setDefault(+ ImageLoader.Builder(this)+ .remote { data, _ -> HttpImageFetcher.fetch(data, NetworkClient::getBytes) }+ .build(),+ )+ }++ @Composable+ override fun Content() {+ OfflineAware {+ Navigation(viewModel)+ }+ }+}
news/src/main/java/com/vayunmathur/news/Navigation.kt
diff --git a/news/src/main/java/com/vayunmathur/news/Navigation.kt b/news/src/main/java/com/vayunmathur/news/Navigation.ktnew file mode 100644index 0000000000..b03b801cf8--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/Navigation.kt@@ -0,0 +1,42 @@+package com.vayunmathur.news++import androidx.compose.runtime.Composable+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.news.platform.NewsViewModel+import com.vayunmathur.news.ui.FeedScreen+import com.vayunmathur.news.ui.ReaderScreen+import com.vayunmathur.news.ui.SavedScreen+import com.vayunmathur.news.ui.SourcesScreen++@Composable+fun Navigation(viewModel: NewsViewModel) {+ val backStack = rememberNavBackStack<Route>(Route.Feed)+ MainNavigation(backStack) {+ entry<Route.Feed> {+ FeedScreen(+ viewModel = viewModel,+ onOpenArticle = { url -> backStack.add(Route.Reader(url)) },+ onOpenSources = { backStack.add(Route.Sources) },+ onOpenSaved = { backStack.add(Route.Saved) },+ )+ }+ entry<Route.Reader> {+ ReaderScreen(+ viewModel = viewModel,+ url = it.url,+ onBack = { backStack.pop() },+ )+ }+ entry<Route.Sources> {+ SourcesScreen(viewModel = viewModel, onBack = { backStack.pop() })+ }+ entry<Route.Saved> {+ SavedScreen(+ viewModel = viewModel,+ onOpenArticle = { url -> backStack.add(Route.Reader(url)) },+ onBack = { backStack.pop() },+ )+ }+ }+}
news/src/main/java/com/vayunmathur/news/Route.kt
diff --git a/news/src/main/java/com/vayunmathur/news/Route.kt b/news/src/main/java/com/vayunmathur/news/Route.ktnew file mode 100644index 0000000000..7f0b2ebb6c--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/Route.kt@@ -0,0 +1,24 @@+package com.vayunmathur.news++import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++@Serializable+/** Navigation destinations for the news app. */+sealed interface Route : NavKey {+ @Serializable+ /** Merged, newest-first feed across enabled sources. */+ data object Feed : Route++ @Serializable+ /** Clean reader (or original web view) for the article at [url]. */+ data class Reader(val url: String) : Route++ @Serializable+ /** Enable/disable built-in sources. */+ data object Sources : Route++ @Serializable+ /** Bookmarked articles, readable offline. */+ data object Saved : Route+}
news/src/main/java/com/vayunmathur/news/data/NewsDatabase.kt
diff --git a/news/src/main/java/com/vayunmathur/news/data/NewsDatabase.kt b/news/src/main/java/com/vayunmathur/news/data/NewsDatabase.ktnew file mode 100644index 0000000000..b33f9bbd9a--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/data/NewsDatabase.kt@@ -0,0 +1,73 @@+package com.vayunmathur.news.data++import androidx.room3.Dao+import androidx.room3.Database+import androidx.room3.Entity+import androidx.room3.PrimaryKey+import androidx.room3.Query+import androidx.room3.RoomDatabase+import androidx.room3.Upsert+import kotlinx.coroutines.flow.Flow++const val DB_NAME = "news-db"++/** Cached feed stub. [bookmarked] rows survive feed pruning. */+@Entity+data class CachedArticle(+ @PrimaryKey val url: String,+ val sourceId: String,+ val title: String,+ val publishedAtMillis: Long,+ val imageUrl: String? = null,+ val keywords: String = "",+ val fetchedAtMillis: Long = 0L,+ val bookmarked: Boolean = false,+)++/** Cached extracted body (blocks as JSON), so read articles open offline. */+@Entity+data class CachedBody(+ @PrimaryKey val url: String,+ val title: String,+ val byline: String? = null,+ val publishedAtMillis: Long? = null,+ val heroImageUrl: String? = null,+ val blocksJson: String = "[]",+ val fetchedAtMillis: Long = 0L,+)++@Dao+interface NewsDao {+ @Query("SELECT * FROM CachedArticle ORDER BY publishedAtMillis DESC")+ fun observeArticles(): Flow<List<CachedArticle>>++ @Query("SELECT * FROM CachedArticle WHERE bookmarked = 1 ORDER BY publishedAtMillis DESC")+ fun observeBookmarked(): Flow<List<CachedArticle>>++ @Query("SELECT * FROM CachedArticle WHERE url = :url")+ suspend fun article(url: String): CachedArticle?++ @Query("SELECT * FROM CachedBody WHERE url = :url")+ suspend fun body(url: String): CachedBody?++ @Upsert+ suspend fun upsertArticles(articles: List<CachedArticle>)++ @Upsert+ suspend fun upsertBody(body: CachedBody)++ @Query("UPDATE CachedArticle SET bookmarked = :bookmarked WHERE url = :url")+ suspend fun setBookmarked(url: String, bookmarked: Boolean)++ /** Prunes unbookmarked stubs older than the newest [keep] rows. */+ @Query(+ "DELETE FROM CachedArticle WHERE bookmarked = 0 AND url NOT IN " ++ "(SELECT url FROM CachedArticle ORDER BY publishedAtMillis DESC LIMIT :keep)",+ )+ suspend fun pruneArticles(keep: Int)+}++@Database(entities = [CachedArticle::class, CachedBody::class], version = 1, exportSchema = true)+abstract class NewsDatabase : RoomDatabase() {+ abstract fun newsDao(): NewsDao+}
news/src/main/java/com/vayunmathur/news/data/NewsPrefs.kt
diff --git a/news/src/main/java/com/vayunmathur/news/data/NewsPrefs.kt b/news/src/main/java/com/vayunmathur/news/data/NewsPrefs.ktnew file mode 100644index 0000000000..d51294faf6--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/data/NewsPrefs.kt@@ -0,0 +1,63 @@+package com.vayunmathur.news.data++import android.content.Context+import androidx.datastore.preferences.core.booleanPreferencesKey+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.intPreferencesKey+import androidx.datastore.preferences.core.stringSetPreferencesKey+import androidx.datastore.preferences.preferencesDataStore+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.catch+import kotlinx.coroutines.flow.map+import java.io.IOException++private val Context.newsDataStore by preferencesDataStore(name = "news")++/**+ * The app's only preferences owner. Enabled sources and reader settings.+ * A corrupt DataStore file reads as the documented defaults (all sources+ * enabled, 17sp sans) instead of crashing — see the catch in [safeData].+ */+class NewsPrefs(context: Context) {+ private val appContext = context.applicationContext++ private val safeData: Flow<androidx.datastore.preferences.core.Preferences> =+ appContext.newsDataStore.data.catch { e ->+ if (e is IOException) emit(androidx.datastore.preferences.core.emptyPreferences()) else throw e+ }++ /** Null means "never set": every source is enabled by default. */+ val disabledSourceIds: Flow<Set<String>> = safeData.map { it[DISABLED_SOURCES] ?: emptySet() }+ val readerTextSp: Flow<Int> = safeData.map { it[TEXT_SP] ?: DEFAULT_TEXT_SP }+ val readerSerif: Flow<Boolean> = safeData.map { it[SERIF] ?: false }+ val readerWebView: Flow<Boolean> = safeData.map { it[WEB_VIEW] ?: false }++ suspend fun setSourceEnabled(id: String, enabled: Boolean) {+ appContext.newsDataStore.edit { prefs ->+ val current = prefs[DISABLED_SOURCES] ?: emptySet()+ prefs[DISABLED_SOURCES] = if (enabled) current - id else current + id+ }+ }++ suspend fun setReaderTextSp(sp: Int) {+ appContext.newsDataStore.edit { it[TEXT_SP] = sp.coerceIn(MIN_TEXT_SP, MAX_TEXT_SP) }+ }++ suspend fun setReaderSerif(serif: Boolean) {+ appContext.newsDataStore.edit { it[SERIF] = serif }+ }++ suspend fun setReaderWebView(webView: Boolean) {+ appContext.newsDataStore.edit { it[WEB_VIEW] = webView }+ }++ companion object {+ const val DEFAULT_TEXT_SP = 17+ const val MIN_TEXT_SP = 13+ const val MAX_TEXT_SP = 24+ private val DISABLED_SOURCES = stringSetPreferencesKey("disabled_sources")+ private val TEXT_SP = intPreferencesKey("reader_text_sp")+ private val SERIF = booleanPreferencesKey("reader_serif")+ private val WEB_VIEW = booleanPreferencesKey("reader_web_view")+ }+}
news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt
diff --git a/news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt b/news/src/main/java/com/vayunmathur/news/data/NewsRepository.ktnew file mode 100644index 0000000000..de5e8f3397--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt@@ -0,0 +1,148 @@+package com.vayunmathur.news.data++import android.content.Context+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.room.RoomRepository+import com.vayunmathur.news.domain.ArticleBlock+import com.vayunmathur.news.domain.ArticleExtractor+import com.vayunmathur.news.domain.ExtractedArticle+import com.vayunmathur.news.domain.FeedMerger+import com.vayunmathur.news.domain.NewsSource+import com.vayunmathur.news.domain.SitemapParser+import com.vayunmathur.news.domain.SourceCatalog+import com.vayunmathur.news.network.Networking+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.flow.Flow+import kotlinx.serialization.builtins.ListSerializer+import kotlinx.serialization.json.Json++/**+ * Owns the Room cache and all feed/article fetching. The [fetch] seam+ * defaults to [Networking] and is replaced by a fake in unit tests, so+ * no test touches the network. Bodies are extracted on device only.+ */+class NewsRepository internal constructor(+ context: Context,+ private val fetch: suspend (String) -> String,+) : RoomRepository<NewsDatabase>(context, NewsDatabase::class, DB_NAME) {++ constructor(context: Context) : this(context, Networking::fetchText)++ private val dao get() = db.newsDao()+ private val json = Json { ignoreUnknownKeys = true }++ val articles: Flow<List<CachedArticle>> get() = dao.observeArticles()+ val bookmarked: Flow<List<CachedArticle>> get() = dao.observeBookmarked()++ suspend fun isBookmarked(url: String): Boolean = dao.article(url)?.bookmarked == true++ suspend fun setBookmarked(url: String, bookmarked: Boolean) =+ dao.setBookmarked(url, bookmarked)++ /**+ * Fetches every enabled source (sitemap indexes are followed one level,+ * recursively through this same function), merges and caches the result.+ * A failing source never fails the refresh. Returns sources that failed.+ */+ suspend fun refresh(sources: List<NewsSource>): List<String> = coroutineScope {+ val results = sources.map { source ->+ async {+ runCatching { fetchFeed(source, depth = 0) }+ .fold(+ onSuccess = { it to null },+ onFailure = { emptyList<com.vayunmathur.news.domain.FeedArticle>() to source.name },+ )+ }+ }.awaitAll()+ val failed = results.mapNotNull { it.second }+ val merged = FeedMerger.merge(results.map { it.first })+ val now = System.currentTimeMillis()+ if (merged.isNotEmpty()) {+ // Preserve bookmark flags already in the cache.+ val rows = merged.map { article ->+ val existing = dao.article(article.url)+ CachedArticle(+ url = article.url, sourceId = article.sourceId, title = article.title,+ publishedAtMillis = article.publishedAtMillis, imageUrl = article.imageUrl,+ keywords = article.keywords.joinToString(","),+ fetchedAtMillis = now, bookmarked = existing?.bookmarked ?: false,+ )+ }+ dao.upsertArticles(rows)+ dao.pruneArticles(keep = 500)+ }+ failed+ }++ private suspend fun fetchFeed(+ source: NewsSource,+ depth: Int,+ ): List<com.vayunmathur.news.domain.FeedArticle> {+ val parsed = SitemapParser.parse(fetch(source.feedUrl), source.id)+ if (parsed.childSitemaps.isEmpty() || depth >= MAX_INDEX_DEPTH) return parsed.articles+ // Indexes list newest child first; the first few carry today's news.+ return coroutineScope {+ parsed.childSitemaps.take(MAX_INDEX_CHILDREN).map { child ->+ async {+ runCatching {+ val childParsed = SitemapParser.parse(fetch(child), source.id)+ if (childParsed.childSitemaps.isNotEmpty() && depth + 1 < MAX_INDEX_DEPTH) {+ childParsed.childSitemaps.take(MAX_INDEX_CHILDREN - 1).flatMap { grandchild ->+ runCatching {+ SitemapParser.parse(fetch(grandchild), source.id).articles+ }.getOrElse {+ Log.error(TAG, "feed fetch failed")+ emptyList()+ }+ }+ } else {+ childParsed.articles+ }+ }.getOrElse {+ Log.error(TAG, "feed fetch failed")+ emptyList()+ }+ }+ }.awaitAll().flatten()+ }+ }++ /** Cached body if present, otherwise fetch + extract + cache. Throws on fetch failure with no cache. */+ suspend fun articleBody(url: String): ExtractedArticle {+ dao.body(url)?.let { return it.toExtracted(json) }+ val extracted = ArticleExtractor.extract(fetch(url), url)+ dao.upsertBody(extracted.toCached(json))+ return extracted+ }++ companion object {+ private const val TAG = "NewsRepository"+ private const val MAX_INDEX_DEPTH = 2+ private const val MAX_INDEX_CHILDREN = 3++ @Volatile+ private var instance: NewsRepository? = null++ fun get(context: Context): NewsRepository =+ instance ?: synchronized(this) {+ instance ?: NewsRepository(context.applicationContext).also { instance = it }+ }+ }+}++internal fun ExtractedArticle.toCached(json: Json): CachedBody = CachedBody(+ url = url, title = title, byline = byline, publishedAtMillis = publishedAtMillis,+ heroImageUrl = heroImageUrl,+ blocksJson = json.encodeToString(ListSerializer(ArticleBlock.serializer()), blocks),+ fetchedAtMillis = System.currentTimeMillis(),+)++internal fun CachedBody.toExtracted(json: Json): ExtractedArticle = ExtractedArticle(+ url = url, title = title, byline = byline, publishedAtMillis = publishedAtMillis,+ heroImageUrl = heroImageUrl,+ blocks = runCatching {+ json.decodeFromString(ListSerializer(ArticleBlock.serializer()), blocksJson)+ }.getOrDefault(emptyList()),+)
news/src/main/java/com/vayunmathur/news/domain/ArticleExtractor.kt
diff --git a/news/src/main/java/com/vayunmathur/news/domain/ArticleExtractor.kt b/news/src/main/java/com/vayunmathur/news/domain/ArticleExtractor.ktnew file mode 100644index 0000000000..ffb1ee6518--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/domain/ArticleExtractor.kt@@ -0,0 +1,155 @@+package com.vayunmathur.news.domain++/**+ * Readability-style on-device extraction. Scores candidate containers by+ * paragraph text density (Readability's core idea), then walks the winner+ * in document order keeping paragraphs, headings, list items, quotes and+ * inline images — dropping navigation, ads, related-links and share chrome+ * by tag, class/id hint and link density. Pure: same input, same output.+ */+object ArticleExtractor {+ private val chromeTags = setOf(+ "nav", "header", "footer", "aside", "form", "button", "select",+ "textarea", "input", "figure", "figcaption",+ )+ private val chromeHints = listOf(+ "nav", "menu", "sidebar", "footer", "header", "advert", "promo",+ "related", "recommend", "share", "social", "newsletter", "cookie",+ "consent", "paywall", "subscribe", "signup", "sign-up", "breadcrumb",+ "pagination", "comment", "toolbar", "masthead", "outbrain", "taboola",+ )+ private val dropPhrases = listOf(+ "read more", "read next", "sign up", "subscribe to", "already a subscriber",+ "share this", "follow us", "advertisement", "click here",+ )++ fun extract(html: String, url: String): ExtractedArticle {+ val doc = HtmlDom.parse(html)+ val title = metaContent(doc, "og:title")+ ?: doc.first("h1")?.textContent()?.takeIf { it.isNotBlank() }+ ?: doc.first("title")?.textContent()?.substringBefore(" | ")?.substringBefore(" - ")+ ?: ""+ val byline = metaContent(doc, "author")+ ?: metaContent(doc, "article:author")+ ?: doc.findAll("a").firstOrNull { it.attr("rel") == "author" }?.textContent()+ val published = metaContent(doc, "article:published_time")+ ?: doc.findAll("time").firstOrNull()?.attr("datetime")+ val hero = metaContent(doc, "og:image")+ val main = pickMain(doc)+ val blocks = mutableListOf<ArticleBlock>()+ val seen = HashSet<String>()+ if (main != null) collectBlocks(main, url, blocks, seen)+ if (hero != null && blocks.none { it is ArticleBlock.Image && it.url == hero }) {+ blocks.add(0, ArticleBlock.Image(hero))+ }+ return ExtractedArticle(+ url = url, title = title.trim(), byline = byline?.trim()?.takeIf { it.isNotEmpty() },+ publishedAtMillis = DateParsing.parseMillis(published),+ heroImageUrl = hero, blocks = blocks,+ )+ }++ private fun metaContent(doc: HtmlElement, property: String): String? =+ doc.findAll("meta").firstOrNull {+ it.attr("property") == property || it.attr("name") == property+ }?.attr("content")?.takeIf { it.isNotBlank() }++ /** The element with the highest paragraph-density score wins, like Readability. */+ private fun pickMain(doc: HtmlElement): HtmlElement? {+ val candidates = mutableListOf<HtmlElement>()+ candidates += doc.findAll("article")+ candidates += doc.findAll("main")+ candidates += doc.findAll("div")+ candidates += doc.findAll("section")+ var best: HtmlElement? = null+ var bestScore = -1.0+ for (candidate in candidates) {+ if (isChrome(candidate)) continue+ var score = 0.0+ for (p in candidate.findAll("p")) {+ val len = p.textContent().length+ if (len >= 40) score += len + if (p.textContent().contains(',')) 20.0 else 0.0+ }+ // Link density is the classic chrome signal: penalise link-heavy containers.+ val totalText = candidate.textContent().length.coerceAtLeast(1)+ val linkText = candidate.findAll("a").sumOf { it.textContent().length }+ score *= (1.0 - linkText.toDouble() / totalText).coerceIn(0.0, 1.0)+ if (candidate.tag == "article" || candidate.tag == "main") score *= 1.5+ if (score > bestScore) {+ bestScore = score+ best = candidate+ }+ }+ return best ?: doc.first("body") ?: doc+ }++ private fun collectBlocks(+ element: HtmlElement,+ baseUrl: String,+ out: MutableList<ArticleBlock>,+ seen: MutableSet<String>,+ ) {+ for (child in element.children) {+ if (child !is HtmlElement || isChrome(child)) continue+ when (child.tag) {+ "p", "blockquote", "li" -> {+ val text = child.textContent()+ if (isKeepableParagraph(text) && seen.add(text)) {+ out += ArticleBlock.Paragraph(text)+ }+ }+ "h2", "h3", "h4" -> {+ val text = child.textContent()+ if (text.length in 3..200 && seen.add(text)) out += ArticleBlock.Heading(text)+ }+ "img" -> imageOf(child, baseUrl)?.let { out += it }+ else -> collectBlocks(child, baseUrl, out, seen)+ }+ }+ }++ private fun imageOf(img: HtmlElement, baseUrl: String): ArticleBlock.Image? {+ val raw = img.attr("src") ?: img.attr("data-src") ?: return null+ if (raw.startsWith("data:") || raw.contains("pixel") || raw.contains("tracker")) return null+ val resolved = resolveUrl(baseUrl, raw) ?: return null+ return ArticleBlock.Image(resolved, img.attr("alt")?.takeIf { it.isNotBlank() })+ }++ private fun isKeepableParagraph(text: String): Boolean {+ if (text.length < 40) return false+ val lower = text.lowercase()+ if (dropPhrases.any { lower.startsWith(it) }) return false+ return true+ }++ private fun isChrome(element: HtmlElement): Boolean {+ if (element.tag in chromeTags) return true+ val hint = ((element.attr("class") ?: "") + " " + (element.attr("id") ?: "")).lowercase()+ if (hint.isNotBlank() && chromeHints.any { hint.contains(it) }) return true+ // A block that is mostly links is navigation, not prose.+ val textLen = element.textContent().length+ if (textLen > 0 && (element.tag == "ul" || element.tag == "div")) {+ val linkLen = element.findAll("a").sumOf { it.textContent().length }+ if (linkLen.toDouble() / textLen > 0.7 && textLen < 600) return true+ }+ return false+ }++ internal fun resolveUrl(base: String, raw: String): String? {+ val value = raw.trim()+ if (value.startsWith("http://") || value.startsWith("https://")) return value+ val schemeEnd = base.indexOf("://")+ if (schemeEnd < 0) return null+ val scheme = base.substring(0, schemeEnd)+ val host = base.substring(schemeEnd + 3).substringBefore('/')+ return when {+ value.startsWith("//") -> "$scheme:$value"+ value.startsWith("/") -> "$scheme://$host$value"+ value.startsWith("./") -> "$scheme://$host/${value.drop(2)}"+ else -> {+ val dir = base.substringBefore('?').substringBeforeLast('/', "")+ if (dir.isEmpty()) null else "$dir/$value"+ }+ }+ }+}
news/src/main/java/com/vayunmathur/news/domain/DateParsing.kt
diff --git a/news/src/main/java/com/vayunmathur/news/domain/DateParsing.kt b/news/src/main/java/com/vayunmathur/news/domain/DateParsing.ktnew file mode 100644index 0000000000..f16ee54c90--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/domain/DateParsing.kt@@ -0,0 +1,35 @@+package com.vayunmathur.news.domain++import java.time.Instant+import java.time.LocalDateTime+import java.time.OffsetDateTime+import java.time.ZoneOffset+import java.time.ZonedDateTime+import java.time.format.DateTimeFormatter+import java.util.Locale++/** Non-throwing date parsing for sitemap/RSS timestamps; null if unrecognised. */+object DateParsing {+ private val parsers: List<(String) -> Long> = listOf(+ { Instant.parse(it).toEpochMilli() },+ { OffsetDateTime.parse(it).toInstant().toEpochMilli() },+ { ZonedDateTime.parse(it, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant().toEpochMilli() },+ {+ val fmt = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH)+ ZonedDateTime.parse(it, fmt).toInstant().toEpochMilli()+ },+ {+ val fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)+ LocalDateTime.parse(it, fmt).toInstant(ZoneOffset.UTC).toEpochMilli()+ },+ )++ fun parseMillis(raw: String?): Long? {+ val text = raw?.trim()?.takeIf { it.isNotEmpty() } ?: return null+ for (parser in parsers) {+ val parsed = runCatching { parser(text) }.getOrNull()+ if (parsed != null) return parsed+ }+ return null+ }+}
news/src/main/java/com/vayunmathur/news/domain/FeedMerger.kt
diff --git a/news/src/main/java/com/vayunmathur/news/domain/FeedMerger.kt b/news/src/main/java/com/vayunmathur/news/domain/FeedMerger.ktnew file mode 100644index 0000000000..b710d91794--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/domain/FeedMerger.kt@@ -0,0 +1,35 @@+package com.vayunmathur.news.domain++/** Feed merging: de-duplicate by normalised URL, newest first. Pure and total. */+object FeedMerger {+ fun merge(feeds: Iterable<List<FeedArticle>>, limit: Int = 500): List<FeedArticle> {+ val seen = HashSet<String>()+ val merged = mutableListOf<FeedArticle>()+ for (article in feeds.flatten()) {+ val key = normaliseUrl(article.url)+ if (key.isEmpty() || !seen.add(key)) continue+ merged += article+ }+ return merged.sortedByDescending { it.publishedAtMillis }.take(limit)+ }++ /** Lower-cases scheme/host, drops fragment and tracking params, trims a trailing slash. */+ fun normaliseUrl(url: String): String {+ val trimmed = url.trim()+ val noFragment = trimmed.substringBefore('#')+ val schemeEnd = noFragment.indexOf("://")+ if (schemeEnd < 0) return noFragment.trimEnd('/')+ val scheme = noFragment.substring(0, schemeEnd).lowercase()+ val rest = noFragment.substring(schemeEnd + 3)+ val host = rest.substringBefore('/').lowercase()+ val pathAndQuery = rest.substring(host.length)+ val path = pathAndQuery.substringBefore('?').ifEmpty { "/" }+ val query = pathAndQuery.substringAfter('?', "")+ .split('&').filter { part ->+ val name = part.substringBefore('=').lowercase()+ name.isNotEmpty() && !name.startsWith("utm_") && name != "ref" && name != "fbclid"+ }.sorted().joinToString("&")+ val base = "$scheme://$host${path.trimEnd('/')}"+ return if (query.isEmpty()) base else "$base?$query"+ }+}
news/src/main/java/com/vayunmathur/news/domain/FeedModels.kt
diff --git a/news/src/main/java/com/vayunmathur/news/domain/FeedModels.kt b/news/src/main/java/com/vayunmathur/news/domain/FeedModels.ktnew file mode 100644index 0000000000..e9678d33e8--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/domain/FeedModels.kt@@ -0,0 +1,46 @@+package com.vayunmathur.news.domain++import kotlinx.serialization.Serializable++/** One article stub from a sitemap or RSS feed, before its body is fetched. */+data class FeedArticle(+ val url: String,+ val sourceId: String,+ val title: String,+ val publishedAtMillis: Long,+ val imageUrl: String? = null,+ val keywords: List<String> = emptyList(),+)++/** One block of an extracted article body, in reading order. */+@Serializable+sealed interface ArticleBlock {+ @Serializable+ data class Paragraph(val text: String) : ArticleBlock++ @Serializable+ data class Heading(val text: String) : ArticleBlock++ @Serializable+ data class Image(val url: String, val caption: String? = null) : ArticleBlock+}++/** The clean, extracted article the reader renders. */+@Serializable+data class ExtractedArticle(+ val url: String,+ val title: String,+ val byline: String? = null,+ val publishedAtMillis: Long? = null,+ val heroImageUrl: String? = null,+ val blocks: List<ArticleBlock> = emptyList(),+) {+ /** Plain-text body length; used to judge extraction quality / truncation. */+ val bodyChars: Int get() = blocks.sumOf {+ when (it) {+ is ArticleBlock.Paragraph -> it.text.length+ is ArticleBlock.Heading -> it.text.length+ is ArticleBlock.Image -> 0+ }+ }+}
news/src/main/java/com/vayunmathur/news/domain/HtmlDom.kt
diff --git a/news/src/main/java/com/vayunmathur/news/domain/HtmlDom.kt b/news/src/main/java/com/vayunmathur/news/domain/HtmlDom.ktnew file mode 100644index 0000000000..ff984fb010--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/domain/HtmlDom.kt@@ -0,0 +1,159 @@+package com.vayunmathur.news.domain++/** Minimal HTML element node built by [HtmlDom]; text children are [HtmlText]. */+sealed interface HtmlNode++data class HtmlText(val text: String) : HtmlNode++data class HtmlElement(+ val tag: String,+ val attrs: Map<String, String> = emptyMap(),+ val children: List<HtmlNode> = emptyList(),+) : HtmlNode {+ /** All descendant text, entity-decoded and whitespace-collapsed. */+ fun textContent(): String {+ val sb = StringBuilder()+ fun walk(node: HtmlNode) {+ when (node) {+ is HtmlText -> sb.append(node.text).append(' ')+ is HtmlElement -> node.children.forEach(::walk)+ }+ }+ walk(this)+ return sb.toString().replace(Regex("""\s+"""), " ").trim()+ }++ fun findAll(tag: String): List<HtmlElement> {+ val out = mutableListOf<HtmlElement>()+ fun walk(node: HtmlNode) {+ if (node is HtmlElement) {+ if (node.tag == tag) out += node+ node.children.forEach(::walk)+ }+ }+ children.forEach(::walk)+ return out+ }++ fun first(tag: String): HtmlElement? = findAll(tag).firstOrNull()++ fun attr(name: String): String? = attrs[name.lowercase()]+}++/**+ * Tolerant stack parser for real-world article HTML: handles void elements,+ * raw-text elements (script/style dropped), comments, doctypes and unclosed+ * tags by auto-closing at the parent boundary. Never throws.+ */+object HtmlDom {+ private val voidTags = setOf(+ "area", "base", "br", "col", "embed", "hr", "img", "input",+ "link", "meta", "param", "source", "track", "wbr",+ )+ private val dropTags = setOf("script", "style", "noscript", "template", "svg")++ fun parse(html: String): HtmlElement {+ val root = Builder("root")+ val stack = ArrayDeque<Builder>()+ stack.addLast(root)+ var i = 0+ while (i < html.length) {+ val lt = html.indexOf('<', i)+ if (lt < 0) {+ stack.last().children += HtmlText(decode(html.substring(i)))+ break+ }+ if (lt > i) stack.last().children += HtmlText(decode(html.substring(i, lt)))+ i = if (html.startsWith("<!--", lt)) skipComment(html, lt) else handleTag(html, lt, stack)+ if (i < 0) break+ }+ while (stack.size > 1) {+ val done = stack.removeLast()+ stack.last().children += done.build()+ }+ return root.build()+ }++ private fun skipComment(html: String, lt: Int): Int {+ val end = html.indexOf("-->", lt + 4)+ return if (end < 0) html.length else end + 3+ }++ /** Handles one tag at [lt]; returns the next scan index, or -1 to stop. */+ private fun handleTag(html: String, lt: Int, stack: ArrayDeque<Builder>): Int {+ val gt = findTagEnd(html, lt)+ if (gt < 0) return -1+ val rawTag = html.substring(lt + 1, gt).trim()+ var next = gt + 1+ if (rawTag.isEmpty() || rawTag.startsWith("!") || rawTag.startsWith("?")) return next+ if (rawTag.startsWith("/")) {+ closeTag(rawTag, stack)+ return next+ }+ val selfClosing = rawTag.endsWith("/")+ val tagBody = if (selfClosing) rawTag.dropLast(1).trim() else rawTag+ val name = tagBody.substringBefore(' ').substringBefore('/').lowercase()+ if (name.isEmpty()) return next+ if (name in dropTags) {+ if (!selfClosing) {+ val close = html.indexOf("</$name", next, ignoreCase = true)+ next = if (close < 0) html.length else close+ }+ return next+ }+ val builder = Builder(name, parseAttrs(tagBody.substring(name.length)))+ if (selfClosing || name in voidTags) {+ stack.last().children += builder.build()+ } else {+ stack.addLast(builder)+ }+ return next+ }++ private fun closeTag(rawTag: String, stack: ArrayDeque<Builder>) {+ val name = rawTag.substring(1).trim().substringBefore(' ').lowercase()+ val idx = stack.indexOfLast { it.tag == name }+ if (idx > 0) {+ while (stack.size > idx) {+ val done = stack.removeLast()+ stack.last().children += done.build()+ }+ }+ }++ private fun findTagEnd(html: String, lt: Int): Int {+ var quote: Char? = null+ var j = lt + 1+ while (j < html.length) {+ val c = html[j]+ if (quote != null) {+ if (c == quote) quote = null+ } else if (c == '"' || c == '\'') {+ quote = c+ } else if (c == '>') {+ return j+ }+ j+++ }+ return -1+ }++ private fun parseAttrs(text: String): Map<String, String> {+ val out = LinkedHashMap<String, String>()+ val regex = Regex("""([a-zA-Z_:][-\w:.]*)\s*(?:=\s*("[^"]*"|'[^']*'|[^\s"'/>]+))?""")+ for (m in regex.findAll(text)) {+ val value = m.groupValues[2].trim('"', '\'')+ out[m.groupValues[1].lowercase()] = decode(value)+ }+ return out+ }++ internal fun decode(text: String): String = SitemapParser.decodeEntities(+ text.replace(" ", " ").replace(" ", " "),+ )++ private class Builder(val tag: String, val attrs: Map<String, String> = emptyMap()) {+ val children = mutableListOf<HtmlNode>()+ fun build() = HtmlElement(tag, attrs, children.toList())+ }+}
news/src/main/java/com/vayunmathur/news/domain/SitemapParser.kt
diff --git a/news/src/main/java/com/vayunmathur/news/domain/SitemapParser.kt b/news/src/main/java/com/vayunmathur/news/domain/SitemapParser.ktnew file mode 100644index 0000000000..3c2192e583--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/domain/SitemapParser.kt@@ -0,0 +1,97 @@+package com.vayunmathur.news.domain++/** Result of parsing one feed document: articles, or child sitemaps to follow. */+data class ParsedFeed(+ val articles: List<FeedArticle> = emptyList(),+ val childSitemaps: List<String> = emptyList(),+)++/**+ * Pure parser for Google News sitemaps (urlset + news extension), plain+ * urlsets, sitemap indexes, RSS 2.0 and Atom. Deliberately string-based+ * (no XML library) so it runs identically on device and in plain JVM unit+ * tests; it tolerates malformed entries by skipping them, never throwing.+ */+object SitemapParser {++ fun parse(xml: String, sourceId: String): ParsedFeed {+ val doc = xml.trimStart('\uFEFF', ' ', '\n', '\r', '\t')+ return when {+ doc.contains("<sitemapindex") -> ParsedFeed(childSitemaps = extractSitemapChildren(doc))+ doc.contains("<urlset") -> ParsedFeed(articles = extractUrlset(doc, sourceId))+ doc.contains("<rss") || doc.contains("<channel") -> ParsedFeed(articles = extractRss(doc, sourceId))+ doc.contains("<feed") -> ParsedFeed(articles = extractAtom(doc, sourceId))+ else -> ParsedFeed()+ }+ }++ private fun extractSitemapChildren(doc: String): List<String> =+ Regex("""<sitemap>\s*<loc>([^<]+)</loc>""").findAll(doc)+ .map { decodeEntities(it.groupValues[1].trim()) }.filter { it.startsWith("http") }.toList()++ private fun extractUrlset(doc: String, sourceId: String): List<FeedArticle> {+ val out = mutableListOf<FeedArticle>()+ for (match in Regex("""<url>(.*?)</url>""", RegexOption.DOT_MATCHES_ALL).findAll(doc)) {+ val block = match.groupValues[1]+ val loc = tagText(block, "loc") ?: continue+ if (!loc.startsWith("http")) continue+ val title = tagText(block, "news:title") ?: tagText(block, "title") ?: loc+ val date = tagText(block, "news:publication_date") ?: tagText(block, "lastmod")+ val keywords = tagText(block, "news:keywords")+ ?.split(",")?.map { it.trim() }?.filter { it.isNotEmpty() } ?: emptyList()+ val image = Regex("""<image:image>\s*<image:loc>([^<]+)</image:loc>""")+ .find(block)?.groupValues?.get(1)?.let { decodeEntities(it.trim()) }+ out += FeedArticle(+ url = loc, sourceId = sourceId, title = title,+ publishedAtMillis = DateParsing.parseMillis(date) ?: 0L,+ imageUrl = image, keywords = keywords,+ )+ }+ return out+ }++ private fun extractRss(doc: String, sourceId: String): List<FeedArticle> {+ val out = mutableListOf<FeedArticle>()+ for (match in Regex("""<item>(.*?)</item>""", RegexOption.DOT_MATCHES_ALL).findAll(doc)) {+ val block = match.groupValues[1]+ val link = tagText(block, "link") ?: continue+ val title = tagText(block, "title") ?: link+ val date = tagText(block, "pubDate") ?: tagText(block, "dc:date")+ val image = Regex("""<media:content[^>]*url="([^"]+)"""").find(block)?.groupValues?.get(1)+ ?: Regex("""enclosure[^>]*url="([^"]+)"""").find(block)?.groupValues?.get(1)+ out += FeedArticle(link, sourceId, title, DateParsing.parseMillis(date) ?: 0L, image)+ }+ return out+ }++ private fun extractAtom(doc: String, sourceId: String): List<FeedArticle> {+ val out = mutableListOf<FeedArticle>()+ for (match in Regex("""<entry>(.*?)</entry>""", RegexOption.DOT_MATCHES_ALL).findAll(doc)) {+ val block = match.groupValues[1]+ val link = Regex("""<link[^>]*href="([^"]+)"""").find(block)?.groupValues?.get(1) ?: continue+ val title = tagText(block, "title") ?: link+ val date = tagText(block, "published") ?: tagText(block, "updated")+ out += FeedArticle(decodeEntities(link), sourceId, title, DateParsing.parseMillis(date) ?: 0L)+ }+ return out+ }++ private fun tagText(block: String, tag: String): String? {+ val raw = Regex("""<$tag>(.*?)</$tag>""", RegexOption.DOT_MATCHES_ALL)+ .find(block)?.groupValues?.get(1) ?: return null+ val cdata = raw.trim().removePrefix("<![CDATA[").removeSuffix("]]>")+ return decodeEntities(cdata.trim()).takeIf { it.isNotEmpty() }+ }++ internal fun decodeEntities(text: String): String {+ var out = text+ .replace("&", "&").replace("<", "<").replace(">", ">")+ .replace(""", "\"").replace("'", "'").replace("'", "'")+ out = out.replace(Regex("""&#x([0-9a-fA-F]+);""")) {+ it.groupValues[1].toIntOrNull(16)?.toChar()?.toString() ?: it.value+ }+ return out.replace(Regex("""&#(\d+);""")) {+ it.groupValues[1].toIntOrNull()?.toChar()?.toString() ?: it.value+ }+ }+}
news/src/main/java/com/vayunmathur/news/domain/SourceCatalog.kt
diff --git a/news/src/main/java/com/vayunmathur/news/domain/SourceCatalog.kt b/news/src/main/java/com/vayunmathur/news/domain/SourceCatalog.ktnew file mode 100644index 0000000000..e980eef690--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/domain/SourceCatalog.kt@@ -0,0 +1,53 @@+package com.vayunmathur.news.domain++/** How a source's feed document is shaped. */+enum class FeedKind { SITEMAP, RSS }++/**+ * One built-in publisher. [badge] is shown in the Sources screen when the+ * feed works but article fetching carries a caveat verified at catalog+ * time (see news/AGENTS.md for the per-source verification evidence).+ * Sources whose article bodies are absent from the raw HTML (JS-only+ * shells, bot walls, hard paywalls) are not in this catalog at all.+ */+data class NewsSource(+ val id: String,+ val name: String,+ val feedUrl: String,+ val kind: FeedKind,+ val badge: String? = null,+)++/** Built-in catalog; every URL here was fetched and parsed during development. */+object SourceCatalog {+ val sources: List<NewsSource> = listOf(+ NewsSource(+ "bbc", "BBC News",+ "https://www.bbc.com/sitemaps/https-sitemap-com-news-1.xml", FeedKind.SITEMAP,+ ),+ NewsSource(+ "guardian", "The Guardian",+ "https://www.theguardian.com/sitemaps/news.xml", FeedKind.SITEMAP,+ badge = "No paywall; article pages refused our datacentre verification IP, " ++ "so full text is verified on-device only.",+ ),+ NewsSource("aljazeera", "Al Jazeera", "https://www.aljazeera.com/news-sitemap.xml", FeedKind.SITEMAP),+ NewsSource("techcrunch", "TechCrunch", "https://techcrunch.com/news-sitemap.xml", FeedKind.SITEMAP),+ NewsSource("propublica", "ProPublica", "https://www.propublica.org/news-sitemap.xml", FeedKind.SITEMAP),+ NewsSource(+ "elpais", "El País", "https://elpais.com/sitemaps/news.xml", FeedKind.SITEMAP,+ badge = "Metered: full article text was present in the raw HTML during " ++ "verification; some articles may still truncate.",+ ),+ NewsSource("npr", "NPR", "https://feeds.npr.org/1001/rss.xml", FeedKind.RSS),+ NewsSource("dw", "DW", "https://rss.dw.com/xml/rss-en-all", FeedKind.RSS),+ NewsSource("ars", "Ars Technica", "https://feeds.arstechnica.com/arstechnica/index", FeedKind.RSS),+ NewsSource("verge", "The Verge", "https://www.theverge.com/rss/index.xml", FeedKind.RSS),+ NewsSource(+ "hn", "Hacker News", "https://news.ycombinator.com/rss", FeedKind.RSS,+ badge = "Links point at third-party sites; reader quality depends on the linked site.",+ ),+ )++ fun byId(id: String): NewsSource? = sources.firstOrNull { it.id == id }+}
news/src/main/java/com/vayunmathur/news/network/Networking.kt
diff --git a/news/src/main/java/com/vayunmathur/news/network/Networking.kt b/news/src/main/java/com/vayunmathur/news/network/Networking.ktnew file mode 100644index 0000000000..88b1d93cd9--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/network/Networking.kt@@ -0,0 +1,26 @@+package com.vayunmathur.news.network++import com.vayunmathur.library.network.NetworkClient+import java.io.IOException++/**+ * The news app's single networking entry point. Owns the client, the+ * browser-like request headers publisher CDNs expect, and status mapping.+ * Every fetch is a direct GET of a publisher URL — there is no backend.+ * Trust is SYSTEM, initialised in MainActivity, because publisher hosts+ * are arbitrary public sites (see TrustBundle docs).+ */+object Networking {+ private val headers = mapOf(+ "User-Agent" to "Mozilla/5.0 (Linux; Android 14) NewsReader",+ "Accept" to "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",+ "Accept-Language" to "en-GB,en;q=0.8",+ )++ /** GET [url] as text; throws [IOException] on transport failure or non-2xx. */+ suspend fun fetchText(url: String): String {+ val response = NetworkClient.execute(url, headers = headers)+ if (!response.isSuccess) throw IOException("HTTP ${response.status} for $url")+ return response.text+ }+}
news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt
diff --git a/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt b/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.ktnew file mode 100644index 0000000000..55e3583b17--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt@@ -0,0 +1,140 @@+package com.vayunmathur.news.platform++import android.app.Application+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.ViewModel+import androidx.lifecycle.ViewModelProvider+import androidx.lifecycle.viewModelScope+import com.vayunmathur.news.data.CachedArticle+import com.vayunmathur.news.data.NewsPrefs+import com.vayunmathur.news.data.NewsRepository+import com.vayunmathur.news.domain.ExtractedArticle+import com.vayunmathur.news.domain.SourceCatalog+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.launch++/** Feed filtering: "all", a source id, or nothing matches (empty feed). */+const val FILTER_ALL = "all"++/** UI state and actions for feed, reader, sources and saved screens. */+class NewsViewModel(+ application: Application,+ private val repository: NewsRepository,+ private val prefs: NewsPrefs,+) : AndroidViewModel(application) {++ private val _isRefreshing = MutableStateFlow(false)+ val isRefreshing: StateFlow<Boolean> = _isRefreshing.asStateFlow()++ private val _refreshFailed = MutableStateFlow(false)+ val refreshFailed: StateFlow<Boolean> = _refreshFailed.asStateFlow()++ private val _sourceFilter = MutableStateFlow(FILTER_ALL)+ val sourceFilter: StateFlow<String> = _sourceFilter.asStateFlow()++ val disabledSourceIds: StateFlow<Set<String>> = prefs.disabledSourceIds+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptySet())++ val articles: StateFlow<List<CachedArticle>> = combine(+ repository.articles, _sourceFilter, disabledSourceIds,+ ) { all, filter, disabled ->+ all.filter { it.sourceId !in disabled && (filter == FILTER_ALL || it.sourceId == filter) }+ }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++ val bookmarked: StateFlow<List<CachedArticle>> = repository.bookmarked+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++ val readerTextSp: StateFlow<Int> = prefs.readerTextSp+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), NewsPrefs.DEFAULT_TEXT_SP)+ val readerSerif: StateFlow<Boolean> = prefs.readerSerif+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)+ val readerWebView: StateFlow<Boolean> = prefs.readerWebView+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)++ private val _readerBody = MutableStateFlow<ExtractedArticle?>(null)+ val readerBody: StateFlow<ExtractedArticle?> = _readerBody.asStateFlow()+ private val _readerError = MutableStateFlow(false)+ val readerError: StateFlow<Boolean> = _readerError.asStateFlow()+ private val _readerBookmarked = MutableStateFlow(false)+ val readerBookmarked: StateFlow<Boolean> = _readerBookmarked.asStateFlow()+ private var readerUrl: String? = null++ init {+ refresh()+ }++ fun setSourceFilter(filter: String) {+ _sourceFilter.value = filter+ }++ fun refresh() {+ if (_isRefreshing.value) return+ viewModelScope.launch {+ _isRefreshing.value = true+ val enabled = SourceCatalog.sources.filter { it.id !in disabledSourceIds.value }+ val failed = runCatching { repository.refresh(enabled) }.getOrElse { listOf("all") }+ _refreshFailed.value = failed.isNotEmpty()+ _isRefreshing.value = false+ }+ }++ fun setSourceEnabled(id: String, enabled: Boolean) {+ viewModelScope.launch {+ prefs.setSourceEnabled(id, enabled)+ if (enabled) refresh()+ }+ }++ /** Loads (cached-first) the body for [url]; stale loads for other URLs are ignored. */+ fun openArticle(url: String) {+ readerUrl = url+ _readerBody.value = null+ _readerError.value = false+ viewModelScope.launch {+ _readerBookmarked.value = repository.isBookmarked(url)+ runCatching { repository.articleBody(url) }+ .onSuccess { if (readerUrl == url) _readerBody.value = it }+ .onFailure { if (readerUrl == url) _readerError.value = true }+ }+ }++ fun toggleReaderBookmark() {+ val url = readerUrl ?: return+ viewModelScope.launch {+ val next = !repository.isBookmarked(url)+ repository.setBookmarked(url, next)+ _readerBookmarked.value = next+ }+ }++ fun toggleBookmark(article: CachedArticle) {+ viewModelScope.launch { repository.setBookmarked(article.url, !article.bookmarked) }+ }++ fun setReaderTextSp(sp: Int) {+ viewModelScope.launch { prefs.setReaderTextSp(sp) }+ }++ fun setReaderSerif(serif: Boolean) {+ viewModelScope.launch { prefs.setReaderSerif(serif) }+ }++ fun setReaderWebView(webView: Boolean) {+ viewModelScope.launch { prefs.setReaderWebView(webView) }+ }+}++/** Factory wiring the repository and prefs owners into [NewsViewModel]. */+class NewsViewModelFactory(+ private val application: Application,+ private val repository: NewsRepository,+) : ViewModelProvider.Factory {+ @Suppress("UNCHECKED_CAST")+ override fun <T : ViewModel> create(modelClass: Class<T>): T =+ NewsViewModel(application, repository, NewsPrefs(application)) as T+}
news/src/main/java/com/vayunmathur/news/ui/ArticleRow.kt
diff --git a/news/src/main/java/com/vayunmathur/news/ui/ArticleRow.kt b/news/src/main/java/com/vayunmathur/news/ui/ArticleRow.ktnew file mode 100644index 0000000000..3839592e1e--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/ui/ArticleRow.kt@@ -0,0 +1,67 @@+package com.vayunmathur.news.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.library.ui.IconBookmark+import com.vayunmathur.library.ui.IconBookmarkBorder+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.news.data.CachedArticle+import com.vayunmathur.news.domain.SourceCatalog++/** One feed row: source, relative time, title and thumbnail when the feed carried one. */+@Composable+fun ArticleRow(+ article: CachedArticle,+ onClick: () -> Unit,+ onToggleBookmark: () -> Unit,+) {+ Row(+ modifier = Modifier.fillMaxWidth().clickable(onClick = onClick).padding(16.dp),+ ) {+ Column(modifier = Modifier.weight(1f)) {+ Text(+ text = "${SourceCatalog.byId(article.sourceId)?.name ?: article.sourceId} · ${relativeTime(article.publishedAtMillis)}",+ style = MaterialTheme.typography.labelMedium,+ color = MaterialTheme.colorScheme.primary,+ )+ Text(article.title, style = MaterialTheme.typography.titleMedium)+ }+ if (article.imageUrl != null) {+ AsyncImage(+ model = article.imageUrl,+ contentDescription = null,+ modifier = Modifier.size(72.dp),+ contentScale = ContentScale.Crop,+ )+ }+ IconButton(onClick = onToggleBookmark) {+ if (article.bookmarked) {+ IconBookmark()+ } else {+ IconBookmarkBorder()+ }+ }+ }+}++private fun relativeTime(millis: Long): String {+ if (millis <= 0L) return ""+ val minutes = ((System.currentTimeMillis() - millis) / 60_000L).coerceAtLeast(0L)+ return when {+ minutes < 1L -> "now"+ minutes < 60L -> "${minutes}m ago"+ minutes < 60L * 24L -> "${minutes / 60L}h ago"+ else -> "${minutes / (60L * 24L)}d ago"+ }+}
news/src/main/java/com/vayunmathur/news/ui/FeedScreen.kt
diff --git a/news/src/main/java/com/vayunmathur/news/ui/FeedScreen.kt b/news/src/main/java/com/vayunmathur/news/ui/FeedScreen.ktnew file mode 100644index 0000000000..13a5a73df3--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/ui/FeedScreen.kt@@ -0,0 +1,89 @@+package com.vayunmathur.news.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.FilterChip+import com.vayunmathur.library.ui.IconBookmark+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconSettings+import com.vayunmathur.library.ui.Text+import com.vayunmathur.news.R+import com.vayunmathur.news.domain.SourceCatalog+import com.vayunmathur.news.platform.FILTER_ALL+import com.vayunmathur.news.platform.NewsViewModel++/** Merged newest-first feed with per-source filter chips and pull-to-refresh. */+@Composable+fun FeedScreen(+ viewModel: NewsViewModel,+ onOpenArticle: (String) -> Unit,+ onOpenSources: () -> Unit,+ onOpenSaved: () -> Unit,+) {+ val articles by viewModel.articles.collectAsState()+ val isRefreshing by viewModel.isRefreshing.collectAsState()+ val refreshFailed by viewModel.refreshFailed.collectAsState()+ val filter by viewModel.sourceFilter.collectAsState()+ val disabled by viewModel.disabledSourceIds.collectAsState()+ AppScaffold(+ title = stringResource(R.string.feed_title),+ isRefreshing = isRefreshing,+ onRefresh = viewModel::refresh,+ actions = {+ IconButton(onClick = onOpenSaved) { IconBookmark() }+ IconButton(onClick = onOpenSources) { IconSettings() }+ },+ ) { padding ->+ Column(modifier = Modifier.fillMaxSize().padding(padding)) {+ LazyRow(modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)) {+ item {+ FilterChip(+ selected = filter == FILTER_ALL,+ onClick = { viewModel.setSourceFilter(FILTER_ALL) },+ label = { Text(stringResource(R.string.feed_all_sources)) },+ )+ }+ items(SourceCatalog.sources.filter { it.id !in disabled }) { source ->+ FilterChip(+ selected = filter == source.id,+ onClick = { viewModel.setSourceFilter(source.id) },+ label = { Text(source.name) },+ modifier = Modifier.padding(start = 8.dp),+ )+ }+ }+ if (refreshFailed) {+ Text(+ stringResource(R.string.feed_refresh_failed),+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),+ )+ }+ if (articles.isEmpty() && !isRefreshing) {+ Text(+ stringResource(R.string.feed_empty),+ modifier = Modifier.padding(16.dp),+ )+ }+ LazyColumn(modifier = Modifier.fillMaxSize()) {+ items(articles, key = { it.url }) { article ->+ ArticleRow(+ article = article,+ onClick = { onOpenArticle(article.url) },+ onToggleBookmark = { viewModel.toggleBookmark(article) },+ )+ }+ }+ }+ }+}
news/src/main/java/com/vayunmathur/news/ui/OriginalWebView.kt
diff --git a/news/src/main/java/com/vayunmathur/news/ui/OriginalWebView.kt b/news/src/main/java/com/vayunmathur/news/ui/OriginalWebView.ktnew file mode 100644index 0000000000..cff89fc7cc--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/ui/OriginalWebView.kt@@ -0,0 +1,26 @@+package com.vayunmathur.news.ui++import android.annotation.SuppressLint+import android.webkit.WebView+import android.webkit.WebViewClient+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.viewinterop.AndroidView++/** The article's original page, for the reader's clean/original toggle. */+@SuppressLint("SetJavaScriptEnabled")+@Composable+fun OriginalWebView(url: String, modifier: Modifier = Modifier) {+ AndroidView(+ modifier = modifier,+ factory = { context ->+ WebView(context).apply {+ webViewClient = WebViewClient()+ settings.javaScriptEnabled = true+ settings.domStorageEnabled = true+ loadUrl(url)+ }+ },+ update = { view -> if (view.url != url) view.loadUrl(url) },+ )+}
news/src/main/java/com/vayunmathur/news/ui/ReaderScreen.kt
diff --git a/news/src/main/java/com/vayunmathur/news/ui/ReaderScreen.kt b/news/src/main/java/com/vayunmathur/news/ui/ReaderScreen.ktnew file mode 100644index 0000000000..27e2367174--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/ui/ReaderScreen.kt@@ -0,0 +1,150 @@+package com.vayunmathur.news.ui++import android.content.Intent+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.core.net.toUri+import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.FilterChip+import com.vayunmathur.library.ui.IconBookmark+import com.vayunmathur.library.ui.IconBookmarkBorder+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconGlobe+import com.vayunmathur.library.ui.IconOpenInNew+import com.vayunmathur.library.ui.IconTextTool+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.news.R+import com.vayunmathur.news.domain.ArticleBlock+import com.vayunmathur.news.platform.NewsViewModel++/**+ * First-class reader: the extracted clean article (title, byline, date,+ * comfortable measure, adjustable size, serif/sans) with a toggle to the+ * original web page and an open-in-browser action.+ */+@Composable+fun ReaderScreen(viewModel: NewsViewModel, url: String, onBack: () -> Unit) {+ val body by viewModel.readerBody.collectAsState()+ val error by viewModel.readerError.collectAsState()+ val bookmarked by viewModel.readerBookmarked.collectAsState()+ val textSp by viewModel.readerTextSp.collectAsState()+ val serif by viewModel.readerSerif.collectAsState()+ val webView by viewModel.readerWebView.collectAsState()+ val context = LocalContext.current+ LaunchedEffect(url) { viewModel.openArticle(url) }+ AppScaffold(+ title = stringResource(R.string.reader_title),+ onNavigateBack = onBack,+ actions = {+ IconButton(onClick = { viewModel.setReaderWebView(!webView) }) { IconGlobe() }+ IconButton(onClick = viewModel::toggleReaderBookmark) {+ if (bookmarked) IconBookmark() else IconBookmarkBorder()+ }+ IconButton(onClick = {+ context.startActivity(Intent(Intent.ACTION_VIEW, url.toUri()))+ }) { IconOpenInNew() }+ },+ ) { padding ->+ if (webView) {+ OriginalWebView(url, Modifier.fillMaxSize().padding(padding))+ return@AppScaffold+ }+ Column(+ modifier = Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState())+ .padding(horizontal = 20.dp, vertical = 12.dp),+ ) {+ ReaderControls(+ textSp = textSp, serif = serif,+ onTextSp = viewModel::setReaderTextSp, onSerif = viewModel::setReaderSerif,+ )+ when {+ error -> Text(stringResource(R.string.reader_loading_failed))+ body == null -> Text("…")+ else -> ReaderBody(title = body!!.title, byline = body!!.byline, textSp = textSp, serif = serif, blocks = body!!.blocks)+ }+ }+ }+}++@Composable+private fun ReaderControls(+ textSp: Int,+ serif: Boolean,+ onTextSp: (Int) -> Unit,+ onSerif: (Boolean) -> Unit,+) {+ Column(modifier = Modifier.fillMaxWidth().padding(bottom = 12.dp)) {+ FilterChip(+ selected = serif,+ onClick = { onSerif(!serif) },+ label = { Text(if (serif) stringResource(R.string.reader_serif) else stringResource(R.string.reader_sans)) },+ leadingIcon = { IconTextTool() },+ )+ FilterChip(+ selected = false,+ onClick = { onTextSp(textSp - 1) },+ label = { Text(stringResource(R.string.reader_text_smaller)) },+ modifier = Modifier.padding(top = 8.dp),+ )+ FilterChip(+ selected = false,+ onClick = { onTextSp(textSp + 1) },+ label = { Text(stringResource(R.string.reader_text_larger)) },+ modifier = Modifier.padding(top = 8.dp),+ )+ }+}++@Composable+private fun ReaderBody(+ title: String,+ byline: String?,+ textSp: Int,+ serif: Boolean,+ blocks: List<ArticleBlock>,+) {+ val family = if (serif) FontFamily.Serif else FontFamily.SansSerif+ Text(title, style = MaterialTheme.typography.headlineMedium)+ if (!byline.isNullOrBlank()) {+ Text(byline, style = MaterialTheme.typography.labelLarge, modifier = Modifier.padding(top = 6.dp))+ }+ for (block in blocks) {+ when (block) {+ is ArticleBlock.Heading -> Text(+ block.text,+ style = MaterialTheme.typography.titleLarge,+ modifier = Modifier.padding(top = 20.dp, bottom = 6.dp),+ )+ is ArticleBlock.Paragraph -> Text(+ block.text,+ fontFamily = family,+ fontSize = textSp.sp,+ lineHeight = (textSp * 1.55f).sp,+ modifier = Modifier.padding(bottom = 12.dp),+ )+ is ArticleBlock.Image -> AsyncImage(+ model = block.url,+ contentDescription = block.caption,+ modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),+ contentScale = ContentScale.FillWidth,+ )+ }+ }+}
news/src/main/java/com/vayunmathur/news/ui/SavedScreen.kt
diff --git a/news/src/main/java/com/vayunmathur/news/ui/SavedScreen.kt b/news/src/main/java/com/vayunmathur/news/ui/SavedScreen.ktnew file mode 100644index 0000000000..40b23684d4--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/ui/SavedScreen.kt@@ -0,0 +1,47 @@+package com.vayunmathur.news.ui++import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.news.R+import com.vayunmathur.news.platform.NewsViewModel++/** Bookmarked articles; their bodies are cached, so they open offline. */+@Composable+fun SavedScreen(+ viewModel: NewsViewModel,+ onOpenArticle: (String) -> Unit,+ onBack: () -> Unit,+) {+ val saved by viewModel.bookmarked.collectAsState()+ AppScaffold(+ title = stringResource(R.string.saved_title),+ onNavigateBack = onBack,+ ) { padding ->+ if (saved.isEmpty()) {+ Text(+ stringResource(R.string.saved_empty),+ modifier = Modifier.padding(padding).padding(16.dp),+ )+ } else {+ LazyColumn(modifier = Modifier.fillMaxSize().padding(padding)) {+ items(saved, key = { it.url }) { article ->+ ArticleRow(+ article = article,+ onClick = { onOpenArticle(article.url) },+ onToggleBookmark = { viewModel.toggleBookmark(article) },+ )+ }+ }+ }+ }+}
news/src/main/java/com/vayunmathur/news/ui/SourcesScreen.kt
diff --git a/news/src/main/java/com/vayunmathur/news/ui/SourcesScreen.kt b/news/src/main/java/com/vayunmathur/news/ui/SourcesScreen.ktnew file mode 100644index 0000000000..77512717b1--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/ui/SourcesScreen.kt@@ -0,0 +1,53 @@+package com.vayunmathur.news.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.Switch+import com.vayunmathur.library.ui.Text+import com.vayunmathur.news.R+import com.vayunmathur.news.domain.SourceCatalog+import com.vayunmathur.news.platform.NewsViewModel++/** Built-in source catalog with per-source enable switches. */+@Composable+fun SourcesScreen(viewModel: NewsViewModel, onBack: () -> Unit) {+ val disabled by viewModel.disabledSourceIds.collectAsState()+ AppScaffold(+ title = stringResource(R.string.sources_title),+ onNavigateBack = onBack,+ ) { padding ->+ Column(modifier = Modifier.fillMaxSize().padding(padding)) {+ Text(+ stringResource(R.string.sources_note),+ modifier = Modifier.padding(16.dp),+ )+ LazyColumn(modifier = Modifier.fillMaxSize()) {+ items(SourceCatalog.sources, key = { it.id }) { source ->+ ListItem(+ headlineContent = { Text(source.name) },+ supportingContent = {+ Text(source.badge ?: source.feedUrl)+ },+ trailingContent = {+ Switch(+ checked = source.id !in disabled,+ onCheckedChange = { viewModel.setSourceEnabled(source.id, it) },+ )+ },+ )+ }+ }+ }+ }+}
news/src/main/res/values/strings.xml
diff --git a/news/src/main/res/values/strings.xml b/news/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..99bcd4c92f--- /dev/null+++ b/news/src/main/res/values/strings.xml@@ -0,0 +1,22 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="app_name">News</string>+ <!-- FeedScreen -->+ <string name="feed_title">News</string>+ <string name="feed_empty">No articles yet. Pull to refresh.</string>+ <string name="feed_all_sources">All</string>+ <string name="feed_refresh_failed">Could not refresh all sources; showing the cached feed.</string>+ <!-- ReaderScreen -->+ <string name="reader_title">Article</string>+ <string name="reader_text_smaller">Smaller text</string>+ <string name="reader_text_larger">Larger text</string>+ <string name="reader_serif">Serif</string>+ <string name="reader_sans">Sans</string>+ <string name="reader_loading_failed">Could not load this article. Try the original page.</string>+ <!-- SourcesScreen -->+ <string name="sources_title">Sources</string>+ <string name="sources_note">Articles are fetched directly from each publisher. No account and no server of ours is involved.</string>+ <!-- SavedScreen -->+ <string name="saved_title">Saved for later</string>+ <string name="saved_empty">Nothing saved yet. Save an article from the reader to read it offline later.</string>+</resources>
news/src/main/res/xml/data_extraction_rules.xml
diff --git a/news/src/main/res/xml/data_extraction_rules.xml b/news/src/main/res/xml/data_extraction_rules.xmlnew file mode 100644index 0000000000..81a97e0f26--- /dev/null+++ b/news/src/main/res/xml/data_extraction_rules.xml@@ -0,0 +1,17 @@+<?xml version="1.0" encoding="utf-8"?>+<data-extraction-rules>+ <cloud-backup>+ <include domain="root" path="." />+ <include domain="file" path="." />+ <include domain="database" path="." />+ <include domain="sharedpref" path="." />+ <include domain="external" path="." />+ </cloud-backup>+ <device-transfer>+ <include domain="root" path="." />+ <include domain="file" path="." />+ <include domain="database" path="." />+ <include domain="sharedpref" path="." />+ <include domain="external" path="." />+ </device-transfer>+</data-extraction-rules>
news/src/test/java/com/vayunmathur/news/NewsTestDb.kt
diff --git a/news/src/test/java/com/vayunmathur/news/NewsTestDb.kt b/news/src/test/java/com/vayunmathur/news/NewsTestDb.ktnew file mode 100644index 0000000000..18c4ef889f--- /dev/null+++ b/news/src/test/java/com/vayunmathur/news/NewsTestDb.kt@@ -0,0 +1,17 @@+package com.vayunmathur.news++import android.content.Context+import androidx.room3.Room+import com.vayunmathur.library.util.databases+import com.vayunmathur.news.data.NewsDatabase++/** Binds the news DB to an in-memory instance (avoids SQLCipher on JVM). */+fun seedNewsDb(context: Context) {+ synchronized(databases) {+ if (databases[NewsDatabase::class] !is NewsDatabase) {+ databases[NewsDatabase::class] = Room.inMemoryDatabaseBuilder(+ context.applicationContext, NewsDatabase::class.java,+ ).allowMainThreadQueries().build()+ }+ }+}
news/src/test/java/com/vayunmathur/news/data/NewsRepositoryTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/data/NewsRepositoryTest.kt b/news/src/test/java/com/vayunmathur/news/data/NewsRepositoryTest.ktnew file mode 100644index 0000000000..ee4304f3da--- /dev/null+++ b/news/src/test/java/com/vayunmathur/news/data/NewsRepositoryTest.kt@@ -0,0 +1,81 @@+package com.vayunmathur.news.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.news.domain.SourceCatalog+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Repository over Room (in the test DB) with a fake fetch seam: no network.+ * The fake serves a sitemap index, its child urlset, and one article page.+ */+@RunWith(RobolectricTestRunner::class)+class NewsRepositoryTest {+ @org.junit.Before fun setUp() { com.vayunmathur.news.seedNewsDb(ApplicationProvider.getApplicationContext()) }++ private val sitemapIndex = """+ <sitemapindex><sitemap><loc>https://fake.example/child.xml</loc></sitemap></sitemapindex>+ """.trimIndent()+ private val childUrlset = """+ <urlset xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">+ <url><loc>https://fake.example/story</loc>+ <news:news><news:publication_date>2026-11-23T10:00:00+00:00</news:publication_date>+ <news:title>Fake Story</news:title></news:news></url>+ </urlset>+ """.trimIndent()+ private val articleHtml = """+ <html><head><meta property="og:title" content="Fake Story"/></head><body><article>+ <p>This is the body of the fake story, long enough to count as real article prose here.</p>+ <p>And a second paragraph so the extracted body has more than one block to return.</p>+ </article></body></html>+ """.trimIndent()++ private fun fakeFetch(calls: MutableList<String>): suspend (String) -> String = { url ->+ calls += url+ when {+ url.endsWith("child.xml") -> childUrlset+ url.endsWith("/story") -> articleHtml+ else -> sitemapIndex+ }+ }++ @Test+ fun refreshFollowsIndexAndCachesArticles() = runBlocking {+ val context = ApplicationProvider.getApplicationContext<Context>()+ val calls = mutableListOf<String>()+ val repo = NewsRepository(context, fakeFetch(calls))+ val source = SourceCatalog.byId("bbc")!!.copy(feedUrl = "https://fake.example/index.xml")+ val failed = repo.refresh(listOf(source))+ assertTrue(failed.isEmpty())+ assertTrue(calls.any { it.endsWith("child.xml") })+ val cached = kotlinx.coroutines.withTimeout(10_000) { repo.articles.first { it.isNotEmpty() } }+ assertEquals(listOf("Fake Story"), cached.map { it.title })+ }++ @Test+ fun articleBodyExtractsAndCaches() = runBlocking {+ val context = ApplicationProvider.getApplicationContext<Context>()+ val calls = mutableListOf<String>()+ val repo = NewsRepository(context, fakeFetch(calls))+ val body = repo.articleBody("https://fake.example/story")+ assertEquals("Fake Story", body.title)+ assertEquals(2, body.blocks.size)+ val callsAfterFirst = calls.size+ repo.articleBody("https://fake.example/story")+ assertEquals(callsAfterFirst, calls.size, "second read must come from the Room cache")+ }++ @Test+ fun failingSourceIsReportedNotThrown() = runBlocking {+ val context = ApplicationProvider.getApplicationContext<Context>()+ val repo = NewsRepository(context) { throw java.io.IOException("offline") }+ val failed = repo.refresh(listOf(SourceCatalog.sources.first()))+ assertEquals(1, failed.size)+ }+}
news/src/test/java/com/vayunmathur/news/domain/ArticleExtractorTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/domain/ArticleExtractorTest.kt b/news/src/test/java/com/vayunmathur/news/domain/ArticleExtractorTest.ktnew file mode 100644index 0000000000..8416355c75--- /dev/null+++ b/news/src/test/java/com/vayunmathur/news/domain/ArticleExtractorTest.kt@@ -0,0 +1,58 @@+package com.vayunmathur.news.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class ArticleExtractorTest {+ private val html = """+ <html><head><title>Site | Big Story</title>+ <meta property="og:title" content="Big Story"/>+ <meta name="author" content="Jane Doe"/>+ <meta property="article:published_time" content="2026-11-23T10:00:00Z"/>+ <meta property="og:image" content="https://example.com/hero.jpg"/></head>+ <body>+ <nav><p>Menu link one and more navigation text that should never appear in output.</p></nav>+ <header><p>Site header promo text that is definitely chrome and not article prose.</p></header>+ <article>+ <h1>Big Story</h1>+ <p>The first paragraph of the article carries the lede, with enough words to be real prose.</p>+ <p>A second paragraph follows with more detail, commas, and a complete thought for readers.</p>+ <h2>A section heading</h2>+ <p>The closing paragraph wraps the story up with a final observation about what happens next.</p>+ <div class="related"><p>Read more stories like this one on our related links rail today.</p></div>+ </article>+ <footer><p>Footer legal text and subscription prompts that must be stripped from reading.</p></footer>+ </body></html>+ """.trimIndent()++ @Test+ fun extractsTitleBylineAndParagraphsInOrder() {+ val article = ArticleExtractor.extract(html, "https://example.com/story")+ assertEquals("Big Story", article.title)+ assertEquals("Jane Doe", article.byline)+ assertEquals("https://example.com/hero.jpg", article.heroImageUrl)+ val paragraphs = article.blocks.filterIsInstance<ArticleBlock.Paragraph>().map { it.text }+ assertEquals(3, paragraphs.size)+ assertTrue(paragraphs[0].startsWith("The first paragraph"))+ assertTrue(paragraphs[2].startsWith("The closing paragraph"))+ assertTrue(article.blocks.any { it is ArticleBlock.Heading && it.text == "A section heading" })+ }++ @Test+ fun stripsChromeAndRelatedLinks() {+ val article = ArticleExtractor.extract(html, "https://example.com/story")+ val allText = article.blocks.filterIsInstance<ArticleBlock.Paragraph>().joinToString(" ") { it.text }+ assertFalse(allText.contains("navigation"))+ assertFalse(allText.contains("Footer legal"))+ assertFalse(allText.contains("related links rail"))+ assertFalse(allText.contains("header promo"))+ }++ @Test+ fun emptyHtmlYieldsEmptyBlocks() {+ val article = ArticleExtractor.extract("<html></html>", "https://example.com/x")+ assertTrue(article.blocks.isEmpty())+ }+}
news/src/test/java/com/vayunmathur/news/domain/FeedMergerTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/domain/FeedMergerTest.kt b/news/src/test/java/com/vayunmathur/news/domain/FeedMergerTest.ktnew file mode 100644index 0000000000..5dced8d0d4--- /dev/null+++ b/news/src/test/java/com/vayunmathur/news/domain/FeedMergerTest.kt@@ -0,0 +1,29 @@+package com.vayunmathur.news.domain++import kotlin.test.Test+import kotlin.test.assertEquals++class FeedMergerTest {+ private fun article(url: String, at: Long) = FeedArticle(url, "s", url, at)++ @Test+ fun dedupesByNormalisedUrlAndSortsNewestFirst() {+ val merged = FeedMerger.merge(+ listOf(+ listOf(article("https://EXAMPLE.com/a/?utm_source=x#frag", 100L), article("https://example.com/b", 300L)),+ listOf(article("https://example.com/a", 200L), article("https://example.com/c", 50L)),+ ),+ )+ assertEquals(+ listOf("https://example.com/b", "https://example.com/a", "https://example.com/c"),+ merged.map { FeedMerger.normaliseUrl(it.url) },+ )+ }++ @Test+ fun respectsLimit() {+ val merged = FeedMerger.merge(listOf((1..10).map { article("https://e.com/$it", it.toLong()) }), limit = 3)+ assertEquals(3, merged.size)+ assertEquals(10L, merged.first().publishedAtMillis)+ }+}
news/src/test/java/com/vayunmathur/news/domain/SitemapParserTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/domain/SitemapParserTest.kt b/news/src/test/java/com/vayunmathur/news/domain/SitemapParserTest.ktnew file mode 100644index 0000000000..a55f92f0f8--- /dev/null+++ b/news/src/test/java/com/vayunmathur/news/domain/SitemapParserTest.kt@@ -0,0 +1,59 @@+package com.vayunmathur.news.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class SitemapParserTest {+ @Test+ fun newsUrlsetParsesTitleDateKeywordsAndImage() {+ val xml = """+ <urlset xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"+ xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">+ <url><loc>https://example.com/a1</loc>+ <news:news><news:publication><news:name>Ex</news:name><news:language>en</news:language></news:publication>+ <news:publication_date>2026-11-23T10:00:00+00:00</news:publication_date>+ <news:title>First & Foremost</news:title><news:keywords>alpha, beta</news:keywords></news:news>+ <image:image><image:loc>https://example.com/a1.jpg</image:loc></image:image></url>+ <url><loc>https://example.com/a2</loc><lastmod>2026-11-22T09:00:00Z</lastmod></url>+ </urlset>+ """.trimIndent()+ val parsed = SitemapParser.parse(xml, "ex")+ assertEquals(2, parsed.articles.size)+ val first = parsed.articles[0]+ assertEquals("First & Foremost", first.title)+ assertEquals(listOf("alpha", "beta"), first.keywords)+ assertEquals("https://example.com/a1.jpg", first.imageUrl)+ assertTrue(first.publishedAtMillis > 0L)+ assertEquals("https://example.com/a2", parsed.articles[1].title)+ }++ @Test+ fun sitemapIndexYieldsChildren() {+ val xml = """+ <sitemapindex><sitemap><loc>https://example.com/s1.xml</loc></sitemap>+ <sitemap><loc>https://example.com/s2.xml</loc></sitemap></sitemapindex>+ """.trimIndent()+ val parsed = SitemapParser.parse(xml, "ex")+ assertEquals(listOf("https://example.com/s1.xml", "https://example.com/s2.xml"), parsed.childSitemaps)+ assertTrue(parsed.articles.isEmpty())+ }++ @Test+ fun rssItemsParse() {+ val xml = """+ <rss><channel><item><title>Story</title><link>https://example.com/s</link>+ <pubDate>Mon, 23 Nov 2026 10:00:00 GMT</pubDate></item></channel></rss>+ """.trimIndent()+ val parsed = SitemapParser.parse(xml, "ex")+ assertEquals(1, parsed.articles.size)+ assertEquals("Story", parsed.articles[0].title)+ assertTrue(parsed.articles[0].publishedAtMillis > 0L)+ }++ @Test+ fun malformedInputNeverThrows() {+ assertTrue(SitemapParser.parse("not xml at all", "ex").articles.isEmpty())+ assertTrue(SitemapParser.parse("", "ex").articles.isEmpty())+ }+}
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex c643c6966f..6b6bca1402 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -89,6 +89,7 @@ include(":openassistant") include(":office") include(":passwords") include(":notes")+include(":news") include(":flashcards") include(":files") include(":photos")