Search in sources :

Example 1 with UserMentionEntity

use of twitter4j.UserMentionEntity in project twicalico by moko256.

the class ShowTweetActivity method updateView.

private void updateView(Status item) {
    TextView tweetIsReply = findViewById(R.id.tweet_show_is_reply_text);
    long replyTweetId = item.getInReplyToStatusId();
    if (replyTweetId != -1) {
        tweetIsReply.setVisibility(VISIBLE);
        tweetIsReply.setOnClickListener(v -> startActivity(getIntent(this, replyTweetId)));
    } else {
        tweetIsReply.setVisibility(GONE);
    }
    StatusView statusView = new StatusView(this);
    statusView.setStatus(item);
    ViewGroup cview = (ViewGroup) statusView.getChildAt(0);
    ViewGroup sview = (ViewGroup) cview.getChildAt(0);
    cview.removeView(sview);
    FrameLayout statusViewFrame = findViewById(R.id.tweet_show_tweet);
    statusViewFrame.removeAllViews();
    statusViewFrame.addView(sview);
    ((TextView) findViewById(R.id.tweet_show_timestamp)).setText(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(item.getCreatedAt()));
    TextView viaText = findViewById(R.id.tweet_show_via);
    viaText.setText(TwitterStringUtils.convertUrlSpanToCustomTabs(Html.fromHtml("via:" + item.getSource()), this));
    viaText.setMovementMethod(new LinkMovementMethod());
    AppCompatEditText replyText = findViewById(R.id.tweet_show_tweet_reply_text);
    AppCompatButton replyButton = findViewById(R.id.tweet_show_tweet_reply_button);
    UserMentionEntity[] users = item.getUserMentionEntities();
    replyText.setText(TwitterStringUtils.convertToReplyTopString(GlobalApplication.userCache.get(GlobalApplication.userId).getScreenName(), item.getUser().getScreenName(), users));
    replyButton.setOnClickListener(v -> {
        replyButton.setEnabled(false);
        PostTweetModel model = PostTweetModelCreator.getInstance(GlobalApplication.twitter, getContentResolver());
        model.setTweetText(replyText.getText().toString());
        model.setInReplyToStatusId(item.getId());
        subscriptions.add(model.postTweet().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(it -> {
            replyText.setText(TwitterStringUtils.convertToReplyTopString(GlobalApplication.userCache.get(GlobalApplication.userId).getScreenName(), item.getUser().getScreenName(), users));
            replyButton.setEnabled(true);
            Toast.makeText(ShowTweetActivity.this, R.string.succeeded, Toast.LENGTH_SHORT).show();
        }, e -> {
            e.printStackTrace();
            Toast.makeText(ShowTweetActivity.this, R.string.error_occurred, Toast.LENGTH_SHORT).show();
            replyButton.setEnabled(true);
        }));
    });
}
Also used : Context(android.content.Context) Bundle(android.os.Bundle) PostTweetModel(com.github.moko256.twicalico.model.base.PostTweetModel) FrameLayout(android.widget.FrameLayout) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) Intent(android.content.Intent) LinkMovementMethod(android.text.method.LinkMovementMethod) TwitterStringUtils(com.github.moko256.twicalico.text.TwitterStringUtils) UserMentionEntity(twitter4j.UserMentionEntity) MenuItem(android.view.MenuItem) AppCompatButton(android.support.v7.widget.AppCompatButton) Single(rx.Single) AppCustomTabsKt(com.github.moko256.twicalico.intent.AppCustomTabsKt) Toast(android.widget.Toast) Menu(android.view.Menu) Schedulers(rx.schedulers.Schedulers) TwitterException(twitter4j.TwitterException) VISIBLE(android.view.View.VISIBLE) ActionBar(android.support.v7.app.ActionBar) DateFormat(java.text.DateFormat) SwipeRefreshLayout(android.support.v4.widget.SwipeRefreshLayout) StatusCacheMap(com.github.moko256.twicalico.cacheMap.StatusCacheMap) AppCompatActivity(android.support.v7.app.AppCompatActivity) ViewGroup(android.view.ViewGroup) CompositeSubscription(rx.subscriptions.CompositeSubscription) TextView(android.widget.TextView) GONE(android.view.View.GONE) Html(android.text.Html) Status(twitter4j.Status) PostTweetModelCreator(com.github.moko256.twicalico.model.impl.PostTweetModelCreator) AppCompatEditText(android.support.v7.widget.AppCompatEditText) AppCompatEditText(android.support.v7.widget.AppCompatEditText) UserMentionEntity(twitter4j.UserMentionEntity) ViewGroup(android.view.ViewGroup) FrameLayout(android.widget.FrameLayout) LinkMovementMethod(android.text.method.LinkMovementMethod) TextView(android.widget.TextView) PostTweetModel(com.github.moko256.twicalico.model.base.PostTweetModel) AppCompatButton(android.support.v7.widget.AppCompatButton)

Example 2 with UserMentionEntity

use of twitter4j.UserMentionEntity in project twicalico by moko256.

the class TwitterStringUtils method setLinkedSequenceTo.

@SuppressLint("StaticFieldLeak")
public static void setLinkedSequenceTo(Status item, TextView textView) {
    Context context = textView.getContext();
    String tweet = item.getText();
    if (GlobalApplication.clientType == Type.MASTODON) {
        Spanned html = Html.fromHtml(tweet);
        int length = html.length();
        // Trim unless \n\n made by fromHtml() after post
        if (length == 3 && item.getMediaEntities().length > 0 && html.charAt(0) == ".".charAt(0)) {
            // If post has media only, context of post from Mastodon is "."
            textView.setText("");
            return;
        } else if (length >= 2) {
            html = (Spanned) html.subSequence(0, length - 2);
        }
        SpannableStringBuilder builder = convertUrlSpanToCustomTabs(html, context);
        textView.setText(builder);
        List<Emoji> list = ((StatusCacheMap.CachedStatus) item).getEmojis();
        if (list != null) {
            Matcher matcher = containsEmoji.matcher(builder);
            boolean matches = matcher.matches();
            int imageSize;
            if (matches) {
                imageSize = (int) Math.floor((textView.getTextSize() * 1.15) * 2.0);
            } else {
                imageSize = (int) Math.floor(textView.getTextSize() * 1.15);
            }
            new AsyncTask<Void, Void, Map<String, Drawable>>() {

                @Override
                protected Map<String, Drawable> doInBackground(Void... params) {
                    Map<String, Drawable> map = new ArrayMap<>();
                    GlideRequests glideRequests = GlideApp.with(context);
                    for (Emoji emoji : list) {
                        try {
                            Drawable value = glideRequests.load(emoji.getUrl()).submit().get();
                            value.setBounds(0, 0, imageSize, imageSize);
                            map.put(emoji.getShortCode(), value);
                        } catch (InterruptedException | ExecutionException e) {
                            e.printStackTrace();
                        }
                    }
                    return map;
                }

                @Override
                protected void onPostExecute(Map<String, Drawable> map) {
                    if (TextUtils.equals(builder, textView.getText())) {
                        boolean found = matches || matcher.find();
                        while (found) {
                            String shortCode = matcher.group(1);
                            Drawable drawable = map.get(shortCode);
                            if (drawable != null) {
                                builder.setSpan(new ImageSpan(drawable), matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            }
                            found = matcher.find();
                        }
                        textView.setText(builder);
                    }
                }
            }.execute();
        }
        return;
    }
    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(tweet);
    for (SymbolEntity symbolEntity : item.getSymbolEntities()) {
        spannableStringBuilder.setSpan(new ClickableSpan() {

            @Override
            public void onClick(View view) {
                context.startActivity(SearchResultActivity.getIntent(context, symbolEntity.getText()));
            }
        }, tweet.offsetByCodePoints(0, symbolEntity.getStart()), tweet.offsetByCodePoints(0, symbolEntity.getEnd()), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    }
    for (HashtagEntity hashtagEntity : item.getHashtagEntities()) {
        spannableStringBuilder.setSpan(new ClickableSpan() {

            @Override
            public void onClick(View view) {
                context.startActivity(SearchResultActivity.getIntent(context, "#" + hashtagEntity.getText()));
            }
        }, tweet.offsetByCodePoints(0, hashtagEntity.getStart()), tweet.offsetByCodePoints(0, hashtagEntity.getEnd()), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    }
    for (UserMentionEntity userMentionEntity : item.getUserMentionEntities()) {
        spannableStringBuilder.setSpan(new ClickableSpan() {

            @Override
            public void onClick(View view) {
                context.startActivity(ShowUserActivity.getIntent(context, userMentionEntity.getScreenName()));
            }
        }, tweet.offsetByCodePoints(0, userMentionEntity.getStart()), tweet.offsetByCodePoints(0, userMentionEntity.getEnd()), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    }
    boolean hasMedia = item.getMediaEntities().length > 0;
    List<URLEntity> urlEntities = new ArrayList<>(item.getURLEntities().length + (hasMedia ? 1 : 0));
    urlEntities.addAll(Arrays.asList(item.getURLEntities()));
    if (hasMedia) {
        urlEntities.add(item.getMediaEntities()[0]);
    }
    int tweetLength = tweet.codePointCount(0, tweet.length());
    int sp = 0;
    for (URLEntity entity : urlEntities) {
        String url = entity.getURL();
        String displayUrl = entity.getDisplayURL();
        int urlLength = url.codePointCount(0, url.length());
        int displayUrlLength = displayUrl.codePointCount(0, displayUrl.length());
        if (entity.getStart() <= tweetLength && entity.getEnd() <= tweetLength) {
            int dusp = displayUrlLength - urlLength;
            spannableStringBuilder.replace(tweet.offsetByCodePoints(0, entity.getStart()) + sp, tweet.offsetByCodePoints(0, entity.getEnd()) + sp, displayUrl);
            spannableStringBuilder.setSpan(new ClickableSpan() {

                @Override
                public void onClick(View view) {
                    AppCustomTabsKt.launchChromeCustomTabs(context, entity.getExpandedURL());
                }
            }, tweet.offsetByCodePoints(0, entity.getStart()) + sp, tweet.offsetByCodePoints(0, entity.getEnd()) + sp + dusp, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            sp += dusp;
        }
    }
    textView.setText(spannableStringBuilder);
}
Also used : Matcher(java.util.regex.Matcher) GlideRequests(com.github.moko256.twicalico.GlideRequests) ArrayList(java.util.ArrayList) SymbolEntity(twitter4j.SymbolEntity) Emoji(com.github.moko256.twicalico.entity.Emoji) HashtagEntity(twitter4j.HashtagEntity) Context(android.content.Context) URLEntity(twitter4j.URLEntity) Drawable(android.graphics.drawable.Drawable) Spanned(android.text.Spanned) ClickableSpan(android.text.style.ClickableSpan) View(android.view.View) TextView(android.widget.TextView) SuppressLint(android.annotation.SuppressLint) UserMentionEntity(twitter4j.UserMentionEntity) ArrayMap(android.support.v4.util.ArrayMap) Map(java.util.Map) StatusCacheMap(com.github.moko256.twicalico.cacheMap.StatusCacheMap) SpannableStringBuilder(android.text.SpannableStringBuilder) ImageSpan(android.text.style.ImageSpan) SuppressLint(android.annotation.SuppressLint)

Example 3 with UserMentionEntity

use of twitter4j.UserMentionEntity in project Talon-for-Twitter by klinker24.

the class TweetLinkUtils method getLinksInStatus.

private static String[] getLinksInStatus(String tweetTexts, UserMentionEntity[] users, HashtagEntity[] hashtags, URLEntity[] urls, MediaEntity[] medias) {
    String mUsers = "";
    for (UserMentionEntity name : users) {
        String n = name.getScreenName();
        if (n.length() > 1) {
            mUsers += n + "  ";
        }
    }
    String mHashtags = "";
    for (HashtagEntity hashtagEntity : hashtags) {
        String text = hashtagEntity.getText();
        if (text.length() > 1) {
            mHashtags += text + "  ";
        }
    }
    String expandedUrls = "";
    String compressedUrls = "";
    for (URLEntity entity : urls) {
        String url = entity.getExpandedURL();
        if (url.length() > 1) {
            expandedUrls += url + "  ";
            compressedUrls += entity.getURL() + "  ";
        }
    }
    String mediaExp = "";
    String mediaComp = "";
    String mediaDisplay = "";
    for (MediaEntity e : medias) {
        String url = e.getURL();
        if (url.length() > 1) {
            mediaComp += url + "  ";
            mediaExp += e.getExpandedURL() + "  ";
            mediaDisplay += e.getDisplayURL() + "  ";
        }
    }
    String[] sExpandedUrls;
    String[] sCompressedUrls;
    String[] sMediaExp;
    String[] sMediaComp;
    String[] sMediaDisplay;
    try {
        sCompressedUrls = compressedUrls.split("  ");
    } catch (Exception e) {
        sCompressedUrls = new String[0];
    }
    try {
        sExpandedUrls = expandedUrls.split("  ");
    } catch (Exception e) {
        sExpandedUrls = new String[0];
    }
    try {
        sMediaComp = mediaComp.split("  ");
    } catch (Exception e) {
        sMediaComp = new String[0];
    }
    try {
        sMediaExp = mediaExp.split("  ");
    } catch (Exception e) {
        sMediaExp = new String[0];
    }
    try {
        sMediaDisplay = mediaDisplay.split("  ");
    } catch (Exception e) {
        sMediaDisplay = new String[0];
    }
    String imageUrl = "";
    String otherUrl = "";
    for (int i = 0; i < sCompressedUrls.length; i++) {
        String comp = sCompressedUrls[i];
        String exp = sExpandedUrls[i];
        if (comp.length() > 1 && exp.length() > 1) {
            String str = exp.toLowerCase();
            try {
                String replacement = exp.replace("http://", "").replace("https://", "").replace("www.", "");
                boolean hasCom = replacement.contains(".com");
                replacement = replacement.substring(0, 30) + "...";
                if (hasCom && !replacement.contains(".com")) {
                    // the link was too long...
                    replacement = exp.replace("http://", "").replace("https://", "").replace("www.", "");
                    replacement = replacement.substring(0, replacement.indexOf(".com") + 6) + "...";
                }
                tweetTexts = tweetTexts.replace(comp, replacement);
            } catch (Exception e) {
                tweetTexts = tweetTexts.replace(comp, exp.replace("http://", "").replace("https://", "").replace("www.", ""));
            }
            if (str.contains("instag") && !str.contains("blog.insta")) {
                imageUrl = exp + "media/?size=l";
                otherUrl += exp + "  ";
            } else if (exp.toLowerCase().contains("youtub") && !(str.contains("channel") || str.contains("user") || str.contains("playlist"))) {
                // first get the youtube surfaceView code
                int start = exp.indexOf("v=") + 2;
                int end = exp.length();
                if (exp.substring(start).contains("&")) {
                    end = exp.indexOf("&");
                } else if (exp.substring(start).contains("?")) {
                    end = exp.indexOf("?");
                }
                try {
                    imageUrl = "http://img.youtube.com/vi/" + exp.substring(start, end) + "/hqdefault.jpg";
                } catch (Exception e) {
                    imageUrl = "http://img.youtube.com/vi/" + exp.substring(start, exp.length() - 1) + "/hqdefault.jpg";
                }
                otherUrl += exp + "  ";
            } else if (str.contains("youtu.be")) {
                // first get the youtube surfaceView code
                int start = exp.indexOf(".be/") + 4;
                int end = exp.length();
                if (exp.substring(start).contains("&")) {
                    end = exp.indexOf("&");
                } else if (exp.substring(start).contains("?")) {
                    end = exp.indexOf("?");
                }
                try {
                    imageUrl = "http://img.youtube.com/vi/" + exp.substring(start, end) + "/hqdefault.jpg";
                } catch (Exception e) {
                    imageUrl = "http://img.youtube.com/vi/" + exp.substring(start, exp.length() - 1) + "/hqdefault.jpg";
                }
                otherUrl += exp + "  ";
            } else if (str.contains("twitpic")) {
                int start = exp.indexOf(".com/") + 5;
                imageUrl = "http://twitpic.com/show/full/" + exp.substring(start).replace("/", "");
                otherUrl += exp + "  ";
            } else if (str.contains("i.imgur") && !str.contains("/a/") && !str.contains(".gifv")) {
                int start = exp.indexOf(".com/") + 5;
                imageUrl = "http://i.imgur.com/" + exp.replace("http://i.imgur.com/", "").replace(".jpg", "") + "l.jpg";
                imageUrl = imageUrl.replace("gallery/", "");
                otherUrl += exp + "  ";
            } else if (str.contains("imgur") && !str.contains("/a/") && !str.contains(".gifv")) {
                int start = exp.indexOf(".com/") + 6;
                imageUrl = "http://i.imgur.com/" + exp.replace("http://imgur.com/", "").replace(".jpg", "") + "l.jpg";
                imageUrl = imageUrl.replace("gallery/", "").replace("a/", "");
                otherUrl += exp + "  ";
            } else if (str.contains("pbs.twimg.com")) {
                imageUrl = exp;
                otherUrl += exp + "  ";
            } else if (str.contains("ow.ly/i/")) {
                imageUrl = "http://static.ow.ly/photos/original/" + exp.substring(exp.lastIndexOf("/")).replaceAll("/", "") + ".jpg";
                otherUrl += exp + "  ";
            } else if (str.contains("p.twipple.jp")) {
                imageUrl = "http://p.twipple.jp/show/large/" + exp.replace("p.twipple.jp/", "").replace("http://", "").replace("https://", "").replace("www.", "");
                otherUrl += exp + "  ";
            } else if (str.contains(".jpg") || str.contains(".png")) {
                imageUrl = exp;
                otherUrl += exp + "  ";
            } else if (str.contains("img.ly")) {
                imageUrl = exp.replace("https", "http").replace("http://img.ly/", "http://img.ly/show/large/");
                otherUrl += exp + "  ";
            } else {
                otherUrl += exp + "  ";
            }
        }
    }
    for (int i = 0; i < sMediaComp.length; i++) {
        String comp = sMediaComp[i];
        String exp = sMediaExp[i];
        if (comp.length() > 1 && exp.length() > 1) {
            try {
                String replacement = sMediaDisplay[i].replace("http://", "").replace("https://", "").replace("www.", "");
                boolean hasCom = replacement.contains(".com");
                replacement = replacement.substring(0, 22) + "...";
                if (hasCom && !replacement.contains(".com")) {
                    // the link was too long...
                    replacement = sMediaDisplay[i].replace("http://", "").replace("https://", "").replace("www.", "");
                    replacement = replacement.substring(0, replacement.indexOf(".com") + 6) + "...";
                }
                tweetTexts = tweetTexts.replace(comp, replacement);
            } catch (Exception e) {
                e.printStackTrace();
                tweetTexts = tweetTexts.replace(comp, sMediaDisplay[i].replace("http://", "").replace("https://", "").replace("www.", ""));
            }
            imageUrl = medias[0].getMediaURL();
            for (MediaEntity m : medias) {
                if (m.getType().equals("photo")) {
                    if (!imageUrl.contains(m.getMediaURL())) {
                        imageUrl += " " + m.getMediaURL();
                    }
                }
            }
            otherUrl += sMediaDisplay[i];
        }
    }
    return new String[] { tweetTexts, imageUrl, otherUrl, mHashtags, mUsers };
}
Also used : UserMentionEntity(twitter4j.UserMentionEntity) URLEntity(twitter4j.URLEntity) HashtagEntity(twitter4j.HashtagEntity) MediaEntity(twitter4j.MediaEntity)

Aggregations

UserMentionEntity (twitter4j.UserMentionEntity)3 Context (android.content.Context)2 TextView (android.widget.TextView)2 StatusCacheMap (com.github.moko256.twicalico.cacheMap.StatusCacheMap)2 HashtagEntity (twitter4j.HashtagEntity)2 URLEntity (twitter4j.URLEntity)2 SuppressLint (android.annotation.SuppressLint)1 Intent (android.content.Intent)1 Drawable (android.graphics.drawable.Drawable)1 Bundle (android.os.Bundle)1 ArrayMap (android.support.v4.util.ArrayMap)1 SwipeRefreshLayout (android.support.v4.widget.SwipeRefreshLayout)1 ActionBar (android.support.v7.app.ActionBar)1 AppCompatActivity (android.support.v7.app.AppCompatActivity)1 AppCompatButton (android.support.v7.widget.AppCompatButton)1 AppCompatEditText (android.support.v7.widget.AppCompatEditText)1 Html (android.text.Html)1 SpannableStringBuilder (android.text.SpannableStringBuilder)1 Spanned (android.text.Spanned)1 LinkMovementMethod (android.text.method.LinkMovementMethod)1