FairEmail/app/src/main/java/eu/faircode/email/HtmlHelper.java

984 lines
37 KiB
Java
Raw Normal View History

2018-08-02 13:33:06 +00:00
package eu.faircode.email;
/*
2018-08-14 05:53:24 +00:00
This file is part of FairEmail.
2018-08-02 13:33:06 +00:00
2018-08-14 05:53:24 +00:00
FairEmail is free software: you can redistribute it and/or modify
2018-08-02 13:33:06 +00:00
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2018-10-29 10:46:49 +00:00
FairEmail is distributed in the hope that it will be useful,
2018-08-02 13:33:06 +00:00
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
2018-10-29 10:46:49 +00:00
along with FairEmail. If not, see <http://www.gnu.org/licenses/>.
2018-08-02 13:33:06 +00:00
2018-12-31 08:04:33 +00:00
Copyright 2018-2019 by Marcel Bokhorst (M66B)
2018-08-02 13:33:06 +00:00
*/
2018-12-14 09:11:45 +00:00
import android.content.Context;
import android.content.SharedPreferences;
2019-04-30 08:33:03 +00:00
import android.content.res.Resources;
2018-12-14 09:11:45 +00:00
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
2019-09-07 18:13:58 +00:00
import android.graphics.ImageDecoder;
2019-07-15 10:17:01 +00:00
import android.graphics.Rect;
2018-12-14 09:11:45 +00:00
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
2019-04-30 08:33:03 +00:00
import android.graphics.drawable.LevelListDrawable;
2019-09-13 11:46:52 +00:00
import android.net.Uri;
2019-09-07 18:13:58 +00:00
import android.os.Build;
2019-04-30 08:33:03 +00:00
import android.os.Handler;
2019-02-10 12:01:21 +00:00
import android.text.Html;
2019-08-29 19:57:04 +00:00
import android.text.SpannableStringBuilder;
2019-02-10 12:01:21 +00:00
import android.text.Spanned;
2018-12-14 09:11:45 +00:00
import android.text.TextUtils;
2019-08-29 19:57:04 +00:00
import android.text.style.ForegroundColorSpan;
2018-12-14 09:11:45 +00:00
import android.util.Base64;
2019-07-15 10:17:01 +00:00
import android.util.DisplayMetrics;
import android.view.View;
2019-04-30 08:33:03 +00:00
import android.widget.TextView;
2018-12-14 09:11:45 +00:00
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.text.HtmlCompat;
import androidx.core.util.PatternsCompat;
import androidx.preference.PreferenceManager;
2018-08-02 13:33:06 +00:00
import org.jsoup.Jsoup;
2019-03-10 19:39:17 +00:00
import org.jsoup.nodes.Attribute;
2018-08-02 13:33:06 +00:00
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
2018-08-02 13:33:06 +00:00
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
2019-03-12 09:04:16 +00:00
import org.jsoup.safety.Cleaner;
2018-08-28 12:52:33 +00:00
import org.jsoup.safety.Whitelist;
2018-08-02 13:33:06 +00:00
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;
2018-12-14 09:11:45 +00:00
import java.io.File;
2019-04-06 09:05:33 +00:00
import java.io.FileInputStream;
2019-01-27 12:01:41 +00:00
import java.io.FileNotFoundException;
2018-12-14 09:11:45 +00:00
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
2019-01-16 13:42:17 +00:00
import java.io.OutputStream;
2018-12-14 09:11:45 +00:00
import java.net.URL;
2019-09-13 11:46:52 +00:00
import java.util.ArrayList;
2019-01-05 11:17:33 +00:00
import java.util.Arrays;
2019-03-14 19:33:01 +00:00
import java.util.Collections;
2019-01-05 11:17:33 +00:00
import java.util.List;
2019-09-23 20:07:22 +00:00
import java.util.Locale;
2019-04-30 08:33:03 +00:00
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
2019-06-05 08:23:41 +00:00
import java.util.regex.Pattern;
2018-08-02 13:33:06 +00:00
import static androidx.core.text.HtmlCompat.FROM_HTML_SEPARATOR_LINE_BREAK_LIST_ITEM;
2019-02-10 12:01:21 +00:00
import static androidx.core.text.HtmlCompat.TO_HTML_PARAGRAPH_LINES_CONSECUTIVE;
public class HtmlHelper {
2019-08-20 18:05:11 +00:00
static final int PREVIEW_SIZE = 250; // characters
2019-09-01 07:44:03 +00:00
private static final int MAX_AUTO_LINK = 250;
2019-08-20 18:05:11 +00:00
private static final int TRACKING_PIXEL_SURFACE = 25; // pixels
2019-05-13 09:03:15 +00:00
2019-03-14 19:33:01 +00:00
private static final List<String> heads = Collections.unmodifiableList(Arrays.asList(
"h1", "h2", "h3", "h4", "h5", "h6", "p", "ol", "ul", "table", "br", "hr"));
private static final List<String> tails = Collections.unmodifiableList(Arrays.asList(
"h1", "h2", "h3", "h4", "h5", "h6", "p", "ol", "ul", "li"));
2018-08-02 13:33:06 +00:00
2019-07-24 06:42:37 +00:00
private static final ExecutorService executor =
Executors.newSingleThreadExecutor(Helper.backgroundThreadFactory);
2019-04-30 08:33:03 +00:00
2019-09-23 18:13:38 +00:00
static String sanitize(Context context, String html, boolean text_color, boolean show_images) {
2019-03-12 09:04:16 +00:00
Document parsed = Jsoup.parse(html);
2019-05-13 09:03:15 +00:00
// <html xmlns:v="urn:schemas-microsoft-com:vml"
// xmlns:o="urn:schemas-microsoft-com:office:office"
// xmlns:w="urn:schemas-microsoft-com:office:word"
// xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"
// xmlns="http://www.w3.org/TR/REC-html40">
// <o:p>&nbsp;</o:p></span>
// Default XHTML namespace: http://www.w3.org/1999/xhtml
String ns = null;
for (Element h : parsed.select("html"))
for (Attribute a : h.attributes()) {
2019-05-15 09:18:14 +00:00
String key = a.getKey();
String value = a.getValue();
if (value != null &&
key.startsWith("xmlns:") &&
value.startsWith("http://www.w3.org/")) {
ns = key.split(":")[1];
2019-05-13 09:03:15 +00:00
break;
}
}
2019-05-15 09:18:14 +00:00
for (Element e : parsed.select("*")) {
String tag = e.tagName();
if (tag.contains(":")) {
if (ns != null && tag.startsWith(ns)) {
2019-05-13 09:03:15 +00:00
e.tagName(tag.split(":")[1]);
Log.i("Updated tag=" + tag + " to=" + e.tagName());
} else {
e.remove();
Log.i("Removed tag=" + tag);
}
}
2019-05-15 09:18:14 +00:00
}
2019-05-13 09:03:15 +00:00
2019-03-12 09:04:16 +00:00
Whitelist whitelist = Whitelist.relaxed()
2019-09-12 08:45:54 +00:00
.addTags("hr", "abbr", "big")
2019-03-10 15:21:46 +00:00
.removeTags("col", "colgroup", "thead", "tbody")
2019-03-12 09:04:16 +00:00
.removeAttributes("table", "width")
.removeAttributes("td", "colspan", "rowspan", "width")
.removeAttributes("th", "colspan", "rowspan", "width")
2018-12-14 09:05:48 +00:00
.addProtocols("img", "src", "cid")
2019-03-12 09:04:16 +00:00
.addProtocols("img", "src", "data");
2019-09-23 18:13:38 +00:00
if (text_color)
2019-09-24 11:31:27 +00:00
whitelist.addAttributes(":all", "style");
2019-09-23 18:13:38 +00:00
2019-03-12 09:04:16 +00:00
final Document document = new Cleaner(whitelist).clean(parsed);
2018-11-24 11:27:44 +00:00
2019-09-23 17:51:17 +00:00
// Sanitize span styles
2019-09-24 11:31:27 +00:00
for (Element span : document.select("*")) {
2019-09-23 17:51:17 +00:00
String style = span.attr("style");
if (!TextUtils.isEmpty(style)) {
StringBuilder sb = new StringBuilder();
String[] params = style.split(";");
for (String param : params) {
String[] kv = param.split(":");
if (kv.length == 2)
2019-09-23 20:07:22 +00:00
switch (kv[0].trim().toLowerCase(Locale.ROOT)) {
2019-09-23 17:51:17 +00:00
case "color":
sb.append(param).append(";");
break;
2019-09-23 20:07:22 +00:00
case "background":
case "background-color":
break;
2019-09-23 17:51:17 +00:00
}
}
span.attr("style", sb.toString());
}
}
2019-09-12 08:45:54 +00:00
// Remove new lines without surrounding content
for (Element br : document.select("br"))
2019-09-12 16:53:57 +00:00
if (br.parent() != null && !hasVisibleContent(br.parent().childNodes()))
2019-09-12 08:45:54 +00:00
br.tagName("span");
// Paragraphs
for (Element p : document.select("p"))
p.tagName("div");
2019-03-10 15:21:46 +00:00
// Short quotes
for (Element q : document.select("q")) {
q.prependText("\"");
q.appendText("\"");
q.tagName("em");
}
// Pre formatted text
2019-09-01 09:10:00 +00:00
for (Element pre : document.select("pre")) {
2019-09-21 16:10:12 +00:00
Element div = document.createElement("div");
for (TextNode tnode : pre.textNodes()) {
String[] lines = tnode.getWholeText().split("\\r?\\n");
for (String line : lines) {
line = Html.escapeHtml(line);
2019-09-02 09:04:51 +00:00
StringBuilder sb = new StringBuilder();
2019-09-23 18:38:39 +00:00
int len = line.length();
for (int j = 0; j < len; j++) {
char kar = line.charAt(j);
if (kar == ' ' &&
j + 1 < len && line.charAt(j + 1) == ' ')
sb.append("&nbsp;");
else
sb.append(kar);
2019-09-02 09:04:51 +00:00
}
2019-09-21 16:10:12 +00:00
Element span = document.createElement("span");
span.html(sb.toString());
div.appendChild(span);
div.appendElement("br");
Log.i("span html=" + span.html());
2019-09-02 09:04:51 +00:00
}
2019-09-01 09:10:00 +00:00
}
2019-09-21 16:10:12 +00:00
pre.replaceWith(div);
2019-03-10 15:21:46 +00:00
}
2019-03-10 11:14:39 +00:00
2019-03-10 15:21:46 +00:00
// Code
2019-09-21 16:10:41 +00:00
document.select("code").tagName("strong");
2019-03-10 15:21:46 +00:00
// Lines
for (Element hr : document.select("hr")) {
hr.tagName("div");
2019-03-18 18:23:43 +00:00
hr.text("----------------------------------------");
2019-02-10 12:01:21 +00:00
}
2019-03-10 15:21:46 +00:00
// Descriptions
document.select("dl").tagName("div");
2019-03-11 08:27:56 +00:00
for (Element dt : document.select("dt")) {
dt.tagName("strong");
2019-03-10 15:21:46 +00:00
dt.appendElement("br");
2019-03-11 08:27:56 +00:00
}
for (Element dd : document.select("dd")) {
dd.tagName("em");
dd.appendElement("br").appendElement("br");
}
2018-11-24 11:27:44 +00:00
2019-03-12 12:13:53 +00:00
// Abbreviations
document.select("abbr").tagName("u");
2019-06-30 07:41:18 +00:00
// Subscript/Superscript
for (Element subp : document.select("sub,sup")) {
Element small = document.createElement("small");
small.html(subp.html());
subp.html(small.outerHtml());
}
// Lists
for (Element li : document.select("li")) {
li.tagName("span");
li.prependText("* ");
li.appendElement("br"); // line break after list item
}
document.select("ol").tagName("div");
document.select("ul").tagName("div");
2018-12-21 14:19:07 +00:00
2019-03-30 16:48:04 +00:00
// Tables
for (Element col : document.select("th,td")) {
2019-09-02 17:01:17 +00:00
// separate columns
2019-09-12 16:53:57 +00:00
if (hasVisibleContent(col.childNodes()))
2019-09-12 08:45:54 +00:00
if (col.nextElementSibling() != null)
2019-09-02 17:01:17 +00:00
col.appendText(" ");
2019-03-30 16:48:04 +00:00
if ("th".equals(col.tagName()))
col.tagName("strong");
else
col.tagName("span");
}
2019-09-12 08:45:54 +00:00
for (Element row : document.select("tr")) {
2019-03-30 16:48:04 +00:00
row.tagName("span");
2019-09-12 16:53:57 +00:00
if (hasVisibleContent(row.childNodes())) {
2019-09-12 13:28:21 +00:00
Element next = row.nextElementSibling();
if (next != null && "tr".equals(next.tagName()))
row.appendElement("br");
}
2019-09-12 08:45:54 +00:00
}
2019-03-30 16:48:04 +00:00
2019-09-11 20:52:15 +00:00
document.select("caption").tagName("div");
2019-06-18 19:56:34 +00:00
for (Element table : document.select("table"))
if (table.parent() != null && "a".equals(table.parent().tagName()))
2019-06-30 07:51:43 +00:00
table.tagName("span"); // Links cannot contain tables
2019-06-18 19:56:34 +00:00
else
table.tagName("div");
2019-03-30 16:48:04 +00:00
2019-07-07 08:49:16 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean disable_tracking = prefs.getBoolean("disable_tracking", true);
2019-09-13 11:46:52 +00:00
// Build list of allowed hosts
List<String> hosts = new ArrayList<>();
if (disable_tracking)
for (Element img : document.select("img")) {
String src = img.attr("src");
if (!TextUtils.isEmpty(src) && !isTrackingPixel(img)) {
Uri uri = Uri.parse(img.attr("src"));
String host = uri.getHost();
if (host != null && !hosts.contains(host))
hosts.add(host);
}
}
// Images
for (Element img : document.select("img")) {
// Remove link tracking pixels
2019-09-13 11:46:52 +00:00
if (disable_tracking) {
String src = img.attr("src");
2019-09-13 11:46:52 +00:00
if (!TextUtils.isEmpty(src) && isTrackingPixel(img)) {
Uri uri = Uri.parse(img.attr("src"));
String host = uri.getHost();
if (host == null || !hosts.contains(host)) {
img.removeAttr("src");
img.tagName("a");
img.attr("href", src);
img.appendText(context.getString(R.string.title_hint_tracking_image,
img.attr("width"), img.attr("height")));
}
}
}
if (!show_images) {
String alt = img.attr("alt");
if (!TextUtils.isEmpty(alt)) {
img.appendText(alt);
2019-06-30 07:41:18 +00:00
}
}
2019-07-26 18:45:53 +00:00
// Annotate source with width and height
if (img.hasAttr("src")) {
2019-07-26 19:33:32 +00:00
int width = 0;
int height = 0;
2019-07-26 18:45:53 +00:00
2019-07-27 05:32:26 +00:00
String awidth = img.attr("width");
for (int i = 0; i < awidth.length(); i++)
if (Character.isDigit(awidth.charAt(i)))
width = width * 10 + (byte) awidth.charAt(i) - (byte) '0';
else
break;
String aheight = img.attr("height");
for (int i = 0; i < aheight.length(); i++)
if (Character.isDigit(aheight.charAt(i)))
height = height * 10 + (byte) aheight.charAt(i) - (byte) '0';
else
break;
2019-07-26 19:33:32 +00:00
if (width != 0 || height != 0) {
String src = img.attr("src");
AnnotatedSource a = new AnnotatedSource(src, width, height);
img.attr("src", a.getAnnotated());
}
2019-07-26 18:45:53 +00:00
}
}
2019-03-30 16:48:04 +00:00
2019-06-30 07:41:18 +00:00
// Autolink
2019-06-13 08:20:45 +00:00
final Pattern pattern = Pattern.compile(
PatternsCompat.AUTOLINK_EMAIL_ADDRESS.pattern() + "|" +
PatternsCompat.AUTOLINK_WEB_URL.pattern());
NodeTraversor.traverse(new NodeVisitor() {
2019-09-01 07:44:03 +00:00
private int links = 0;
2019-08-20 18:05:11 +00:00
@Override
public void head(Node node, int depth) {
2019-09-01 07:44:03 +00:00
if (links < MAX_AUTO_LINK && node instanceof TextNode) {
2019-02-16 21:55:44 +00:00
TextNode tnode = (TextNode) node;
2019-09-21 16:21:49 +00:00
String text = tnode.getWholeText();
2019-02-16 21:55:44 +00:00
2019-06-13 08:20:45 +00:00
Matcher matcher = pattern.matcher(text);
2019-03-30 08:21:52 +00:00
if (matcher.find()) {
2019-03-12 09:04:16 +00:00
Element span = document.createElement("span");
int pos = 0;
2019-03-30 08:21:52 +00:00
do {
2019-03-12 09:04:16 +00:00
boolean linked = false;
Node parent = tnode.parent();
while (parent != null) {
if ("a".equals(parent.nodeName())) {
linked = true;
break;
}
parent = parent.parent();
2019-02-19 07:29:03 +00:00
}
2019-06-05 08:23:41 +00:00
boolean email = matcher.group().contains("@") && !matcher.group().contains(":");
2019-03-12 09:04:16 +00:00
if (BuildConfig.DEBUG)
Log.i("Web url=" + matcher.group() +
" " + matcher.start() + "..." + matcher.end() + "/" + text.length() +
2019-09-01 07:44:03 +00:00
" linked=" + linked + " email=" + email + " count=" + links);
2019-02-19 07:29:03 +00:00
2019-08-29 18:24:30 +00:00
if (linked)
2019-03-12 09:04:16 +00:00
span.appendText(text.substring(pos, matcher.end()));
else {
span.appendText(text.substring(pos, matcher.start()));
2019-02-19 07:29:03 +00:00
2019-03-12 09:04:16 +00:00
Element a = document.createElement("a");
2019-06-05 08:23:41 +00:00
a.attr("href", (email ? "mailto:" : "") + matcher.group());
2019-03-12 09:04:16 +00:00
a.text(matcher.group());
span.appendChild(a);
2019-08-20 18:05:11 +00:00
2019-09-01 07:44:03 +00:00
links++;
2019-03-12 09:04:16 +00:00
}
2019-02-19 07:29:03 +00:00
2019-03-12 09:04:16 +00:00
pos = matcher.end();
2019-09-01 07:44:03 +00:00
} while (links < MAX_AUTO_LINK && matcher.find());
2019-06-13 08:20:45 +00:00
2019-03-12 09:04:16 +00:00
span.appendText(text.substring(pos));
2019-02-16 21:55:44 +00:00
2019-03-12 09:04:16 +00:00
tnode.before(span);
tnode.text("");
2018-09-02 11:18:32 +00:00
}
}
}
2018-09-02 11:18:32 +00:00
@Override
public void tail(Node node, int depth) {
}
2019-03-12 09:04:16 +00:00
}, document);
2019-09-12 08:45:54 +00:00
// Selective new lines
for (Element div : document.select("div"))
if (div.children().select("div").size() == 0 &&
2019-09-12 16:53:57 +00:00
hasVisibleContent(div.childNodes())) {
2019-09-11 17:52:04 +00:00
div.appendElement("br");
2019-09-11 20:20:00 +00:00
div.appendElement("br");
}
2019-09-12 08:45:54 +00:00
for (Element div : document.select("div"))
div.tagName("span");
2019-07-08 18:14:33 +00:00
2019-03-12 10:13:24 +00:00
Element body = document.body();
return (body == null ? "" : body.html());
2018-08-02 13:33:06 +00:00
}
2018-12-14 09:11:45 +00:00
2019-09-12 16:53:57 +00:00
private static boolean hasVisibleContent(List<Node> nodes) {
2019-09-12 08:45:54 +00:00
for (Node node : nodes)
if (node instanceof TextNode && !((TextNode) node).isBlank())
return true;
else if (node instanceof Element) {
Element element = (Element) node;
if (!element.isBlock() &&
(element.hasText() || element.selectFirst("img") != null))
return true;
}
return false;
2019-09-02 17:01:17 +00:00
}
2019-07-26 18:45:53 +00:00
static Drawable decodeImage(final Context context, final long id, String source, boolean show, final TextView view) {
2019-07-06 10:52:00 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
2019-03-30 16:55:00 +00:00
boolean compact = prefs.getBoolean("compact", false);
int zoom = prefs.getInt("zoom", compact ? 0 : 1);
boolean inline = prefs.getBoolean("inline_images", false);
2019-03-30 16:55:00 +00:00
2019-07-06 10:52:00 +00:00
final int px = Helper.dp2pixels(context, (zoom + 1) * 24);
2019-04-30 08:33:03 +00:00
2019-07-06 10:52:00 +00:00
final Resources.Theme theme = context.getTheme();
final Resources res = context.getResources();
2018-12-14 09:11:45 +00:00
2019-07-26 18:45:53 +00:00
final AnnotatedSource a = new AnnotatedSource(source);
if (TextUtils.isEmpty(a.source)) {
2019-04-30 08:33:03 +00:00
Drawable d = res.getDrawable(R.drawable.baseline_broken_image_24, theme);
d.setBounds(0, 0, px, px);
2018-12-14 09:11:45 +00:00
return d;
}
2019-07-26 18:45:53 +00:00
boolean embedded = a.source.startsWith("cid:");
boolean data = a.source.startsWith("data:");
2019-02-19 07:29:03 +00:00
if (BuildConfig.DEBUG)
Log.i("Image show=" + show + " inline=" + inline +
2019-07-26 18:45:53 +00:00
" embedded=" + embedded + " data=" + data + " source=" + a.source);
2018-12-14 09:11:45 +00:00
2019-01-29 13:29:39 +00:00
// Embedded images
if (embedded && (show || inline)) {
2019-07-06 10:52:00 +00:00
DB db = DB.getInstance(context);
2019-07-26 18:45:53 +00:00
String cid = "<" + a.source.substring(4) + ">";
2019-03-14 07:18:42 +00:00
EntityAttachment attachment = db.attachment().getAttachment(id, cid);
2019-01-29 13:29:39 +00:00
if (attachment == null) {
2019-05-24 07:14:38 +00:00
Log.i("Image not found CID=" + cid);
2019-04-30 08:33:03 +00:00
Drawable d = res.getDrawable(R.drawable.baseline_broken_image_24, theme);
2019-01-29 13:29:39 +00:00
d.setBounds(0, 0, px, px);
return d;
} else if (!attachment.available) {
2019-05-24 07:14:38 +00:00
Log.i("Image not available CID=" + cid);
2019-04-30 08:33:03 +00:00
Drawable d = res.getDrawable(R.drawable.baseline_photo_library_24, theme);
2019-01-29 13:29:39 +00:00
d.setBounds(0, 0, px, px);
return d;
} else {
2019-09-07 18:13:58 +00:00
int scaleToPixels = res.getDisplayMetrics().widthPixels;
if ("image/gif".equals(attachment.type) &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
ImageDecoder.Source isource = ImageDecoder.createSource(attachment.getFile(context));
Drawable gif;
try {
gif = ImageDecoder.decodeDrawable(isource, new ImageDecoder.OnHeaderDecodedListener() {
@Override
public void onHeaderDecoded(
@NonNull ImageDecoder decoder,
@NonNull ImageDecoder.ImageInfo info,
@NonNull ImageDecoder.Source source) {
int factor = 1;
while (info.getSize().getWidth() / factor > scaleToPixels)
factor *= 2;
decoder.setTargetSampleSize(factor);
}
});
} catch (IOException ex) {
Log.w(ex);
gif = null;
}
if (gif == null) {
Log.i("GIF not decodable CID=" + cid);
Drawable d = res.getDrawable(R.drawable.baseline_broken_image_24, theme);
d.setBounds(0, 0, px, px);
return d;
} else {
if (view != null)
fitDrawable(gif, a, view);
return gif;
}
2019-02-02 18:35:40 +00:00
} else {
2019-09-07 18:13:58 +00:00
Bitmap bm = Helper.decodeImage(attachment.getFile(context), scaleToPixels);
if (bm == null) {
Log.i("Image not decodable CID=" + cid);
Drawable d = res.getDrawable(R.drawable.baseline_broken_image_24, theme);
d.setBounds(0, 0, px, px);
return d;
} else {
Drawable d = new BitmapDrawable(res, bm);
DisplayMetrics dm = context.getResources().getDisplayMetrics();
d.setBounds(0, 0, Math.round(bm.getWidth() * dm.density), Math.round(bm.getHeight() * dm.density));
if (view != null)
fitDrawable(d, a, view);
return d;
}
2019-02-02 18:35:40 +00:00
}
2019-01-29 13:29:39 +00:00
}
}
2018-12-14 09:11:45 +00:00
2019-01-29 13:29:39 +00:00
// Data URI
if (data && (show || inline))
2018-12-14 09:11:45 +00:00
try {
2019-07-26 18:45:53 +00:00
Drawable d = getDataDrawable(context, a.source);
2019-07-15 10:17:01 +00:00
if (view != null)
2019-07-26 18:45:53 +00:00
fitDrawable(d, a, view);
2019-07-15 10:17:01 +00:00
return d;
2019-01-29 13:29:39 +00:00
} catch (IllegalArgumentException ex) {
Log.w(ex);
2019-04-30 08:33:03 +00:00
Drawable d = res.getDrawable(R.drawable.baseline_broken_image_24, theme);
d.setBounds(0, 0, px, px);
2018-12-14 09:11:45 +00:00
return d;
2019-01-29 13:29:39 +00:00
}
if (!show) {
// Show placeholder icon
int resid = (embedded || data ? R.drawable.baseline_photo_library_24 : R.drawable.baseline_image_24);
Drawable d = res.getDrawable(resid, theme);
d.setBounds(0, 0, px, px);
return d;
}
// Get cache file name
2019-07-06 10:52:00 +00:00
File dir = new File(context.getCacheDir(), "images");
if (!dir.exists())
dir.mkdir();
2019-07-26 18:45:53 +00:00
final File file = new File(dir, id + "_" + Math.abs(a.source.hashCode()) + ".png");
2019-07-06 10:52:00 +00:00
Drawable cached = getCachedImage(context, file);
2019-07-15 10:17:01 +00:00
if (cached != null || view == null) {
2019-07-26 17:17:24 +00:00
if (view == null)
if (cached == null) {
Drawable d = res.getDrawable(R.drawable.baseline_hourglass_empty_24, theme);
d.setBounds(0, 0, px, px);
return d;
} else
return cached;
else
2019-07-26 18:45:53 +00:00
fitDrawable(cached, a, view);
return cached;
2019-07-15 10:17:01 +00:00
}
2019-04-30 08:33:03 +00:00
final LevelListDrawable lld = new LevelListDrawable();
Drawable wait = res.getDrawable(R.drawable.baseline_hourglass_empty_24, theme);
2019-07-06 10:14:34 +00:00
lld.addLevel(1, 1, wait);
2019-04-30 08:33:03 +00:00
lld.setBounds(0, 0, px, px);
2019-07-06 10:14:34 +00:00
lld.setLevel(1);
2019-01-29 13:29:39 +00:00
2019-04-30 08:33:03 +00:00
executor.submit(new Runnable() {
@Override
public void run() {
try {
Drawable cached = getCachedImage(context, file);
if (cached != null) {
2019-07-26 18:45:53 +00:00
fitDrawable(cached, a, view);
post(cached, a.source);
return;
}
2019-04-30 08:33:03 +00:00
BitmapFactory.Options options = new BitmapFactory.Options();
2019-07-26 18:45:53 +00:00
Log.i("Probe " + a.source);
try (InputStream probe = new URL(a.source).openStream()) {
2019-04-30 08:33:03 +00:00
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(probe, null, options);
}
2019-07-26 18:45:53 +00:00
Log.i("Download " + a.source);
2019-04-30 08:33:03 +00:00
Bitmap bm;
2019-07-26 18:45:53 +00:00
try (InputStream is = new URL(a.source).openStream()) {
2019-05-25 18:04:53 +00:00
int scaleTo = res.getDisplayMetrics().widthPixels;
2019-04-30 08:33:03 +00:00
int factor = 1;
while (options.outWidth / factor > scaleTo)
factor *= 2;
if (factor > 1) {
Log.i("Download image factor=" + factor);
options.inJustDecodeBounds = false;
options.inSampleSize = factor;
bm = BitmapFactory.decodeStream(is, null, options);
} else
bm = BitmapFactory.decodeStream(is);
}
if (bm == null)
2019-07-26 18:45:53 +00:00
throw new FileNotFoundException("Download image failed source=" + a.source);
2019-01-29 13:29:39 +00:00
2019-07-26 18:45:53 +00:00
Log.i("Downloaded image source=" + a.source);
2019-01-29 13:29:39 +00:00
try (OutputStream os = new FileOutputStream(file)) {
2019-04-30 08:33:03 +00:00
bm.compress(Bitmap.CompressFormat.PNG, 90, os);
}
2019-01-29 13:29:39 +00:00
2019-04-30 08:33:03 +00:00
// Create drawable from bitmap
Drawable d = new BitmapDrawable(res, bm);
2019-07-15 10:17:01 +00:00
DisplayMetrics dm = context.getResources().getDisplayMetrics();
d.setBounds(0, 0, Math.round(bm.getWidth() * dm.density), Math.round(bm.getHeight() * dm.density));
2019-07-26 18:45:53 +00:00
fitDrawable(d, a, view);
post(d, a.source);
2019-04-30 08:33:03 +00:00
} catch (Throwable ex) {
2019-07-06 10:14:34 +00:00
// Show broken icon
2019-04-30 08:33:03 +00:00
Log.w(ex);
int resid = (ex instanceof IOException && !(ex instanceof FileNotFoundException)
? R.drawable.baseline_cloud_off_24
: R.drawable.baseline_broken_image_24);
Drawable d = res.getDrawable(resid, theme);
d.setBounds(0, 0, px, px);
2019-07-26 18:45:53 +00:00
post(d, a.source);
2019-04-30 08:33:03 +00:00
}
2019-01-29 13:29:39 +00:00
}
2019-04-30 08:33:03 +00:00
private void post(final Drawable d, String source) {
Log.i("Posting image=" + source);
2019-07-15 10:17:01 +00:00
new Handler(context.getMainLooper()).post(new Runnable() {
2019-04-30 08:33:03 +00:00
@Override
public void run() {
2019-07-15 10:17:01 +00:00
Rect bounds = d.getBounds();
2019-05-03 16:06:58 +00:00
2019-07-06 10:14:34 +00:00
lld.addLevel(0, 0, d);
2019-07-15 10:17:01 +00:00
lld.setBounds(0, 0, bounds.width(), bounds.height());
2019-07-06 10:14:34 +00:00
lld.setLevel(0);
2019-05-03 16:06:58 +00:00
2019-04-30 08:33:03 +00:00
view.setText(view.getText());
}
});
}
});
return lld;
2018-12-14 09:11:45 +00:00
}
2018-12-14 11:04:50 +00:00
2019-07-26 18:45:53 +00:00
private static void fitDrawable(Drawable d, AnnotatedSource a, View view) {
2019-07-15 10:17:01 +00:00
Rect bounds = d.getBounds();
int w = bounds.width();
int h = bounds.height();
2019-07-26 18:45:53 +00:00
if (a.width == 0 && a.height != 0)
a.width = Math.round(a.height * w / (float) h);
if (a.height == 0 && a.width != 0)
a.height = Math.round(a.width * h / (float) w);
if (a.width != 0 && a.height != 0) {
w = Helper.dp2pixels(view.getContext(), a.width);
h = Helper.dp2pixels(view.getContext(), a.height);
d.setBounds(0, 0, w, h);
}
2019-07-15 10:17:01 +00:00
float width = view.getWidth();
if (w > width) {
float scale = width / w;
w = Math.round(w * scale);
h = Math.round(h * scale);
d.setBounds(0, 0, w, h);
}
}
private static Drawable getDataDrawable(Context context, String source) {
2019-07-06 10:16:42 +00:00
// "<img src=\"data:image/png;base64,iVBORw0KGgoAAA" +
// "ANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4" +
// "//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU" +
// "5ErkJggg==\" alt=\"Red dot\" />";
String base64 = source.substring(source.indexOf(',') + 1);
byte[] bytes = Base64.decode(base64.getBytes(), 0);
Bitmap bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
if (bm == null)
throw new IllegalArgumentException("decode byte array failed");
2019-07-15 10:17:01 +00:00
Drawable d = new BitmapDrawable(context.getResources(), bm);
DisplayMetrics dm = context.getResources().getDisplayMetrics();
d.setBounds(0, 0, Math.round(bm.getWidth() * dm.density), Math.round(bm.getHeight() * dm.density));
2019-07-06 10:16:42 +00:00
return d;
}
static private Drawable getCachedImage(Context context, File file) {
if (file.exists()) {
Log.i("Using cached " + file);
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
if (bm != null) {
Drawable d = new BitmapDrawable(context.getResources(), bm);
2019-07-15 10:17:01 +00:00
DisplayMetrics dm = context.getResources().getDisplayMetrics();
d.setBounds(0, 0, Math.round(bm.getWidth() * dm.density), Math.round(bm.getHeight() * dm.density));
return d;
}
}
return null;
}
2018-12-24 20:09:47 +00:00
static String getPreview(String body) {
String text = (body == null ? null : Jsoup.parse(body).text());
2019-01-05 11:17:33 +00:00
return (text == null ? null : text.substring(0, Math.min(text.length(), PREVIEW_SIZE)));
}
static String getText(String html) {
final StringBuilder sb = new StringBuilder();
html = html.replace("<br> ", "<br>");
2019-01-05 11:17:33 +00:00
NodeTraversor.traverse(new NodeVisitor() {
2019-02-10 12:01:21 +00:00
private int qlevel = 0;
2019-02-11 15:36:42 +00:00
private int tlevel = 0;
2019-09-07 06:22:46 +00:00
private int plevel = 0;
2019-08-23 06:29:58 +00:00
private boolean nl = true;
2019-02-10 12:01:21 +00:00
2019-01-05 11:17:33 +00:00
public void head(Node node, int depth) {
2019-08-23 06:29:58 +00:00
if (node instanceof TextNode)
2019-09-07 06:22:46 +00:00
if (plevel > 0) {
String[] lines = ((TextNode) node).getWholeText().split("\\r?\\n");
for (String line : lines) {
append(line);
newline();
}
} else
append(((TextNode) node).text());
2019-08-23 06:29:58 +00:00
else {
2019-01-05 11:17:33 +00:00
String name = node.nodeName();
2019-02-10 12:01:21 +00:00
if ("li".equals(name))
2019-08-23 06:29:58 +00:00
append("*");
2019-02-10 12:01:21 +00:00
else if ("blockquote".equals(name))
qlevel++;
2019-09-07 06:22:46 +00:00
else if ("pre".equals(name))
plevel++;
2019-02-10 12:01:21 +00:00
if (heads.contains(name))
newline();
2019-01-05 11:17:33 +00:00
}
}
public void tail(Node node, int depth) {
String name = node.nodeName();
2019-08-23 06:29:58 +00:00
if ("a".equals(name))
2019-09-11 18:20:16 +00:00
append("[" + node.attr("href") + "] ");
2019-08-23 06:29:58 +00:00
else if ("img".equals(name))
2019-09-11 18:20:16 +00:00
append("[" + node.attr("src") + "] ");
2019-08-23 06:29:58 +00:00
else if ("th".equals(name) || "td".equals(name)) {
2019-02-10 12:01:21 +00:00
Node next = node.nextSibling();
if (next == null || !("th".equals(next.nodeName()) || "td".equals(next.nodeName())))
newline();
} else if ("blockquote".equals(name))
qlevel--;
2019-09-07 06:22:46 +00:00
else if ("pre".equals(name))
plevel--;
2019-02-10 12:01:21 +00:00
2019-01-05 11:17:33 +00:00
if (tails.contains(name))
2019-02-10 12:01:21 +00:00
newline();
}
2019-02-11 15:36:42 +00:00
private void append(String text) {
if (tlevel != qlevel) {
newline();
tlevel = qlevel;
}
2019-08-23 06:29:58 +00:00
if (!nl)
sb.append(" ");
2019-02-11 15:36:42 +00:00
sb.append(text);
2019-08-23 06:29:58 +00:00
nl = false;
2019-02-11 15:36:42 +00:00
}
2019-02-10 12:01:21 +00:00
private void newline() {
sb.append("\n");
for (int i = 0; i < qlevel; i++)
sb.append('>');
if (qlevel > 0)
sb.append(' ');
2019-08-23 06:29:58 +00:00
nl = true;
2019-01-05 11:17:33 +00:00
}
}, Jsoup.parse(html));
2019-02-10 12:01:21 +00:00
sb.append("\n");
2019-01-05 11:17:33 +00:00
return sb.toString();
2018-12-24 20:09:47 +00:00
}
2019-02-10 12:01:21 +00:00
2019-09-20 17:39:37 +00:00
static void embedImages(Context context, long id, Document document) throws IOException {
2019-04-06 09:05:33 +00:00
DB db = DB.getInstance(context);
2019-09-20 17:39:37 +00:00
for (Element img : document.select("img")) {
2019-04-06 09:05:33 +00:00
String src = img.attr("src");
if (src.startsWith("cid:")) {
String cid = '<' + src.substring(4) + '>';
EntityAttachment attachment = db.attachment().getAttachment(id, cid);
if (attachment != null && attachment.available) {
File file = attachment.getFile(context);
try (InputStream is = new FileInputStream(file)) {
2019-04-06 09:05:33 +00:00
byte[] bytes = new byte[(int) file.length()];
if (is.read(bytes) != bytes.length)
throw new IOException("length");
StringBuilder sb = new StringBuilder();
sb.append("data:");
sb.append(attachment.type);
sb.append(";base64,");
sb.append(Base64.encodeToString(bytes, Base64.DEFAULT));
img.attr("src", sb.toString());
}
}
}
}
2019-09-20 17:39:37 +00:00
}
2019-04-06 09:05:33 +00:00
2019-09-20 17:39:37 +00:00
static void removeViewportLimitations(Document document) {
for (Element meta : document.select("meta").select("[name=viewport]")) {
String content = meta.attr("content");
String[] params = content.split(";");
if (params.length > 0) {
List<String> viewport = new ArrayList<>();
for (String param : params)
2019-09-23 20:07:22 +00:00
if (!param.toLowerCase(Locale.ROOT).contains("maximum-scale") &&
!param.toLowerCase(Locale.ROOT).contains("user-scalable"))
2019-09-20 17:39:37 +00:00
viewport.add(param.trim());
if (viewport.size() == 0)
meta.attr("content", "");
else
meta.attr("content", TextUtils.join(" ;", viewport) + ";");
}
}
2019-04-06 09:05:33 +00:00
}
private static boolean isTrackingPixel(Element img) {
2019-03-12 11:49:13 +00:00
String width = img.attr("width").trim();
String height = img.attr("height").trim();
if (TextUtils.isEmpty(width) || TextUtils.isEmpty(height))
return false;
try {
return (Integer.parseInt(width) * Integer.parseInt(height) <= TRACKING_PIXEL_SURFACE);
} catch (NumberFormatException ignored) {
return false;
}
}
2019-08-29 19:57:04 +00:00
static Spanned highlightHeaders(Context context, String headers) {
int colorAccent = Helper.resolveColor(context, R.attr.colorAccent);
SpannableStringBuilder ssb = new SpannableStringBuilder(headers);
int index = 0;
for (String line : headers.split("\n")) {
if (line.length() > 0 && !Character.isWhitespace(line.charAt(0))) {
int colon = line.indexOf(':');
if (colon > 0)
ssb.setSpan(new ForegroundColorSpan(colorAccent), index, index + colon, 0);
}
index += line.length() + 1;
}
return ssb;
}
2019-02-10 12:01:21 +00:00
static Spanned fromHtml(@NonNull String html) {
return fromHtml(html, null, null);
}
static Spanned fromHtml(@NonNull String html, @Nullable Html.ImageGetter imageGetter, @Nullable Html.TagHandler tagHandler) {
Spanned spanned = HtmlCompat.fromHtml(html, FROM_HTML_SEPARATOR_LINE_BREAK_LIST_ITEM, imageGetter, tagHandler);
int i = spanned.length();
while (i > 1 && spanned.charAt(i - 2) == '\n' && spanned.charAt(i - 1) == '\n')
i--;
if (i != spanned.length())
spanned = (Spanned) spanned.subSequence(0, i);
return spanned;
2019-02-10 12:01:21 +00:00
}
static String toHtml(Spanned spanned) {
2019-05-01 13:58:41 +00:00
String html = HtmlCompat.toHtml(spanned, TO_HTML_PARAGRAPH_LINES_CONSECUTIVE);
// @Google: why convert size to and from in a different way?
Document doc = Jsoup.parse(html);
for (Element element : doc.select("span")) {
String style = element.attr("style");
if (style.startsWith("font-size:")) {
int colon = style.indexOf(':');
int semi = style.indexOf("em;", colon);
if (semi > colon)
try {
String hsize = style.substring(colon + 1, semi).replace(',', '.');
float size = Float.parseFloat(hsize);
element.tagName(size < 1.0f ? "small" : "big");
element.attributes().remove("style");
} catch (NumberFormatException ex) {
Log.e(ex);
}
}
}
2019-09-23 17:18:21 +00:00
return doc.html();
2019-02-10 12:01:21 +00:00
}
2019-07-26 18:45:53 +00:00
public static class AnnotatedSource {
private String source;
private int width = 0;
private int height = 0;
// Encapsulate some ugliness
AnnotatedSource(String source) {
this.source = source;
if (source != null && source.endsWith("###")) {
int pos = source.substring(0, source.length() - 3).lastIndexOf("###");
if (pos > 0) {
int x = source.indexOf("x", pos + 3);
if (x > 0)
try {
this.width = Integer.parseInt(source.substring(pos + 3, x));
this.height = Integer.parseInt(source.substring(x + 1, source.length() - 3));
this.source = source.substring(0, pos);
} catch (NumberFormatException ex) {
Log.e(ex);
this.width = 0;
this.height = 0;
}
}
}
}
private AnnotatedSource(String source, int width, int height) {
this.source = source;
this.width = width;
this.height = height;
}
public String getSource() {
return this.source;
}
private String getAnnotated() {
return (width == 0 && height == 0
? source
: source + "###" + width + "x" + height + "###");
}
}
2018-08-02 13:33:06 +00:00
}