Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / news / src / main / java / com / vayunmathur / news / domain / ServerFeedParser.kt

ServerFeedParser.kt136 lines · 6.6 KiBRaw
1package com.vayunmathur.news.domain
2
3import kotlinx.serialization.json.Json
4import kotlinx.serialization.json.JsonArray
5import kotlinx.serialization.json.JsonObject
6import kotlinx.serialization.json.JsonPrimitive
7import kotlinx.serialization.json.contentOrNull
8import kotlinx.serialization.json.jsonArray
9import kotlinx.serialization.json.jsonObject
10
11/**
12 * Parser for the server-published static feed contract
13 * (`https://static.maproj.org/news/v1/news.json`, written by
14 * location_share_server's background refresh):
15 *
16 * ```
17 * { "generated_at": ..., "articles": [
18 * { "title": ..., "url": ..., "source": ..., "published_at": ...,
19 * "image_url": ..., "metered": false, "language": "en" } ] }
20 * ```
21 *
22 * Contract assumptions (flagged for reconciliation with the server agent):
23 * - `source` is a [SourceCatalog] id (`bbc`) or its exact display name
24 * (`BBC News`); both resolve to the catalog id. Anything else is kept
25 * verbatim as the sourceId — such articles are then dropped by the
26 * kept and shown under "All" only (no category), never re-attributed
27 * to a different source.
28 * - `published_at` is an ISO-8601/RFC-1123 string (parsed by
29 * [DateParsing]) or epoch seconds/millis as a JSON number.
30 * - `image_url` may be absent/null; `metered` may be absent (defaults
31 * false). `metered` is carried on [FeedArticle] but not persisted:
32 * the catalog already badges metered sources.
33 * - `language` is a BCP-47 tag stated per article by the server (its
34 * per-article refinement of the source default); when absent it
35 * defaults from [SourceCatalog] for the resolved source.
36 * - There is no category field. Category is derived client-side only:
37 * the resolved catalog id maps to [NewsSource.categories] in
38 * [SourceCatalog] (see [NewsCategory]), and the feed/search filters
39 * apply that mapping to the article's `sourceId`. Unresolved ids have
40 * no category and match the feed's "All" filter only.
41 * - Story grouping (server-side only; the client never groups):
42 * `story_id` (same for all articles of one story — the client's
43 * sole grouping key, used exactly), `story_one_liner` (generated
44 * one-line summary — the only server text the client may display;
45 * extracted article text is NEVER served), and optional
46 * `story_title`. All optional: articles without a `story_id`
47 * (the fallback crawl path produces no story fields at all) each
48 * render as a single-article story. Alias keys `story_oneliner` /
49 * `story_summary` are also accepted for the one-liner until the
50 * server schema freezes.
51 *
52 * Pure and non-throwing: malformed documents/articles yield an empty or
53 * partial list, which the repository treats as server-feed failure and
54 * falls back to the on-device sitemap crawl.
55 */
56object ServerFeedParser {
57 private val json = Json { ignoreUnknownKeys = true }
58
59 fun parse(text: String): List<FeedArticle> {
60 val root = runCatching { json.parseToJsonElement(text).jsonObject }.getOrNull() ?: return emptyList()
61 val articles: JsonArray = root["articles"]?.let {
62 runCatching { it.jsonArray }.getOrNull()
63 } ?: return emptyList()
64 return articles.mapNotNull { element ->
65 val obj = runCatching { element.jsonObject }.getOrNull() ?: return@mapNotNull null
66 parseArticle(obj)
67 }
68 }
69
70 /**
71 * The document's `generated_at` stamp, read without parsing the whole
72 * document: it sits in the prologue before `articles`, so a bounded
73 * prefix scan finds it. The repository uses this as the feed's identity:
74 * an unchanged stamp means the (potentially large) article array is the
75 * one already merged into Room, so re-parsing and re-publishing it on
76 * every cold start is skipped. Null when absent or not in the prefix.
77 */
78 fun feedStamp(text: String): String? {
79 val prefix = text.substring(0, minOf(text.length, STAMP_SCAN_CHARS))
80 val key = prefix.indexOf("\"generated_at\"")
81 if (key < 0) return null
82 val colon = prefix.indexOf(':', key)
83 if (colon < 0) return null
84 val start = prefix.indexOf('"', colon)
85 if (start < 0) return null
86 val end = prefix.indexOf('"', start + 1)
87 if (end < 0) return null
88 return prefix.substring(start + 1, end).takeIf { it.isNotEmpty() }
89 }
90
91 private fun parseArticle(obj: JsonObject): FeedArticle? {
92 val url = obj.string("url")?.takeIf { it.startsWith("http") } ?: return null
93 val title = obj.string("title")?.takeIf { it.isNotBlank() } ?: return null
94 val sourceRaw = obj.string("source")?.takeIf { it.isNotBlank() } ?: return null
95 val source = resolveSource(sourceRaw)
96 val sourceId = source?.id ?: sourceRaw.trim()
97 return FeedArticle(
98 url = url,
99 sourceId = sourceId,
100 title = title,
101 publishedAtMillis = parsePublishedAt(obj["published_at"]),
102 imageUrl = obj.string("image_url"),
103 metered = (obj["metered"] as? JsonPrimitive)?.contentOrNull?.toBooleanStrictOrNull() ?: false,
104 language = obj.string("language") ?: source?.language,
105 topics = (obj["topics"] as? JsonArray)?.mapNotNull {
106 (it as? JsonPrimitive)?.contentOrNull?.trim()?.takeIf { t -> t.isNotEmpty() }
107 } ?: emptyList(),
108 serverStoryId = obj.string("story_id"),
109 storyOneLiner = obj.string("story_one_liner") ?: obj.string("story_oneliner")
110 ?: obj.string("story_summary"),
111 serverStoryTitle = obj.string("story_title"),
112 )
113 }
114
115 /** Catalog id for a catalog id or exact catalog name; otherwise [raw] verbatim. */
116 fun resolveSourceId(raw: String): String = resolveSource(raw)?.id ?: raw.trim()
117
118 /** Catalog source for a catalog id or exact catalog name; null when unresolved (kept verbatim). */
119 fun resolveSource(raw: String): NewsSource? {
120 val trimmed = raw.trim()
121 return SourceCatalog.byId(trimmed) ?: SourceCatalog.byName(trimmed)
122 }
123
124 private const val STAMP_SCAN_CHARS = 1024
125
126 private fun parsePublishedAt(element: kotlinx.serialization.json.JsonElement?): Long {
127 val primitive = element as? JsonPrimitive ?: return 0L
128 if (primitive.isString) return DateParsing.parseMillis(primitive.contentOrNull) ?: 0L
129 val value = primitive.contentOrNull?.toLongOrNull() ?: return 0L
130 // < 10^10 is epoch seconds (year 2286 in millis terms); else millis.
131 return if (value in 1 until 10_000_000_000L) value * 1_000L else value
132 }
133
134 private fun JsonObject.string(key: String): String? =
135 (this[key] as? JsonPrimitive)?.contentOrNull?.trim()?.takeIf { it.isNotEmpty() }
136}