Search in sources :

Example 6 with T2WUser

use of h2weibo.model.T2WUser in project twitter-2-weibo by rjyo.

the class Twitter2Weibo method syncTwitter.

public void syncTwitter(String userId) {
    T2WUser user = helper.findOneByUser(userId);
    weibo.setToken(user.getToken());
    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()));
    }
    StatusFilters filters = new StatusFilters();
    // should be used first
    filters.use(new NoSyncFilter());
    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) {
                // Record latestId, and sync next time
                user.setLatestId(statuses.get(0).getId());
            }
            log.info(String.format("First time use for @%s. Set latest ID to %d.", userId, latestId));
        } else {
            Timeline tl = new Timeline();
            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);
                // safe keeper
                if (status.getId() < user.getLatestId())
                    continue;
                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 {
                                // with image urls removed
                                statusText = buf.toString();
                                tl.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) {
                        tl.UpdateStatus(statusText, (float) location.getLatitude(), (float) location.getLongitude(), "");
                        log.info(String.format("@%s - %s sent with geo locations.", name, statusText));
                    } else {
                        tl.UpdateStatus(statusText);
                        log.info(String.format("@%s - %s sent.", name, statusText));
                    }
                } catch (WeiboException e) {
                    if (e.getStatusCode() != 400) {
                        // resending same tweet
                        log.warn("Failed to update Weibo");
                        break;
                    }
                }
                user.setLatestId(status.getId());
            }
        }
        helper.saveUser(user);
    } catch (Exception e) {
        if (!(e instanceof TwitterException)) {
            log.error("Failed to update.", e);
        }
    }
}
Also used : AccessToken(twitter4j.auth.AccessToken) StatusImageExtractor(h2weibo.utils.StatusImageExtractor) WeiboException(weibo4j.model.WeiboException) Timeline(weibo4j.Timeline) WeiboException(weibo4j.model.WeiboException) T2WUser(h2weibo.model.T2WUser) ImageItem(weibo4j.http.ImageItem)

Example 7 with T2WUser

use of h2weibo.model.T2WUser in project twitter-2-weibo by rjyo.

the class SaveOptionsServlet method doPost.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession(false);
    String loginUser = (String) session.getAttribute(Keys.SESSION_LOGIN_USER);
    log.info("Saving options for @" + loginUser);
    DBHelper helper = (DBHelper) request.getAttribute(Keys.REQUEST_DB_HELPER);
    T2WUser user = helper.findOneByUser(loginUser);
    String[] values = request.getParameterValues("options");
    if (values != null) {
        List<String> list = Arrays.asList(values);
        user.setOptions(new HashSet<String>(list));
    } else {
        user.setOptions(null);
    }
    helper.saveUser(user);
    session.setAttribute(Keys.SESSION_MESSAGE, "User Options Saved.");
    response.setStatus(200);
}
Also used : T2WUser(h2weibo.model.T2WUser) HttpSession(javax.servlet.http.HttpSession) DBHelper(h2weibo.model.DBHelper)

Example 8 with T2WUser

use of h2weibo.model.T2WUser in project twitter-2-weibo by rjyo.

the class TweetServlet method doGet.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession(false);
    String loginUser = (String) session.getAttribute(Keys.SESSION_LOGIN_USER);
    DBHelper helper = (DBHelper) request.getAttribute(Keys.REQUEST_DB_HELPER);
    T2WUser t2wUser = helper.findOneByUser(loginUser);
    TwitterFactory factory = new TwitterFactory();
    Twitter t = factory.getInstance();
    t.setOAuthAccessToken(new AccessToken(t2wUser.getTwitterToken(), t2wUser.getTwitterTokenSecret()));
    try {
        t.updateStatus("Twitter, say hello to Weibo! Now syncing Twitter 2 Weibo using http://h2weibo.cloudfoundry.com #t2w_sync");
    } catch (TwitterException e) {
        log.error("Failed to send tweets", e);
    }
    response.setStatus(200);
}
Also used : T2WUser(h2weibo.model.T2WUser) HttpSession(javax.servlet.http.HttpSession) DBHelper(h2weibo.model.DBHelper) AccessToken(twitter4j.auth.AccessToken)

Aggregations

T2WUser (h2weibo.model.T2WUser)8 DBHelper (h2weibo.model.DBHelper)6 HttpSession (javax.servlet.http.HttpSession)5 AccessToken (twitter4j.auth.AccessToken)3 WeiboException (weibo4j.model.WeiboException)3 HttpServletRouter (h2weibo.HttpServletRouter)2 StatusImageExtractor (h2weibo.utils.StatusImageExtractor)1 PrintWriter (java.io.PrintWriter)1 twitter4j (twitter4j)1 Twitter (twitter4j.Twitter)1 TwitterException (twitter4j.TwitterException)1 TwitterFactory (twitter4j.TwitterFactory)1 RequestToken (twitter4j.auth.RequestToken)1 Account (weibo4j.Account)1 Oauth (weibo4j.Oauth)1 Timeline (weibo4j.Timeline)1 Users (weibo4j.Users)1 Weibo (weibo4j.Weibo)1 AccessToken (weibo4j.http.AccessToken)1 ImageItem (weibo4j.http.ImageItem)1