Example usage for twitter4j Status getMediaEntities

List of usage examples for twitter4j Status getMediaEntities

Introduction

In this page you can find the example usage for twitter4j Status getMediaEntities.

Prototype

MediaEntity[] getMediaEntities();

Source Link

Document

Returns an array of MediaEntities if medias are available in the tweet.

Usage

From source file:fr.ybonnel.modele.TweetPhoto.java

License:Apache License

public static Stream<TweetPhoto> fromStatus(Status status) {
    String user = status.getUser().getScreenName();
    String avatar = status.getUser().getBiggerProfileImageURL();
    String text = status.getText();
    return Arrays.stream(status.getMediaEntities()).map(MediaEntity::getMediaURL)
            .map(url -> new TweetPhoto(user, avatar, url, text));
}

From source file:h2weibo.Twitter2Weibo.java

License:Open Source License

public void syncTwitter(String userId) {
    T2WUser user = helper.findOneByUser(userId);

    weibo.setToken(user.getToken(), user.getTokenSecret());

    Twitter twitter = new TwitterFactory().getInstance();
    if (user.getTwitterToken() != null) {
        twitter.setOAuthAccessToken(new AccessToken(user.getTwitterToken(), user.getTwitterTokenSecret()));
        log.debug(String.format("Using OAuth for %s", user.getUserId()));
    }/* w  w w. j a v a 2 s .  c o  m*/

    StatusFilters filters = new StatusFilters();
    filters.use(new NoSyncFilter()); // should be used first
    filters.use(new TcoStatusFilter()).use(new URLStatusFilter()).use(new TagStatusFilter())
            .use(new FlickrImageFilter());

    NoMentionFilter mentionFilter = new NoMentionFilter();
    UserMappingFilter mappingFilter = new UserMappingFilter(helper);

    if (!user.ready()) {
        log.debug(String.format("Skipping @%s ...", user.getUserId()));
        return;
    }

    // gets Twitter instance with default credentials
    String screenName = user.getUserId();
    long latestId = user.getLatestId();

    log.debug(String.format("Checking @%s's timeline, latest ID = %d.", userId, latestId));

    try {
        if (latestId == 0) {
            List<Status> statuses = twitter.getUserTimeline(screenName);
            if (statuses.size() > 0) {
                user.setLatestId(statuses.get(0).getId()); // Record latestId, and sync next time
            }
            log.info(String.format("First time use for @%s. Set latest ID to %d.", userId, latestId));
        } else {
            Paging paging = new Paging(latestId);
            List<Status> statuses = twitter.getUserTimeline(screenName, paging);

            // sync from the oldest one
            for (int i = statuses.size() - 1; i >= 0; i--) {
                Status status = statuses.get(i);

                if (status.getId() < user.getLatestId())
                    continue; // safe keeper

                String name = status.getUser().getScreenName();
                String statusText = status.getText();
                log.info(String.format("%s - %s", name, statusText));
                try {
                    if (status.isRetweet()) {
                        if (user.isDropRetweets()) {
                            user.setLatestId(status.getId());
                            log.debug("Skipped " + statusText + " because status is a retweet.");
                            continue;
                        } else {
                            filters.remove(mentionFilter);
                            filters.use(mappingFilter);
                        }
                    } else {
                        if (user.isDropMentions()) {
                            filters.remove(mappingFilter);
                            filters.use(mentionFilter);
                        } else {
                            filters.remove(mentionFilter);
                            filters.use(mappingFilter);
                        }
                    }

                    statusText = filters.filter(statusText);
                    if (statusText == null) {
                        user.setLatestId(status.getId());
                        log.info(String.format("Skipped %s because of the filter.", statusText));
                        continue;
                    }

                    if (!user.isNoImage()) {
                        // add twitter images to status text
                        MediaEntity[] mediaEntities = status.getMediaEntities();
                        if (mediaEntities != null) {
                            for (MediaEntity entity : mediaEntities) {
                                statusText += " " + entity.getMediaURL();
                            }
                            log.info("with media url: " + statusText);
                        }

                        StatusImageExtractor ex = new StatusImageExtractor();
                        StringBuffer buf = new StringBuffer(statusText);
                        byte[] image = ex.extract(buf);
                        if (image != null) {
                            user.setLatestId(status.getId());
                            try {
                                statusText = buf.toString(); // with image urls removed
                                weibo.uploadStatus(statusText, new ImageItem(image));
                                log.info(String.format("@%s - %s sent with image.", name, statusText));
                            } catch (WeiboException e) {
                                log.error("Faile to update image.", e);
                            }
                            continue;
                        }
                    }

                    GeoLocation location = status.getGeoLocation();
                    if (user.isWithGeo() && location != null) {
                        weibo.updateStatus(statusText, location.getLatitude(), location.getLongitude());
                        log.info(String.format("@%s - %s sent with geo locations.", name, statusText));
                    } else {
                        weibo.updateStatus(statusText);
                        log.info(String.format("@%s - %s sent.", name, statusText));
                    }
                } catch (WeiboException e) {
                    if (e.getStatusCode() != 400) { // resending same tweet
                        log.error("Failed to update Weibo", e);
                        break;
                    } else {
                        log.error("Sending same message", e);
                    }
                }
                log.info(String.format("Sent: by %s - %s", name, statusText));
                user.setLatestId(status.getId());
            }
        }
        helper.saveUser(user);
    } catch (Exception e) {
        if (!(e instanceof TwitterException)) {
            log.error("Failed to update.", e);
        }
    }
}

From source file:info.usbo.skypetwitter.Run.java

License:Apache License

public static void main(String[] args) throws SkypeException, IOException {
    System.out.println("Working Directory = " + System.getProperty("user.dir"));
    Properties props = new Properties();
    loadProperties(props, "twitter4j.properties");
    loadProperties(props, "skype.properties");
    loadProperties(props, "app.properties");
    String chat_group_id = props.getProperty("skype.chat_group_id");
    String twitter_user_id = props.getProperty("twitter.user");
    data_dir = props.getProperty("data.dir");
    Integer twitter_timeout = Integer.parseInt(props.getProperty("twitter.timeout"));
    System.out.println("Twitter user: " + twitter_user_id);
    System.out.println("Twitter timeout: " + twitter_timeout);
    if ("".equals(twitter_user_id)) {
        return;// w w  w.ja  va2  s. c o  m
    }
    if (load_file() == 0) {
        System.out.println("File not found");
        return;
    }
    while (true) {
        bChanged = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
        System.out.println("Looking at " + sdf.format(Calendar.getInstance().getTime()));
        Chat ch = Skype.chat(chat_group_id);
        Twitter twitter = new TwitterFactory().getInstance();
        try {
            List<Status> statuses;
            statuses = twitter.getUserTimeline(twitter_user_id);
            String sText;
            for (Status status : statuses) {
                Date d = status.getCreatedAt();
                //  ?
                Calendar cal = Calendar.getInstance();
                cal.setTime(d);
                cal.add(Calendar.HOUR_OF_DAY, 7);
                d = cal.getTime();
                sText = "@" + status.getUser().getScreenName() + "  " + sdf.format(d)
                        + " ( https://twitter.com/" + twitter_user_id + "/status/" + status.getId() + " ): \r\n"
                        + status.getText() + "\r\n***";
                for (URLEntity e : status.getURLEntities()) {
                    sText = sText.replaceAll(e.getURL(), e.getExpandedURL());
                }
                for (MediaEntity e : status.getMediaEntities()) {
                    sText = sText.replaceAll(e.getURL(), e.getMediaURL());
                }
                if (twitter_ids.indexOf(status.getId()) == -1) {
                    System.out.println(sText);
                    ch.send(sText);
                    twitter_ids.add(status.getId());
                    bChanged = 1;
                }
            }
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to get timeline: " + te.getMessage());
            // System.exit(-1);
        } catch (SkypeException ex) {
            ex.printStackTrace();
            System.out.println("Failed to send message: " + ex.getMessage());
        }

        // VK
        try {
            vk();
            for (VK v : vk) {
                if (vk_ids.indexOf(v.getId()) == -1) {
                    Date d = v.getDate();
                    //  ?
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(d);
                    cal.add(Calendar.HOUR_OF_DAY, 7);
                    d = cal.getTime();
                    String sText = "@Depersonilized (VK)  " + sdf.format(d)
                            + " ( http://vk.com/Depersonilized?w=wall-0_" + v.getId() + " ): \r\n"
                            + v.getText();
                    if (!"".equals(v.getAttachment())) {
                        sText += "\r\n" + v.getAttachment();
                    }
                    sText += "\r\n***";
                    System.out.println(sText);
                    ch.send(sText);
                    vk_ids.add(v.getId());
                    bChanged = 1;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("Failed to get vk: " + e.getMessage());
            // System.exit(-1);
        } catch (SkypeException ex) {
            ex.printStackTrace();
            System.out.println("Failed to send message: " + ex.getMessage());
        }
        if (bChanged == 1) {
            save_file();
        }
        try {
            Thread.sleep(1000 * 60 * twitter_timeout);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
            System.out.println("Failed to sleep: " + ex.getMessage());
        }
    }
}

From source file:io.rakam.datasource.twitter.TweetProcessor.java

License:Apache License

@Override
public void onStatus(Status status) {
    Map<String, Object> map = new HashMap<>();

    GeoLocation geoLocation = status.getGeoLocation();
    if (geoLocation != null) {
        map.put("latitude", geoLocation.getLatitude());
        map.put("longitude", geoLocation.getLongitude());
    }//from  w  w  w  .  j  a  v a 2 s.  com

    map.put("_time", status.getCreatedAt().getTime());
    Place place = status.getPlace();
    if (place != null) {
        map.put("country_code", place.getCountryCode());
        map.put("place", place.getName());
        map.put("place_type", place.getPlaceType());
        map.put("place_id", place.getId());
    }

    User user = status.getUser();
    map.put("_user", user.getId());
    map.put("user_lang", user.getLang());
    map.put("user_created", user.getCreatedAt());
    map.put("user_followers", user.getFollowersCount());
    map.put("user_status_count", user.getStatusesCount());
    map.put("user_verified", user.isVerified());

    map.put("id", status.getId());
    map.put("is_reply", status.getInReplyToUserId() > -1);
    map.put("is_retweet", status.isRetweet());
    map.put("has_media", status.getMediaEntities().length > 0);
    map.put("urls",
            Arrays.stream(status.getURLEntities()).map(URLEntity::getText).collect(Collectors.toList()));
    map.put("hashtags", Arrays.stream(status.getHashtagEntities()).map(HashtagEntity::getText)
            .collect(Collectors.toList()));
    map.put("user_mentions", Arrays.stream(status.getUserMentionEntities()).map(UserMentionEntity::getText)
            .collect(Collectors.toList()));
    map.put("language", "und".equals(status.getLang()) ? null : status.getLang());
    map.put("is_positive", classifier.isPositive(status.getText()));

    Event event = new Event().properties(map).collection(collection);
    buffer.add(event);

    commitIfNecessary();
}

From source file:moderation.Moderate.java

public List getTwitterpost() {

    List posts = new ArrayList();
    try {/*from  w w w.ja v  a 2  s.  c o  m*/
        List savedpost = getSavedList(album_id);
        String tagname = this.hash;
        Twitter twitter = setting.TwitterToken.twitterObject();
        Query query = new Query(tagname);
        query.setCount(50);
        QueryResult result;
        result = twitter.search(query);
        List<Status> tweets = result.getTweets();
        for (Status tweet : tweets) {
            System.out.println("\n\n\n" + tweet);
            PostModel post = new PostModel();
            post.setAlbum_id(this.album_id);
            if (savedpost.contains(tweet.getId()))
                post.setStatus("old");
            else
                post.setStatus("new");
            post.setPost_id("" + tweet.getId());
            post.setSender_name(URLEncoder.encode(tweet.getUser().getScreenName(), "UTF-8"));
            post.setCaption_text(URLEncoder.encode(tweet.getText(), "UTF-8"));
            post.setSender_pic(tweet.getUser().getProfileImageURL());
            post.setSender_id("" + tweet.getUser().getId());

            for (MediaEntity mediaEntity : tweet.getMediaEntities()) {
                post.setImage_standard(mediaEntity.getMediaURL());
                post.setImage_low(mediaEntity.getMediaURL());
            }
            post.setPost_time(tweet.getCreatedAt().toString());
            post.setType("twitter_post");
            post.setLink(null);
            post.setParam("post_id=" + post.getPost_id() + "&album_id=" + post.getAlbum_id() + "&type="
                    + post.getType() + "&post_time=" + post.getPost_time() + "&link=" + post.getLink()
                    + "&pic_low=" + post.getImage_low() + "&pic_standard=" + post.getImage_standard()
                    + "&post_message=" + post.getCaption_text() + "&sender_name=" + post.getSender_name()
                    + "&sender_id=" + post.getSender_id() + "&sender_pic=" + post.getSender_pic());

            posts.add(post);

        }
        this.twitternext = result.nextQuery();

    } catch (Exception e) {
        System.err.println("Exception occure in getTwitter " + e);
    }

    return posts;
}

From source file:net.lacolaco.smileessence.view.dialog.StatusDetailDialogFragment.java

License:Open Source License

private MediaEntity[] getMediaEntities(Status status) {
    if (status.getExtendedMediaEntities().length == 0) {
        return status.getMediaEntities();
    } else {//from   w w  w  .  j a v  a  2 s .  c  om
        return status.getExtendedMediaEntities();
    }
}

From source file:net.lacolaco.smileessence.view.dialog.StatusMenuDialogFragment.java

License:Open Source License

public void addBottomCommands(Activity activity, Status status, Account account, ArrayList<Command> commands) {
    commands.add(new CommandSaveAsTemplate(activity, TwitterUtils.getOriginalStatusText(status)));
    //User/*w  w w  .j  ava  2  s  . c  om*/
    for (String screenName : TwitterUtils.getScreenNames(status, null)) {
        commands.add(new CommandOpenUserDetail(activity, screenName, account));
    }
    for (Command command : getHashtagCommands(activity, status)) {
        commands.add(command);
    }
    // Media
    if (status.getURLEntities() != null) {
        for (URLEntity urlEntity : status.getURLEntities()) {
            commands.add(new CommandOpenURL(activity, urlEntity.getExpandedURL()));
        }
    }
    for (MediaEntity mediaEntity : status.getExtendedMediaEntities().length == 0 ? status.getMediaEntities()
            : status.getExtendedMediaEntities()) {
        commands.add(new CommandOpenURL(activity, mediaEntity.getMediaURL()));
    }
}

From source file:net.lacolaco.smileessence.viewmodel.StatusViewModel.java

License:Open Source License

public StatusViewModel(Status status, Account account) {
    if (status.isRetweet()) {
        retweetedStatus = new StatusViewModel(status.getRetweetedStatus(), account);
    }//from  w w  w . ja va2  s .co  m
    id = status.getId();
    text = TwitterUtils.replaceURLEntities(status.getText(), status.getURLEntities(), false);
    createdAt = status.getCreatedAt();
    source = status.getSource();
    mentions = status.getUserMentionEntities();
    hashtags = status.getHashtagEntities();
    media = status.getMediaEntities();
    urls = status.getURLEntities();
    symbols = status.getSymbolEntities();
    User user = status.getUser();
    UserCache.getInstance().put(user);
    userID = user.getId();
    screenName = user.getScreenName();
    name = user.getName();
    iconURL = user.getProfileImageURLHttps();
    isProtected = user.isProtected();
    setMention(isMention(account.screenName));
    setMyStatus(isMyStatus(account.userID));
    setRetweetOfMe(isRetweetOfMe(account.userID));
}

From source file:net.nokok.twitduke.core.twitter.StatusParser.java

License:Open Source License

/**
 * ???????/*from  www.  j  a  v a 2s .  com*/
 *
 * @param status 
 *
 * @return ?
 */
public List<MediaEntity> createMediaEntityList(Status status) {
    return Stream.of(status.getMediaEntities()).collect(Collectors.toCollection(ArrayList::new));
}

From source file:nl.isaac.dotcms.twitter.pojo.CustomStatus.java

License:Creative Commons License

public CustomStatus(Status status) {
    this.createdAt = status.getCreatedAt();
    this.id = status.getId();
    this.id_str = String.valueOf(status.getId());
    this.text = status.getText();
    this.source = status.getSource();
    this.isTruncated = status.isTruncated();
    this.inReplyToStatusId = status.getInReplyToStatusId();
    this.inReplyToUserId = status.getInReplyToUserId();
    this.isFavorited = status.isFavorited();
    this.inReplyToScreenName = status.getInReplyToScreenName();
    this.geoLocation = status.getGeoLocation();
    this.place = status.getPlace();
    this.retweetCount = status.getRetweetCount();
    this.isPossiblySensitive = status.isPossiblySensitive();

    this.contributorsIDs = status.getContributors();

    this.retweetedStatus = status.getRetweetedStatus();
    this.userMentionEntities = status.getUserMentionEntities();
    this.urlEntities = status.getURLEntities();
    this.hashtagEntities = status.getHashtagEntities();
    this.mediaEntities = status.getMediaEntities();
    this.currentUserRetweetId = status.getCurrentUserRetweetId();

    this.isRetweet = status.isRetweet();
    this.isRetweetedByMe = status.isRetweetedByMe();

    this.rateLimitStatus = status.getRateLimitStatus();
    this.accessLevel = status.getAccessLevel();
    this.user = status.getUser();
}