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 com.google.common.base.Splitter;
38import com.google.common.collect.Collections2;
39import com.google.common.collect.ImmutableList;
40import com.google.common.collect.Iterables;
41import com.google.common.collect.Lists;
42import eu.siacs.conversations.entities.Account;
43import eu.siacs.conversations.entities.ListItem;
44import eu.siacs.conversations.utils.StylingHelper;
45import eu.siacs.conversations.utils.XmppUri;
46import eu.siacs.conversations.xmpp.Jid;
47import java.util.Arrays;
48import java.util.List;
49import java.util.Objects;
50
51public class Linkify {
52
53 private static final android.text.util.Linkify.MatchFilter MATCH_FILTER =
54 (s, start, end) -> isPassAdditionalValidation(s.subSequence(start, end).toString());
55
56 private static boolean isPassAdditionalValidation(final String match) {
57 final var scheme = Iterables.getFirst(Splitter.on(':').limit(2).splitToList(match), null);
58 if (scheme == null) {
59 return false;
60 }
61 return switch (scheme) {
62 case "tel" -> Patterns.URI_TEL.matcher(match).matches();
63 case "http", "https" -> Patterns.URI_HTTP.matcher(match).matches();
64 case "geo" -> Patterns.URI_GEO.matcher(match).matches();
65 case "xmpp" -> new XmppUri(Uri.parse(match)).isValidJid();
66 case "web+ap" -> {
67 if (Patterns.URI_WEB_AP.matcher(match).matches()) {
68 final var webAp = new MiniUri(match);
69 // TODO once we have fragment support check that there aren't any
70 yield Objects.nonNull(webAp.getAuthority()) && webAp.getParameter().isEmpty();
71 } else {
72 yield false;
73 }
74 }
75 default -> true;
76 };
77 }
78
79 public static void addLinks(final Editable body) {
80 android.text.util.Linkify.addLinks(body, Patterns.URI_GENERIC, null, MATCH_FILTER, null);
81 }
82
83 public static void addLinks(final Editable body, final Account account, final Jid context) {
84 addLinks(body);
85 final var roster = account.getRoster();
86 urlspan:
87 for (final URLSpan urlspan : body.getSpans(0, body.length() - 1, URLSpan.class)) {
88 final var start = body.getSpanStart(urlspan);
89 if (start < 0) continue;
90 for (final var span : body.getSpans(start, start, Object.class)) {
91 // instanceof TypefaceSpan is to block in XHTML code blocks. Probably a bit heavy-handed but works for now
92 if ((body.getSpanFlags(span) & Spanned.SPAN_USER) >> Spanned.SPAN_USER_SHIFT == StylingHelper.NOLINKIFY || span instanceof TypefaceSpan) {
93 body.removeSpan(urlspan);
94 continue urlspan;
95 }
96 }
97 Uri uri = Uri.parse(urlspan.getURL());
98 if ("xmpp".equals(uri.getScheme())) {
99 try {
100 if (!body.subSequence(body.getSpanStart(urlspan), body.getSpanEnd(urlspan)).toString().startsWith("xmpp:")) {
101 // Already customized
102 continue;
103 }
104
105 XmppUri xmppUri = new XmppUri(uri);
106 Jid jid = xmppUri.getJid();
107 String display = xmppUri.toString();
108 if (jid.asBareJid().equals(context) && xmppUri.isAction("message") && xmppUri.getBody() != null) {
109 display = xmppUri.getBody();
110 } else if (jid.asBareJid().equals(context) && xmppUri.parameterString().length() > 0) {
111 display = xmppUri.parameterString();
112 } else {
113 ListItem item = account.getBookmark(jid);
114 if (item == null) item = roster.getContact(jid);
115 display = item.getDisplayName() + xmppUri.displayParameterString();
116 }
117 body.replace(
118 body.getSpanStart(urlspan),
119 body.getSpanEnd(urlspan),
120 display
121 );
122 } catch (final IllegalArgumentException | IndexOutOfBoundsException e) { /* bad JID or span gone */ }
123 }
124 }
125 }
126
127 public static List<MiniUri> getLinks(final String body) {
128 final var builder = new ImmutableList.Builder<MiniUri>();
129 final var matcher = Patterns.URI_GENERIC.matcher(body);
130 while (matcher.find()) {
131 final var match = matcher.group();
132 if (isPassAdditionalValidation(match)) {
133 builder.add(new MiniUri(match));
134 }
135 }
136 return builder.build();
137 }
138
139 public static List<String> extractLinks(final Editable body) {
140 addLinks(body);
141 final var spans =
142 Arrays.asList(body.getSpans(0, body.length() - 1, URLSpan.class));
143 final var urlWrappers =
144 Collections2.filter(
145 Collections2.transform(
146 spans,
147 s ->
148 s == null
149 ? null
150 : new UrlWrapper(body.getSpanStart(s), s.getURL())),
151 uw -> uw != null);
152 List<UrlWrapper> sorted = ImmutableList.sortedCopyOf(
153 (a, b) -> Integer.compare(a.position, b.position), urlWrappers);
154 return Lists.transform(sorted, uw -> uw.url);
155
156 }
157
158 private static class UrlWrapper {
159 private final int position;
160 private final String url;
161
162 private UrlWrapper(int position, String url) {
163 this.position = position;
164 this.url = url;
165 }
166 }
167}