Search in sources :

Example 1 with CLIENT_TYPE_TWITTER

use of com.github.moko256.latte.client.twitter.TwitterApiClientImplKt.CLIENT_TYPE_TWITTER in project twicalico by moko256.

the class UserInfoFragment method onCreateView.

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.content_show_user, container, false);
    glideRequests = Glide.with(this);
    header = view.findViewById(R.id.show_user_bgimage);
    header.setWidthPerHeight((client.getAccessToken().getClientType() == CLIENT_TYPE_TWITTER) ? 3 : 2);
    icon = view.findViewById(R.id.show_user_image);
    ShapeDrawable iconBackground = new ShapeDrawable();
    iconBackground.setColorFilter(new PorterDuffColorFilter(((ColorDrawable) requireActivity().getWindow().getDecorView().getBackground()).getColor(), PorterDuff.Mode.SRC_ATOP));
    iconBackground.setShape(new OvalShape());
    icon.setBackground(iconBackground);
    userNameText = view.findViewById(R.id.show_user_name);
    userIdText = view.findViewById(R.id.show_user_id);
    userBioText = view.findViewById(R.id.show_user_bio);
    userBioText.setMovementMethod(LinkMovementMethod.getInstance());
    userLocation = view.findViewById(R.id.show_user_location);
    userUrl = view.findViewById(R.id.show_user_url);
    userCreatedAt = view.findViewById(R.id.show_user_created_at);
    userCounts = view.findViewById(R.id.show_user_counts);
    userIsYouOrFollowedYou = view.findViewById(R.id.followed_or_you);
    userFollowButton = view.findViewById(R.id.follow);
    userUnfollowButton = view.findViewById(R.id.unfollow);
    return view;
}
Also used : ColorDrawable(android.graphics.drawable.ColorDrawable) ShapeDrawable(android.graphics.drawable.ShapeDrawable) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) OvalShape(android.graphics.drawable.shapes.OvalShape) ImageView(android.widget.ImageView) View(android.view.View) TextView(android.widget.TextView) UserHeaderImageView(com.github.moko256.twitlatte.widget.UserHeaderImageView) Nullable(androidx.annotation.Nullable)

Example 2 with CLIENT_TYPE_TWITTER

use of com.github.moko256.latte.client.twitter.TwitterApiClientImplKt.CLIENT_TYPE_TWITTER in project twicalico by moko256.

the class OAuthActivity method initType.

private void initType(int authClientType) {
    switch(authClientType) {
        case CLIENT_TYPE_TWITTER:
            model = new OAuthModelImpl(OAuthApiClientGeneratorKt.generateTwitterOAuthApiClient());
            break;
        case CLIENT_TYPE_MASTODON:
            model = new OAuthModelImpl(OAuthApiClientGeneratorKt.generateMastodonOAuthApiClient(OkHttpHolderKt.getAppOkHttpClientInstance()));
            break;
        default:
            model = null;
            authClientType = CLIENT_TYPE_NOTHING;
            break;
    }
    this.authClientType = authClientType;
}
Also used : OAuthModelImpl(com.github.moko256.twitlatte.model.impl.OAuthModelImpl)

Example 3 with CLIENT_TYPE_TWITTER

use of com.github.moko256.latte.client.twitter.TwitterApiClientImplKt.CLIENT_TYPE_TWITTER in project twicalico by moko256.

the class PostActivity method onCreate.

@SuppressLint("SetTextI18n")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post);
    TypedValue value = new TypedValue();
    getTheme().resolveAttribute(android.R.attr.textColorTertiary, value, true);
    COLOR_STABLE = ContextCompat.getColor(this, value.resourceId);
    getTheme().resolveAttribute(R.attr.colorError, value, true);
    COLOR_ERROR = ContextCompat.getColor(this, value.resourceId);
    RequestManager requestManager = Glide.with(this);
    client = GlobalApplicationKt.getClient(this);
    model = new PostStatusModelImpl(getContentResolver(), client.getApiClient());
    disposable = new CompositeDisposable();
    rootViewGroup = findViewById(android.R.id.content);
    actionBar = Objects.requireNonNull(getSupportActionBar());
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeAsUpIndicator(R.drawable.ic_clear_white_24dp);
    actionBar.setDisplayShowCustomEnabled(true);
    userIcon = new ImageView(this);
    final int dp36 = DpToPxKt.dpToPx(this, 36);
    ActionBar.LayoutParams userIconParams = new ActionBar.LayoutParams(dp36, dp36);
    userIconParams.setMarginStart(dp36 / 3 * 2);
    actionBar.setCustomView(userIcon, userIconParams);
    disposable.add(Single.create(new VerifyCredentialOnSubscribe(client)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(user -> requestManager.load(client.getMediaUrlConverter().convertProfileIconUriBySize(user, dp36)).circleCrop().into(userIcon), Throwable::printStackTrace));
    counterTextView = findViewById(R.id.tweet_text_edit_counter);
    editText = findViewById(R.id.tweet_text_edit);
    editText.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            model.getUpdateStatus().setContext(s.toString());
            updateCounter();
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
    editText.setFilters(NoSpanInputFilterKt.getNoSpanInputFilter());
    editText.setImageAddedListener(imageUri -> {
        if (model.getUriList().size() < model.getUriListSizeLimit()) {
            addedImagesAdapter.addImageAndUpdateView(imageUri);
            model.getUriList().add(imageUri);
            updateCounter();
            isPossiblySensitive.setEnabled(true);
            return true;
        } else {
            return false;
        }
    });
    editText.setOnKeyListener((v, keyCode, event) -> {
        if (!isPosting && event.getAction() == KeyEvent.ACTION_DOWN && event.isCtrlPressed() && keyCode == KeyEvent.KEYCODE_ENTER) {
            postOrConfirmIfValid();
            return true;
        }
        return false;
    });
    imagesRecyclerView = findViewById(R.id.activity_tweet_send_images_recycler_view);
    addedImagesAdapter = new AddedImagesAdapter(this, requestManager);
    imagesRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
    imagesRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {

        @Override
        public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
            outRect.right = DpToPxKt.oneDpToPx(getResources().getDisplayMetrics().density);
        }
    });
    addedImagesAdapter.limit = model.getUriListSizeLimit();
    addedImagesAdapter.onAddButtonClickListener = v -> startActivityForResult(Intent.createChooser(new Intent(Intent.ACTION_GET_CONTENT).addCategory(Intent.CATEGORY_OPENABLE).putExtra(Intent.EXTRA_MIME_TYPES, new String[] { "image/*", "video/*" }).putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true).setType("*/*"), getString(R.string.add_media)), REQUEST_GET_IMAGE);
    addedImagesAdapter.onDeleteButtonListener = position -> {
        addedImagesAdapter.removeImageAndUpdateView(position);
        model.getUriList().remove(position);
        boolean enabled = model.getUriList().size() > 0;
        updateCounter();
        isPossiblySensitive.setEnabled(enabled);
        isPossiblySensitive.setChecked(isPossiblySensitive.isChecked() && enabled);
    };
    addedImagesAdapter.onImageClickListener = position -> {
        try {
            Intent open = new Intent(Intent.ACTION_VIEW).setData(model.getUriList().get(position)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(Intent.createChooser(open, getString(R.string.open_media)));
        } catch (Throwable e) {
            e.printStackTrace();
        }
    };
    imagesRecyclerView.setAdapter(addedImagesAdapter);
    emojiInputRecyclerView = findViewById(R.id.suggestions_of_emoji);
    isPossiblySensitive = findViewById(R.id.activity_tweet_is_possibly_sensitive);
    isPossiblySensitive.setEnabled(addedImagesAdapter.getImagesList().size() > 0);
    isPossiblySensitive.setOnCheckedChangeListener((buttonView, isChecked) -> model.getUpdateStatus().setPossiblySensitive(isChecked));
    postVisibility = findViewById(R.id.activity_tweet_visibility_spinner);
    contentWarningText = findViewById(R.id.tweet_text_warning);
    contentWarningEnabled = findViewById(R.id.activity_tweet_add_content_warning);
    pollsText = new EditText[] { findViewById(R.id.edit_poll_0), findViewById(R.id.edit_poll_1), findViewById(R.id.edit_poll_2), findViewById(R.id.edit_poll_3) };
    pollsExpiredAt = findViewById(R.id.edit_poll_expired_at);
    pollsExpireAtLabel = findViewById(R.id.edit_poll_expired_at_description);
    pollsMultiple = findViewById(R.id.poll_multiple);
    pollsHideTotals = findViewById(R.id.hide_totals);
    addPoll = findViewById(R.id.activity_add_poll);
    ArraysKt.forEach(pollsText, editText -> {
        editText.setVisibility(View.GONE);
        return Unit.INSTANCE;
    });
    pollsExpiredAt.setVisibility(View.GONE);
    pollsMultiple.setVisibility(View.GONE);
    pollsHideTotals.setVisibility(View.GONE);
    pollsExpireAtLabel.setVisibility(View.GONE);
    if (client.getAccessToken().getClientType() == CLIENT_TYPE_MASTODON) {
        emojiAdapter = new EmojiAdapter(emojiList, this, requestManager, emoji -> {
            int selectionEnd = editText.getSelectionEnd();
            String shortCode = emoji.getShortCode();
            Editable text = editText.getText();
            if (text != null) {
                text.insert(selectionEnd, ":").insert(selectionEnd + 1, shortCode).insert(selectionEnd + 1 + shortCode.length(), ": ");
            } else {
                editText.setText(":" + shortCode + ": ");
            }
            editText.setSelection(selectionEnd + shortCode.length() + 3);
            return Unit.INSTANCE;
        }, () -> {
            disposable.add(model.requestCustomEmojis().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(emojis -> {
                emojiList.clear();
                emojiList.addAll(emojis);
                emojiAdapter.notifyDataSetChanged();
            }, this::errorNotify));
            return Unit.INSTANCE;
        });
        contentWarningText.setFilters(NoSpanInputFilterKt.getNoSpanInputFilter());
        emojiInputRecyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        emojiInputRecyclerView.setAdapter(emojiAdapter);
        contentWarningText.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                model.getUpdateStatus().setContentWarning(s.toString());
                updateCounter();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        contentWarningEnabled.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                contentWarningText.setVisibility(View.VISIBLE);
                contentWarningText.requestFocus();
            } else {
                contentWarningText.setVisibility(View.GONE);
                model.getUpdateStatus().setContentWarning("");
            }
        });
        postVisibility.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                model.getUpdateStatus().setVisibility(POST_VISIBILITY[position]);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        ArrayList<String> options = new ArrayList<>(4);
        ArraysKt.forEachIndexed(pollsText, (i, editText) -> {
            if (i < 2) {
                editText.setHint(getString(R.string.poll_n, i + 1));
            } else {
                editText.setHint(getString(R.string.poll_n_optional, i + 1));
            }
            options.add("");
            editText.addTextChangedListener(new TextWatcher() {

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    options.set(i, s.toString());
                    model.getUpdateStatus().setPollList(options);
                }

                @Override
                public void afterTextChanged(Editable s) {
                }
            });
            return Unit.INSTANCE;
        });
        pollsExpiredAt.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                model.getUpdateStatus().setPollExpiredSecond(POLL_EXPIRED_AT[position]);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        pollsMultiple.setOnCheckedChangeListener((buttonView, isChecked) -> model.getUpdateStatus().setPollSelectableMultiple(isChecked));
        pollsHideTotals.setOnCheckedChangeListener((buttonView, isChecked) -> model.getUpdateStatus().setPollHideTotalsUntilExpired(isChecked));
        addPoll.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                ArraysKt.forEach(pollsText, editText -> {
                    editText.setVisibility(View.VISIBLE);
                    return Unit.INSTANCE;
                });
                pollsExpiredAt.setVisibility(View.VISIBLE);
                pollsMultiple.setVisibility(View.VISIBLE);
                pollsHideTotals.setVisibility(View.VISIBLE);
                pollsExpireAtLabel.setVisibility(View.VISIBLE);
            } else {
                model.getUpdateStatus().setPollList(null);
                ArraysKt.forEach(pollsText, editText -> {
                    editText.setVisibility(View.GONE);
                    editText.setText("");
                    return Unit.INSTANCE;
                });
                pollsExpiredAt.setVisibility(View.GONE);
                pollsMultiple.setVisibility(View.GONE);
                pollsHideTotals.setVisibility(View.GONE);
                pollsExpireAtLabel.setVisibility(View.GONE);
            }
        });
    } else {
        emojiInputRecyclerView.setVisibility(View.GONE);
        contentWarningEnabled.setVisibility(View.GONE);
        postVisibility.setVisibility(View.GONE);
        findViewById(R.id.activity_tweet_visibility_description).setVisibility(View.GONE);
        addPoll.setVisibility(View.GONE);
    }
    addLocation = findViewById(R.id.activity_tweet_add_location);
    if (client.getAccessToken().getClientType() == CLIENT_TYPE_TWITTER) {
        addLocation.setVisibility(View.VISIBLE);
        addLocation.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                locationText.setVisibility(View.VISIBLE);
                if (PermissionChecker.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PermissionChecker.PERMISSION_GRANTED) {
                    updateLocation();
                } else {
                    ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_CODE_PERMISSION_LOCATION);
                }
            } else {
                model.getUpdateStatus().setLocation(null);
                locationText.setVisibility(View.GONE);
                locationText.setText("");
            }
        });
    } else {
        addLocation.setVisibility(View.GONE);
    }
    locationText = findViewById(R.id.activity_tweet_location_result);
    locationText.setVisibility(View.GONE);
    if (getIntent() != null) {
        model.getUpdateStatus().setInReplyToStatusId(getIntent().getLongExtra(INTENT_EXTRA_IN_REPLY_TO_STATUS_ID, -1));
        if (savedInstanceState == null) {
            String text = getIntent().getStringExtra(INTENT_EXTRA_TWEET_TEXT);
            if (text != null) {
                editText.setText(text);
                editText.setSelection(text.length());
            } else {
                editText.setText("");
            }
            ArrayList<Uri> uris = getIntent().getParcelableArrayListExtra(INTENT_EXTRA_IMAGE_URI);
            if (uris != null) {
                addedImagesAdapter.getImagesList().addAll(uris);
                model.getUriList().addAll(uris);
                updateCounter();
                isPossiblySensitive.setEnabled(true);
            }
        }
    }
    editText.setHint(model.isReply() ? R.string.reply : R.string.post);
}
Also used : Rect(android.graphics.Rect) Bundle(android.os.Bundle) NonNull(androidx.annotation.NonNull) Pair(kotlin.Pair) Uri(android.net.Uri) ImageView(android.widget.ImageView) AppCompatActivity(androidx.appcompat.app.AppCompatActivity) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) ActionBar(androidx.appcompat.app.ActionBar) Manifest(android.Manifest) CheckBox(android.widget.CheckBox) RequestManager(com.bumptech.glide.RequestManager) LocationSingleBuilder(com.github.moko256.twitlatte.rx.LocationSingleBuilder) View(android.view.View) Schedulers(io.reactivex.schedulers.Schedulers) AdapterView(android.widget.AdapterView) RecyclerView(androidx.recyclerview.widget.RecyclerView) ContextCompat(androidx.core.content.ContextCompat) PostStatusModelImpl(com.github.moko256.twitlatte.model.impl.PostStatusModelImpl) NoSpanInputFilterKt(com.github.moko256.twitlatte.text.NoSpanInputFilterKt) Objects(java.util.Objects) DpToPxKt(com.github.moko256.twitlatte.view.DpToPxKt) List(java.util.List) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Unit(kotlin.Unit) TextView(android.widget.TextView) PostStatusModel(com.github.moko256.twitlatte.model.base.PostStatusModel) ImageKeyboardEditText(com.github.moko256.twitlatte.widget.ImageKeyboardEditText) Emoji(com.github.moko256.latte.client.base.entity.Emoji) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) LocationManager(android.location.LocationManager) Snackbar(com.google.android.material.snackbar.Snackbar) TextWatcher(android.text.TextWatcher) Context(android.content.Context) KeyEvent(android.view.KeyEvent) AlertDialog(androidx.appcompat.app.AlertDialog) ArraysKt(kotlin.collections.ArraysKt) Intent(android.content.Intent) CLIENT_TYPE_TWITTER(com.github.moko256.latte.client.twitter.TwitterApiClientImplKt.CLIENT_TYPE_TWITTER) Single(io.reactivex.Single) Editable(android.text.Editable) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) ClipData(android.content.ClipData) PermissionChecker(androidx.core.content.PermissionChecker) SuppressLint(android.annotation.SuppressLint) Menu(android.view.Menu) Parcelable(android.os.Parcelable) ActivityCompat(androidx.core.app.ActivityCompat) Client(com.github.moko256.twitlatte.entity.Client) VerifyCredentialOnSubscribe(com.github.moko256.twitlatte.rx.VerifyCredentialOnSubscribe) Spinner(android.widget.Spinner) Glide(com.bumptech.glide.Glide) TypedValue(android.util.TypedValue) EditText(android.widget.EditText) CLIENT_TYPE_MASTODON(com.github.moko256.latte.client.mastodon.MastodonApiClientImplKt.CLIENT_TYPE_MASTODON) ArrayList(java.util.ArrayList) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) Uri(android.net.Uri) RequestManager(com.bumptech.glide.RequestManager) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) ImageView(android.widget.ImageView) ActionBar(androidx.appcompat.app.ActionBar) TypedValue(android.util.TypedValue) Rect(android.graphics.Rect) Intent(android.content.Intent) VerifyCredentialOnSubscribe(com.github.moko256.twitlatte.rx.VerifyCredentialOnSubscribe) ImageView(android.widget.ImageView) View(android.view.View) AdapterView(android.widget.AdapterView) RecyclerView(androidx.recyclerview.widget.RecyclerView) TextView(android.widget.TextView) SuppressLint(android.annotation.SuppressLint) PostStatusModelImpl(com.github.moko256.twitlatte.model.impl.PostStatusModelImpl) RecyclerView(androidx.recyclerview.widget.RecyclerView) AdapterView(android.widget.AdapterView) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) SuppressLint(android.annotation.SuppressLint)

Example 4 with CLIENT_TYPE_TWITTER

use of com.github.moko256.latte.client.twitter.TwitterApiClientImplKt.CLIENT_TYPE_TWITTER in project twicalico by moko256.

the class SettingsFragment method onCreatePreferences.

@Override
public void onCreatePreferences(Bundle bundle, String rootKey) {
    setPreferencesFromResource(R.xml.settings, rootKey);
    if (rootKey == null) {
        AccountsModel accountsModel = GlobalApplicationKt.getAccountsModel(requireActivity());
        List<AccessToken> accessTokens = accountsModel.getAccessTokens();
        CharSequence[] entriesAccountList = new CharSequence[accessTokens.size() + 1];
        CharSequence[] entryValues = new CharSequence[accessTokens.size() + 1];
        for (int i = 0; i < accessTokens.size(); i++) {
            AccessToken accessToken = accessTokens.get(i);
            entriesAccountList[i] = TwitterStringUtils.plusAtMark(accessToken.getScreenName(), accessToken.getUrl());
            entryValues[i] = accessToken.getKeyString();
        }
        entriesAccountList[entriesAccountList.length - 1] = getString(R.string.login_with_another_account);
        entryValues[entryValues.length - 1] = "-1";
        ListPreference nowAccountList = findPreference(KEY_ACCOUNT_KEY);
        nowAccountList.setEntries(entriesAccountList);
        nowAccountList.setEntryValues(entryValues);
        nowAccountList.setDefaultValue(GlobalApplicationKt.preferenceRepository.getString(KEY_ACCOUNT_KEY, "-1"));
        nowAccountList.setOnPreferenceChangeListener((preference, newValue) -> {
            if (newValue.equals("-1")) {
                startActivityForResult(new Intent(getContext(), OAuthActivity.class), REQUEST_OAUTH_OR_CANCEL);
                return false;
            } else {
                AccessToken accessToken = GlobalApplicationKt.getAccountsModel(requireActivity()).get((String) newValue);
                ((GlobalApplication) requireActivity().getApplication()).initCurrentClient(accessToken);
                startActivity(new Intent(getContext(), MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
                return true;
            }
        });
        List<AccessToken> accessTokensTwitter = accountsModel.getAccessTokensByType(CLIENT_TYPE_TWITTER);
        CharSequence[] entriesLinkOpen = new CharSequence[accessTokensTwitter.size() + 1];
        CharSequence[] entriesLinkOpenValue = new CharSequence[accessTokensTwitter.size() + 1];
        for (int i = 0; i < accessTokensTwitter.size(); i++) {
            AccessToken accessToken = accessTokensTwitter.get(i);
            entriesLinkOpen[i] = TwitterStringUtils.plusAtMark(accessToken.getScreenName(), accessToken.getUrl());
            entriesLinkOpenValue[i] = accessToken.getKeyString();
        }
        entriesLinkOpen[entriesLinkOpen.length - 1] = getString(R.string.not_set);
        entriesLinkOpenValue[entriesLinkOpenValue.length - 1] = "-1";
        ListPreference linkOpenAccountList = findPreference(KEY_ACCOUNT_KEY_LINK_OPEN);
        linkOpenAccountList.setEntries(entriesLinkOpen);
        linkOpenAccountList.setEntryValues(entriesLinkOpenValue);
        linkOpenAccountList.setDefaultValue("-1");
        findPreference("logout").setOnPreferenceClickListener(preference -> {
            new AlertDialog.Builder(requireContext()).setMessage(R.string.confirm_logout).setCancelable(true).setPositiveButton(R.string.do_logout, (dialog, i) -> {
                accountsModel.delete(accountsModel.get(GlobalApplicationKt.preferenceRepository.getString(KEY_ACCOUNT_KEY, "-1")));
                int point = accountsModel.size() - 1;
                if (point != -1) {
                    AccessToken accessToken = accountsModel.getAccessTokens().get(point);
                    GlobalApplicationKt.preferenceRepository.putString(KEY_ACCOUNT_KEY, accessToken.getKeyString());
                    ((GlobalApplication) requireActivity().getApplication()).initCurrentClient(accessToken);
                    startActivity(new Intent(getContext(), MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
                } else {
                    GlobalApplicationKt.preferenceRepository.putString(KEY_ACCOUNT_KEY, "-1");
                    ((GlobalApplication) requireActivity().getApplication()).clearCurrentClient();
                    startActivity(new Intent(getContext(), MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
                }
            }).setNegativeButton(android.R.string.cancel, null).show();
            return false;
        });
        ListPreference nowThemeMode = findPreference(KEY_NIGHT_MODE);
        nowThemeMode.setOnPreferenceChangeListener((preference, newValue) -> {
            AppCompatDelegate.setDefaultNightMode(ThemePreferenceConverterKt.convertToAppCompatNightThemeMode(String.valueOf(newValue)));
            ((AppCompatActivity) requireActivity()).getDelegate().applyDayNight();
            return true;
        });
        Preference licenseThisApp = findPreference("license_at_this_app");
        licenseThisApp.setOnPreferenceClickListener(preference -> {
            requireContext().startActivity(new Intent(getContext(), LicensesActivity.class).putExtra("title", getResources().getText(R.string.app_name)).putExtra("library_name", "twitlatte"));
            return true;
        });
        Preference sourceCodeLink = findPreference("source_code_link");
        sourceCodeLink.setOnPreferenceClickListener(preference -> {
            AppCustomTabsKt.launchChromeCustomTabs(requireContext(), "https://github.com/moko256/twitlatte", false);
            return true;
        });
        Preference version = findPreference("app_version");
        version.setSummary(BuildConfig.VERSION_NAME);
        version.setOnPreferenceClickListener(preference -> {
            eggCount--;
            if (eggCount <= 0) {
                startActivity(new Intent(getActivity(), AboutActivity.class));
                eggCount = 3;
            }
            return true;
        });
    } else if (rootKey.equals("regexMute")) {
        PreferenceScreen regexMute = getPreferenceScreen();
        for (int i = 0, length = regexMute.getPreferenceCount(); i < length; i++) {
            Preference name = regexMute.getPreference(i);
            if (name instanceof EditTextPreference) {
                name.setOnPreferenceChangeListener((preference, newValue) -> {
                    try {
                        GlobalApplicationKt.preferenceRepository.updateRegex(preference.getKey(), (String) newValue);
                    } catch (PatternSyntaxException e) {
                        e.printStackTrace();
                        Toast.makeText(requireContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                    return true;
                });
            }
        }
    } else if (rootKey.equals("license")) {
        PreferenceScreen license = getPreferenceScreen();
        for (int i = 0, length = license.getPreferenceCount(); i < length; i++) {
            license.getPreference(i).setOnPreferenceClickListener(preference -> {
                startActivity(new Intent(getContext(), LicensesActivity.class).putExtra("title", preference.getTitle()).putExtra("library_name", // "license_lib_".length
                preference.getKey().substring(12)));
                return true;
            });
        }
    } else if (rootKey.equals("contributors")) {
        PreferenceScreen contributorCategory = getPreferenceScreen();
        for (int c = 0, length = contributorCategory.getPreferenceCount(); c < length; c++) {
            PreferenceCategory contributor = (PreferenceCategory) contributorCategory.getPreference(c);
            for (int i = 0, l = contributor.getPreferenceCount(); i < l; i++) {
                Preference name = contributor.getPreference(i);
                String uri = "https://github.com/" + name.getKey();
                name.setSummary(uri);
                name.setOnPreferenceClickListener(preference -> {
                    AppCustomTabsKt.launchChromeCustomTabs(requireContext(), uri, false);
                    return true;
                });
            }
        }
    }
}
Also used : AlertDialog(androidx.appcompat.app.AlertDialog) Bundle(android.os.Bundle) AlertDialog(androidx.appcompat.app.AlertDialog) ThemePreferenceConverterKt(com.github.moko256.twitlatte.text.ThemePreferenceConverterKt) KEY_ACCOUNT_KEY_LINK_OPEN(com.github.moko256.twitlatte.repository.PreferenceRepositoryKt.KEY_ACCOUNT_KEY_LINK_OPEN) RESULT_OK(android.app.Activity.RESULT_OK) PreferenceCategory(androidx.preference.PreferenceCategory) AccountsModel(com.github.moko256.twitlatte.model.AccountsModel) Intent(android.content.Intent) CLIENT_TYPE_TWITTER(com.github.moko256.latte.client.twitter.TwitterApiClientImplKt.CLIENT_TYPE_TWITTER) AppCompatActivity(androidx.appcompat.app.AppCompatActivity) PreferenceFragmentCompat(androidx.preference.PreferenceFragmentCompat) AppCustomTabsKt(com.github.moko256.twitlatte.intent.AppCustomTabsKt) TwitterStringUtils(com.github.moko256.twitlatte.text.TwitterStringUtils) Toast(android.widget.Toast) EditTextPreference(androidx.preference.EditTextPreference) PreferenceScreen(androidx.preference.PreferenceScreen) PatternSyntaxException(java.util.regex.PatternSyntaxException) AppCompatDelegate(androidx.appcompat.app.AppCompatDelegate) KEY_ACCOUNT_KEY(com.github.moko256.twitlatte.repository.PreferenceRepositoryKt.KEY_ACCOUNT_KEY) Preference(androidx.preference.Preference) AccessToken(com.github.moko256.latte.client.base.entity.AccessToken) List(java.util.List) KEY_NIGHT_MODE(com.github.moko256.twitlatte.repository.PreferenceRepositoryKt.KEY_NIGHT_MODE) Nullable(androidx.annotation.Nullable) ListPreference(androidx.preference.ListPreference) PreferenceScreen(androidx.preference.PreferenceScreen) AccountsModel(com.github.moko256.twitlatte.model.AccountsModel) Intent(android.content.Intent) ListPreference(androidx.preference.ListPreference) EditTextPreference(androidx.preference.EditTextPreference) EditTextPreference(androidx.preference.EditTextPreference) Preference(androidx.preference.Preference) ListPreference(androidx.preference.ListPreference) PreferenceCategory(androidx.preference.PreferenceCategory) AccessToken(com.github.moko256.latte.client.base.entity.AccessToken) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 5 with CLIENT_TYPE_TWITTER

use of com.github.moko256.latte.client.twitter.TwitterApiClientImplKt.CLIENT_TYPE_TWITTER in project twicalico by moko256.

the class OAuthActivity method startAuthAndOpenDialogIfNeeded.

private void startAuthAndOpenDialogIfNeeded(@NonNull String url) {
    String callbackUrl;
    if (requirePin) {
        showPinDialog();
        callbackUrl = null;
    } else {
        callbackUrl = getString(R.string.app_name) + "://OAuthActivity";
    }
    if (useAnotherConsumerToken && authClientType == CLIENT_TYPE_TWITTER) {
        compositeDisposable.add(EditTextsDialogShowerKt.createEditTextsDialog(this, "Consumer key/secret", true, null, new DialogContent("consumer key", enteringConsumerKey, EditorInfo.TYPE_CLASS_TEXT, ck -> {
            enteringConsumerKey = ck;
            return Unit.INSTANCE;
        }), new DialogContent("consumer secret", enteringConsumerSecret, EditorInfo.TYPE_CLASS_TEXT, cs -> {
            enteringConsumerSecret = cs;
            return Unit.INSTANCE;
        })).subscribe(() -> startAuth(url, callbackUrl, enteringConsumerKey, enteringConsumerSecret)));
    } else {
        startAuth(url, callbackUrl, null, null);
    }
}
Also used : OAuthModelImpl(com.github.moko256.twitlatte.model.impl.OAuthModelImpl) Bundle(android.os.Bundle) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) DialogContent(com.github.moko256.twitlatte.view.DialogContent) Intent(android.content.Intent) CLIENT_TYPE_TWITTER(com.github.moko256.latte.client.twitter.TwitterApiClientImplKt.CLIENT_TYPE_TWITTER) AppCompatActivity(androidx.appcompat.app.AppCompatActivity) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) AppCustomTabsKt(com.github.moko256.twitlatte.intent.AppCustomTabsKt) OAuthModel(com.github.moko256.twitlatte.model.base.OAuthModel) MenuItem(android.view.MenuItem) CustomTabsIntent(androidx.browser.customtabs.CustomTabsIntent) Toast(android.widget.Toast) Menu(android.view.Menu) TokenSQLiteOpenHelper(com.github.moko256.twitlatte.database.TokenSQLiteOpenHelper) View(android.view.View) Schedulers(io.reactivex.schedulers.Schedulers) CLIENT_TYPE_NOTHING(com.github.moko256.latte.client.base.ApiClientKt.CLIENT_TYPE_NOTHING) ContextCompat(androidx.core.content.ContextCompat) OAuthApiClientGeneratorKt(com.github.moko256.twitlatte.api.OAuthApiClientGeneratorKt) EditTextsDialogShowerKt(com.github.moko256.twitlatte.view.EditTextsDialogShowerKt) KEY_ACCOUNT_KEY(com.github.moko256.twitlatte.repository.PreferenceRepositoryKt.KEY_ACCOUNT_KEY) AccessToken(com.github.moko256.latte.client.base.entity.AccessToken) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) Unit(kotlin.Unit) EditorInfo(android.view.inputmethod.EditorInfo) OkHttpHolderKt(com.github.moko256.twitlatte.net.OkHttpHolderKt) CLIENT_TYPE_MASTODON(com.github.moko256.latte.client.mastodon.MastodonApiClientImplKt.CLIENT_TYPE_MASTODON) DialogContent(com.github.moko256.twitlatte.view.DialogContent)

Aggregations

Intent (android.content.Intent)3 Bundle (android.os.Bundle)3 View (android.view.View)3 AppCompatActivity (androidx.appcompat.app.AppCompatActivity)3 CLIENT_TYPE_TWITTER (com.github.moko256.latte.client.twitter.TwitterApiClientImplKt.CLIENT_TYPE_TWITTER)3 Uri (android.net.Uri)2 Menu (android.view.Menu)2 MenuItem (android.view.MenuItem)2 ImageView (android.widget.ImageView)2 TextView (android.widget.TextView)2 Toast (android.widget.Toast)2 NonNull (androidx.annotation.NonNull)2 AlertDialog (androidx.appcompat.app.AlertDialog)2 ContextCompat (androidx.core.content.ContextCompat)2 AccessToken (com.github.moko256.latte.client.base.entity.AccessToken)2 CLIENT_TYPE_MASTODON (com.github.moko256.latte.client.mastodon.MastodonApiClientImplKt.CLIENT_TYPE_MASTODON)2 AppCustomTabsKt (com.github.moko256.twitlatte.intent.AppCustomTabsKt)2 KEY_ACCOUNT_KEY (com.github.moko256.twitlatte.repository.PreferenceRepositoryKt.KEY_ACCOUNT_KEY)2 AndroidSchedulers (io.reactivex.android.schedulers.AndroidSchedulers)2 CompositeDisposable (io.reactivex.disposables.CompositeDisposable)2