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 eu.siacs.conversations.ui.util;
31
32import android.net.Uri;
33import android.os.Build;
34import android.text.Editable;
35import android.text.style.URLSpan;
36import android.text.util.Linkify;
37
38import com.google.common.collect.Collections2;
39import com.google.common.collect.ImmutableList;
40import com.google.common.collect.Lists;
41
42import java.util.Arrays;
43import java.util.Collection;
44import java.util.List;
45import java.util.Locale;
46import java.util.Objects;
47
48import eu.siacs.conversations.entities.Account;
49import eu.siacs.conversations.entities.ListItem;
50import eu.siacs.conversations.entities.Roster;
51import eu.siacs.conversations.ui.text.FixedURLSpan;
52import eu.siacs.conversations.utils.GeoHelper;
53import eu.siacs.conversations.utils.Patterns;
54import eu.siacs.conversations.utils.XmppUri;
55import eu.siacs.conversations.xmpp.Jid;
56
57public class MyLinkify {
58
59 private static final Linkify.TransformFilter WEBURL_TRANSFORM_FILTER = (matcher, url) -> {
60 if (url == null) {
61 return null;
62 }
63 final String lcUrl = url.toLowerCase(Locale.US);
64 if (lcUrl.startsWith("http://") || lcUrl.startsWith("https://")) {
65 return removeTrailingBracket(url);
66 } else {
67 return "http://" + removeTrailingBracket(url);
68 }
69 };
70
71 private static String removeTrailingBracket(final String url) {
72 int numOpenBrackets = 0;
73 for (char c : url.toCharArray()) {
74 if (c == '(') {
75 ++numOpenBrackets;
76 } else if (c == ')') {
77 --numOpenBrackets;
78 }
79 }
80 if (numOpenBrackets != 0 && url.charAt(url.length() - 1) == ')') {
81 return url.substring(0, url.length() - 1);
82 } else {
83 return url;
84 }
85 }
86
87 private static final Linkify.MatchFilter WEBURL_MATCH_FILTER = (cs, start, end) -> {
88 if (start > 0) {
89 if (cs.charAt(start - 1) == '@' || cs.charAt(start - 1) == '.'
90 || cs.subSequence(Math.max(0, start - 3), start).equals("://")) {
91 return false;
92 }
93 }
94
95 if (end < cs.length()) {
96 // Reject strings that were probably matched only because they contain a dot followed by
97 // by some known TLD (see also comment for WORD_BOUNDARY in Patterns.java)
98 return !isAlphabetic(cs.charAt(end - 1)) || !isAlphabetic(cs.charAt(end));
99 }
100
101 return true;
102 };
103
104 private static final Linkify.MatchFilter XMPPURI_MATCH_FILTER = (s, start, end) -> {
105 XmppUri uri = new XmppUri(s.subSequence(start, end).toString());
106 return uri.isValidJid();
107 };
108
109 private static boolean isAlphabetic(final int code) {
110 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
111 return Character.isAlphabetic(code);
112 }
113
114 switch (Character.getType(code)) {
115 case Character.UPPERCASE_LETTER:
116 case Character.LOWERCASE_LETTER:
117 case Character.TITLECASE_LETTER:
118 case Character.MODIFIER_LETTER:
119 case Character.OTHER_LETTER:
120 case Character.LETTER_NUMBER:
121 return true;
122 default:
123 return false;
124 }
125 }
126
127 public static void addLinks(Editable body, boolean includeGeo) {
128 Linkify.addLinks(body, Patterns.XMPP_PATTERN, "xmpp", XMPPURI_MATCH_FILTER, null);
129 Linkify.addLinks(body, Patterns.AUTOLINK_WEB_URL, "http", WEBURL_MATCH_FILTER, WEBURL_TRANSFORM_FILTER);
130 if (includeGeo) {
131 Linkify.addLinks(body, GeoHelper.GEO_URI, "geo");
132 }
133 FixedURLSpan.fix(body);
134 }
135
136 public static void addLinks(Editable body, Account account, Jid context) {
137 addLinks(body, true);
138 Roster roster = account.getRoster();
139 for (final URLSpan urlspan : body.getSpans(0, body.length() - 1, URLSpan.class)) {
140 Uri uri = Uri.parse(urlspan.getURL());
141 if ("xmpp".equals(uri.getScheme())) {
142 if (!body.subSequence(body.getSpanStart(urlspan), body.getSpanEnd(urlspan)).toString().startsWith("xmpp:")) {
143 // Already customized
144 continue;
145 }
146
147 try {
148 XmppUri xmppUri = new XmppUri(uri);
149 Jid jid = xmppUri.getJid();
150 String display = xmppUri.toString();
151 if (jid.asBareJid().equals(context) && xmppUri.isAction("message") && xmppUri.getBody() != null) {
152 display = xmppUri.getBody();
153 } else if (jid.asBareJid().equals(context)) {
154 display = xmppUri.parameterString();
155 } else {
156 ListItem item = account.getBookmark(jid);
157 if (item == null) item = roster.getContact(jid);
158 display = item.getDisplayName() + xmppUri.parameterString();
159 }
160 body.replace(
161 body.getSpanStart(urlspan),
162 body.getSpanEnd(urlspan),
163 display
164 );
165 } catch (final IllegalArgumentException e) { /* bad JID */ }
166 }
167 }
168 }
169
170 public static List<String> extractLinks(final Editable body) {
171 MyLinkify.addLinks(body, false);
172 final Collection<URLSpan> spans =
173 Arrays.asList(body.getSpans(0, body.length() - 1, URLSpan.class));
174 final Collection<UrlWrapper> urlWrappers =
175 Collections2.filter(
176 Collections2.transform(
177 spans,
178 s ->
179 s == null
180 ? null
181 : new UrlWrapper(body.getSpanStart(s), s.getURL())),
182 uw -> uw != null);
183 List<UrlWrapper> sorted = ImmutableList.sortedCopyOf(
184 (a, b) -> Integer.compare(a.position, b.position), urlWrappers);
185 return Lists.transform(sorted, uw -> uw.url);
186
187 }
188
189 private static class UrlWrapper {
190 private final int position;
191 private final String url;
192
193 private UrlWrapper(int position, String url) {
194 this.position = position;
195 this.url = url;
196 }
197 }
198}