Search in sources :

Example 1 with JSONObject

use of com.ichi2.utils.JSONObject in project AnkiChinaAndroid by ankichinateam.

the class AbstractFlashcardViewer method updateCard.

private void updateCard(final String newContent) {
    Timber.d("updateCard()");
    mCacheContent = newContent;
    mUseTimerDynamicMS = 0;
    // Add CSS for font color and font size
    if (mCurrentCard == null) {
        processCardAction(cardWebView -> cardWebView.getSettings().setDefaultFontSize(calculateDynamicFontSize(newContent)));
    }
    if (sDisplayAnswer) {
        addAnswerSounds(newContent);
    } else {
        // reset sounds each time first side of card is displayed, which may happen repeatedly without ever
        // leaving the card (such as when edited)
        mSoundPlayer.resetSounds();
        mAnswerSoundsAdded = false;
        mSoundPlayer.addSounds(mBaseUrl, newContent, SoundSide.QUESTION);
        if (mUseTimer && !mAnswerSoundsAdded && getConfigForCurrentCard().optBoolean("autoplay", false)) {
            addAnswerSounds(mCurrentCard.a());
        }
    }
    String content = Sound.expandSounds(mBaseUrl, newContent);
    content = CardAppearance.fixBoldStyle(content);
    Timber.v("content card = \n %s", content);
    String style = mCardAppearance.getStyle();
    Timber.v("::style:: / %s", style);
    // CSS class for card-specific styling
    String cardClass = mCardAppearance.getCardClass(mCurrentCard.getOrd() + 1, Themes.getCurrentTheme(this));
    if (Template.textContainsMathjax(content)) {
        cardClass += " mathjax-needs-to-render";
    }
    if (isInNightMode()) {
        if (!mCardAppearance.hasUserDefinedNightMode(mCurrentCard)) {
            content = HtmlColors.invertColors(content);
        }
    }
    content = CardAppearance.convertSmpToHtmlEntity(content);
    SharedPreferences prefs = AnkiDroidApp.getSharedPrefs(this);
    String localViewSettingStr = prefs.getString(Consts.KEY_LOCAL_LAYOUT_CONFIG, "");
    boolean dark = false;
    if (AnkiDroidApp.getSharedPrefs(this).getBoolean("invertedColors", false)) {
        int theme = Integer.parseInt(prefs.getString("nightTheme", "0"));
        dark = theme == THEME_NIGHT_DARK || theme == THEME_NIGHT_BLACK;
    }
    if (mCurrentCSS.isEmpty() || mCurrentCSSModelID != mCurrentCard.model().getLong("id")) {
        mCurrentCSSModelID = mCurrentCard.model().getLong("id");
        Timber.i("find new model id css %s", mCurrentCSS);
        if (localViewSettingStr != null && !localViewSettingStr.isEmpty()) {
            try {
                JSONObject viewSetting = new JSONObject(localViewSettingStr);
                JSONObject currentModelSetting = viewSetting.getJSONObject(String.valueOf(mCurrentCSSModelID));
                if (currentModelSetting != null) {
                    mCurrentCSS = convertJson2Css(currentModelSetting, false);
                } else {
                    mCurrentCSS = "";
                }
            } catch (Exception e) {
                e.printStackTrace();
                mCurrentCSS = "";
            }
        }
    }
    Timber.i("now theme is dark:%s", dark);
    if (!dark) {
        if (!mCurrentCSS.isEmpty()) {
            Matcher bgMatcher = Pattern.compile("background-color:(.+?);").matcher(mCurrentCSS);
            Window window = getWindow();
            if (bgMatcher.find()) {
                String fld1 = bgMatcher.group(1).trim();
                if (shouldChangeToolbarBgLikeCss2()) {
                    findViewById(R.id.toolbar).setBackgroundColor(Color.parseColor(fld1));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        window.setStatusBarColor(Color.parseColor(fld1));
                    }
                }
                mCardWebView.setBackgroundColor(Color.parseColor(fld1));
                findViewById(R.id.bottom_area_layout).setBackgroundColor(Color.parseColor(fld1));
            } else {
                if (shouldChangeToolbarBgLikeCss2()) {
                    int[] attrs = new int[] { R.attr.reviewStatusBarColor };
                    TypedArray ta = obtainStyledAttributes(attrs);
                    findViewById(R.id.toolbar).setBackground(ta.getDrawable(0));
                    ta.recycle();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        window.setStatusBarColor(Themes.getColorFromAttr(this, getStatusBarColorAttr()));
                    }
                }
                mCardWebView.setBackgroundColor(Color.WHITE);
                findViewById(R.id.bottom_area_layout).setBackgroundColor(Color.TRANSPARENT);
            }
        } else {
            if (shouldChangeToolbarBgLikeCss2()) {
                int[] attrs = new int[] { R.attr.reviewStatusBarColor };
                TypedArray ta = obtainStyledAttributes(attrs);
                findViewById(R.id.toolbar).setBackground(ta.getDrawable(0));
                ta.recycle();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    Window window = getWindow();
                    window.setStatusBarColor(Themes.getColorFromAttr(this, getStatusBarColorAttr()));
                }
            }
            mCardWebView.setBackgroundColor(Color.WHITE);
            findViewById(R.id.bottom_area_layout).setBackgroundColor(Color.TRANSPARENT);
        }
    }
    // if (mCurrentCSS.isEmpty()) {//保存的配置文件没有,则直接找默认的css
    // mCurrentCSS = mCurrentCard.css().replace("<style>", "").replace("</style>", "");
    // }
    mCardContent = mCardTemplate.replace("::content::", content).replace("::style::", style).replace("::class::", cardClass).replace("::style2::", mCurrentCSS).replace("::class2::", sDisplayAnswer ? "ck-back" : "ck-front");
    Timber.d("base url = %s", mBaseUrl);
    Timber.v("::content:: / %s", content);
    Timber.v("::style2:: / %s", mCurrentCSS);
    if (AnkiDroidApp.getSharedPrefs(this).getBoolean("html_javascript_debugging", false)) {
        try {
            try (FileOutputStream f = new FileOutputStream(new File(CollectionHelper.getCurrentAnkiDroidDirectory(this), "card.html"))) {
                f.write(mCardContent.getBytes());
            }
        } catch (IOException e) {
            Timber.d(e, "failed to save card");
        }
    }
    fillFlashcard();
    if (!mConfigurationChanged) {
        playSoundsVIP(false);
    }
}
Also used : Window(android.view.Window) SharedPreferences(android.content.SharedPreferences) Matcher(java.util.regex.Matcher) IOException(java.io.IOException) SuppressLint(android.annotation.SuppressLint) JSONException(com.ichi2.utils.JSONException) IOException(java.io.IOException) ActivityNotFoundException(android.content.ActivityNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONObject(com.ichi2.utils.JSONObject) TypedArray(android.content.res.TypedArray) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 2 with JSONObject

use of com.ichi2.utils.JSONObject in project AnkiChinaAndroid by ankichinateam.

the class AbstractFlashcardViewer method getAnswerFormat.

/**
 * getAnswerFormat returns the answer part of this card's template as entered by user, without any parsing
 */
public String getAnswerFormat() {
    JSONObject model = mCurrentCard.model();
    JSONObject template;
    if (model.getInt("type") == Consts.MODEL_STD) {
        template = model.getJSONArray("tmpls").getJSONObject(mCurrentCard.getOrd());
    } else {
        template = model.getJSONArray("tmpls").getJSONObject(0);
    }
    return template.getString("afmt");
}
Also used : JSONObject(com.ichi2.utils.JSONObject)

Example 3 with JSONObject

use of com.ichi2.utils.JSONObject in project AnkiChinaAndroid by ankichinateam.

the class ContentProviderTest method testInsertAndRemoveNote.

/**
 * Check that inserting and removing a note into default deck works as expected
 */
@Test
public void testInsertAndRemoveNote() {
    // Get required objects for test
    final ContentResolver cr = InstrumentationRegistry.getInstrumentation().getTargetContext().getContentResolver();
    // Add the note
    ContentValues values = new ContentValues();
    values.put(FlashCardsContract.Note.MID, mModelId);
    values.put(FlashCardsContract.Note.FLDS, Utils.joinFields(TEST_NOTE_FIELDS));
    values.put(FlashCardsContract.Note.TAGS, TEST_TAG);
    Uri newNoteUri = cr.insert(FlashCardsContract.Note.CONTENT_URI, values);
    assertNotNull("Check that URI returned from addNewNote is not null", newNoteUri);
    // test that the changes are physically saved to the DB
    final Collection col = reopenCol();
    // Check that it looks as expected
    assertNotNull("check note URI path", newNoteUri.getLastPathSegment());
    Note addedNote = new Note(col, Long.parseLong(newNoteUri.getLastPathSegment()));
    addedNote.load();
    assertArrayEquals("Check that fields were set correctly", addedNote.getFields(), TEST_NOTE_FIELDS);
    assertEquals("Check that tag was set correctly", TEST_TAG, addedNote.getTags().get(0));
    JSONObject model = col.getModels().get(mModelId);
    assertNotNull("Check model", model);
    int expectedNumCards = model.getJSONArray("tmpls").length();
    assertEquals("Check that correct number of cards generated", expectedNumCards, addedNote.numberOfCards());
    // Now delete the note
    cr.delete(newNoteUri, null, null);
    try {
        addedNote.load();
        fail("Expected RuntimeException to be thrown when deleting note");
    } catch (RuntimeException e) {
    // Expect RuntimeException to be thrown when loading deleted note
    }
}
Also used : ContentValues(android.content.ContentValues) JSONObject(com.ichi2.utils.JSONObject) Note(com.ichi2.libanki.Note) Collection(com.ichi2.libanki.Collection) Uri(android.net.Uri) ContentResolver(android.content.ContentResolver) Test(org.junit.Test)

Example 4 with JSONObject

use of com.ichi2.utils.JSONObject in project AnkiChinaAndroid by ankichinateam.

the class NoteEditor method updateCards.

/**
 * Update the list of card templates for current note type
 */
private void updateCards(JSONObject model) {
    Timber.d("updateCards()");
    JSONArray tmpls = model.getJSONArray("tmpls");
    StringBuilder cardsList = new StringBuilder();
    // Build comma separated list of card names
    Timber.d("updateCards() template count is %s", tmpls.length());
    for (int i = 0; i < tmpls.length(); i++) {
        String name = tmpls.getJSONObject(i).optString("name");
        // If more than one card, and we have an existing card, underline existing card
        if (!mAddNote && tmpls.length() > 1 && model == mEditorNote.model() && mCurrentEditedCard != null && mCurrentEditedCard.template().optString("name").equals(name)) {
            name = "<u>" + name + "</u>";
        }
        cardsList.append(name);
        if (i < tmpls.length() - 1) {
            cardsList.append(", ");
        }
    }
    // Make cards list red if the number of cards is being reduced
    if (!mAddNote && tmpls.length() < mEditorNote.model().getJSONArray("tmpls").length()) {
        cardsList = new StringBuilder("<font color='red'>" + cardsList + "</font>");
    }
    mCardsButton.setText(CompatHelper.getCompat().fromHtml(getResources().getString(R.string.CardEditorCards, cardsList.toString())));
}
Also used : JSONArray(com.ichi2.utils.JSONArray) SuppressLint(android.annotation.SuppressLint)

Example 5 with JSONObject

use of com.ichi2.utils.JSONObject 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)

Aggregations

JSONObject (com.ichi2.utils.JSONObject)272 JSONArray (com.ichi2.utils.JSONArray)110 ArrayList (java.util.ArrayList)59 Test (org.junit.Test)55 Collection (com.ichi2.libanki.Collection)46 IOException (java.io.IOException)40 RobolectricTest (com.ichi2.anki.RobolectricTest)34 JSONException (com.ichi2.utils.JSONException)34 Note (com.ichi2.libanki.Note)33 Model (com.ichi2.libanki.Model)31 HashMap (java.util.HashMap)31 SuppressLint (android.annotation.SuppressLint)29 JSONObject (org.json.JSONObject)27 Response (okhttp3.Response)25 JSONException (org.json.JSONException)24 NonNull (androidx.annotation.NonNull)23 Card (com.ichi2.libanki.Card)21 File (java.io.File)21 Map (java.util.Map)20 Intent (android.content.Intent)19