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.net.Uri;
 33import android.os.Build;
 34import android.text.Editable;
 35import android.text.style.URLSpan;
 36import android.text.util.Linkify;
 37
 38import java.util.Locale;
 39
 40import eu.siacs.conversations.entities.Account;
 41import eu.siacs.conversations.entities.ListItem;
 42import eu.siacs.conversations.entities.Roster;
 43import eu.siacs.conversations.ui.text.FixedURLSpan;
 44import eu.siacs.conversations.utils.GeoHelper;
 45import eu.siacs.conversations.utils.Patterns;
 46import eu.siacs.conversations.utils.XmppUri;
 47import eu.siacs.conversations.xmpp.Jid;
 48
 49public class MyLinkify {
 50
 51    private static final Linkify.TransformFilter WEBURL_TRANSFORM_FILTER = (matcher, url) -> {
 52        if (url == null) {
 53            return null;
 54        }
 55        final String lcUrl = url.toLowerCase(Locale.US);
 56        if (lcUrl.startsWith("http://") || lcUrl.startsWith("https://")) {
 57            return removeTrailingBracket(url);
 58        } else {
 59            return "http://" + removeTrailingBracket(url);
 60        }
 61    };
 62
 63    private static String removeTrailingBracket(final String url) {
 64        int numOpenBrackets = 0;
 65        for (char c : url.toCharArray()) {
 66            if (c == '(') {
 67                ++numOpenBrackets;
 68            } else if (c == ')') {
 69                --numOpenBrackets;
 70            }
 71        }
 72        if (numOpenBrackets != 0 && url.charAt(url.length() - 1) == ')') {
 73            return url.substring(0, url.length() - 1);
 74        } else {
 75            return url;
 76        }
 77    }
 78
 79    private static final Linkify.MatchFilter WEBURL_MATCH_FILTER = (cs, start, end) -> {
 80        if (start > 0) {
 81            if (cs.charAt(start - 1) == '@' || cs.charAt(start - 1) == '.'
 82                    || cs.subSequence(Math.max(0, start - 3), start).equals("://")) {
 83                return false;
 84            }
 85        }
 86
 87        if (end < cs.length()) {
 88            // Reject strings that were probably matched only because they contain a dot followed by
 89            // by some known TLD (see also comment for WORD_BOUNDARY in Patterns.java)
 90            return !isAlphabetic(cs.charAt(end - 1)) || !isAlphabetic(cs.charAt(end));
 91        }
 92
 93        return true;
 94    };
 95
 96    private static final Linkify.MatchFilter XMPPURI_MATCH_FILTER = (s, start, end) -> {
 97        XmppUri uri = new XmppUri(s.subSequence(start, end).toString());
 98        return uri.isValidJid();
 99    };
100
101    private static boolean isAlphabetic(final int code) {
102        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
103            return Character.isAlphabetic(code);
104        }
105
106        switch (Character.getType(code)) {
107            case Character.UPPERCASE_LETTER:
108            case Character.LOWERCASE_LETTER:
109            case Character.TITLECASE_LETTER:
110            case Character.MODIFIER_LETTER:
111            case Character.OTHER_LETTER:
112            case Character.LETTER_NUMBER:
113                return true;
114            default:
115                return false;
116        }
117    }
118
119    public static void addLinks(Editable body, boolean includeGeo) {
120        Linkify.addLinks(body, Patterns.XMPP_PATTERN, "xmpp", XMPPURI_MATCH_FILTER, null);
121        Linkify.addLinks(body, Patterns.AUTOLINK_WEB_URL, "http", WEBURL_MATCH_FILTER, WEBURL_TRANSFORM_FILTER);
122        if (includeGeo) {
123            Linkify.addLinks(body, GeoHelper.GEO_URI, "geo");
124        }
125        FixedURLSpan.fix(body);
126    }
127
128    public static void addLinks(Editable body, Account account) {
129        addLinks(body, true);
130        Roster roster = account.getRoster();
131        for (final URLSpan urlspan : body.getSpans(0, body.length() - 1, URLSpan.class)) {
132            Uri uri = Uri.parse(urlspan.getURL());
133            if ("xmpp".equals(uri.getScheme())) {
134                try {
135                    Jid jid = new XmppUri(uri).getJid();
136                    ListItem item = account.getBookmark(jid);
137                    if (item == null) item = roster.getContact(jid);
138                    body.replace(
139                        body.getSpanStart(urlspan),
140                        body.getSpanEnd(urlspan),
141                        item.getDisplayName()
142                    );
143                } catch (final IllegalArgumentException e) { /* bad JID */ }
144            }
145        }
146    }
147}