1/*
2 * Copyright (c) 2018, Daniel Gultsch All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without modification,
5 * are permitted provided that the following conditions are met:
6 *
7 * 1. Redistributions of source code must retain the above copyright notice, this
8 * list of conditions and the following disclaimer.
9 *
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation and/or
12 * other materials provided with the distribution.
13 *
14 * 3. Neither the name of the copyright holder nor the names of its contributors
15 * may be used to endorse or promote products derived from this software without
16 * specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
22 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
25 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30package de.gultsch.common;
31
32import android.net.Uri;
33import android.text.Editable;
34import android.text.Spanned;
35import android.text.style.TypefaceSpan;
36import android.text.style.URLSpan;
37import android.text.Spannable;
38import com.google.common.base.Splitter;
39import com.google.common.collect.Collections2;
40import com.google.common.collect.ImmutableList;
41import com.google.common.collect.Iterables;
42import com.google.common.collect.Lists;
43import eu.siacs.conversations.entities.Account;
44import eu.siacs.conversations.entities.ListItem;
45import eu.siacs.conversations.utils.StylingHelper;
46import eu.siacs.conversations.utils.XmppUri;
47import eu.siacs.conversations.xmpp.Jid;
48import java.util.Arrays;
49import java.util.List;
50import java.util.Objects;
51
52public class Linkify {
53
54 private static final android.text.util.Linkify.MatchFilter MATCH_FILTER =
55 (s, start, end) -> isPassAdditionalValidation(s.subSequence(start, end).toString());
56
57 private static boolean isPassAdditionalValidation(final String match) {
58 final var scheme = Iterables.getFirst(Splitter.on(':').limit(2).splitToList(match), null);
59 if (scheme == null) {
60 return false;
61 }
62 return switch (scheme) {
63 case "tel" -> Patterns.URI_TEL.matcher(match).matches();
64 case "http", "https" -> Patterns.URI_HTTP.matcher(match).matches();
65 case "geo" -> Patterns.URI_GEO.matcher(match).matches();
66 case "xmpp" -> new XmppUri(Uri.parse(match)).isValidJid();
67 case "web+ap" -> {
68 if (Patterns.URI_WEB_AP.matcher(match).matches()) {
69 final var webAp = new MiniUri(match);
70 // TODO once we have fragment support check that there aren't any
71 yield Objects.nonNull(webAp.getAuthority()) && webAp.getParameter().isEmpty();
72 } else {
73 yield false;
74 }
75 }
76 default -> true;
77 };
78 }
79
80 public static void addLinks(final Spannable body) {
81 android.text.util.Linkify.addLinks(body, Patterns.URI_GENERIC, null, MATCH_FILTER, null);
82 for (final URLSpan span : body.getSpans(0, body.length(), URLSpan.class)) {
83 try {
84 new java.net.URI(span.getURL());
85 } catch (final java.net.URISyntaxException e) {
86 body.removeSpan(span);
87 }
88 }
89 }
90
91 public static void addLinks(final Editable body, final Account account, final Jid context) {
92 addLinks(body);
93 final var roster = account.getRoster();
94 urlspan:
95 for (final URLSpan urlspan : body.getSpans(0, body.length() - 1, URLSpan.class)) {
96 final var start = body.getSpanStart(urlspan);
97 if (start < 0) continue;
98 for (final var span : body.getSpans(start, start, Object.class)) {
99 // instanceof TypefaceSpan is to block in XHTML code blocks. Probably a bit heavy-handed but works for now
100 if ((body.getSpanFlags(span) & Spanned.SPAN_USER) >> Spanned.SPAN_USER_SHIFT == StylingHelper.NOLINKIFY || span instanceof TypefaceSpan) {
101 body.removeSpan(urlspan);
102 continue urlspan;
103 }
104 }
105 Uri uri = Uri.parse(urlspan.getURL());
106 if ("xmpp".equals(uri.getScheme())) {
107 try {
108 if (!body.subSequence(body.getSpanStart(urlspan), body.getSpanEnd(urlspan)).toString().startsWith("xmpp:")) {
109 // Already customized
110 continue;
111 }
112
113 XmppUri xmppUri = new XmppUri(uri);
114 Jid jid = xmppUri.getJid();
115 String display = xmppUri.toString();
116 if (jid.asBareJid().equals(context) && xmppUri.isAction("message") && xmppUri.getBody() != null) {
117 display = xmppUri.getBody();
118 } else if (jid.asBareJid().equals(context) && xmppUri.parameterString().length() > 0) {
119 display = xmppUri.parameterString();
120 } else {
121 ListItem item = account.getBookmark(jid);
122 if (item == null) item = roster.getContact(jid);
123 display = item.getDisplayName() + xmppUri.displayParameterString();
124 }
125 body.replace(
126 body.getSpanStart(urlspan),
127 body.getSpanEnd(urlspan),
128 display
129 );
130 } catch (final IllegalArgumentException | IndexOutOfBoundsException e) { /* bad JID or span gone */ }
131 }
132 }
133 }
134
135 public static List<MiniUri> getLinks(final String body) {
136 final var builder = new ImmutableList.Builder<MiniUri>();
137 final var matcher = Patterns.URI_GENERIC.matcher(body);
138 while (matcher.find()) {
139 final var match = matcher.group();
140 if (isPassAdditionalValidation(match)) {
141 builder.add(new MiniUri(match));
142 }
143 }
144 return builder.build();
145 }
146
147 public static List<String> extractLinks(final Editable body) {
148 addLinks(body);
149 final var spans =
150 Arrays.asList(body.getSpans(0, body.length() - 1, URLSpan.class));
151 final var urlWrappers =
152 Collections2.filter(
153 Collections2.transform(
154 spans,
155 s ->
156 s == null
157 ? null
158 : new UrlWrapper(body.getSpanStart(s), s.getURL())),
159 uw -> uw != null);
160 List<UrlWrapper> sorted = ImmutableList.sortedCopyOf(
161 (a, b) -> Integer.compare(a.position, b.position), urlWrappers);
162 return Lists.transform(sorted, uw -> uw.url);
163
164 }
165
166 private static class UrlWrapper {
167 private final int position;
168 private final String url;
169
170 private UrlWrapper(int position, String url) {
171 this.position = position;
172 this.url = url;
173 }
174 }
175}