${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").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${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 { """${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