Search in sources :

Example 46 with TwitterException

use of twitter4j.TwitterException in project twicalico by moko256.

the class MainActivity method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    subscription = new CompositeSubscription();
    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.getChildAt(0).setOnClickListener(v -> {
        Fragment fragment = getMainFragment();
        if (fragment instanceof MovableTopInterface) {
            ((MovableTopInterface) fragment).moveToTop();
        }
    });
    drawer = findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();
    drawer.addDrawerListener(new DrawerLayout.DrawerListener() {

        @Override
        public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
        }

        @Override
        public void onDrawerOpened(@NonNull View drawerView) {
        }

        @Override
        public void onDrawerClosed(@NonNull View drawerView) {
            if (isDrawerAccountsSelection) {
                changeIsDrawerAccountsSelection();
            }
        }

        @Override
        public void onDrawerStateChanged(int newState) {
        }
    });
    navigationView = findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(item -> {
        int id = item.getItemId();
        if (!item.isChecked()) {
            switch(id) {
                case R.id.nav_timeline:
                    replaceFragment(new HomeTimeLineFragment());
                    break;
                case R.id.nav_mentions:
                    replaceFragment(new MentionsFragment());
                    break;
                case R.id.nav_account:
                    startMyUserActivity();
                    break;
                case R.id.nav_follow_and_follower:
                    replaceFragment(new MyFollowFollowerFragment());
                    break;
                case R.id.nav_like:
                    replaceFragment(UserLikeFragment.newInstance(GlobalApplication.userId));
                    break;
                case R.id.nav_settings:
                    startActivity(new Intent(this, SettingsActivity.class));
                    break;
            }
        }
        drawer.closeDrawer(GravityCompat.START);
        return (id != R.id.nav_settings) && (id != R.id.nav_account);
    });
    headerView = navigationView.inflateHeaderView(R.layout.nav_header_main);
    userNameText = headerView.findViewById(R.id.user_name);
    userIdText = headerView.findViewById(R.id.user_id);
    userImage = headerView.findViewById(R.id.user_image);
    userBackgroundImage = headerView.findViewById(R.id.user_bg_image);
    userBackgroundImage.setOnClickListener(v -> changeIsDrawerAccountsSelection());
    updateDrawerImage();
    accountListView = new RecyclerView(this);
    accountListView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    accountListView.setLayoutManager(new LinearLayoutManager(this));
    accountListView.setOverScrollMode(View.OVER_SCROLL_NEVER);
    accountListView.setVisibility(View.GONE);
    navigationView.addHeaderView(accountListView);
    SelectAccountsAdapter adapter = new SelectAccountsAdapter(this);
    adapter.setOnImageButtonClickListener(accessToken -> {
        drawer.closeDrawer(GravityCompat.START);
        if (accessToken.getUserId() != GlobalApplication.userId) {
            PreferenceManager.getDefaultSharedPreferences(this).edit().putString("AccountKey", accessToken.getKeyString()).apply();
            ((GlobalApplication) getApplication()).initTwitter(accessToken);
            updateDrawerImage();
            clearAndPrepareFragment();
        }
    });
    adapter.setOnAddButtonClickListener(v -> {
        PreferenceManager.getDefaultSharedPreferences(this).edit().putString("AccountKey", "-1").apply();
        GlobalApplication.twitter = null;
        startActivity(new Intent(this, OAuthActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
    });
    adapter.setOnRemoveButtonClickListener(v -> new AlertDialog.Builder(this).setMessage(R.string.confirm_logout).setCancelable(true).setPositiveButton(R.string.do_logout, (dialog, i) -> {
        SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        TokenSQLiteOpenHelper helper = new TokenSQLiteOpenHelper(this);
        helper.deleteAccessToken(helper.getAccessToken(defaultSharedPreferences.getString("AccountKey", "-1")));
        int point = helper.getSize() - 1;
        if (point != -1) {
            AccessToken accessToken = helper.getAccessTokens()[point];
            defaultSharedPreferences.edit().putString("AccountKey", accessToken.getKeyString()).apply();
            ((GlobalApplication) getApplication()).initTwitter(accessToken);
            updateDrawerImage();
            clearAndPrepareFragment();
        } else {
            adapter.getOnAddButtonClickListener().onClick(v);
        }
        helper.close();
    }).setNeutralButton(R.string.back, (dialog, i) -> dialog.cancel()).show());
    accountListView.setAdapter(adapter);
    subscription.add(Single.create(singleSubscriber -> {
        TokenSQLiteOpenHelper helper = new TokenSQLiteOpenHelper(this);
        AccessToken[] accessTokens = helper.getAccessTokens();
        helper.close();
        ArrayList<Pair<User, AccessToken>> r = new ArrayList<>(accessTokens.length);
        for (AccessToken accessToken : accessTokens) {
            long id = accessToken.getUserId();
            CachedUsersSQLiteOpenHelper userHelper = new CachedUsersSQLiteOpenHelper(this, id, accessToken.getType() == Type.TWITTER);
            User user = userHelper.getCachedUser(id);
            if (user == null) {
                try {
                    user = ((GlobalApplication) getApplication()).getTwitterInstance(accessToken).verifyCredentials();
                    userHelper.addCachedUser(user);
                } catch (TwitterException e) {
                    singleSubscriber.onError(e);
                    return;
                } finally {
                    userHelper.close();
                }
            }
            r.add(new Pair<>(user, accessToken));
        }
        singleSubscriber.onSuccess(r);
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(o -> {
        ArrayList<Pair<User, AccessToken>> pairs = (ArrayList<Pair<User, AccessToken>>) o;
        adapter.getImagesList().addAll(pairs);
        adapter.notifyDataSetChanged();
    }, Throwable::printStackTrace));
    findViewById(R.id.fab).setOnClickListener(v -> startActivity(new Intent(this, PostActivity.class)));
    tabLayout = findViewById(R.id.toolbar_tab);
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            Fragment fragment = ((FragmentPagerAdapter) ((UseTabsInterface) getMainFragment()).getTabsViewPager().getAdapter()).getFragment(tab.getPosition());
            if (fragment instanceof MovableTopInterface) {
                ((MovableTopInterface) fragment).moveToTop();
            }
        }
    });
    tweetListViewPool = new RecyclerView.RecycledViewPool();
    userListViewPool = new RecyclerView.RecycledViewPool();
    getSupportFragmentManager().addOnBackStackChangedListener(() -> attachFragment(getMainFragment()));
    if (savedInstanceState == null) {
        prepareFragment();
    }
}
Also used : NavigationView(android.support.design.widget.NavigationView) LinearLayout(android.widget.LinearLayout) Type(com.github.moko256.twicalico.entity.Type) Bundle(android.os.Bundle) ImageView(android.widget.ImageView) CachedUsersSQLiteOpenHelper(com.github.moko256.twicalico.database.CachedUsersSQLiteOpenHelper) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) Intent(android.content.Intent) NonNull(android.support.annotation.NonNull) TwitterStringUtils(com.github.moko256.twicalico.text.TwitterStringUtils) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) TabLayout(android.support.design.widget.TabLayout) GravityCompat(android.support.v4.view.GravityCompat) Single(rx.Single) Menu(android.view.Menu) Schedulers(rx.schedulers.Schedulers) User(twitter4j.User) View(android.view.View) TwitterException(twitter4j.TwitterException) PreferenceManager(android.preference.PreferenceManager) DrawerLayout(android.support.v4.widget.DrawerLayout) AccessToken(com.github.moko256.twicalico.entity.AccessToken) Fragment(android.support.v4.app.Fragment) ActivityOptionsCompat(android.support.v4.app.ActivityOptionsCompat) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) AppCompatActivity(android.support.v7.app.AppCompatActivity) ViewGroup(android.view.ViewGroup) CompositeSubscription(rx.subscriptions.CompositeSubscription) RecyclerView(android.support.v7.widget.RecyclerView) FragmentManager(android.support.v4.app.FragmentManager) AlertDialog(android.support.v7.app.AlertDialog) TextView(android.widget.TextView) SharedPreferences(android.content.SharedPreferences) Toolbar(android.support.v7.widget.Toolbar) Pair(android.support.v4.util.Pair) TokenSQLiteOpenHelper(com.github.moko256.twicalico.database.TokenSQLiteOpenHelper) FragmentPagerAdapter(com.github.moko256.twicalico.widget.FragmentPagerAdapter) ActionBarDrawerToggle(android.support.v7.app.ActionBarDrawerToggle) User(twitter4j.User) ActionBarDrawerToggle(android.support.v7.app.ActionBarDrawerToggle) ArrayList(java.util.ArrayList) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) Fragment(android.support.v4.app.Fragment) AccessToken(com.github.moko256.twicalico.entity.AccessToken) TabLayout(android.support.design.widget.TabLayout) DrawerLayout(android.support.v4.widget.DrawerLayout) TwitterException(twitter4j.TwitterException) TokenSQLiteOpenHelper(com.github.moko256.twicalico.database.TokenSQLiteOpenHelper) Pair(android.support.v4.util.Pair) SharedPreferences(android.content.SharedPreferences) CachedUsersSQLiteOpenHelper(com.github.moko256.twicalico.database.CachedUsersSQLiteOpenHelper) Intent(android.content.Intent) NavigationView(android.support.design.widget.NavigationView) ImageView(android.widget.ImageView) View(android.view.View) RecyclerView(android.support.v7.widget.RecyclerView) TextView(android.widget.TextView) CompositeSubscription(rx.subscriptions.CompositeSubscription) RecyclerView(android.support.v7.widget.RecyclerView) LinearLayout(android.widget.LinearLayout)

Example 47 with TwitterException

use of twitter4j.TwitterException in project opennms by OpenNMS.

the class MicroblogNotificationStrategy method send.

/**
 * {@inheritDoc}
 */
@Override
public int send(List<Argument> arguments) {
    Twitter svc = buildUblogService(arguments);
    String messageBody = buildMessageBody(arguments);
    Status response;
    final String baseURL = svc.getConfiguration().getClientURL();
    LOG.debug("Dispatching microblog notification at base URL '{}' with message '{}'", baseURL, messageBody);
    try {
        response = svc.updateStatus(messageBody);
    } catch (TwitterException e) {
        LOG.error("Microblog notification failed at service URL '{}'", baseURL, e);
        return 1;
    }
    LOG.info("Microblog notification succeeded: update posted with ID {}", response.getId());
    return 0;
}
Also used : Status(twitter4j.Status) Twitter(twitter4j.Twitter) TwitterException(twitter4j.TwitterException)

Example 48 with TwitterException

use of twitter4j.TwitterException in project opennms by OpenNMS.

the class MicroblogReplyNotificationStrategy method send.

/**
 * {@inheritDoc}
 */
@Override
public int send(final List<Argument> arguments) {
    final Twitter svc = buildUblogService(arguments);
    String destUser = findDestName(arguments);
    Status response;
    if (destUser == null || "".equals(destUser)) {
        LOG.error("Cannot send a microblog reply notice to a user with no microblog username set. Either set a microblog username for this OpenNMS user or use the MicroblogUpdateNotificationStrategy instead.");
        return 1;
    }
    // In case the user tried to be helpful, avoid a double @@
    if (destUser.startsWith("@"))
        destUser = destUser.substring(1);
    final String fullMessage = String.format("@%s %s", destUser, buildMessageBody(arguments));
    LOG.debug("Dispatching microblog reply notification at base URL '{}' with message '{}'", svc.getConfiguration().getClientURL(), fullMessage);
    try {
        response = svc.updateStatus(fullMessage);
    } catch (final TwitterException e) {
        LOG.error("Microblog notification failed at service URL '{}'", svc.getConfiguration().getClientURL(), e);
        return 1;
    }
    LOG.info("Microblog reply notification succeeded: reply update posted with ID {}", response.getId());
    return 0;
}
Also used : Status(twitter4j.Status) Twitter(twitter4j.Twitter) TwitterException(twitter4j.TwitterException)

Example 49 with TwitterException

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

the class DMFragment method onRefreshStarted.

@Override
public void onRefreshStarted() {
    new AsyncTask<Void, Void, Void>() {

        private boolean update;

        private int numberNew;

        @Override
        protected void onPreExecute() {
            DrawerActivity.canSwitch = false;
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                twitter = Utils.getTwitter(context, DrawerActivity.settings);
                User user = twitter.verifyCredentials();
                long lastId = sharedPrefs.getLong("last_direct_message_id_" + currentAccount, 0);
                Paging paging;
                if (lastId != 0) {
                    paging = new Paging(1).sinceId(lastId);
                } else {
                    paging = new Paging(1, 500);
                }
                List<DirectMessage> dm = twitter.getDirectMessages(paging);
                List<DirectMessage> sent = twitter.getSentDirectMessages(paging);
                if (dm.size() != 0) {
                    sharedPrefs.edit().putLong("last_direct_message_id_" + currentAccount, dm.get(0).getId()).commit();
                    update = true;
                    numberNew = dm.size();
                } else {
                    update = false;
                    numberNew = 0;
                }
                DMDataSource dataSource = DMDataSource.getInstance(context);
                for (DirectMessage directMessage : dm) {
                    try {
                        dataSource.createDirectMessage(directMessage, currentAccount);
                    } catch (IllegalStateException e) {
                        dataSource = DMDataSource.getInstance(context);
                        dataSource.createDirectMessage(directMessage, currentAccount);
                    }
                }
                for (DirectMessage directMessage : sent) {
                    try {
                        dataSource.createDirectMessage(directMessage, currentAccount);
                    } catch (Exception e) {
                        dataSource = DMDataSource.getInstance(context);
                        dataSource.createDirectMessage(directMessage, currentAccount);
                    }
                }
            } catch (TwitterException e) {
                // Error in updating status
                Log.d("Twitter Update Error", e.getMessage());
            }
            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            long now = new Date().getTime();
            long alarm = now + DrawerActivity.settings.dmRefresh;
            Log.v("alarm_date", "direct message " + new Date(alarm).toString());
            PendingIntent pendingIntent = PendingIntent.getService(context, DM_REFRESH_ID, new Intent(context, DirectMessageRefreshService.class), 0);
            if (DrawerActivity.settings.dmRefresh != 0)
                am.setRepeating(AlarmManager.RTC_WAKEUP, alarm, DrawerActivity.settings.dmRefresh, pendingIntent);
            else
                am.cancel(pendingIntent);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            try {
                if (update) {
                    getCursorAdapter(false);
                    CharSequence text = numberNew == 1 ? numberNew + " " + getResources().getString(R.string.new_direct_message) : numberNew + " " + getResources().getString(R.string.new_direct_messages);
                    showToastBar(text + "", jumpToTop, 400, true, toTopListener);
                    int size = toDP(5) + mActionBarSize + (DrawerActivity.translucent ? DrawerActivity.statusBarHeight : 0);
                    listView.setSelectionFromTop(numberNew + (MainActivity.isPopup || landscape || MainActivity.settings.jumpingWorkaround ? 1 : 2), size);
                } else {
                    getCursorAdapter(false);
                    CharSequence text = getResources().getString(R.string.no_new_direct_messages);
                    showToastBar(text + "", allRead, 400, true, toTopListener);
                }
                refreshLayout.setRefreshing(false);
            } catch (IllegalStateException e) {
            // fragment not attached to activity
            }
            DrawerActivity.canSwitch = true;
        }
    }.execute();
}
Also used : DirectMessage(twitter4j.DirectMessage) User(twitter4j.User) Paging(twitter4j.Paging) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) DMDataSource(com.klinker.android.twitter.data.sq_lite.DMDataSource) TwitterException(twitter4j.TwitterException) Date(java.util.Date) AlarmManager(android.app.AlarmManager) ArrayList(java.util.ArrayList) List(java.util.List) PendingIntent(android.app.PendingIntent) TwitterException(twitter4j.TwitterException)

Example 50 with TwitterException

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

the class CatchupPull method onHandleIntent.

@Override
public void onHandleIntent(Intent intent) {
    if (CatchupPull.isRunning || WidgetRefreshService.isRunning || TimelineRefreshService.isRunning || !MainActivity.canSwitch) {
        return;
    }
    CatchupPull.isRunning = true;
    Log.v("talon_pull", "catchup pull started");
    sharedPrefs = getSharedPreferences("com.klinker.android.twitter_world_preferences", 0);
    final Context context = getApplicationContext();
    int unreadNow = sharedPrefs.getInt("pull_unread", 0);
    // stop it just in case
    context.sendBroadcast(new Intent("com.klinker.android.twitter.STOP_PUSH_SERVICE"));
    AppSettings settings = AppSettings.getInstance(context);
    if (settings.liveStreaming) {
        Log.v("talon_pull", "into the try for catchup service");
        Twitter twitter = Utils.getTwitter(context, settings);
        HomeDataSource dataSource = HomeDataSource.getInstance(context);
        int currentAccount = sharedPrefs.getInt("current_account", 1);
        List<Status> statuses = new ArrayList<Status>();
        boolean foundStatus = false;
        Paging paging = new Paging(1, 200);
        long[] lastId;
        long id;
        try {
            lastId = dataSource.getLastIds(currentAccount);
            id = lastId[0];
        } catch (Exception e) {
            context.startService(new Intent(context, TalonPullNotificationService.class));
            CatchupPull.isRunning = false;
            return;
        }
        try {
            paging.setSinceId(id);
        } catch (Exception e) {
            paging.setSinceId(1l);
        }
        for (int i = 0; i < settings.maxTweetsRefresh; i++) {
            try {
                if (!foundStatus) {
                    paging.setPage(i + 1);
                    List<Status> list = twitter.getHomeTimeline(paging);
                    statuses.addAll(list);
                    if (statuses.size() <= 1 || statuses.get(statuses.size() - 1).getId() == lastId[0]) {
                        Log.v("talon_inserting", "found status");
                        foundStatus = true;
                    } else {
                        Log.v("talon_inserting", "haven't found status");
                        foundStatus = false;
                    }
                }
            } catch (Exception e) {
                // the page doesn't exist
                foundStatus = true;
                e.printStackTrace();
            } catch (OutOfMemoryError o) {
                // don't know why...
                o.printStackTrace();
            }
        }
        Log.v("talon_pull", "got statuses, new = " + statuses.size());
        // hash set to remove duplicates I guess
        HashSet hs = new HashSet();
        hs.addAll(statuses);
        statuses.clear();
        statuses.addAll(hs);
        Log.v("talon_inserting", "tweets after hashset: " + statuses.size());
        lastId = dataSource.getLastIds(currentAccount);
        int inserted = dataSource.insertTweets(statuses, currentAccount, lastId);
        if (inserted > 0 && statuses.size() > 0) {
            sharedPrefs.edit().putLong("account_" + currentAccount + "_lastid", statuses.get(0).getId()).commit();
            unreadNow += statuses.size();
        }
        if (settings.preCacheImages) {
            // delay it 15 seconds so that we can finish checking mentions first
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    startService(new Intent(context, PreCacheService.class));
                }
            }, 15000);
        }
        sharedPrefs.edit().putBoolean("refresh_me", true).commit();
    }
    try {
        Twitter twitter = Utils.getTwitter(context, settings);
        int currentAccount = sharedPrefs.getInt("current_account", 1);
        User user = twitter.verifyCredentials();
        MentionsDataSource dataSource = MentionsDataSource.getInstance(context);
        long[] lastId = dataSource.getLastIds(currentAccount);
        Paging paging;
        paging = new Paging(1, 200);
        if (lastId[0] > 0) {
            paging.sinceId(lastId[0]);
        }
        List<twitter4j.Status> statuses = twitter.getMentionsTimeline(paging);
        int numNew = dataSource.insertTweets(statuses, currentAccount);
        sharedPrefs.edit().putBoolean("refresh_me", true).commit();
        sharedPrefs.edit().putBoolean("refresh_me_mentions", true).commit();
        if (settings.notifications && settings.mentionsNot && numNew > 0) {
            NotificationUtils.refreshNotification(context);
        }
    } catch (TwitterException e) {
        // Error in updating status
        Log.d("Twitter Update Error", e.getMessage());
    }
    sharedPrefs.edit().putInt("pull_unread", unreadNow).commit();
    context.startService(new Intent(context, TalonPullNotificationService.class));
    context.sendBroadcast(new Intent("com.klinker.android.talon.UPDATE_WIDGET"));
    getContentResolver().notifyChange(HomeContentProvider.CONTENT_URI, null);
    Log.v("talon_pull", "finished with the catchup service");
    CatchupPull.isRunning = false;
}
Also used : Context(android.content.Context) Status(twitter4j.Status) User(twitter4j.User) AppSettings(com.klinker.android.twitter.settings.AppSettings) Paging(twitter4j.Paging) ArrayList(java.util.ArrayList) Twitter(twitter4j.Twitter) Handler(android.os.Handler) Intent(android.content.Intent) MentionsDataSource(com.klinker.android.twitter.data.sq_lite.MentionsDataSource) TwitterException(twitter4j.TwitterException) HomeDataSource(com.klinker.android.twitter.data.sq_lite.HomeDataSource) TwitterException(twitter4j.TwitterException) HashSet(java.util.HashSet)

Aggregations

TwitterException (twitter4j.TwitterException)96 Twitter (twitter4j.Twitter)69 TwitterFactory (twitter4j.TwitterFactory)54 Status (twitter4j.Status)21 User (twitter4j.User)12 Intent (android.content.Intent)11 ArrayList (java.util.ArrayList)9 File (java.io.File)6 IDs (twitter4j.IDs)6 Context (android.content.Context)5 Date (java.util.Date)4 DirectMessage (twitter4j.DirectMessage)4 Paging (twitter4j.Paging)4 AccessToken (twitter4j.auth.AccessToken)4 Activity (android.app.Activity)3 SharedPreferences (android.content.SharedPreferences)3 ActivityOptionsCompat (android.support.v4.app.ActivityOptionsCompat)3 View (android.view.View)3 ImageView (android.widget.ImageView)3 TextView (android.widget.TextView)3