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    }
 83
 84    public static void addLinks(final Editable body, final Account account, final Jid context) {
 85        addLinks(body);
 86        final var roster = account.getRoster();
 87        urlspan:
 88        for (final URLSpan urlspan : body.getSpans(0, body.length() - 1, URLSpan.class)) {
 89            final var start = body.getSpanStart(urlspan);
 90            if (start < 0) continue;
 91            for (final var span : body.getSpans(start, start, Object.class))  {
 92                // instanceof TypefaceSpan is to block in XHTML code blocks. Probably a bit heavy-handed but works for now
 93                if ((body.getSpanFlags(span) & Spanned.SPAN_USER) >> Spanned.SPAN_USER_SHIFT == StylingHelper.NOLINKIFY || span instanceof TypefaceSpan) {
 94                    body.removeSpan(urlspan);
 95                    continue urlspan;
 96                }
 97            }
 98            Uri uri = Uri.parse(urlspan.getURL());
 99            if ("xmpp".equals(uri.getScheme())) {
100                try {
101                    if (!body.subSequence(body.getSpanStart(urlspan), body.getSpanEnd(urlspan)).toString().startsWith("xmpp:")) {
102                        // Already customized
103                        continue;
104                    }
105
106                    XmppUri xmppUri = new XmppUri(uri);
107                    Jid jid = xmppUri.getJid();
108                    String display = xmppUri.toString();
109                    if (jid.asBareJid().equals(context) && xmppUri.isAction("message") && xmppUri.getBody() != null) {
110                        display = xmppUri.getBody();
111                    } else if (jid.asBareJid().equals(context) && xmppUri.parameterString().length() > 0) {
112                        display = xmppUri.parameterString();
113                    } else {
114                        ListItem item = account.getBookmark(jid);
115                        if (item == null) item = roster.getContact(jid);
116                        display = item.getDisplayName() + xmppUri.displayParameterString();
117                    }
118                    body.replace(
119                        body.getSpanStart(urlspan),
120                        body.getSpanEnd(urlspan),
121                        display
122                    );
123                } catch (final IllegalArgumentException | IndexOutOfBoundsException e) { /* bad JID or span gone */ }
124            }
125        }
126    }
127
128    public static List<MiniUri> getLinks(final String body) {
129        final var builder = new ImmutableList.Builder<MiniUri>();
130        final var matcher = Patterns.URI_GENERIC.matcher(body);
131        while (matcher.find()) {
132            final var match = matcher.group();
133            if (isPassAdditionalValidation(match)) {
134                builder.add(new MiniUri(match));
135            }
136        }
137        return builder.build();
138    }
139
140	public static List<String> extractLinks(final Editable body) {
141        addLinks(body);
142        final var spans =
143                Arrays.asList(body.getSpans(0, body.length() - 1, URLSpan.class));
144        final var urlWrappers =
145                Collections2.filter(
146                        Collections2.transform(
147                                spans,
148                                s ->
149                                        s == null
150                                                ? null
151                                                : new UrlWrapper(body.getSpanStart(s), s.getURL())),
152                        uw -> uw != null);
153        List<UrlWrapper> sorted = ImmutableList.sortedCopyOf(
154                (a, b) -> Integer.compare(a.position, b.position), urlWrappers);
155        return Lists.transform(sorted, uw -> uw.url);
156
157    }
158
159    private static class UrlWrapper {
160        private final int position;
161        private final String url;
162
163        private UrlWrapper(int position, String url) {
164            this.position = position;
165            this.url = url;
166        }
167    }
168}