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

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

FeedMerger.kt35 lines · 1.6 KiBRaw
1package com.vayunmathur.news.domain
2
3/** Feed merging: de-duplicate by normalised URL, newest first. Pure and total. */
4object FeedMerger {
5 fun merge(feeds: Iterable<List<FeedArticle>>, limit: Int = 500): List<FeedArticle> {
6 val seen = HashSet<String>()
7 val merged = mutableListOf<FeedArticle>()
8 for (article in feeds.flatten()) {
9 val key = normaliseUrl(article.url)
10 if (key.isEmpty() || !seen.add(key)) continue
11 merged += article
12 }
13 return merged.sortedByDescending { it.publishedAtMillis }.take(limit)
14 }
15
16 /** Lower-cases scheme/host, drops fragment and tracking params, trims a trailing slash. */
17 fun normaliseUrl(url: String): String {
18 val trimmed = url.trim()
19 val noFragment = trimmed.substringBefore('#')
20 val schemeEnd = noFragment.indexOf("://")
21 if (schemeEnd < 0) return noFragment.trimEnd('/')
22 val scheme = noFragment.substring(0, schemeEnd).lowercase()
23 val rest = noFragment.substring(schemeEnd + 3)
24 val host = rest.substringBefore('/').lowercase()
25 val pathAndQuery = rest.substring(host.length)
26 val path = pathAndQuery.substringBefore('?').ifEmpty { "/" }
27 val query = pathAndQuery.substringAfter('?', "")
28 .split('&').filter { part ->
29 val name = part.substringBefore('=').lowercase()
30 name.isNotEmpty() && !name.startsWith("utm_") && name != "ref" && name != "fbclid"
31 }.sorted().joinToString("&")
32 val base = "$scheme://$host${path.trimEnd('/')}"
33 return if (query.isEmpty()) base else "$base?$query"
34 }
35}