Search in sources :

Example 1 with Token

use of com.ichi2.libanki.template.Tokenizer.Token in project AnkiChinaAndroid by ankichinateam.

the class AbstractFlashcardViewer method readCardText.

private void readCardText(final Card card, final SoundSide cardSide) {
    final String cardSideContent;
    if (!cardContentIsEmpty() && ((sDisplayAnswer && mFinalLoadAnswer.isEmpty()) || (!sDisplayAnswer && mFinalLoadQuestion.isEmpty()))) {
        mainHandler.postDelayed(() -> {
            showProgressBar();
            Toast.makeText(AbstractFlashcardViewer.this, "卡牌加载中,网络不佳", Toast.LENGTH_SHORT).show();
        }, 3000);
        nNeedSpeakFinalRenderContent = true;
        if (!fetchingRenderContent) {
            fetchWebViewRenderContent(mCardWebView);
        }
        return;
    }
    mainHandler.removeCallbacksAndMessages(null);
    hideProgressBar();
    // 在这里获取最后的内容
    cardSideContent = cardSide == SoundSide.QUESTION ? mFinalLoadQuestion : mFinalLoadAnswer;
    Timber.i("finally i wanna say:%s,showing answer:%s", cardSideContent, sDisplayAnswer);
    // 如果不是设置了离线模式且当前没网时,且非强制离线模式,则默认使用在线模式
    if (AnkiDroidApp.getSharedPrefs(this).getBoolean(KEY_SELECT_ONLINE_SPEAK_ENGINE, false) && !mOfflineSpeakingForOnce) {
        // 使用在线语音引擎
        File target = new File(FileUtil.createTmpDir(this), card.getId() + "-" + cardSide + ".wav");
        Timber.i("target audio :%s", target.getAbsolutePath());
        if (target.exists()) {
            Timber.i("target audio is exists,play it now");
            mSoundPlayer.playSound(target.getAbsolutePath(), mp -> mOnlineSpeaking = false);
            mOnlineSpeaking = true;
            speakingHandler.postDelayed(speakingRunnable, 300);
            return;
        }
        if (!isNetworkAvailable(AbstractFlashcardViewer.this)) {
            CustomStyleDialog customStyleDialog = new CustomStyleDialog.Builder(AbstractFlashcardViewer.this).setCustomLayout(R.layout.dialog_common_custom_next).setTitle("在线朗读需联网!").centerTitle().setMessage("没有网络时可以点下方按钮切换成本地引擎").setPositiveButton("切换本地引擎", (dialog, which) -> {
                dialog.dismiss();
                AnkiDroidApp.getSharedPrefs(this).edit().putBoolean(KEY_SELECT_ONLINE_SPEAK_ENGINE, false).apply();
            }).create();
            customStyleDialog.show();
            return;
        }
        getAccount().getToken(this, new MyAccount.TokenCallback() {

            @Override
            public void onSuccess(String token) {
                mCacheToken = token;
                // if (mFreeOnlineEngineCount != -10086) {
                // if (mFreeOnlineEngineCount > 0) {
                // String voice=ReadText.getAzureLanguage(card.getDid(), card.getOrd(), cardSide);
                // if (voice.isEmpty()) {
                // //选择语言
                // CustomStyleDialog d = new CustomStyleDialog.Builder(AbstractFlashcardViewer.this)
                // .setCustomLayout(R.layout.dialog_common_custom_next)
                // .setTitle("首次朗读,请设置语言")
                // .centerTitle()
                // .setMessage("设置语言后,朗读效果更优,还可以选择是否自动朗读。")
                // .setPositiveButton("前往设置", (dialog, which) -> {
                // dialog.dismiss();
                // SpeakSettingActivity.OpenSpeakSetting(card.getId(), card.getDid(), AbstractFlashcardViewer.this);
                // })  .create();
                // d.show();
                // return;
                // }
                List<Pair<String, String>> texts = splitAry(cardSideContent, 59, String.valueOf(card.getId()), cardSide);
                Map<String, String> params = new HashMap<>();
                params.put(SpeechSynthesizer.PARAM_SPEED, String.valueOf(ReadText.getSpeechRate(mCurrentCard.getDid(), mCurrentCard.getOrd()) * 5));
                synthesizer.setParams(params);
                int result = synthesizer.batchSpeak(texts);
                checkResult(result, "speak");
            // 
            // } else {
            // CustomStyleDialog customStyleDialog = new CustomStyleDialog.Builder(AbstractFlashcardViewer.this)
            // .setCustomLayout(R.layout.dialog_common_custom_next)
            // .setTitle("在线朗读次数已用完")
            // .centerTitle()
            // .setMessage("请前往充值在线朗读次数,学霸用户可以切换离线引擎,不限朗读次数")
            // .setPositiveButton("前往充值", (dialog, which) -> {
            // dialog.dismiss();
            // WebViewActivity.openUrlInApp(AbstractFlashcardViewer.this, String.format(mBuyOnlineEngineUrl, token, BuildConfig.VERSION_NAME), token, REFRESH_VOICE_INFO);
            // }).setNegativeButton("使用离线引擎", (dialog, which) -> {
            // dialog.dismiss();
            // AnkiDroidApp.getSharedPrefs(AbstractFlashcardViewer.this).edit().putBoolean(KEY_SELECT_ONLINE_SPEAK_ENGINE, false).apply();
            // })
            // 
            // .create();
            // 
            // customStyleDialog.show();
            // }
            // } else {
            // updateOnlineVoiceInfo(token);
            // }
            }

            @Override
            public void onFail(String message) {
                Timber.e("need login while using online speak engine ");
                Toast.makeText(AbstractFlashcardViewer.this, "当前未使用Anki记忆卡账号登录,无法使用在线语音引擎", Toast.LENGTH_SHORT).show();
                Intent myAccount = new Intent(AbstractFlashcardViewer.this, MyAccount.class);
                myAccount.putExtra("notLoggedIn", true);
                startActivityForResultWithAnimation(myAccount, REFRESH_VOICE_INFO, ActivityTransitionAnimation.FADE);
            }
        });
        speakingHandler.postDelayed(speakingRunnable, 300);
        return;
    }
    mOfflineSpeakingForOnce = false;
    String clozeReplacement = this.getString(R.string.reviewer_tts_cloze_spoken_replacement);
    ReadText.readCardSide(cardSide, cardSideContent, card.getId(), getDeckIdForCard(card), card.getOrd(), clozeReplacement, true);
    speakingHandler.postDelayed(speakingRunnable, 300);
}
Also used : JavascriptInterface(android.webkit.JavascriptInterface) UI_PLAY_END(com.ichi2.bd.MainHandlerConstant.UI_PLAY_END) Version(com.github.zafarkhaja.semver.Version) Bundle(android.os.Bundle) TagsDialog(com.ichi2.anki.dialogs.TagsDialog) JsResult(android.webkit.JsResult) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) AbstractSched(com.ichi2.libanki.sched.AbstractSched) RangeSeekBar(com.jaygoo.widget.RangeSeekBar) RenderProcessGoneDetail(android.webkit.RenderProcessGoneDetail) HitTestResult(android.webkit.WebView.HitTestResult) ActionBar(androidx.appcompat.app.ActionBar) FileSaveListener(com.ichi2.bd.FileSaveListener) Decks(com.ichi2.libanki.Decks) Matcher(java.util.regex.Matcher) Handler(android.os.Handler) DeckConfig(com.ichi2.libanki.DeckConfig) Map(java.util.Map) JSONException(com.ichi2.utils.JSONException) THEME_NIGHT_BLACK(com.ichi2.themes.Themes.THEME_NIGHT_BLACK) OnRangeChangedListener(com.jaygoo.widget.OnRangeChangedListener) ContextCompat(androidx.core.content.ContextCompat) TargetApi(android.annotation.TargetApi) Log(android.util.Log) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) ConnectivityManager(android.net.ConnectivityManager) HtmlUtils(com.ichi2.utils.HtmlUtils) CoordinatorLayout(androidx.coordinatorlayout.widget.CoordinatorLayout) TtsMode(com.baidu.tts.client.TtsMode) IntentFilter(android.content.IntentFilter) CardMarker(com.ichi2.anki.reviewer.CardMarker) Set(java.util.Set) JSONObject(com.ichi2.utils.JSONObject) BE_VIP(com.ichi2.anki.DeckPicker.BE_VIP) IdRes(androidx.annotation.IdRes) StringRes(androidx.annotation.StringRes) Nullable(androidx.annotation.Nullable) Message(android.os.Message) Consts(com.ichi2.libanki.Consts) OKHttpUtil(com.ichi2.utils.OKHttpUtil) CompatHelper(com.ichi2.compat.CompatHelper) WebViewDebugging(com.ichi2.utils.WebViewDebugging) DiffEngine(com.ichi2.utils.DiffEngine) TypedAnswer(com.ichi2.anki.cardviewer.TypedAnswer) WebResourceResponse(android.webkit.WebResourceResponse) Dialog(android.app.Dialog) SystemClock(android.os.SystemClock) SdCardReceiver(com.ichi2.anki.receiver.SdCardReceiver) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) CardAppearance.calculateDynamicFontSize(com.ichi2.anki.cardviewer.CardAppearance.calculateDynamicFontSize) ViewAnimation(com.ichi2.anim.ViewAnimation) ArrayList(java.util.ArrayList) REFRESH_VOICE_INFO(com.ichi2.anki.DeckPicker.REFRESH_VOICE_INFO) WebResourceRequest(android.webkit.WebResourceRequest) Toast(android.widget.Toast) Menu(android.view.Menu) Connection(com.ichi2.async.Connection) Response(okhttp3.Response) Call(okhttp3.Call) CardAppearance(com.ichi2.anki.cardviewer.CardAppearance) WebChromeClient(android.webkit.WebChromeClient) LinkedHashSet(java.util.LinkedHashSet) PRINT(com.ichi2.bd.MainHandlerConstant.PRINT) CheckResult(androidx.annotation.CheckResult) MissingImageHandler(com.ichi2.anki.cardviewer.MissingImageHandler) FileOutputStream(java.io.FileOutputStream) TextUtils(android.text.TextUtils) IOException(java.io.IOException) SoundSide(com.ichi2.libanki.Sound.SoundSide) File(java.io.File) Gravity(android.view.Gravity) Lock(java.util.concurrent.locks.Lock) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) FileUtil(com.ichi2.utils.FileUtil) Configuration(android.content.res.Configuration) ActivityTransitionAnimation(com.ichi2.anim.ActivityTransitionAnimation) EditText(android.widget.EditText) SpeechSynthesizerListener(com.baidu.tts.client.SpeechSynthesizerListener) ImageButton(android.widget.ImageButton) REQUEST_CODE_SPEAK_SETTING(com.ichi2.anki.SpeakSettingActivity.REQUEST_CODE_SPEAK_SETTING) LinearLayout(android.widget.LinearLayout) URLDecoder(java.net.URLDecoder) HtmlColors(com.ichi2.themes.HtmlColors) GestureDetectorCompat(androidx.core.view.GestureDetectorCompat) WindowManager(android.view.WindowManager) NonBlockSyntherizer(com.ichi2.bd.NonBlockSyntherizer) FormBody(okhttp3.FormBody) ByteArrayInputStream(java.io.ByteArrayInputStream) ViewerCommand(com.ichi2.anki.cardviewer.ViewerCommand) Gson(com.google.gson.Gson) Locale(java.util.Locale) WebViewClient(android.webkit.WebViewClient) View(android.view.View) Button(android.widget.Button) TaskData(com.ichi2.async.TaskData) WebView(android.webkit.WebView) InitConfig(com.ichi2.bd.InitConfig) Auth(com.ichi2.bd.Auth) SimpleOnGestureListener(android.view.GestureDetector.SimpleOnGestureListener) SynthesizerTool(com.baidu.tts.client.SynthesizerTool) BroadcastReceiver(android.content.BroadcastReceiver) ViewGroup(android.view.ViewGroup) Timber(timber.log.Timber) IOfflineResourceConst(com.ichi2.bd.IOfflineResourceConst) MySyntherizer(com.ichi2.bd.MySyntherizer) List(java.util.List) TextView(android.widget.TextView) ActivityNotFoundException(android.content.ActivityNotFoundException) SpeechSynthesizer(com.baidu.tts.client.SpeechSynthesizer) KEY_SELECT_ONLINE_SPEAK_ENGINE(com.ichi2.libanki.Consts.KEY_SELECT_ONLINE_SPEAK_ENGINE) Toolbar(androidx.appcompat.widget.Toolbar) RelativeLayout(android.widget.RelativeLayout) THEME_NIGHT_DARK(com.ichi2.themes.Themes.THEME_NIGHT_DARK) OfflineResource(com.ichi2.bd.OfflineResource) AudioView(com.ichi2.anki.multimediacard.AudioView) Pattern(java.util.regex.Pattern) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Window(android.view.Window) EditorInfo(android.view.inputmethod.EditorInfo) Snackbar(com.google.android.material.snackbar.Snackbar) UnsupportedEncodingException(java.io.UnsupportedEncodingException) KEY_SHOW_TTS_ICON(com.ichi2.libanki.Consts.KEY_SHOW_TTS_ICON) Note(com.ichi2.libanki.Note) Context(android.content.Context) TaskListener(com.ichi2.async.TaskListener) UI_CHANGE_SYNTHES_TEXT_SELECTION(com.ichi2.bd.MainHandlerConstant.UI_CHANGE_SYNTHES_TEXT_SELECTION) KeyEvent(android.view.KeyEvent) Pair(android.util.Pair) Intent(android.content.Intent) ReviewerCustomFonts(com.ichi2.anki.reviewer.ReviewerCustomFonts) HashMap(java.util.HashMap) REFRESH_LOGIN_STATE_AND_TURN_TO_VIP_HTML(com.ichi2.anki.DeckPicker.REFRESH_LOGIN_STATE_AND_TURN_TO_VIP_HTML) Collection(com.ichi2.libanki.Collection) TypedArray(android.content.res.TypedArray) MenuItem(android.view.MenuItem) InputMethodManager(android.view.inputmethod.InputMethodManager) RequestBody(okhttp3.RequestBody) TASK_TYPE(com.ichi2.async.CollectionTask.TASK_TYPE) HashSet(java.util.HashSet) ConnectivityManagerCompat(androidx.core.net.ConnectivityManagerCompat) SuppressLint(android.annotation.SuppressLint) JSONArray(com.ichi2.utils.JSONArray) MotionEvent(android.view.MotionEvent) Build(android.os.Build) WeakReference(java.lang.ref.WeakReference) LinkedList(java.util.LinkedList) Sound(com.ichi2.libanki.Sound) Utils(com.ichi2.libanki.Utils) LoggerProxy(com.baidu.tts.chainofresponsibility.logger.LoggerProxy) Consumer(com.ichi2.utils.FunctionalInterfaces.Consumer) Function(com.ichi2.utils.FunctionalInterfaces.Function) UI_CHANGE_INPUT_TEXT_SELECTION(com.ichi2.bd.MainHandlerConstant.UI_CHANGE_INPUT_TEXT_SELECTION) FlagDef(com.ichi2.anki.reviewer.CardMarker.FlagDef) LayoutInflater(android.view.LayoutInflater) ReviewerUi(com.ichi2.anki.reviewer.ReviewerUi) CollectionTask(com.ichi2.async.CollectionTask) Chronometer(android.widget.Chronometer) Themes(com.ichi2.themes.Themes) Template(com.ichi2.libanki.template.Template) Color(android.graphics.Color) WebResourceError(android.webkit.WebResourceError) UI_PLAY_START(com.ichi2.bd.MainHandlerConstant.UI_PLAY_START) AdaptionUtil(com.ichi2.utils.AdaptionUtil) Card(com.ichi2.libanki.Card) Activity(android.app.Activity) VisibleForTesting(androidx.annotation.VisibleForTesting) CustomStyleDialog(com.ichi2.ui.CustomStyleDialog) Resources(android.content.res.Resources) OnClickListener(android.view.View.OnClickListener) CustomStyleDialog(com.ichi2.ui.CustomStyleDialog) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) Intent(android.content.Intent) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with Token

use of com.ichi2.libanki.template.Tokenizer.Token in project AnkiChinaAndroid by ankichinateam.

the class AbstractFlashcardViewer method consumeOnlineVoiceInfo.

private void consumeOnlineVoiceInfo(String token) {
    RequestBody formBody = new FormBody.Builder().build();
    OKHttpUtil.post(Consts.ANKI_CHINA_BASE + Consts.API_VERSION + "users/consumeVoice", formBody, token, "", new OKHttpUtil.MyCallBack() {

        @Override
        public void onFailure(Call call, IOException e) {
        }

        @Override
        public void onResponse(Call call, String token, Object arg1, Response response) {
            if (response.isSuccessful()) {
                try {
                    final org.json.JSONObject object = new org.json.JSONObject(response.body().string());
                    final org.json.JSONObject item = object.getJSONObject("data");
                    mFreeOnlineEngineCount = item.getInt("total");
                    // mFreeOnlineEngineCount = 100;
                    preferences.edit().putInt(Consts.KEY_REST_ONLINE_SPEAK_COUNT, mFreeOnlineEngineCount).apply();
                    Timber.e("consume voice successfully, current total is %d", mFreeOnlineEngineCount);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Timber.e("consume voice failed, error code %d", response.code());
            }
        }
    });
}
Also used : Call(okhttp3.Call) OKHttpUtil(com.ichi2.utils.OKHttpUtil) FormBody(okhttp3.FormBody) IOException(java.io.IOException) JSONException(com.ichi2.utils.JSONException) IOException(java.io.IOException) ActivityNotFoundException(android.content.ActivityNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) WebResourceResponse(android.webkit.WebResourceResponse) Response(okhttp3.Response) JSONObject(com.ichi2.utils.JSONObject) JSONObject(com.ichi2.utils.JSONObject) RequestBody(okhttp3.RequestBody)

Example 3 with Token

use of com.ichi2.libanki.template.Tokenizer.Token in project AnkiChinaAndroid by ankichinateam.

the class DeckPicker method getVipInfo.

public void getVipInfo() {
    mRefreshVipStateOnResume = false;
    if (!Permissions.hasStorageAccessPermission(this)) {
        return;
    }
    mVip = AnkiDroidApp.getSharedPrefs(DeckPicker.this).getBoolean(Consts.KEY_IS_VIP, false);
    mVipUrl = AnkiDroidApp.getSharedPrefs(DeckPicker.this).getString(Consts.KEY_VIP_URL, "");
    refreshVipState(true);
    getAccount().getToken(this, new MyAccount.TokenCallback() {

        @Override
        public void onSuccess(String token) {
            // 获取vip状态
            OKHttpUtil.get(Consts.ANKI_CHINA_BASE + Consts.API_VERSION + "users/vipInfo", token, "", new OKHttpUtil.MyCallBack() {

                @Override
                public void onFailure(Call call, IOException e) {
                    refreshVipState(false);
                    if (mOpenVipHtmlWhenGetUrl) {
                        mOpenVipHtmlWhenGetUrl = false;
                        runOnUiThread(() -> Toast.makeText(DeckPicker.this, "信息获取失败,请检查网络或稍候再试", Toast.LENGTH_SHORT).show());
                    }
                }

                @Override
                public void onResponse(Call call, String token, Object arg1, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        // Timber.i("init vip info successfully!:%s", response.body());
                        try {
                            final JSONObject object = new JSONObject(response.body().string());
                            final JSONObject item = object.getJSONObject("data");
                            mVipUrl = item.getString("vip_url");
                            Timber.i("get vip url :%s", mVipUrl);
                            if (!mVip && mTurnToVipHtml) {
                                mTurnToVipHtml = false;
                                WebViewActivity.openUrlInApp(DeckPicker.this, String.format(mVipUrl, token, BuildConfig.VERSION_NAME), token, BE_VIP);
                            }
                            mVip = item.getBoolean("is_vip");
                            mVipDay = item.getInt("vip_day");
                            mVipExpireAt = item.getString("vip_end_at");
                            AnkiDroidApp.getSharedPrefs(DeckPicker.this).edit().putBoolean(Consts.KEY_IS_VIP, mVip).putString(Consts.KEY_VIP_URL, mVipUrl).putString(Consts.KEY_VIP_EXPIRED, mVipExpireAt).apply();
                            if (mOpenVipHtmlWhenGetUrl) {
                                mOpenVipHtmlWhenGetUrl = false;
                                openVipUrl(mVipUrl);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        Timber.e("init vip info failed, error code %d", response.code());
                    }
                    refreshVipState(true);
                }
            });
        }

        @Override
        public void onFail(String message) {
            OKHttpUtil.get(Consts.ANKI_CHINA_BASE + Consts.API_VERSION + "users/vipInfo", "", "", new OKHttpUtil.MyCallBack() {

                @Override
                public void onFailure(Call call, IOException e) {
                    refreshVipState(false);
                }

                @Override
                public void onResponse(Call call, String token, Object arg1, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        Timber.i("init vip info successfully!:%s", response.body());
                        try {
                            final JSONObject object = new JSONObject(response.body().string());
                            final JSONObject item = object.getJSONObject("data");
                            mVipUrl = item.getString("vip_url");
                            mVip = item.getBoolean("is_vip");
                            mVipDay = item.getInt("vip_day");
                            mVipExpireAt = item.getString("vip_end_at");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        Timber.e("init vip info failed, error code %d", response.code());
                    }
                    refreshVipState(false);
                }
            });
        }
    });
}
Also used : Response(okhttp3.Response) Call(okhttp3.Call) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) SpannableString(android.text.SpannableString) IOException(java.io.IOException) JSONException(com.ichi2.utils.JSONException) CustomSyncServerUrlException(com.ichi2.libanki.sync.CustomSyncServerUrlException) IOException(java.io.IOException) ParseException(java.text.ParseException) ConfirmModSchemaException(com.ichi2.anki.exception.ConfirmModSchemaException)

Example 4 with Token

use of com.ichi2.libanki.template.Tokenizer.Token in project AnkiChinaAndroid by ankichinateam.

the class DeckPicker method onActivityResult.

@SuppressWarnings("deprecation")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    Timber.i("on activity result:%s", requestCode);
    if (requestCode == REQUEST_PATH_UPDATE) {
        // The collection path was inaccessible on startup so just close the activity and let user restart
        finishWithoutAnimation();
    } else if (resultCode == RESULT_MEDIA_EJECTED) {
        this.onSdCardNotMounted();
        return;
    } else if (resultCode == RESULT_DB_ERROR) {
        handleDbError();
        return;
    } else if (resultCode == RESULT_UPDATE_REST_SPACE) {
        getAccount().getToken(getBaseContext(), new MyAccount.TokenCallback() {

            @Override
            public void onSuccess(String token) {
                OKHttpUtil.get(Consts.ANKI_CHINA_BASE + Consts.API_VERSION + "clouds/current", token, new Object[] { "nothing", false }, checkRestServerSpaceListener);
            }

            @Override
            public void onFail(String message) {
                handleGetTokenFailed(message);
            }
        });
        return;
    }
    if (requestCode == REPORT_ERROR) {
        showStartupScreensAndDialogs(AnkiDroidApp.getSharedPrefs(this), 4);
    } else if (requestCode == SHOW_INFO_WELCOME || requestCode == SHOW_INFO_NEW_VERSION) {
        if (resultCode == RESULT_OK) {
            showStartupScreensAndDialogs(AnkiDroidApp.getSharedPrefs(this), requestCode == SHOW_INFO_WELCOME ? 2 : 3);
        } else {
            finishWithAnimation(ActivityTransitionAnimation.DOWN);
        }
    } else if (requestCode == LOG_IN_FOR_SYNC) {
        mRefreshVipStateOnResume = true;
        mSyncOnResume = resultCode == RESULT_OK;
    } else if ((requestCode == REQUEST_REVIEW || requestCode == SHOW_STUDYOPTIONS) && resultCode == Reviewer.RESULT_NO_MORE_CARDS) {
        // Show a message when reviewing has finished
        if (getCol().getSched().count() == 0) {
            UIUtils.showSimpleSnackbar(this, R.string.studyoptions_congrats_finished, false);
        } else {
            UIUtils.showSimpleSnackbar(this, R.string.studyoptions_no_cards_due, false);
        }
        refreshDeckListUI(false);
    } else if (requestCode == REQUEST_BROWSE_CARDS) {
        // Store the selected deck after opening browser
        if (intent != null && intent.getBooleanExtra("allDecksSelected", false)) {
            AnkiDroidApp.getSharedPrefs(this).edit().putLong("browserDeckIdFromDeckPicker", -1L).apply();
        } else {
            long selectedDeck = getCol().getDecks().selected();
            AnkiDroidApp.getSharedPrefs(this).edit().putLong("browserDeckIdFromDeckPicker", selectedDeck).apply();
        }
    }
    if (requestCode == BE_VIP || requestCode == REFRESH_LOGIN_STATE_AND_TURN_TO_VIP_HTML || requestCode == SHOW_STUDYOPTIONS || requestCode == CHANGE_ACCOUNT) {
        mRefreshVipStateOnResume = true;
        mSyncOnResume = requestCode == CHANGE_ACCOUNT;
        mTurnToVipHtml = requestCode == REFRESH_LOGIN_STATE_AND_TURN_TO_VIP_HTML;
    } else {
        getSupportFragmentManager().getFragments();
        if (getSupportFragmentManager().getFragments().size() > 0) {
            List<Fragment> fragments = getSupportFragmentManager().getFragments();
            for (Fragment mFragment : fragments) {
                mFragment.onActivityResult(requestCode, resultCode, intent);
            }
        }
    }
}
Also used : SpannableString(android.text.SpannableString) Fragment(androidx.fragment.app.Fragment) AsyncDialogFragment(com.ichi2.anki.dialogs.AsyncDialogFragment)

Example 5 with Token

use of com.ichi2.libanki.template.Tokenizer.Token in project AnkiChinaAndroid by ankichinateam.

the class AnkiActivity method syncChina.

// private final OKHttpUtil.MyCallBack checkRestServerSpaceListener = new OKHttpUtil.MyCallBack() {
// @Override
// public void onFailure(Call call, IOException e) {
// 
// }
// 
// 
// @Override
// public void onResponse(Call call, String token, Object arg1, Response response) throws IOException {
// //            Timber.i("http get result:%s,body:%s", response.toString() ,response.body()==null?"":response.body().string());
// if (response.isSuccessful()) {
// try {
// org.json.JSONObject result = (new org.json.JSONObject(response.body().string())).getJSONObject("data");
// Timber.i("fetch server space result:%s ", result.toString());
// long total = result.getLong("origin_size");
// long used = result.getLong("origin_used_size");
// String totalStr = result.getString("size");
// String usedStr = result.getString("used_size");
// String hint = String.format("%s/%s", usedStr, totalStr);
// long rest = total - used;
// Timber.i("fetch server space result:%d,%d,%d", total, used, rest);
// saveServerRestSpace(rest);
// if (rest <= 0) {
// showNoSpaceDialog();
// return;
// }
// //获取剩余空间
// runOnUiThread(() ->syncChina(token) );
// } catch (org.json.JSONException e) {
// e.printStackTrace();
// }
// }
// }
// };
protected void syncChina(String token) {
    if (getServerRestSpace() <= 0) {
        showNoSpaceDialog();
        return;
    }
    AnkiChinaSyncer syncer = new AnkiChinaSyncer(AnkiActivity.this, token, new AnkiChinaSyncer.OnSyncCallback() {

        @Override
        public void onError(int code, String message) {
            onSyncChinaError(code, message);
        }

        @Override
        public void onCompletedAll() {
            onSyncCompletedAll();
        }

        @Override
        public void onCompletedData() {
            onSyncCompletedData();
        }
    });
    syncer.sync();
    onSyncChinaStart();
}
Also used : AnkiChinaSyncer(com.ichi2.libanki.sync.AnkiChinaSyncer)

Aggregations

IOException (java.io.IOException)14 Call (okhttp3.Call)13 Response (okhttp3.Response)13 JSONObject (com.ichi2.utils.JSONObject)10 OKHttpUtil (com.ichi2.utils.OKHttpUtil)8 File (java.io.File)7 FileNotFoundException (java.io.FileNotFoundException)7 ArrayList (java.util.ArrayList)6 RequestBody (okhttp3.RequestBody)6 Dialog (android.app.Dialog)5 SharedPreferences (android.content.SharedPreferences)5 SQLiteConstraintException (android.database.sqlite.SQLiteConstraintException)5 SpannableString (android.text.SpannableString)5 JSONArray (com.ichi2.utils.JSONArray)5 JSONObject (org.json.JSONObject)5 SuppressLint (android.annotation.SuppressLint)4 Intent (android.content.Intent)4 Color (android.graphics.Color)4 View (android.view.View)4 Window (android.view.Window)4