diff --git a/build.gradle b/build.gradle index a621e0781a..567e314bbd 100644 --- a/build.gradle +++ b/build.gradle @@ -517,6 +517,9 @@ dependencies { implementation libs.xdrop.fuzzywuzzy // Flexera Launcher: encodes the QR code on the About screen. Nothing else of it is used. implementation libs.zxing.core + // Flexera Launcher: finds an article's text in its web page, and cleans what the RSS reader + // shows of it (app.flexera.reader.ArticleStore). + implementation libs.jsoup implementation libs.bundles.opto implementation libs.androidx.datastore.preferences @@ -589,6 +592,8 @@ licensee { allowUrl("https://github.com/patrykmichalik/opto/blob/master/LICENSE") allowUrl("https://github.com/RikkaApps/HiddenApiRefinePlugin/blob/main/LICENSE") allowUrl("https://opensource.org/licenses/mit-license.php") + // Flexera Launcher: jsoup's licence page, the MIT licence. + allowUrl("https://jsoup.org/license") bundleAndroidAsset = true androidAssetReportPath = 'licenses.json' diff --git a/flexera/res/drawable/ic_flexera_back.xml b/flexera/res/drawable/ic_flexera_back.xml new file mode 100644 index 0000000000..1f6fc42e9b --- /dev/null +++ b/flexera/res/drawable/ic_flexera_back.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/flexera/res/drawable/ic_flexera_open_in_new.xml b/flexera/res/drawable/ic_flexera_open_in_new.xml new file mode 100644 index 0000000000..cb58efac9b --- /dev/null +++ b/flexera/res/drawable/ic_flexera_open_in_new.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/flexera/res/drawable/ic_flexera_share.xml b/flexera/res/drawable/ic_flexera_share.xml new file mode 100644 index 0000000000..79aa50003a --- /dev/null +++ b/flexera/res/drawable/ic_flexera_share.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/flexera/res/values/flexera_strings.xml b/flexera/res/values/flexera_strings.xml index 6c7e09fb4a..5f285c7f9b 100644 --- a/flexera/res/values/flexera_strings.xml +++ b/flexera/res/values/flexera_strings.xml @@ -291,6 +291,20 @@ Their posts appear together on the reader\'s page, the newest first. Pull the list down to refresh. Remove %1$s + + now + + %1$dm + + %1$dh + + %1$dd + Share + + Back to your feeds + Visit article + Loading the whole article… + This is as much of the article as could be brought here. Visit article to read it on the site. Choose Open RSS reader for a gesture, such as a swipe past the first page, and your feeds slide in. diff --git a/flexera/src/app/flexera/reader/ArticleStore.kt b/flexera/src/app/flexera/reader/ArticleStore.kt new file mode 100644 index 0000000000..4332face5a --- /dev/null +++ b/flexera/src/app/flexera/reader/ArticleStore.kt @@ -0,0 +1,413 @@ +package app.flexera.reader + +import android.content.Context +import android.text.TextUtils +import android.util.Log +import app.lawnchair.util.kotlinxJson +import java.io.ByteArrayInputStream +import java.io.File +import java.security.MessageDigest +import java.util.Locale +import java.util.concurrent.TimeUnit +import kotlin.math.max +import org.jsoup.Jsoup +import org.jsoup.nodes.Document +import org.jsoup.nodes.Element +import org.jsoup.safety.Safelist + +/** + * The text of the RSS reader's posts, for the article view ([ArticleView]). + * + * A feed carries some of each post as HTML, often only its start. That is kept as it comes, a + * file per post, when the feed is fetched ([saveFeedText]). Opening a post shows it at once + * ([fromFeed]); when it is short of a whole article, the post's web page is fetched and its + * article found in it ([fromPage]): the element whose paragraphs hold the most text, after the + * parts that are plainly not the article (menus, sharing, related stories, comments) are taken + * out, as reading modes do. Whatever is shown is cleaned first: only text, pictures, links and + * plain structure stay; no scripts, frames, forms or styles of the site's own. The files are + * in the cache, which Android may empty; a post is then fetched again when opened. + */ +object ArticleStore { + + private const val TAG = "ArticleStore" + private const val DIR = "flexera_rss_articles" + + /** A feed's text this long, in characters, is taken for the whole article. */ + private const val WHOLE_TEXT = 2500 + + /** An article found in a page is believed only from this length on. */ + private const val MIN_FOUND_TEXT = 400 + + /** Kept files go after this many days. */ + private const val KEEP_DAYS = 21L + + /** What the article view shows of a post: cleaned HTML, and whether it is all of it. */ + class Readable(val html: String, val whole: Boolean) + + private val safelist: Safelist = Safelist.relaxed() + .addTags("figure", "figcaption", "hr", "mark", "s", "del", "ins", "abbr", "time", "small") + .removeAttributes("img", "width", "height", "align") + + private fun dir(context: Context) = File(context.cacheDir, DIR) + + private fun file(context: Context, id: String, kind: String) = File(dir(context), "${hash(id)}.$kind") + + private fun hash(id: String): String = + MessageDigest.getInstance("SHA-1").digest(id.toByteArray()).joinToString("") { "%02x".format(it) } + + /** Keeps what the feed carries of a post, unless it is kept already. For a background thread. */ + fun saveFeedText(context: Context, articleId: String, html: String) { + if (html.isBlank()) return + try { + val target = file(context, articleId, "feed") + if (target.exists()) return + target.parentFile?.mkdirs() + target.writeText(html) + } catch (e: Exception) { + Log.w(TAG, "Could not keep a post's text", e) + } + } + + /** + * What there is of [item] without going online: the article found in its page before, or + * the feed's text, or at least the summary. For a background thread. + */ + fun fromFeed(context: Context, item: RssReader.Item): Readable { + val article = item.article + readOrNull(file(context, article.id, "page"))?.let { return Readable(it, whole = true) } + val feedHtml = readOrNull(file(context, article.id, "feed"))?.let { clean(it, base(article), article.imageUrl) } + if (feedHtml != null && textLength(feedHtml) >= WHOLE_TEXT) return Readable(feedHtml, whole = true) + val html = feedHtml?.takeIf { textLength(it) > 0 } + ?: article.summary.takeIf { it.isNotEmpty() }?.let { "

${TextUtils.htmlEncode(it)}

" } + ?: "" + return Readable(html, whole = false) + } + + /** + * Fetches [item]'s web page and finds the article in it. Null when that is no longer than + * [knownLength] characters of text already shown; the page is then no help. For a background + * thread; throws [RssFetcher.FetchException] when the page cannot be fetched. + */ + fun fromPage(context: Context, item: RssReader.Item, knownLength: Int): String? { + val article = item.article + if (article.link.isEmpty()) return null + val page = RssFetcher.fetchPage(context, article.link) + val document = Jsoup.parse(ByteArrayInputStream(page.body), charsetOf(page.contentType), page.url) + val found = Extractor.articleOf(document, article.title) ?: return null + val html = clean(found, page.url, article.imageUrl) + val length = textLength(html) + if (length < MIN_FOUND_TEXT || length <= knownLength) return null + try { + val target = file(context, article.id, "page") + target.parentFile?.mkdirs() + target.writeText(html) + } catch (e: Exception) { + Log.w(TAG, "Could not keep an article", e) + } + return html + } + + /** How many characters of text [html] shows. */ + fun textLength(html: String): Int = Jsoup.parseBodyFragment(html).text().length + + /** Deletes kept texts older than [KEEP_DAYS]. For a background thread. */ + fun prune(context: Context) { + val cutoff = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(KEEP_DAYS) + dir(context).listFiles()?.forEach { if (it.lastModified() < cutoff) it.delete() } + } + + private fun base(article: RssArticle) = article.link.ifEmpty { article.feedUrl } + + private fun readOrNull(file: File): String? = try { + if (file.exists()) file.readText() else null + } catch (e: Exception) { + null + } + + private fun charsetOf(contentType: String?): String? = + contentType?.substringAfter("charset=", "")?.trim(' ', '"', ';')?.takeIf { it.isNotEmpty() } + ?.takeIf { runCatching { charset(it) }.isSuccess } + + /** + * [html] with only what is safe and plain left: no scripts, styles, frames or forms, links + * and pictures made whole addresses, and pictures fetched encrypted. The post's own picture + * ([hero]), which the view shows above the title, is taken out where the text starts with it. + */ + private fun clean(html: String, base: String, hero: String?): String { + val raw = Jsoup.parseBodyFragment(html, base) + useLazyPictures(raw) + val cleaned = Jsoup.parseBodyFragment(Jsoup.clean(raw.body().html(), base, safelist), base) + for (img in cleaned.select("img")) { + val src = img.attr("src") + when { + src.isBlank() -> img.remove() + src.startsWith("http://") -> img.attr("src", "https://" + src.removePrefix("http://")) + } + } + if (hero != null) { + cleaned.select("img").firstOrNull { sameImage(it.attr("src"), hero) }?.let { same -> + val figure = same.closest("figure") + if (figure != null && figure.select("img").size == 1) figure.remove() else same.remove() + } + } + cleaned.select("h1").remove() + // Paragraphs left empty by the cleaning. + for (el in cleaned.select("p, div, span, figure, a")) { + if (!el.hasText() && el.select("img, hr, br").isEmpty()) el.remove() + } + return cleaned.body().html() + } + + /** Pages often load their pictures only when scrolled to; their real address is elsewhere. */ + private fun useLazyPictures(document: Document) { + for (img in document.select("img")) { + val src = img.attr("src") + if (src.isNotBlank() && !src.startsWith("data:")) continue + val lazy = listOf("data-src", "data-lazy-src", "data-original", "data-url", "data-hi-res-src") + .map { img.attr(it) }.firstOrNull { it.isNotBlank() } + ?: firstOfSrcset(img.attr("srcset").ifBlank { img.attr("data-srcset") }) + ?: img.parent()?.takeIf { it.tagName() == "picture" } + ?.select("source")?.firstNotNullOfOrNull { firstOfSrcset(it.attr("srcset")) } + if (lazy != null) img.attr("src", lazy) else img.remove() + } + } + + private fun firstOfSrcset(srcset: String): String? = + srcset.split(',').map { it.trim().substringBefore(' ') }.lastOrNull { it.isNotBlank() } + + /** Whether two picture addresses name the same picture, perhaps at another size. */ + private fun sameImage(a: String, b: String): Boolean { + fun name(url: String) = url.substringBefore('?').substringAfterLast('/') + .lowercase(Locale.ROOT) + .replace(Regex("""-\d+x\d+(?=\.\w+$)"""), "") + .substringBeforeLast('.') + val left = name(a) + return left.isNotEmpty() && left == name(b) + } + + /** Finds the article in a web page. */ + private object Extractor { + + /** Class and id words of the parts of a page that are not the article. */ + private val UNLIKELY = Regex( + """(?i)(^|[-_\s])(ad|ads|advert\w*|banner|breadcrumbs?|comments?|community|cookie|consent|disqus|footer|gdpr|header|menu|modal|nav\w*|newsletter|outbrain|pagination|popup|promo\w*|recirc\w*|related|share|sharing|sidebar|signup|social|sponsor\w*|subscribe|subscription|taboola|toolbar|trending|most-popular|read-more|more-stories|author-bio|tags?)([-_\s]|$)""", + ) + + /** Words that make a part likely to be the article after all. */ + private val LIKELY = Regex("""(?i)article|body|content|main|story|entry|post-?text|prose""") + + private val TEXT_TAGS = setOf("p", "pre", "td", "blockquote", "li") + + /** + * Lines of the page that are about the site rather than the article: commission notices, + * invitations to follow or subscribe. + */ + private val PROMO = Regex( + """(?i)earns? (a )?commission|affiliate links?|ethics statement|follow topics|receive email updates|sign up for|subscribe (to|for)|all rights reserved|support our journalism|share this (article|story)""", + ) + + /** + * A paragraph this long, in characters, is the article's own text; a page's subtitle and + * byline are shorter. + */ + private const val REAL_PARAGRAPH = 100 + + /** Blocks this short, in characters, around a date or an author's picture are a byline. */ + private const val BYLINE_LENGTH = 160 + private const val AUTHOR_BOX_LENGTH = 400 + + /** A short line that names the writer: "by Jane Doe", "By Jane Doe and John Roe". */ + private val BY = Regex("""(?i)^\s*by\s+\S.{0,60}$""") + + fun articleOf(document: Document, title: String): String? { + val fromJson = articleBodyFromJson(document) + document.select( + "script, style, noscript, iframe, form, nav, header, footer, aside, button, svg, input, " + + "select, textarea, template, dialog, canvas, object, embed, video, audio", + ).remove() + val body = document.body() + for (el in body.getAllElements().toList()) { + if (el === body || el.tagName() == "article" || el.tagName() == "main") continue + val words = el.className() + " " + el.id() + if (UNLIKELY.containsMatchIn(words) && !LIKELY.containsMatchIn(words)) el.remove() + } + + val scores = HashMap() + for (el in body.select("p, pre, td, blockquote")) { + val text = el.text() + if (text.length < 25) continue + val score = 1.0 + text.count { it == ',' } + minOf(text.length / 100, 3) + val parent = el.parent() ?: continue + scores[parent] = (scores[parent] ?: initial(parent)) + score + parent.parent()?.let { grand -> scores[grand] = (scores[grand] ?: initial(grand)) + score / 2 } + } + val best = scores.maxByOrNull { (el, score) -> score * (1 - linkDensity(el)) }?.key + val found = best?.let { withSiblings(promote(it), scores, scores[it] ?: 0.0) } + // Measured before the tidying, which takes the page's own header off: the page keeps + // the links and the pictures that the structured data, plain text, does not have. + val foundLength = found?.text()?.length ?: 0 + if (fromJson != null && Jsoup.parseBodyFragment(fromJson).text().length > foundLength * 1.3) return fromJson + return found?.also { tidy(it, title) }?.html() + } + + /** + * Takes what the page puts around the article out of [root]: its own copy of the title + * (the view shows the title once, above), and everything before the first real paragraph + * (kicker, title, byline, date, the author's box, the lead picture) and after the last + * one (the author again, invitations to follow), and the site's notices in between. + */ + private fun tidy(root: Element, title: String) { + root.select("h1").remove() + val wanted = comparable(title) + if (wanted.isNotEmpty()) { + root.select("h2, h3, p, div, span").filter { comparable(it.text()) == wanted }.forEach { it.remove() } + } + root.select("p, div, span, aside, section, small") + .filter { el -> el.text().let { it.length < 300 && PROMO.containsMatchIn(it) } && el.select("p").size <= 1 } + .forEach { it.remove() } + // A subtitle the page has twice, for small and large screens: neither copy is text. + root.select("p, h2, h3").groupBy { comparable(it.text()) } + .filter { (text, copies) -> copies.size > 1 && text.length in 20..300 } + .values.flatten().forEach { it.remove() } + // The byline: the date with what is around it, a "by" line, the author's picture and note. + for (time in root.select("time")) outermostShort(time, root, BYLINE_LENGTH)?.takeIf { it !== time }?.remove() + root.select("p, div, span").filter { BY.matches(it.text()) && it.select("p").size <= 1 }.forEach { it.remove() } + for (img in root.select("a[href*=/author] img, a[href*=/people/] img, a[href*=/staff/] img")) { + outermostShort(img, root, AUTHOR_BOX_LENGTH)?.takeIf { it !== img }?.remove() + } + val paragraphs = root.select("p").filter { it.text().length >= REAL_PARAGRAPH } + paragraphs.firstOrNull()?.let { removeAround(it, root, before = true) } + paragraphs.lastOrNull()?.let { removeAround(it, root, before = false) } + } + + /** + * The article's text where a page splits it into blocks side by side, with advertising + * between them: [top] with the blocks beside it that are of the same kind (the same + * classes) or hold a fair share of the text themselves, in their order. [top] alone + * when there are none. + */ + private fun withSiblings(top: Element, scores: Map, bestScore: Double): Element { + val parent = top.parent() ?: return top + if (parent.tagName() == "body") return top + val threshold = max(10.0, bestScore * 0.2) + val kind = top.className() + // A block's score is that of its best-scoring part: the paragraphs' own container + // may lie a few wrappers deep. + val within = HashMap() + for ((el, score) in scores) { + var node: Element? = el + while (node != null && node.parent() !== parent) node = node.parent() + if (node != null) within[node] = max(within[node] ?: 0.0, score) + } + val parts = parent.children().filter { sibling -> + sibling === top || + (kind.isNotEmpty() && sibling.className() == kind) || + (within[sibling] ?: 0.0) >= threshold && linkDensity(sibling) < 0.3 || + (sibling.tagName() == "p" && sibling.text().length >= REAL_PARAGRAPH && linkDensity(sibling) < 0.25) + } + if (parts.size <= 1) return top + val joined = Element("div") + parts.toList().forEach { joined.appendChild(it) } + return joined + } + + /** The largest element around [el], inside [root], with less than [limit] characters of text. */ + private fun outermostShort(el: Element, root: Element, limit: Int): Element? { + var found: Element? = null + var current: Element? = el + while (current != null && current !== root && current.text().length < limit) { + found = current + current = current.parent() + } + return found + } + + /** Removes everything in [root] before (or after) [el], keeping the elements around it. */ + private fun removeAround(el: Element, root: Element, before: Boolean) { + var current: Element = el + while (current !== root) { + var node = if (before) current.previousSibling() else current.nextSibling() + while (node != null) { + val next = if (before) node.previousSibling() else node.nextSibling() + // After the text, a closing list, picture, quote or line still belongs to it; + // what goes is short: the author's name, a lone link. + if (before || !(node is Element && endsArticle(node))) node.remove() + node = next + } + current = current.parent() ?: return + } + } + + private fun endsArticle(el: Element): Boolean = + el.select("ul, ol, figure, blockquote, table, img").isNotEmpty() || + el.select("p").any { it.text().length >= 40 } || + (el.tagName() == "p" && el.text().length >= 40) + + /** Text reduced to its letters and digits, for telling whether two say the same. */ + private fun comparable(text: String): String = + text.lowercase(Locale.ROOT).filter { it.isLetterOrDigit() } + + /** Some kinds of element are likelier to hold the article than others. */ + private fun initial(el: Element): Double = when { + el.attr("itemprop") == "articleBody" -> 25.0 + el.tagName() == "article" -> 10.0 + el.tagName() == "main" || el.tagName() == "div" -> 5.0 + el.tagName() in TEXT_TAGS -> 3.0 + el.tagName() in setOf("ul", "ol", "dl", "form") -> -3.0 + el.tagName().matches(Regex("h[1-6]")) -> -5.0 + else -> 0.0 + } + + /** An article element around the best text, when the text is one part of it. */ + private fun promote(el: Element): Element { + var current = el + while (true) { + val parent = current.parent() ?: return current + if (parent.tagName() == "body") return current + val isArticle = parent.tagName() == "article" || parent.attr("itemprop") == "articleBody" + if (isArticle && parent.text().length < current.text().length * 2) return parent + if (parent.text().length > current.text().length * 1.25) return current + current = parent + } + } + + /** The share of an element's text that is in links: menus and lists of stories are mostly that. */ + private fun linkDensity(el: Element): Double { + val text = el.text().length + if (text == 0) return 1.0 + val inLinks = el.select("a").sumOf { it.text().length } + return inLinks.toDouble() / text + } + + /** Plain text as HTML: a paragraph per line, and lines that start with "* " or "- " as a list. */ + private fun paragraphsOf(text: String): String { + val html = StringBuilder() + var inList = false + for (line in text.split('\n').map { it.trim() }.filter { it.isNotEmpty() }) { + val item = line.startsWith("* ") || line.startsWith("- ") || line.startsWith("• ") + if (item && !inList) html.append("
    ") + if (!item && inList) html.append("
") + inList = item + if (item) { + html.append("
  • ").append(TextUtils.htmlEncode(line.drop(2).trim())).append("
  • ") + } else { + html.append("

    ").append(TextUtils.htmlEncode(line)).append("

    ") + } + } + if (inList) html.append("") + return html.toString() + } + + /** The article's text from the page's structured data, where a site gives it there. */ + private fun articleBodyFromJson(document: Document): String? { + for (script in document.select("script[type=application/ld+json]")) { + val match = Regex(""""articleBody"\s*:\s*"((?:[^"\\]|\\.)*)"""").find(script.data()) ?: continue + val text = runCatching { kotlinxJson.decodeFromString("\"${match.groupValues[1]}\"") }.getOrNull() + ?: continue + if (text.length < MIN_FOUND_TEXT) continue + return paragraphsOf(text) + } + return null + } + } +} diff --git a/flexera/src/app/flexera/reader/ArticleView.kt b/flexera/src/app/flexera/reader/ArticleView.kt new file mode 100644 index 0000000000..b3764009af --- /dev/null +++ b/flexera/src/app/flexera/reader/ArticleView.kt @@ -0,0 +1,488 @@ +package app.flexera.reader + +import android.animation.Animator +import android.animation.AnimatorListenerAdapter +import android.animation.ValueAnimator +import android.annotation.SuppressLint +import android.content.ActivityNotFoundException +import android.content.Intent +import android.content.res.ColorStateList +import android.graphics.Color +import android.graphics.PorterDuff +import android.graphics.Rect +import android.graphics.Typeface +import android.graphics.drawable.ColorDrawable +import android.graphics.drawable.GradientDrawable +import android.graphics.drawable.RippleDrawable +import android.net.Uri +import android.text.TextUtils +import android.text.format.DateUtils +import android.util.TypedValue +import android.view.Gravity +import android.view.MotionEvent +import android.view.VelocityTracker +import android.view.View +import android.view.ViewConfiguration +import android.view.animation.DecelerateInterpolator +import android.webkit.WebResourceRequest +import android.webkit.WebSettings +import android.webkit.WebView +import android.webkit.WebViewClient +import android.widget.FrameLayout +import android.widget.ImageView +import android.widget.TextView +import android.widget.Toast +import com.android.launcher3.Insettable +import com.android.launcher3.Launcher +import com.android.launcher3.R +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.roundToInt +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.MainScope +import kotlinx.coroutines.cancel +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * A post of the RSS reader, read inside the reader instead of on its site. It slides in over + * the list from the side where text ends, with the post's picture, title, feed, date and author + * above its text. That is at first what the feed carries; when that is only the start of the + * article, the article's page is fetched and its text found in it ([ArticleStore]), and the + * view shows the whole of it as soon as it is there. The site itself is one tap away, on the + * "Visit article" button that stays at the bottom, within reach of the thumb. + * + * The text is shown by a [WebView] with no JavaScript and no access to files, given only + * cleaned HTML; a link in it opens in the browser. Back, the arrow at the top, or a swipe + * towards the side it came from takes the article away again. + */ +@SuppressLint("ViewConstructor") +internal class ArticleView( + private val launcher: Launcher, + private val onShare: (RssReader.Item) -> Unit, + /** How much of the list the article covers, from 0 to 1, whenever that changes. */ + private val onCover: (Float) -> Unit, +) : FrameLayout(launcher), Insettable { + + private companion object { + /** All but opaque: the list beneath is blurred away, and the text is read on near black. */ + const val BACKGROUND = 0xFA0C0C0E.toInt() + const val BUTTON = 0xFFE8EAED.toInt() + const val BUTTON_TEXT = 0xFF202124.toInt() + const val PRESSED = 0x26FFFFFF + + const val SLIDE_MS = 280L + + /** Swiped this far, as a share of the width, letting go takes the article away. */ + const val CLOSE_DISTANCE = 0.3f + const val FLICK_DP_PER_SECOND = 600f + + /** How far Android's back preview draws the article aside before Back is let go. */ + const val BACK_PEEK = 0.2f + } + + private val density = resources.displayMetrics.density + private var web: WebView? = null + private val topShade = View(launcher) + private val bottomShade = View(launcher) + private val back = ImageView(launcher) + private val share = ImageView(launcher) + private val visit = TextView(launcher) + private var insets = Rect() + private var scope: CoroutineScope? = null + private var loading: Job? = null + private var animator: ValueAnimator? = null + + /** The post shown, while the view is open. */ + var item: RssReader.Item? = null + private set + + val isOpen: Boolean get() = item != null + + /** +1 when the article comes from the right, -1 from the left (right-to-left reading). */ + private val side: Float get() = if (layoutDirection == LAYOUT_DIRECTION_RTL) -1f else 1f + + private val touchSlop = ViewConfiguration.get(launcher).scaledTouchSlop + private var downX = 0f + private var downY = 0f + private var dragFrom = 0f + private var dragging = false + private var tracker: VelocityTracker? = null + + init { + visibility = GONE + setBackgroundColor(BACKGROUND) + // Its own touches only: none goes through to the list beneath. + isClickable = true + + topShade.background = GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, intArrayOf(BACKGROUND, Color.TRANSPARENT)) + bottomShade.background = GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, intArrayOf(BACKGROUND, Color.TRANSPARENT)) + for (shade in listOf(topShade, bottomShade)) shade.importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO + addView(topShade, LayoutParams(LayoutParams.MATCH_PARENT, 0, Gravity.TOP)) + addView(bottomShade, LayoutParams(LayoutParams.MATCH_PARENT, 0, Gravity.BOTTOM)) + + setUpIcon(back, R.drawable.ic_flexera_back, R.string.flexera_rss_back) { close(animate = true) } + setUpIcon(share, R.drawable.ic_flexera_share, R.string.flexera_rss_share) { item?.let(onShare) } + addView(back, LayoutParams(dp(48), dp(48), Gravity.TOP or Gravity.START)) + addView(share, LayoutParams(dp(48), dp(48), Gravity.TOP or Gravity.END)) + + visit.setText(R.string.flexera_rss_visit_article) + visit.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f) + visit.setTextColor(BUTTON_TEXT) + visit.typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) + visit.gravity = Gravity.CENTER + visit.minHeight = dp(48) + visit.setPadding(dp(20), dp(12), dp(24), dp(12)) + visit.compoundDrawablePadding = dp(10) + visit.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_flexera_open_in_new, 0, 0, 0) + visit.compoundDrawableTintList = ColorStateList.valueOf(BUTTON_TEXT) + visit.compoundDrawableTintMode = PorterDuff.Mode.SRC_IN + visit.background = RippleDrawable( + ColorStateList.valueOf(0x33000000), + GradientDrawable().apply { + cornerRadius = dp(24).toFloat() + setColor(BUTTON) + }, + null, + ) + visit.elevation = dp(4).toFloat() + visit.setOnClickListener { item?.let { openOnSite(it.article.link) } } + addView(visit, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL)) + } + + override fun setTranslationX(translationX: Float) { + super.setTranslationX(translationX) + reportCover() + } + + override fun setVisibility(visibility: Int) { + super.setVisibility(visibility) + reportCover() + } + + private fun reportCover() { + val across = if (width > 0) width else (parent as? View)?.width ?: 0 + val cover = when { + visibility != VISIBLE -> 0f + across <= 0 -> 1f + else -> (1f - abs(translationX) / across).coerceIn(0f, 1f) + } + // Called from the constructor too, before the callback is set. + @Suppress("SENSELESS_COMPARISON") + if (onCover != null) onCover(cover) + } + + private fun setUpIcon(view: ImageView, icon: Int, description: Int, onClick: () -> Unit) { + view.setImageResource(icon) + view.contentDescription = resources.getString(description) + view.scaleType = ImageView.ScaleType.CENTER + view.background = RippleDrawable(ColorStateList.valueOf(PRESSED), null, ColorDrawable(Color.WHITE)).apply { radius = dp(24) } + view.setOnClickListener { onClick() } + } + + override fun setInsets(insets: Rect) { + this.insets.set(insets) + (back.layoutParams as LayoutParams).apply { + topMargin = insets.top + dp(8) + marginStart = insets.left + dp(8) + } + (share.layoutParams as LayoutParams).apply { + topMargin = insets.top + dp(8) + marginEnd = insets.right + dp(8) + } + (visit.layoutParams as LayoutParams).bottomMargin = insets.bottom + dp(20) + topShade.layoutParams.height = insets.top + dp(72) + bottomShade.layoutParams.height = insets.bottom + dp(110) + requestLayout() + } + + override fun onAttachedToWindow() { + super.onAttachedToWindow() + scope = MainScope() + } + + override fun onDetachedFromWindow() { + scope?.cancel() + scope = null + web?.let { + removeView(it) + it.destroy() + } + web = null + item = null + visibility = GONE + super.onDetachedFromWindow() + } + + /** Slides [post] in, showing what there is of it at once and the rest when it has come. */ + fun open(post: RssReader.Item) { + item = post + loading?.cancel() + val view = webView() + view.scrollTo(0, 0) + show(post, ArticleStore.Readable(placeholderHtml(post), whole = false), loadingMore = false) + visibility = VISIBLE + bringToFront() + // Not laid out yet the first time: as wide as what it lies over. + val across = if (width > 0) width else (parent as? View)?.width ?: resources.displayMetrics.widthPixels + slideTo(0f, from = side * across) + + val scope = scope ?: return + loading = scope.launch { + val first = withContext(Dispatchers.IO) { ArticleStore.fromFeed(launcher, post) } + if (item !== post) return@launch + val online = !first.whole && post.article.link.isNotEmpty() + show(post, first, loadingMore = online) + if (!online) return@launch + val whole = withContext(Dispatchers.IO) { + runCatching { ArticleStore.fromPage(launcher, post, ArticleStore.textLength(first.html)) }.getOrNull() + } + if (item !== post) return@launch + if (whole != null) { + show(post, ArticleStore.Readable(whole, whole = true), loadingMore = false, keepScroll = true) + } else { + show(post, first, loadingMore = false, keepScroll = true) + } + } + } + + /** Takes the article away, sliding it out when [animate]. */ + fun close(animate: Boolean) { + if (!isOpen) return + item = null + loading?.cancel() + loading = null + if (animate && isShown) { + slideTo(side * width, from = translationX) { finishClose() } + } else { + cancelAnimation() + finishClose() + } + } + + private fun finishClose() { + if (isOpen) return + visibility = GONE + translationX = 0f + // Frees the page and stops pictures still loading. + web?.loadDataWithBaseURL(null, "", "text/html", "utf-8", null) + } + + fun onBackStarted() = cancelAnimation() + + fun onBackProgressed(progress: Float) { + translationX = side * BACK_PEEK * progress * width + } + + fun onBackCancelled() { + if (isOpen) slideTo(0f, from = translationX) + } + + private fun slideTo(target: Float, from: Float, then: (() -> Unit)? = null) { + cancelAnimation() + translationX = from + val anim = ValueAnimator.ofFloat(from, target) + anim.duration = SLIDE_MS + anim.interpolator = DecelerateInterpolator(1.5f) + anim.addUpdateListener { translationX = it.animatedValue as Float } + anim.addListener(object : AnimatorListenerAdapter() { + private var cancelled = false + + override fun onAnimationCancel(animation: Animator) { + cancelled = true + } + + override fun onAnimationEnd(animation: Animator) { + if (animator === anim) animator = null + if (!cancelled) then?.invoke() + } + }) + animator = anim + anim.start() + } + + private fun cancelAnimation() { + animator?.let { + animator = null + it.cancel() + } + } + + @SuppressLint("SetJavaScriptEnabled") + private fun webView(): WebView { + web?.let { return it } + val view = WebView(launcher) + view.setBackgroundColor(Color.TRANSPARENT) + view.settings.apply { + javaScriptEnabled = false + allowFileAccess = false + allowContentAccess = false + domStorageEnabled = false + setSupportZoom(false) + builtInZoomControls = false + mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW + textZoom = (resources.configuration.fontScale * 100).roundToInt() + } + view.isVerticalScrollBarEnabled = false + view.webViewClient = object : WebViewClient() { + override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { + openOnSite(request.url.toString()) + return true + } + + override fun onPageFinished(view: WebView, url: String?) { + val scroll = pendingScroll + pendingScroll = -1 + if (scroll > 0) view.scrollTo(0, scroll) + } + } + addView(view, 0, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) + web = view + return view + } + + private var pendingScroll = -1 + + private fun show(post: RssReader.Item, readable: ArticleStore.Readable, loadingMore: Boolean, keepScroll: Boolean = false) { + val view = webView() + pendingScroll = if (keepScroll) view.scrollY else -1 + val note = when { + loadingMore -> resources.getString(R.string.flexera_rss_loading_article) + !readable.whole -> resources.getString(R.string.flexera_rss_article_partial) + else -> null + } + val base = post.article.link.ifEmpty { post.article.feedUrl } + view.loadDataWithBaseURL(base, document(post, readable.html, note), "text/html", "utf-8", null) + } + + /** Before anything is read: the summary, which is always there. */ + private fun placeholderHtml(post: RssReader.Item): String = + post.article.summary.takeIf { it.isNotEmpty() }?.let { "

    ${TextUtils.htmlEncode(it)}

    " }.orEmpty() + + /** The page the view shows: the post's picture, title and details, then its text. */ + private fun document(post: RssReader.Item, body: String, note: String?): String { + val article = post.article + val top = (insets.top / density).roundToInt() + 64 + val bottom = (insets.bottom / density).roundToInt() + 112 + val hero = article.imageUrl?.replaceFirst("http://", "https://") + val date = DateUtils.formatDateTime( + launcher, + article.published, + DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_ABBREV_MONTH, + ) + val details = listOfNotNull(post.source, date, article.author).joinToString(" · ") { TextUtils.htmlEncode(it) } + val icon = post.iconUrl?.let { """""" }.orEmpty() + return """ + + + +${hero?.let { """""" }.orEmpty()} +

    ${TextUtils.htmlEncode(article.title)}

    +
    $icon$details
    +
    $body
    +${note?.let { """

    ${TextUtils.htmlEncode(it)}

    """ }.orEmpty()} +""" + } + + private fun openOnSite(link: String) { + if (link.isEmpty()) return + val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + try { + launcher.startActivity(intent) + } catch (e: ActivityNotFoundException) { + Toast.makeText(launcher, R.string.flexera_rss_no_app, Toast.LENGTH_SHORT).show() + } + } + + // A swipe towards the side the article came from takes it away, as Back does. + + override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { + track(ev) + when (ev.actionMasked) { + MotionEvent.ACTION_DOWN -> { + downX = ev.x + downY = ev.y + dragging = false + } + MotionEvent.ACTION_MOVE -> if (startsDrag(ev)) return true + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> stopTracking() + } + return false + } + + override fun onTouchEvent(ev: MotionEvent): Boolean { + track(ev) + when (ev.actionMasked) { + MotionEvent.ACTION_MOVE -> { + if (!dragging) startsDrag(ev) + if (dragging) translationX = side * max(0f, side * (ev.rawX - dragFrom)) + } + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { + if (dragging) { + dragging = false + val velocity = tracker?.let { + it.computeCurrentVelocity(1000) + it.xVelocity * side + } ?: 0f + val flick = FLICK_DP_PER_SECOND * density + val away = ev.actionMasked == MotionEvent.ACTION_UP && when { + velocity >= flick -> true + velocity <= -flick -> false + else -> abs(translationX) > width * CLOSE_DISTANCE + } + if (away) close(animate = true) else slideTo(0f, from = translationX) + } + stopTracking() + } + } + return true + } + + private fun startsDrag(ev: MotionEvent): Boolean { + if (!isOpen || animator != null) return false + val dx = (ev.x - downX) * side + val dy = ev.y - downY + if (dx > touchSlop && dx > abs(dy) * 1.5f) { + dragging = true + dragFrom = ev.rawX - translationX + parent?.requestDisallowInterceptTouchEvent(true) + return true + } + return false + } + + private fun track(ev: MotionEvent) { + if (ev.actionMasked == MotionEvent.ACTION_DOWN) stopTracking() + // Raw positions: the view itself moves under the finger. + val raw = MotionEvent.obtain(ev).apply { setLocation(ev.rawX, ev.rawY) } + (tracker ?: VelocityTracker.obtain().also { tracker = it }).addMovement(raw) + raw.recycle() + } + + private fun stopTracking() { + tracker?.recycle() + tracker = null + } + + private fun dp(value: Int): Int = (value * density + 0.5f).toInt() +} diff --git a/flexera/src/app/flexera/reader/ReaderDrawables.kt b/flexera/src/app/flexera/reader/ReaderDrawables.kt new file mode 100644 index 0000000000..98cd77f02d --- /dev/null +++ b/flexera/src/app/flexera/reader/ReaderDrawables.kt @@ -0,0 +1,70 @@ +package app.flexera.reader + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.ColorFilter +import android.graphics.Paint +import android.graphics.PixelFormat +import android.graphics.Typeface +import android.graphics.drawable.Drawable +import android.widget.ImageView +import java.util.Locale + +/** A picture as wide as it is laid out, and [ratio] times less high. */ +internal class RatioImageView(context: Context, private val ratio: Float) : ImageView(context) { + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + val width = MeasureSpec.getSize(widthMeasureSpec) + super.onMeasure( + MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec((width / ratio).toInt(), MeasureSpec.EXACTLY), + ) + } +} + +/** + * A feed's first letter on a round patch of colour, for a feed whose site has no icon, and + * while the icon loads. The colour comes from the name, so a feed always has the same one. + */ +internal class LetterDrawable(name: String) : Drawable() { + + private companion object { + /** Muted colours that white reads well on, over the reader's dark backdrop. */ + val COLORS = intArrayOf( + 0xFF5C6BC0.toInt(), 0xFF26A69A.toInt(), 0xFFEF6C00.toInt(), 0xFF8E24AA.toInt(), + 0xFF43A047.toInt(), 0xFFD81B60.toInt(), 0xFF1E88E5.toInt(), 0xFF6D4C41.toInt(), + ) + } + + private val letter = name.trim().firstOrNull { it.isLetterOrDigit() }?.toString()?.uppercase(Locale.getDefault()) ?: "•" + private val circle = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = COLORS[Math.floorMod(name.hashCode(), COLORS.size)] + } + private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.WHITE + textAlign = Paint.Align.CENTER + typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) + } + + override fun draw(canvas: Canvas) { + val b = bounds + val radius = minOf(b.width(), b.height()) / 2f + canvas.drawCircle(b.exactCenterX(), b.exactCenterY(), radius, circle) + text.textSize = radius * 1.1f + val y = b.exactCenterY() - (text.descent() + text.ascent()) / 2 + canvas.drawText(letter, b.exactCenterX(), y, text) + } + + override fun setAlpha(alpha: Int) { + circle.alpha = alpha + text.alpha = alpha + } + + override fun setColorFilter(colorFilter: ColorFilter?) { + circle.colorFilter = colorFilter + text.colorFilter = colorFilter + } + + @Deprecated("Deprecated in Java") + override fun getOpacity(): Int = PixelFormat.TRANSLUCENT +} diff --git a/flexera/src/app/flexera/reader/ReaderPage.kt b/flexera/src/app/flexera/reader/ReaderPage.kt index a71c78f7c2..c4c30086ff 100644 --- a/flexera/src/app/flexera/reader/ReaderPage.kt +++ b/flexera/src/app/flexera/reader/ReaderPage.kt @@ -121,6 +121,9 @@ class ReaderPage private constructor(private val launcher: Launcher) : QuickLaun private var animator: ValueAnimator? = null private var sentinel: Sentinel? = null private var backFrom = 1f + + /** Whether the back gesture under way takes away an open post rather than the page. */ + private var backOnArticle = false private val shift = Matrix() private val view = PageView(launcher) private val content = ReaderView(launcher) @@ -269,18 +272,40 @@ class ReaderPage private constructor(private val launcher: Launcher) : QuickLaun } private fun onBackStarted() { + backOnArticle = content.isArticleOpen + if (backOnArticle) { + content.onArticleBackStarted() + return + } cancelAnimation() backFrom = progress } private fun onBackProgressed(backProgress: Float) { + if (backOnArticle) { + content.onArticleBackProgressed(backProgress) + return + } show(backFrom - BACK_PEEK * backProgress) } private fun onBackCancelled() { + if (backOnArticle) { + backOnArticle = false + content.onArticleBackCancelled() + return + } if (target == 1f) settleTo(open = true, speed = 0f) } + /** Back: an open post goes first, then the page. True when it was a post. */ + private fun onBackInvoked(): Boolean { + backOnArticle = false + if (!content.isArticleOpen) return false + content.closeArticle(animate = true) + return true + } + private fun apply() { val p = progress view.visibility = if (p > 0f) View.VISIBLE else View.INVISIBLE @@ -326,6 +351,9 @@ class ReaderPage private constructor(private val launcher: Launcher) : QuickLaun private var downY = 0f private var dragFrom = 0f private var dragging = false + + /** A sideways move away from the home screen: kept from the posts, and does nothing. */ + private var swallowing = false private var tracker: VelocityTracker? = null init { @@ -377,6 +405,7 @@ class ReaderPage private constructor(private val launcher: Launcher) : QuickLaun downX = ev.x downY = ev.y dragging = false + swallowing = false } MotionEvent.ACTION_MOVE -> if (startsDrag(ev)) return true MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> stopTracking() @@ -392,9 +421,10 @@ class ReaderPage private constructor(private val launcher: Launcher) : QuickLaun downX = ev.x downY = ev.y dragging = false + swallowing = false } MotionEvent.ACTION_MOVE -> { - if (!dragging) startsDrag(ev) + if (!dragging && !swallowing) startsDrag(ev) if (dragging) { val back = if (fromLeft) dragFrom - ev.x else ev.x - dragFrom show(1f - max(0f, back) / max(1, width)) @@ -421,9 +451,12 @@ class ReaderPage private constructor(private val launcher: Launcher) : QuickLaun return true } - /** A sideways move towards the home screen, while the page is in, takes the page out. */ + /** + * A sideways move towards the home screen, while the page is in, takes the page out. + * Not while a post is open over the list: the post has a swipe of its own. + */ private fun startsDrag(ev: MotionEvent): Boolean { - if (target != 1f) return false + if (target != 1f || content.isArticleOpen) return false val dx = ev.x - downX val dy = ev.y - downY val back = if (fromLeft) -dx else dx @@ -434,6 +467,11 @@ class ReaderPage private constructor(private val launcher: Launcher) : QuickLaun parent?.requestDisallowInterceptTouchEvent(true) return true } + // The other way, a sideways swipe would end as a tap on the post under it. + if (-back > touchSlop && -back > abs(dy) * 1.5f) { + swallowing = true + return true + } return false } @@ -480,5 +518,9 @@ class ReaderPage private constructor(private val launcher: Launcher) : QuickLaun override fun onBackCancelled() { page.onBackCancelled() } + + override fun onBackInvoked() { + if (!page.onBackInvoked()) super.onBackInvoked() + } } } diff --git a/flexera/src/app/flexera/reader/ReaderView.kt b/flexera/src/app/flexera/reader/ReaderView.kt index 25ce3ea5b0..ac4e1dda7c 100644 --- a/flexera/src/app/flexera/reader/ReaderView.kt +++ b/flexera/src/app/flexera/reader/ReaderView.kt @@ -2,7 +2,6 @@ package app.flexera.reader import android.animation.ObjectAnimator import android.animation.ValueAnimator -import android.app.ActivityOptions import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent @@ -11,11 +10,12 @@ import android.content.res.ColorStateList import android.graphics.Color import android.graphics.Outline import android.graphics.Rect +import android.graphics.RenderEffect +import android.graphics.Shader import android.graphics.Typeface import android.graphics.drawable.ColorDrawable import android.graphics.drawable.GradientDrawable import android.graphics.drawable.RippleDrawable -import android.net.Uri import android.os.Build import android.text.TextUtils import android.text.format.DateUtils @@ -57,10 +57,9 @@ import kotlinx.coroutines.launch /** * What the RSS reader's page shows ([ReaderPage]): a heading that scrolls away with the list, * with refresh and the feeds' settings beside it, and every feed's posts together, the newest - * first. A post is a line naming its feed and its age, its title, two lines of its text and a - * picture beside them when it has one. A tap opens it in the browser, and it is shown dimmed - * from then on; a long press shares its link. Pulling the list down at the top fetches the - * feeds anew. + * first, each on a card ([PostHolder]). A tap opens the post in the reader itself + * ([ArticleView]), and it is shown dimmed from then on; the share button or a long press shares + * its link. Pulling the list down at the top fetches the feeds anew. */ internal class ReaderView(private val launcher: Launcher) : FrameLayout(launcher), Insettable { @@ -69,8 +68,15 @@ internal class ReaderView(private val launcher: Launcher) : FrameLayout(launcher const val REFRESH_PULL = 0.12f const val SIDE_DP = 20 - const val PICTURE_DP = 76 - const val PICTURE_CORNER_DP = 14 + const val CARD_SIDE_DP = 12 + const val CARD_CORNER_DP = 24 + const val ICON_DP = 20 + + /** A card's picture is this many times as wide as it is high. */ + const val PICTURE_RATIO = 16f / 9f + + /** A card: a little lighter than the backdrop it lies on. */ + const val CARD = 0x1FFFFFFF const val PRIMARY = Color.WHITE const val SECONDARY = 0x99FFFFFF.toInt() @@ -121,6 +127,27 @@ internal class ReaderView(private val launcher: Launcher) : FrameLayout(launcher private val list = RecyclerView(launcher) private val shade = View(launcher) private val adapter = Adapter() + private val article = ArticleView(launcher, onShare = { sharePost(it) }, onCover = ::coverList) + + /** How far the list is blurred behind an open post: as strong as behind the app drawer. */ + private val maxListBlur = 40f * resources.displayMetrics.density + + /** + * The list beneath a post that slides in blurs and dims the more of it the post covers, and + * is not drawn at all once covered: the post's text is read on its own. + */ + private fun coverList(cover: Float) { + val hidden = cover >= 1f + list.visibility = if (hidden) View.INVISIBLE else View.VISIBLE + shade.visibility = list.visibility + list.alpha = 1f - 0.5f * cover + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + val radius = maxListBlur * cover + list.setRenderEffect( + if (radius < 1f || hidden) null else RenderEffect.createBlurEffect(radius, radius, Shader.TileMode.CLAMP), + ) + } + } private var scope: CoroutineScope? = null private var state = RssReader.State() private var topInset = 0 @@ -138,13 +165,27 @@ internal class ReaderView(private val launcher: Launcher) : FrameLayout(launcher shade.background = GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, intArrayOf(TOP_SHADE, Color.TRANSPARENT)) shade.importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO addView(shade, LayoutParams(LayoutParams.MATCH_PARENT, 0)) + addView(article, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) } + /** Whether a post is open over the list. */ + val isArticleOpen: Boolean get() = article.isOpen + + /** Back while a post is open takes the post away, with Android's back preview. */ + fun onArticleBackStarted() = article.onBackStarted() + + fun onArticleBackProgressed(progress: Float) = article.onBackProgressed(progress) + + fun onArticleBackCancelled() = article.onBackCancelled() + + fun closeArticle(animate: Boolean) = article.close(animate) + override fun setInsets(insets: Rect) { topInset = insets.top list.setPadding(insets.left, 0, insets.right, insets.bottom + dp(24)) shade.layoutParams = (shade.layoutParams as LayoutParams).apply { height = insets.top + dp(12) } adapter.notifyItemChanged(0) + article.setInsets(insets) } override fun onAttachedToWindow() { @@ -166,8 +207,8 @@ internal class ReaderView(private val launcher: Launcher) : FrameLayout(launcher adapter.notifyItemRangeChanged(0, adapter.itemCount) } - /** The page is out. */ - fun onClosed() = Unit + /** The page is out; so is any post that was open. */ + fun onClosed() = article.close(animate = false) private fun bind(newState: RssReader.State) { state = newState @@ -215,17 +256,9 @@ internal class ReaderView(private val launcher: Launcher) : FrameLayout(launcher return DateUtils.getRelativeTimeSpanString(millis, now, DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE).toString() } - private fun openPost(row: View, item: RssReader.Item) { - val link = item.article.link - if (link.isEmpty()) return + private fun openPost(item: RssReader.Item) { RssReader.markRead(launcher, item.article) - val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - try { - val options = ActivityOptions.makeScaleUpAnimation(row, 0, 0, row.width, row.height) - launcher.startActivity(intent, options.toBundle()) - } catch (e: ActivityNotFoundException) { - Toast.makeText(launcher, R.string.flexera_rss_no_app, Toast.LENGTH_SHORT).show() - } + article.open(item) } private fun sharePost(item: RssReader.Item) { @@ -433,50 +466,87 @@ internal class ReaderView(private val launcher: Launcher) : FrameLayout(launcher } } - private inner class PostHolder : RecyclerView.ViewHolder(LinearLayout(context)) { - private val root = itemView as LinearLayout - private val meta = text(13f, SECONDARY) - private val title = text(17f, PRIMARY, bold = true) + /** + * A post as a card, as in the feeds of the phone makers' launchers: its picture across the + * top, its title under it, then the feed's icon, name and the post's age, and a share + * button. A post without a picture shows three lines of its text instead. + */ + private inner class PostHolder : RecyclerView.ViewHolder(FrameLayout(context)) { + private val card = LinearLayout(context) + private val picture = RatioImageView(context, PICTURE_RATIO) + private val title = text(18f, PRIMARY, bold = true) private val summary = text(14f, SECONDARY) - private val picture = ImageView(context) + private val icon = ImageView(context) + private val meta = text(13f, SECONDARY) + private val share = ImageView(context) private var item: RssReader.Item? = null init { - root.orientation = LinearLayout.HORIZONTAL - root.layoutParams = RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT) - root.setPadding(dp(SIDE_DP), dp(14), dp(SIDE_DP), dp(14)) - root.background = RippleDrawable(ColorStateList.valueOf(PRESSED), null, ColorDrawable(Color.WHITE)) - val words = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL } - meta.isSingleLine = true - meta.ellipsize = TextUtils.TruncateAt.END + val frame = itemView as FrameLayout + frame.layoutParams = RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT) + frame.setPadding(dp(CARD_SIDE_DP), dp(6), dp(CARD_SIDE_DP), dp(6)) + + card.orientation = LinearLayout.VERTICAL + val cardShape = GradientDrawable().apply { + cornerRadius = dp(CARD_CORNER_DP).toFloat() + setColor(CARD) + } + card.background = RippleDrawable(ColorStateList.valueOf(PRESSED), cardShape, null) + card.outlineProvider = object : ViewOutlineProvider() { + override fun getOutline(view: View, outline: Outline) { + outline.setRoundRect(0, 0, view.width, view.height, dp(CARD_CORNER_DP).toFloat()) + } + } + card.clipToOutline = true + frame.addView(card, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)) + + picture.scaleType = ImageView.ScaleType.CENTER_CROP + picture.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO + card.addView(picture, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)) + title.maxLines = 3 title.ellipsize = TextUtils.TruncateAt.END title.setLineSpacing(0f, 1.15f) - summary.maxLines = 2 + card.addView(title, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply { + setMargins(dp(18), dp(16), dp(18), 0) + }) + summary.maxLines = 3 summary.ellipsize = TextUtils.TruncateAt.END - summary.setLineSpacing(0f, 1.15f) - words.addView(meta) - words.addView(title, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply { - topMargin = dp(6) + summary.setLineSpacing(0f, 1.2f) + card.addView(summary, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply { + setMargins(dp(18), dp(8), dp(18), 0) }) - words.addView(summary, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply { - topMargin = dp(6) - }) - root.addView(words, LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)) - picture.scaleType = ImageView.ScaleType.CENTER_CROP - picture.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO - picture.outlineProvider = object : ViewOutlineProvider() { - override fun getOutline(view: View, outline: Outline) { - outline.setRoundRect(0, 0, view.width, view.height, dp(PICTURE_CORNER_DP).toFloat()) - } + + val footer = LinearLayout(context).apply { + orientation = LinearLayout.HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + setPaddingRelative(dp(18), dp(4), dp(6), dp(6)) } - picture.clipToOutline = true - root.addView(picture, LinearLayout.LayoutParams(dp(PICTURE_DP), dp(PICTURE_DP)).apply { - marginStart = dp(16) - topMargin = dp(2) + icon.scaleType = ImageView.ScaleType.CENTER_CROP + icon.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO + icon.outlineProvider = ViewOutlineProvider.BACKGROUND + icon.background = GradientDrawable().apply { + shape = GradientDrawable.OVAL + setColor(0x1AFFFFFF) + } + icon.clipToOutline = true + footer.addView(icon, LinearLayout.LayoutParams(dp(ICON_DP), dp(ICON_DP)).apply { marginEnd = dp(10) }) + meta.isSingleLine = true + meta.ellipsize = TextUtils.TruncateAt.END + footer.addView(meta, LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)) + share.setImageResource(R.drawable.ic_flexera_share) + share.imageAlpha = 0xB3 + share.scaleType = ImageView.ScaleType.CENTER + share.contentDescription = resources.getString(R.string.flexera_rss_share) + share.background = RippleDrawable(ColorStateList.valueOf(PRESSED), null, ColorDrawable(Color.WHITE)).apply { radius = dp(22) } + share.setOnClickListener { item?.let { sharePost(it) } } + footer.addView(share, LinearLayout.LayoutParams(dp(44), dp(44))) + card.addView(footer, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply { + topMargin = dp(6) }) - root.setOnClickListener { item?.let { openPost(root, it) } } - root.setOnLongClickListener { + + card.setOnClickListener { item?.let { openPost(it) } } + card.setOnLongClickListener { val post = item ?: return@setOnLongClickListener false it.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) sharePost(post) @@ -487,14 +557,12 @@ internal class ReaderView(private val launcher: Launcher) : FrameLayout(launcher fun bind(post: RssReader.Item) { item = post val article = post.article - meta.text = "${post.source} · ${age(article.published)}" + meta.text = "${post.source} · ${shortAge(article.published)}" title.text = article.title - summary.text = article.summary - summary.visibility = if (article.summary.isEmpty()) View.GONE else View.VISIBLE title.setTextColor(if (post.read) READ_PRIMARY else PRIMARY) - summary.setTextColor(if (post.read) READ_SECONDARY else SECONDARY) meta.setTextColor(if (post.read) READ_SECONDARY else SECONDARY) - root.contentDescription = listOf(article.title, post.source, age(article.published)).joinToString(", ") + summary.setTextColor(if (post.read) READ_SECONDARY else SECONDARY) + card.contentDescription = listOf(article.title, post.source, age(article.published)).joinToString(", ") val url = article.imageUrl if (url == null) { @@ -503,15 +571,49 @@ internal class ReaderView(private val launcher: Launcher) : FrameLayout(launcher picture.visibility = View.GONE } else { picture.visibility = View.VISIBLE - val request = ImageRequest.Builder(context) - .data(url) - .size(dp(PICTURE_DP)) - .placeholder(ColorDrawable(0x14FFFFFF)) - .target(picture) - .listener(onError = { _, _ -> if (item === post) picture.visibility = View.GONE }) - .build() - images(context).enqueue(request) + images(context).enqueue( + ImageRequest.Builder(context) + .data(url) + .placeholder(ColorDrawable(0x14FFFFFF)) + .target(picture) + .listener(onError = { _, _ -> if (item === post) picture.visibility = View.GONE }) + .build(), + ) } + // Without a picture, the start of the text fills the card instead. + summary.text = article.summary + summary.visibility = if (url == null && article.summary.isNotEmpty()) View.VISIBLE else View.GONE + + val letter = LetterDrawable(post.source) + val iconUrl = post.iconUrl + if (iconUrl == null) { + CoilUtils.dispose(icon) + icon.setImageDrawable(letter) + } else { + images(context).enqueue( + ImageRequest.Builder(context) + .data(iconUrl) + .size(dp(ICON_DP) * 2) + .crossfade(false) + .placeholder(letter) + .error(letter) + .target(icon) + .build(), + ) + } + } + } + + /** The age of a post in the fewest letters: "now", "5m", "3h", "2d", then its date. */ + private fun shortAge(millis: Long): String { + val res = resources + val ago = System.currentTimeMillis() - millis + return when { + ago < DateUtils.MINUTE_IN_MILLIS -> res.getString(R.string.flexera_rss_age_now) + ago < DateUtils.HOUR_IN_MILLIS -> res.getString(R.string.flexera_rss_age_minutes, ago / DateUtils.MINUTE_IN_MILLIS) + ago < DateUtils.DAY_IN_MILLIS -> res.getString(R.string.flexera_rss_age_hours, ago / DateUtils.HOUR_IN_MILLIS) + ago < 7 * DateUtils.DAY_IN_MILLIS -> res.getString(R.string.flexera_rss_age_days, ago / DateUtils.DAY_IN_MILLIS) + else -> DateUtils.formatDateTime(context, millis, DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_ABBREV_MONTH) } } diff --git a/flexera/src/app/flexera/reader/RssFetcher.kt b/flexera/src/app/flexera/reader/RssFetcher.kt index 07727a2128..c4cf0a9e20 100644 --- a/flexera/src/app/flexera/reader/RssFetcher.kt +++ b/flexera/src/app/flexera/reader/RssFetcher.kt @@ -36,6 +36,8 @@ object RssFetcher { private const val ACCEPT = "application/rss+xml, application/atom+xml, application/rdf+xml, " + "application/xml;q=0.9, text/xml;q=0.9, text/html;q=0.5, */*;q=0.1" + private const val PAGE_ACCEPT = "text/html, application/xhtml+xml;q=0.9, */*;q=0.1" + /** Where sites without a feed link in their page often have their feed. */ private val USUAL_PLACES = listOf("/feed", "/rss", "/feed.xml", "/rss.xml", "/atom.xml", "/index.xml") @@ -151,7 +153,23 @@ object RssFetcher { return withScheme } - private fun get(context: Context, url: String, etag: String?, lastModified: String?): Answer { + /** A web page as fetched: where it ended up after redirects, and its bytes and type. */ + class Page(val url: String, val body: ByteArray, val contentType: String?) + + /** Fetches the web page at [url], an article's, for the article view. */ + fun fetchPage(context: Context, url: String): Page { + val answer = get(context, url, null, null, PAGE_ACCEPT) + val body = answer.body ?: throw FetchException(RssProblem.SERVER, "Empty answer") + return Page(answer.url, body, answer.contentType) + } + + private fun get( + context: Context, + url: String, + etag: String?, + lastModified: String?, + accept: String = ACCEPT, + ): Answer { var address = upgrade(url) for (hop in 0..MAX_REDIRECTS) { val connection = try { @@ -166,7 +184,7 @@ object RssFetcher { connection.connectTimeout = CONNECT_TIMEOUT_MS connection.readTimeout = READ_TIMEOUT_MS connection.setRequestProperty("User-Agent", USER_AGENT) - connection.setRequestProperty("Accept", ACCEPT) + connection.setRequestProperty("Accept", accept) if (hop == 0) { etag?.let { connection.setRequestProperty("If-None-Match", it) } lastModified?.let { connection.setRequestProperty("If-Modified-Since", it) } diff --git a/flexera/src/app/flexera/reader/RssModel.kt b/flexera/src/app/flexera/reader/RssModel.kt index ca08ff9920..a4a8a5684c 100644 --- a/flexera/src/app/flexera/reader/RssModel.kt +++ b/flexera/src/app/flexera/reader/RssModel.kt @@ -23,6 +23,7 @@ data class RssArticle( val imageUrl: String? = null, /** When it was published, in milliseconds; when the feed does not say, when first seen. */ val published: Long, + val author: String? = null, ) /** Why a feed could not be fetched, in terms the owner can act on. */ diff --git a/flexera/src/app/flexera/reader/RssParser.kt b/flexera/src/app/flexera/reader/RssParser.kt index 1fb4edb981..4d0be000d9 100644 --- a/flexera/src/app/flexera/reader/RssParser.kt +++ b/flexera/src/app/flexera/reader/RssParser.kt @@ -1,6 +1,7 @@ package app.flexera.reader import android.text.Html +import android.text.TextUtils import android.util.Xml import java.io.ByteArrayInputStream import java.net.URL @@ -23,7 +24,14 @@ import org.xmlpull.v1.XmlPullParser object RssParser { /** A feed as read, before the reader makes its articles of it. */ - class Feed(val title: String, val entries: List) + class Feed( + val title: String, + val entries: List, + /** The site's page, when the feed names it. */ + val siteLink: String? = null, + /** The feed's own small picture (Atom icon or logo, RSS channel image), if any. */ + val iconUrl: String? = null, + ) class Entry( val id: String?, @@ -33,6 +41,9 @@ object RssParser { val imageUrl: String?, /** Milliseconds, or null when the feed gives no date it could read. */ val date: Long?, + /** The post as HTML, as much of it as the feed carries; the article view shows it. */ + val contentHtml: String = "", + val author: String? = null, ) /** Raised when what was read is no feed; [html] when it is a web page instead. */ @@ -45,6 +56,9 @@ object RssParser { /** Longest summary kept, in characters; two lines need far fewer. */ private const val SUMMARY_LENGTH = 300 + /** Most of a post's HTML kept for the article view; a whole long article fits. */ + private const val MAX_CONTENT_LENGTH = 400_000 + /** How much of a post's HTML is looked at for its summary and its first picture. */ private const val HTML_LOOK_LENGTH = 20_000 @@ -111,6 +125,8 @@ object RssParser { var title: String? = null var siteLink: String? = null + var icon: String? = null + var logo: String? = null val entries = ArrayList() while (event != XmlPullParser.END_DOCUMENT) { if (event == XmlPullParser.START_TAG) { @@ -125,13 +141,24 @@ object RssParser { "link" -> if (siteLink == null && parser.depth <= 3) { siteLink = linkOf(parser)?.let { resolve(base, it) } } - // A channel's picture has a title and a link of its own. - "image" -> if (parser.namespace != ITUNES) skip(parser) + // A channel's picture, with a title and a link of its own besides its address. + "image" -> if (parser.namespace == ITUNES) { + if (logo == null) logo = parser.getAttributeValue(null, "href") + } else if (parser.depth <= 3) { + val url = imageUrlOf(parser) + if (icon == null) icon = url + } else { + skip(parser) + } + "icon" -> if (parser.namespace == ATOM && parser.depth == 2) icon = readInner(parser, null).trim() + "logo" -> if (parser.namespace == ATOM && parser.depth == 2) logo = readInner(parser, null).trim() } } event = parser.next() } - return Feed(title.orEmpty(), entries) + val picture = (icon?.takeIf { it.isNotEmpty() } ?: logo?.takeIf { it.isNotEmpty() }) + ?.let { resolve(siteLink ?: base, it) }?.takeIf { it.startsWith("http") } + return Feed(title.orEmpty(), entries, siteLink, picture) } /** @@ -148,6 +175,19 @@ object RssParser { return readInner(parser, null).trim().takeIf { it.isNotEmpty() } } + /** The address in an RSS channel's image element, which the parser is at; leaves it at its end. */ + private fun imageUrlOf(parser: XmlPullParser): String? { + val depth = parser.depth + var url: String? = null + while (true) { + when (parser.next()) { + XmlPullParser.START_TAG -> if (parser.name == "url" && url == null) url = readInner(parser, null).trim() + XmlPullParser.END_TAG -> if (parser.depth == depth) return url + XmlPullParser.END_DOCUMENT -> return url + } + } + } + private fun readEntry(parser: XmlPullParser, base: String): Entry? { val depth = parser.depth var id: String? = null @@ -162,6 +202,7 @@ object RssParser { var mediaImage: String? = null var enclosureImage: String? = null var itunesImage: String? = null + var author: String? = null val inlineImages = ArrayList() var event = parser.next() @@ -192,9 +233,12 @@ object RssParser { "date" -> if (published == null) published = readInner(parser, null) "updated", "modified" -> updated = readInner(parser, null) "description", "summary" -> if (ns != MEDIA && description == null) { - description = readInner(parser, inlineImages) + description = readBody(parser, inlineImages) } "encoded" -> if (content == null) content = readInner(parser, inlineImages) + // Dublin Core's creator in RSS; the name in an Atom author. + "creator" -> if (author == null) author = plain(readInner(parser, null)) + "name" -> if (ns == ATOM && author == null) author = plain(readInner(parser, null)) "content" -> when (ns) { MEDIA -> { val medium = parser.getAttributeValue(null, "medium") @@ -206,7 +250,7 @@ object RssParser { mediaImage = url } } - else -> if (content == null) content = readInner(parser, inlineImages) + else -> if (content == null) content = readBody(parser, inlineImages) } "thumbnail" -> if (ns == MEDIA && mediaThumbnail == null) { mediaThumbnail = parser.getAttributeValue(null, "url") @@ -231,9 +275,12 @@ object RssParser { val summary = plain(html).take(SUMMARY_LENGTH) val page = (link ?: guidLink)?.let { resolve(base, it) } if (cleanTitle.isEmpty() && page == null) return null - val picture = mediaThumbnail ?: mediaImage ?: enclosureImage ?: itunesImage + // The largest first: the reader shows it across a whole card. + val picture = mediaImage ?: enclosureImage ?: mediaThumbnail ?: itunesImage ?: inlineImages.firstOrNull() ?: firstImage(content.orEmpty()) ?: firstImage(description.orEmpty()) + // The longer of the two is the more of the post. + val body = listOfNotNull(content, description).maxByOrNull { it.length }.orEmpty() return Entry( id = id?.takeIf { it.isNotEmpty() } ?: page ?: cleanTitle, title = cleanTitle.ifEmpty { summary.take(80) }, @@ -241,6 +288,8 @@ object RssParser { summary = if (summary == cleanTitle) "" else summary, imageUrl = picture?.let { resolve(base, it.trim()) }?.takeIf { it.startsWith("http") }, date = parseDate(published) ?: parseDate(updated), + contentHtml = body.take(MAX_CONTENT_LENGTH), + author = author?.takeIf { it.isNotEmpty() }, ) } @@ -267,6 +316,36 @@ object RssParser { } } + /** + * A post's text as HTML: escaped HTML as it is, or an Atom post's XHTML written out again + * as markup, its pictures added to [images]. Leaves the parser at the element's end. + */ + private fun readBody(parser: XmlPullParser, images: MutableList): String { + if (parser.getAttributeValue(null, "type") != "xhtml") return readInner(parser, images) + val depth = parser.depth + val html = StringBuilder() + while (true) { + when (parser.next()) { + XmlPullParser.TEXT -> html.append(TextUtils.htmlEncode(parser.text)) + XmlPullParser.START_TAG -> { + val name = parser.name + if (name.equals("img", ignoreCase = true)) parser.getAttributeValue(null, "src")?.let(images::add) + html.append('<').append(name) + for (i in 0 until parser.attributeCount) { + html.append(' ').append(parser.getAttributeName(i)).append("=\"") + .append(TextUtils.htmlEncode(parser.getAttributeValue(i))).append('"') + } + html.append('>') + } + XmlPullParser.END_TAG -> { + if (parser.depth == depth) return html.toString() + html.append("') + } + XmlPullParser.END_DOCUMENT -> return html.toString() + } + } + } + private fun skip(parser: XmlPullParser) { val depth = parser.depth while (true) { diff --git a/flexera/src/app/flexera/reader/RssReader.kt b/flexera/src/app/flexera/reader/RssReader.kt index 783e932a2d..ca9cc0e8d1 100644 --- a/flexera/src/app/flexera/reader/RssReader.kt +++ b/flexera/src/app/flexera/reader/RssReader.kt @@ -49,8 +49,11 @@ object RssReader { private const val MAX_READ = 3000 private const val PARALLEL_FETCHES = 4 - /** A post as the page shows it: with its feed's name and whether it was opened. */ - data class Item(val article: RssArticle, val source: String, val read: Boolean) + /** + * A post as the page shows it: with its feed's name, the feed's small picture (or the site's + * own icon) and whether it was opened. + */ + data class Item(val article: RssArticle, val source: String, val read: Boolean, val iconUrl: String? = null) /** A feed that could not be fetched the last time it was tried. */ data class Failure(val feed: RssFeed, val problem: RssProblem) @@ -80,6 +83,8 @@ object RssReader { val articles: List = emptyList(), val etag: String? = null, val lastModified: String? = null, + val iconUrl: String? = null, + val siteUrl: String? = null, ) @Serializable @@ -182,12 +187,19 @@ object RssReader { list.firstOrNull { it.url == found.url }?.let { return@withContext AddResult.AlreadyThere(it) } val title = found.feed.title.ifBlank { runCatching { URL(found.url).host.removePrefix("www.") }.getOrDefault(found.url) } val feed = RssFeed(found.url, title) + keepTexts(context, feed.url, found.feed) // Not while holding the lock: the stored posts are read with it. mutableState.first { it.loaded } lock.withLock { stored = stored.copy( - feeds = stored.feeds.filter { it.url != feed.url } + - FeedCache(feed.url, articlesOf(feed.url, found.feed, emptyList()), found.etag, found.lastModified), + feeds = stored.feeds.filter { it.url != feed.url } + FeedCache( + url = feed.url, + articles = articlesOf(feed.url, found.feed, emptyList()), + etag = found.etag, + lastModified = found.lastModified, + iconUrl = found.feed.iconUrl, + siteUrl = found.feed.siteLink, + ), ) failures.remove(feed.url) save() @@ -244,6 +256,11 @@ object RssReader { } }.awaitAll() } + // The posts' text, for the article view; files, so not while holding the lock. + for ((feed, outcome) in results) { + (outcome.getOrNull() as? RssFetcher.Result.Fetched)?.let { keepTexts(app, feed.url, it.feed) } + } + if (only == null) ArticleStore.prune(app) lock.withLock { var all = stored.feeds for ((feed, outcome) in results) { @@ -256,8 +273,14 @@ object RssReader { if (result is RssFetcher.Result.Fetched) { val before = all.firstOrNull { it.url == feed.url } val articles = articlesOf(feed.url, result.feed, before?.articles.orEmpty()) - all = all.filter { it.url != feed.url } + - FeedCache(feed.url, articles, result.etag, result.lastModified) + all = all.filter { it.url != feed.url } + FeedCache( + url = feed.url, + articles = articles, + etag = result.etag, + lastModified = result.lastModified, + iconUrl = result.feed.iconUrl, + siteUrl = result.feed.siteLink, + ) } } stored = stored.copy( @@ -279,7 +302,7 @@ object RssReader { val earlier = before.associateBy { it.id } return feed.entries.asSequence() .map { entry -> - val id = "$feedUrl|${entry.id}" + val id = articleId(feedUrl, entry) RssArticle( id = id, feedUrl = feedUrl, @@ -288,6 +311,7 @@ object RssReader { summary = entry.summary, imageUrl = entry.imageUrl, published = entry.date ?: earlier[id]?.published ?: now, + author = entry.author, ) } .distinctBy { it.id } @@ -296,13 +320,35 @@ object RssReader { .toList() } + private fun articleId(feedUrl: String, entry: RssParser.Entry) = "$feedUrl|${entry.id}" + + /** Keeps what [feed] carries of each post, for the article view. For a background thread. */ + private fun keepTexts(context: Context, feedUrl: String, feed: RssParser.Feed) { + for (entry in feed.entries.take(MAX_PER_FEED * 2)) { + ArticleStore.saveFeedText(context, articleId(feedUrl, entry), entry.contentHtml) + } + } + + /** + * The small picture beside a feed's posts: the feed's own, or else the site's icon, where + * sites keep it. + */ + private fun iconOf(cache: FeedCache): String? { + cache.iconUrl?.let { return it } + val page = cache.siteUrl ?: cache.articles.firstOrNull { it.link.isNotEmpty() }?.link ?: cache.url + return runCatching { URL(page).let { "https://${it.host}/favicon.ico" } }.getOrNull() + } + /** Puts what is stored before the page. Called with [lock] held. */ private fun publish(refreshing: Boolean = mutableState.value.refreshing) { val names = feeds.associate { it.url to it.title } val read = stored.read.toHashSet() val items = stored.feeds.asSequence() .filter { it.url in names } - .flatMap { cache -> cache.articles.asSequence().map { Item(it, names.getValue(cache.url), it.id in read) } } + .flatMap { cache -> + val icon = iconOf(cache) + cache.articles.asSequence().map { Item(it, names.getValue(cache.url), it.id in read, icon) } + } .sortedByDescending { it.article.published } .take(MAX_ARTICLES) .toList() diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index cde6033d53..c7bb2cd4b9 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -130,6 +130,8 @@ hoko-blur = "io.github.hokofly:hoko-blur:1.5.5" javax-inject = "javax.inject:javax.inject:1" # Flexera Launcher: QR code on the About screen (app.flexera.ui.FlexeraAbout). zxing-core = "com.google.zxing:core:3.5.3" +# Flexera Launcher: reads web pages for the RSS reader's article view (app.flexera.reader.ArticleStore). +jsoup = "org.jsoup:jsoup:1.23.2" kdrag0n-colorkt = "dev.kdrag0n:colorkt:1.0.5" leakcanary-android = "com.squareup.leakcanary:leakcanary-android:2.14" leakcanary-androidstudio = "com.android.tools.studio.leakcanary:leakcanary:1.0.0"