Search in sources :

Example 6 with AccessToken

use of com.github.moko256.latte.client.base.entity.AccessToken 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 7 with AccessToken

use of com.github.moko256.latte.client.base.entity.AccessToken in project twicalico by moko256.

the class TwitterStringUtils method getLinkedSequence.

public static CharSequence getLinkedSequence(AccessToken accessToken, String text, Link[] links) {
    if (links == null) {
        return text;
    }
    SpannableString spannableString = new SpannableString(text);
    for (Link link : links) {
        Object span;
        final Uri uri = Uri.parse(link.getUrl());
        if (uri.getScheme() != null && uri.getHost() != null && uri.getScheme().equals("twitlatte")) {
            switch(uri.getHost()) {
                case "symbol":
                    span = new ClickableNoLineSpan() {

                        @Override
                        public void onClick(@NonNull View view) {
                            Context context = view.getContext();
                            context.startActivity(SearchResultActivity.getIntent(context, "$" + uri.getLastPathSegment()));
                        }
                    };
                    break;
                case "hashtag":
                    span = new ClickableNoLineSpan() {

                        @Override
                        public void onClick(@NonNull View view) {
                            Context context = view.getContext();
                            context.startActivity(SearchResultActivity.getIntent(context, "#" + uri.getLastPathSegment()));
                        }
                    };
                    break;
                case "user":
                    String name = uri.getLastPathSegment();
                    if (name != null) {
                        if (name.split("@")[0].equals(accessToken.getScreenName())) {
                            span = new ClickableBoldSpan() {

                                @Override
                                public void onClick(@NonNull View view) {
                                    Context context = view.getContext();
                                    context.startActivity(ShowUserActivity.getIntent(context, name));
                                }
                            };
                        } else {
                            span = new ClickableNoLineSpan() {

                                @Override
                                public void onClick(@NonNull View view) {
                                    Context context = view.getContext();
                                    context.startActivity(ShowUserActivity.getIntent(context, name));
                                }
                            };
                        }
                    } else {
                        span = null;
                    }
                    break;
                default:
                    span = new ClickableNoLineSpan() {

                        @Override
                        public void onClick(@NonNull View view) {
                            Context context = view.getContext();
                            context.startActivity(SearchResultActivity.getIntent(context, uri.getLastPathSegment()));
                        }
                    };
                    break;
            }
        } else {
            span = new ClickableNoLineSpan() {

                @Override
                public void onClick(@NonNull View view) {
                    Context context = view.getContext();
                    AppCustomTabsKt.launchChromeCustomTabs(context, uri, false);
                }
            };
        }
        int nowLength = text.length();
        int start = link.getStart();
        int end = link.getEnd();
        if (start < end && end <= nowLength) {
            spannableString.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
    return spannableString;
}
Also used : SpannableString(android.text.SpannableString) Context(android.content.Context) ClickableBoldSpan(com.github.moko256.twitlatte.text.style.ClickableBoldSpan) ClickableNoLineSpan(com.github.moko256.twitlatte.text.style.ClickableNoLineSpan) SpannableString(android.text.SpannableString) Uri(android.net.Uri) View(android.view.View) TextView(android.widget.TextView) Link(com.github.moko256.latte.html.entity.Link)

Example 8 with AccessToken

use of com.github.moko256.latte.client.base.entity.AccessToken in project twicalico by moko256.

the class TokenSQLiteOpenHelperTest method updateToken.

private void updateToken() {
    AccessToken accessToken = generateAccessToken(TEST_USER_1_USER_ID, TEST_USER_1_USER_SCREEN_NAME_2, TEST_USER_1_USER_TOKEN_2, TEST_USER_1_USER_TOKEN_SECRET_2);
    helper.addAccessToken(accessToken);
    final long updateAccessTokenResult = getSize();
    assertEquals(updateAccessTokenResult, 1);
    AccessToken updatedAccessTokenResult = helper.getAccessToken(accessToken.getKeyString());
    assertEquals(updatedAccessTokenResult.getScreenName(), TEST_USER_1_USER_SCREEN_NAME_2);
    assertEquals(updatedAccessTokenResult.getToken(), TEST_USER_1_USER_TOKEN_2);
    assertEquals(updatedAccessTokenResult.getTokenSecret(), TEST_USER_1_USER_TOKEN_SECRET_2);
}
Also used : AccessToken(com.github.moko256.latte.client.base.entity.AccessToken)

Example 9 with AccessToken

use of com.github.moko256.latte.client.base.entity.AccessToken in project twicalico by moko256.

the class TokenSQLiteOpenHelper method getAccessTokenInternal.

private AccessToken[] getAccessTokenInternal(SQLiteDatabase database) {
    AccessToken[] accessTokens;
    Cursor c = database.query(TABLE_NAME, TABLE_COLUMNS, null, null, null, null, null);
    accessTokens = new AccessToken[c.getCount()];
    while (c.moveToNext()) {
        accessTokens[c.getPosition()] = convertFromCursor(c);
    }
    c.close();
    return accessTokens;
}
Also used : AccessToken(com.github.moko256.latte.client.base.entity.AccessToken) Cursor(android.database.Cursor)

Example 10 with AccessToken

use of com.github.moko256.latte.client.base.entity.AccessToken in project twicalico by moko256.

the class TokenSQLiteOpenHelper method onUpgrade.

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
    if (oldVersion == 1) {
        Cursor c = sqLiteDatabase.query("AccountTokenList", new String[] { "userName", "userId", "token", "tokenSecret" }, null, null, null, null, null);
        AccessToken[] accessTokens = new AccessToken[c.getCount()];
        while (c.moveToNext()) {
            Integer type;
            String url;
            String userName;
            String tokenSecret = null;
            if (c.getString(3).matches(".*\\..*")) {
                type = Type.MASTODON;
                userName = c.getString(0).split("@")[0];
                url = c.getString(3);
            } else {
                type = Type.TWITTER;
                userName = c.getString(0);
                url = TWITTER_URL;
                tokenSecret = c.getString(3);
            }
            accessTokens[c.getPosition()] = new AccessToken(type, url, Long.valueOf(c.getString(1)), userName, c.getString(2), tokenSecret);
        }
        c.close();
        sqLiteDatabase.beginTransaction();
        sqLiteDatabase.execSQL("DROP TABLE AccountTokenList");
        onCreate(sqLiteDatabase);
        for (AccessToken accessToken : accessTokens) {
            ContentValues contentValues = new ContentValues();
            contentValues.put("type", accessToken.getType());
            contentValues.put("url", accessToken.getUrl());
            contentValues.put("userName", accessToken.getScreenName());
            contentValues.put("userId", String.valueOf(accessToken.getUserId()));
            contentValues.put("token", accessToken.getToken());
            contentValues.put("tokenSecret", accessToken.getTokenSecret());
            sqLiteDatabase.replace("AccountTokenList", null, contentValues);
        }
        sqLiteDatabase.setTransactionSuccessful();
        sqLiteDatabase.endTransaction();
    }
}
Also used : ContentValues(android.content.ContentValues) AccessToken(com.github.moko256.twicalico.entity.AccessToken) Cursor(android.database.Cursor)

Aggregations

AccessToken (com.github.moko256.latte.client.base.entity.AccessToken)9 AccessToken (com.github.moko256.twicalico.entity.AccessToken)8 Intent (android.content.Intent)6 Cursor (android.database.Cursor)5 Bundle (android.os.Bundle)5 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)4 View (android.view.View)4 TextView (android.widget.TextView)4 SharedPreferences (android.content.SharedPreferences)3 Menu (android.view.Menu)3 Toast (android.widget.Toast)3 Nullable (androidx.annotation.Nullable)3 AlertDialog (androidx.appcompat.app.AlertDialog)3 AppCompatActivity (androidx.appcompat.app.AppCompatActivity)3 TokenSQLiteOpenHelper (com.github.moko256.twicalico.database.TokenSQLiteOpenHelper)3 AccountsModel (com.github.moko256.twitlatte.model.AccountsModel)3 KEY_ACCOUNT_KEY (com.github.moko256.twitlatte.repository.PreferenceRepositoryKt.KEY_ACCOUNT_KEY)3 TwitterStringUtils (com.github.moko256.twitlatte.text.TwitterStringUtils)3 List (java.util.List)3 Build (android.os.Build)2