MyLinkify.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 eu.siacs.conversations.ui.util;
 31
 32import android.os.Build;
 33import android.text.Editable;
 34import android.text.style.URLSpan;
 35import android.text.util.Linkify;
 36
 37import com.google.common.collect.Collections2;
 38import com.google.common.collect.ImmutableList;
 39import com.google.common.collect.Lists;
 40
 41import java.util.Arrays;
 42import java.util.Collection;
 43import java.util.List;
 44import java.util.Locale;
 45import java.util.Objects;
 46
 47import eu.siacs.conversations.ui.text.FixedURLSpan;
 48import eu.siacs.conversations.utils.GeoHelper;
 49import eu.siacs.conversations.utils.Patterns;
 50import eu.siacs.conversations.utils.XmppUri;
 51
 52public class MyLinkify {
 53
 54    private static final Linkify.TransformFilter WEBURL_TRANSFORM_FILTER = (matcher, url) -> {
 55        if (url == null) {
 56            return null;
 57        }
 58        final String lcUrl = url.toLowerCase(Locale.US);
 59        if (lcUrl.startsWith("http://") || lcUrl.startsWith("https://")) {
 60            return removeTrailingBracket(url);
 61        } else {
 62            return "http://" + removeTrailingBracket(url);
 63        }
 64    };
 65
 66    private static String removeTrailingBracket(final String url) {
 67        int numOpenBrackets = 0;
 68        for (char c : url.toCharArray()) {
 69            if (c == '(') {
 70                ++numOpenBrackets;
 71            } else if (c == ')') {
 72                --numOpenBrackets;
 73            }
 74        }
 75        if (numOpenBrackets != 0 && url.charAt(url.length() - 1) == ')') {
 76            return url.substring(0, url.length() - 1);
 77        } else {
 78            return url;
 79        }
 80    }
 81
 82    private static final Linkify.MatchFilter WEBURL_MATCH_FILTER = (cs, start, end) -> {
 83        if (start > 0) {
 84            if (cs.charAt(start - 1) == '@' || cs.charAt(start - 1) == '.'
 85                    || cs.subSequence(Math.max(0, start - 3), start).equals("://")) {
 86                return false;
 87            }
 88        }
 89
 90        if (end < cs.length()) {
 91            // Reject strings that were probably matched only because they contain a dot followed by
 92            // by some known TLD (see also comment for WORD_BOUNDARY in Patterns.java)
 93            return !isAlphabetic(cs.charAt(end - 1)) || !isAlphabetic(cs.charAt(end));
 94        }
 95
 96        return true;
 97    };
 98
 99    private static final Linkify.MatchFilter XMPPURI_MATCH_FILTER = (s, start, end) -> {
100        XmppUri uri = new XmppUri(s.subSequence(start, end).toString());
101        return uri.isValidJid();
102    };
103
104    private static boolean isAlphabetic(final int code) {
105        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
106            return Character.isAlphabetic(code);
107        }
108
109        switch (Character.getType(code)) {
110            case Character.UPPERCASE_LETTER:
111            case Character.LOWERCASE_LETTER:
112            case Character.TITLECASE_LETTER:
113            case Character.MODIFIER_LETTER:
114            case Character.OTHER_LETTER:
115            case Character.LETTER_NUMBER:
116                return true;
117            default:
118                return false;
119        }
120    }
121
122    public static void addLinks(Editable body, boolean includeGeo) {
123        Linkify.addLinks(body, Patterns.XMPP_PATTERN, "xmpp", XMPPURI_MATCH_FILTER, null);
124        Linkify.addLinks(body, Patterns.AUTOLINK_WEB_URL, "http", WEBURL_MATCH_FILTER, WEBURL_TRANSFORM_FILTER);
125        if (includeGeo) {
126            Linkify.addLinks(body, GeoHelper.GEO_URI, "geo");
127        }
128        FixedURLSpan.fix(body);
129    }
130
131    public static List<String> extractLinks(final Editable body) {
132        MyLinkify.addLinks(body, false);
133        final Collection<URLSpan> spans =
134                Arrays.asList(body.getSpans(0, body.length() - 1, URLSpan.class));
135        final Collection<UrlWrapper> urlWrappers =
136                Collections2.filter(
137                        Collections2.transform(
138                                spans,
139                                s ->
140                                        s == null
141                                                ? null
142                                                : new UrlWrapper(body.getSpanStart(s), s.getURL())),
143                        uw -> uw != null);
144        List<UrlWrapper> sorted = ImmutableList.sortedCopyOf(
145                (a, b) -> Integer.compare(a.position, b.position), urlWrappers);
146        return Lists.transform(sorted, uw -> uw.url);
147
148    }
149
150    private static class UrlWrapper {
151        private final int position;
152        private final String url;
153
154        private UrlWrapper(int position, String url) {
155            this.position = position;
156            this.url = url;
157        }
158    }
159}