Search in sources :

Example 6 with JSONArray

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

the class CustomStudyDialog method customStudyFromTags.

private void customStudyFromTags(List<String> selectedTags, int option) {
    StringBuilder sb = new StringBuilder();
    switch(option) {
        case 1:
            sb.append("is:new ");
            break;
        case 2:
            sb.append("is:due ");
            break;
        default:
            // Logging here might be appropriate : )
            break;
    }
    List<String> arr = new ArrayList<>();
    if (selectedTags.size() > 0) {
        for (String tag : selectedTags) {
            arr.add(String.format("tag:'%s'", tag));
        }
        sb.append("(").append(TextUtils.join(" or ", arr)).append(")");
    }
    createCustomStudySession(new JSONArray(), new Object[] { sb.toString(), Consts.DYN_MAX_SIZE, Consts.DYN_RANDOM }, true);
}
Also used : ArrayList(java.util.ArrayList) JSONArray(com.ichi2.utils.JSONArray)

Example 7 with JSONArray

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

the class CardContentProvider method addModelToCursor.

private void addModelToCursor(Long modelId, Models models, MatrixCursor rv, String[] columns) {
    Model jsonObject = models.get(modelId);
    MatrixCursor.RowBuilder rb = rv.newRow();
    try {
        for (String column : columns) {
            if (column.equals(FlashCardsContract.Model._ID)) {
                rb.add(modelId);
            } else if (column.equals(FlashCardsContract.Model.NAME)) {
                rb.add(jsonObject.getString("name"));
            } else if (column.equals(FlashCardsContract.Model.FIELD_NAMES)) {
                JSONArray flds = jsonObject.getJSONArray("flds");
                String[] allFlds = new String[flds.length()];
                for (int idx = 0; idx < flds.length(); idx++) {
                    allFlds[idx] = flds.getJSONObject(idx).optString("name", "");
                }
                rb.add(Utils.joinFields(allFlds));
            } else if (column.equals(FlashCardsContract.Model.NUM_CARDS)) {
                rb.add(jsonObject.getJSONArray("tmpls").length());
            } else if (column.equals(FlashCardsContract.Model.CSS)) {
                rb.add(jsonObject.getString("css"));
            } else if (column.equals(FlashCardsContract.Model.DECK_ID)) {
                // #6378 - Anki Desktop changed schema temporarily to allow null
                rb.add(jsonObject.optLong("did", Consts.DEFAULT_DECK_ID));
            } else if (column.equals(FlashCardsContract.Model.SORT_FIELD_INDEX)) {
                rb.add(jsonObject.getLong("sortf"));
            } else if (column.equals(FlashCardsContract.Model.TYPE)) {
                rb.add(jsonObject.getLong("type"));
            } else if (column.equals(FlashCardsContract.Model.LATEX_POST)) {
                rb.add(jsonObject.getString("latexPost"));
            } else if (column.equals(FlashCardsContract.Model.LATEX_PRE)) {
                rb.add(jsonObject.getString("latexPre"));
            } else if (column.equals(FlashCardsContract.Model.NOTE_COUNT)) {
                rb.add(models.useCount(jsonObject));
            } else {
                throw new UnsupportedOperationException("Column \"" + column + "\" is unknown");
            }
        }
    } catch (JSONException e) {
        Timber.e(e, "Error parsing JSONArray");
        throw new IllegalArgumentException("Model " + modelId + " is malformed", e);
    }
}
Also used : Model(com.ichi2.libanki.Model) JSONArray(com.ichi2.utils.JSONArray) JSONException(com.ichi2.utils.JSONException) MatrixCursor(android.database.MatrixCursor)

Example 8 with JSONArray

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

the class CollectionTask method doInBackgroundSaveModel.

/**
 * Handles everything for a model change at once - template add / deletes as well as content updates
 */
private TaskData doInBackgroundSaveModel(TaskData param) {
    Timber.d("doInBackgroundSaveModel");
    Collection col = getCol();
    Object[] args = param.getObjArray();
    Model model = (Model) args[0];
    ArrayList<Object[]> templateChanges = (ArrayList<Object[]>) args[1];
    Model oldModel = col.getModels().get(model.getLong("id"));
    // TODO need to save all the cards that will go away, for undo
    // (do I need to remove them from graves during undo also?)
    // - undo (except for cards) could just be Models.update(model) / Models.flush() / Collection.reset() (that was prior "undo")
    JSONArray newTemplates = model.getJSONArray("tmpls");
    col.getDb().getDatabase().beginTransaction();
    try {
        for (Object[] change : templateChanges) {
            JSONArray oldTemplates = oldModel.getJSONArray("tmpls");
            switch((TemporaryModel.ChangeType) change[1]) {
                case ADD:
                    Timber.d("doInBackgroundSaveModel() adding template %s", change[0]);
                    try {
                        col.getModels().addTemplate(oldModel, newTemplates.getJSONObject((int) change[0]));
                    } catch (Exception e) {
                        Timber.e(e, "Unable to add template %s to model %s", change[0], model.getLong("id"));
                        return new TaskData(e.getLocalizedMessage(), false);
                    }
                    break;
                case DELETE:
                    Timber.d("doInBackgroundSaveModel() deleting template currently at ordinal %s", change[0]);
                    try {
                        col.getModels().remTemplate(oldModel, oldTemplates.getJSONObject((int) change[0]));
                    } catch (Exception e) {
                        Timber.e(e, "Unable to delete template %s from model %s", change[0], model.getLong("id"));
                        return new TaskData(e.getLocalizedMessage(), false);
                    }
                    break;
                default:
                    Timber.w("Unknown change type? %s", change[1]);
                    break;
            }
        }
        col.getModels().save(model, true);
        col.getModels().update(model);
        col.reset();
        col.save();
        if (col.getDb().getDatabase().inTransaction()) {
            col.getDb().getDatabase().setTransactionSuccessful();
        } else {
            Timber.i("CollectionTask::SaveModel was not in a transaction? Cannot mark transaction successful.");
        }
    } finally {
        if (col.getDb().getDatabase().inTransaction()) {
            col.getDb().getDatabase().endTransaction();
        } else {
            Timber.i("CollectionTask::SaveModel was not in a transaction? Cannot end transaction.");
        }
    }
    return new TaskData(true);
}
Also used : Model(com.ichi2.libanki.Model) TemporaryModel(com.ichi2.anki.TemporaryModel) ArrayList(java.util.ArrayList) JSONArray(com.ichi2.utils.JSONArray) Collection(com.ichi2.libanki.Collection) JSONObject(com.ichi2.utils.JSONObject) JSONException(com.ichi2.utils.JSONException) CancellationException(java.util.concurrent.CancellationException) FileNotFoundException(java.io.FileNotFoundException) ConfirmModSchemaException(com.ichi2.anki.exception.ConfirmModSchemaException) ImportExportException(com.ichi2.anki.exception.ImportExportException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException)

Example 9 with JSONArray

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

the class NoteService method createEmptyNote.

/**
 * Creates an empty Note from given Model
 *
 * @param model the model in JSOBObject format
 * @return a new note instance
 */
public static MultimediaEditableNote createEmptyNote(JSONObject model) {
    try {
        JSONArray fieldsArray = model.getJSONArray("flds");
        int numOfFields = fieldsArray.length();
        if (numOfFields > 0) {
            MultimediaEditableNote note = new MultimediaEditableNote();
            note.setNumFields(numOfFields);
            for (int i = 0; i < numOfFields; i++) {
                JSONObject fieldObject = fieldsArray.getJSONObject(i);
                TextField uiTextField = new TextField();
                uiTextField.setName(fieldObject.getString("name"));
                uiTextField.setText(fieldObject.getString("name"));
                note.setField(i, uiTextField);
            }
            note.setModelId(model.getLong("id"));
            return note;
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}
Also used : MultimediaEditableNote(com.ichi2.anki.multimediacard.impl.MultimediaEditableNote) IMultimediaEditableNote(com.ichi2.anki.multimediacard.IMultimediaEditableNote) JSONObject(com.ichi2.utils.JSONObject) JSONArray(com.ichi2.utils.JSONArray) TextField(com.ichi2.anki.multimediacard.fields.TextField) JSONException(com.ichi2.utils.JSONException)

Example 10 with JSONArray

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

the class Finder method findReplace.

/**
 * Find and replace fields in a note
 *
 * @param col     The collection to search into.
 * @param nids    The cards to be searched for.
 * @param src     The original text to find.
 * @param dst     The text to change to.
 * @param isRegex If true, the src is treated as a regex. Default = false.
 * @param field   Limit the search to specific field. If null, it searches all fields.
 * @param fold    If true the search is case-insensitive. Default = true.
 * @return Number of notes with fields that were updated.
 */
public static int findReplace(Collection col, List<Long> nids, String src, String dst, boolean isRegex, String field, boolean fold) {
    Map<Long, Integer> mmap = new HashMap<>();
    if (field != null) {
        for (JSONObject m : col.getModels().all()) {
            JSONArray flds = m.getJSONArray("flds");
            for (int fi = 0; fi < flds.length(); ++fi) {
                JSONObject f = flds.getJSONObject(fi);
                if (f.getString("name").equalsIgnoreCase(field)) {
                    mmap.put(m.getLong("id"), f.getInt("ord"));
                }
            }
        }
        if (mmap.isEmpty()) {
            return 0;
        }
    }
    // find and gather replacements
    if (!isRegex) {
        src = Pattern.quote(src);
        dst = dst.replace("\\", "\\\\");
    }
    if (fold) {
        src = "(?i)" + src;
    }
    Pattern regex = Pattern.compile(src);
    ArrayList<Object[]> d = new ArrayList<>();
    String snids = Utils.ids2str(nids);
    nids = new ArrayList<>();
    try (Cursor cur = col.getDb().getDatabase().query("select id, mid, flds from notes where id in " + snids, null)) {
        while (cur.moveToNext()) {
            String flds = cur.getString(2);
            String origFlds = flds;
            // does it match?
            String[] sflds = Utils.splitFields(flds);
            if (field != null) {
                long mid = cur.getLong(1);
                if (!mmap.containsKey(mid)) {
                    // note doesn't have that field
                    continue;
                }
                int ord = mmap.get(mid);
                sflds[ord] = regex.matcher(sflds[ord]).replaceAll(dst);
            } else {
                for (int i = 0; i < sflds.length; ++i) {
                    sflds[i] = regex.matcher(sflds[i]).replaceAll(dst);
                }
            }
            flds = Utils.joinFields(sflds);
            if (!flds.equals(origFlds)) {
                long nid = cur.getLong(0);
                nids.add(nid);
                // order based on query below
                d.add(new Object[] { flds, col.getTime().intTime(), col.usn(), nid });
            }
        }
    }
    if (d.isEmpty()) {
        return 0;
    }
    // replace
    col.getDb().executeMany("update notes set flds=?,mod=?,usn=? where id=?", d);
    long[] pnids = Utils.toPrimitive(nids);
    col.updateFieldCache(pnids);
    col.genCards(pnids);
    return d.size();
}
Also used : Pattern(java.util.regex.Pattern) HashMap(java.util.HashMap) JSONArray(com.ichi2.utils.JSONArray) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) JSONObject(com.ichi2.utils.JSONObject)

Aggregations

JSONArray (com.ichi2.utils.JSONArray)188 JSONObject (com.ichi2.utils.JSONObject)97 Collection (com.ichi2.libanki.Collection)54 Test (org.junit.Test)44 ArrayList (java.util.ArrayList)42 Note (com.ichi2.libanki.Note)40 Card (com.ichi2.libanki.Card)39 DeckConfig (com.ichi2.libanki.DeckConfig)37 RobolectricTest (com.ichi2.anki.RobolectricTest)36 Deck (com.ichi2.libanki.Deck)19 Model (com.ichi2.libanki.Model)19 JSONException (com.ichi2.utils.JSONException)19 Cursor (android.database.Cursor)17 HashMap (java.util.HashMap)16 SuppressLint (android.annotation.SuppressLint)15 IOException (java.io.IOException)14 NonNull (androidx.annotation.NonNull)13 File (java.io.File)10 Response (okhttp3.Response)10 JSONArray (org.json.JSONArray)8