Linkify.java

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