Search in sources :

Example 21 with TaskData

use of com.ichi2.async.TaskData in project AnkiChinaAndroid by ankichinateam.

the class CollectionTask method doInBackGroundAddField.

/**
 * Adds a field with name in given model
 */
private TaskData doInBackGroundAddField(TaskData param) {
    Timber.d("doInBackgroundRepositionField");
    Object[] objects = param.getObjArray();
    Model model = (Model) objects[0];
    String fieldName = (String) objects[1];
    Collection col = getCol();
    col.getModels().addFieldModChanged(model, col.getModels().newField(fieldName));
    col.save();
    return new TaskData(true);
}
Also used : Model(com.ichi2.libanki.Model) TemporaryModel(com.ichi2.anki.TemporaryModel) Collection(com.ichi2.libanki.Collection) JSONObject(com.ichi2.utils.JSONObject)

Example 22 with TaskData

use of com.ichi2.async.TaskData in project AnkiChinaAndroid by ankichinateam.

the class CollectionTask method doInBackgroundImportReplace.

private TaskData doInBackgroundImportReplace(TaskData param) {
    Timber.d("doInBackgroundImportReplace");
    String path = param.getString();
    Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources();
    // extract the deck from the zip file
    String colPath = CollectionHelper.getCollectionPath(mContext);
    File dir = new File(new File(colPath).getParentFile(), "tmpzip");
    if (dir.exists()) {
        BackupManager.removeDir(dir);
    }
    // from anki2.py
    String colname = "collection.anki21";
    ZipFile zip;
    try {
        zip = new ZipFile(new File(path));
    } catch (IOException e) {
        Timber.e(e, "doInBackgroundImportReplace - Error while unzipping");
        AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace0");
        return new TaskData(false);
    }
    try {
        // v2 scheduler?
        if (zip.getEntry(colname) == null) {
            colname = CollectionHelper.COLLECTION_FILENAME;
        }
        Utils.unzipFiles(zip, dir.getAbsolutePath(), new String[] { colname, "media" }, null);
    } catch (IOException e) {
        AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace - unzip");
        return new TaskData(false);
    }
    String colFile = new File(dir, colname).getAbsolutePath();
    if (!(new File(colFile)).exists()) {
        return new TaskData(false);
    }
    Collection tmpCol = null;
    try {
        tmpCol = Storage.Collection(mContext, colFile);
        if (!tmpCol.validCollection()) {
            tmpCol.close();
            return new TaskData(false);
        }
    } catch (Exception e) {
        Timber.e("Error opening new collection file... probably it's invalid");
        try {
            tmpCol.close();
        } catch (Exception e2) {
        // do nothing
        }
        AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace - open col");
        return new TaskData(false);
    } finally {
        if (tmpCol != null) {
            tmpCol.close();
        }
    }
    publishProgress(new TaskData(res.getString(R.string.importing_collection)));
    if (hasValidCol()) {
        // unload collection and trigger a backup
        Time time = CollectionHelper.getInstance().getTimeSafe(mContext);
        CollectionHelper.getInstance().closeCollection(true, "Importing new collection");
        CollectionHelper.getInstance().lockCollection();
        BackupManager.performBackupInBackground(colPath, true, time);
    }
    // overwrite collection
    File f = new File(colFile);
    if (!f.renameTo(new File(colPath))) {
        // Exit early if this didn't work
        return new TaskData(false);
    }
    int addedCount = -1;
    try {
        CollectionHelper.getInstance().unlockCollection();
        // because users don't have a backup of media, it's safer to import new
        // data and rely on them running a media db check to get rid of any
        // unwanted media. in the future we might also want to duplicate this step
        // import media
        HashMap<String, String> nameToNum = new HashMap<>();
        HashMap<String, String> numToName = new HashMap<>();
        File mediaMapFile = new File(dir.getAbsolutePath(), "media");
        if (mediaMapFile.exists()) {
            JsonReader jr = new JsonReader(new FileReader(mediaMapFile));
            jr.beginObject();
            String name;
            String num;
            while (jr.hasNext()) {
                num = jr.nextName();
                name = jr.nextString();
                nameToNum.put(name, num);
                numToName.put(num, name);
            }
            jr.endObject();
            jr.close();
        }
        String mediaDir = Media.getCollectionMediaPath(colPath);
        int total = nameToNum.size();
        int i = 0;
        for (Map.Entry<String, String> entry : nameToNum.entrySet()) {
            String file = entry.getKey();
            String c = entry.getValue();
            File of = new File(mediaDir, file);
            if (!of.exists()) {
                Utils.unzipFiles(zip, mediaDir, new String[] { c }, numToName);
            }
            ++i;
            publishProgress(new TaskData(res.getString(R.string.import_media_count, (i + 1) * 100 / total)));
        }
        zip.close();
        // delete tmp dir
        BackupManager.removeDir(dir);
        return new TaskData(true);
    } catch (RuntimeException e) {
        Timber.e(e, "doInBackgroundImportReplace - RuntimeException");
        AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace1");
        return new TaskData(false);
    } catch (FileNotFoundException e) {
        Timber.e(e, "doInBackgroundImportReplace - FileNotFoundException");
        AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace2");
        return new TaskData(false);
    } catch (IOException e) {
        Timber.e(e, "doInBackgroundImportReplace - IOException");
        AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace3");
        return new TaskData(false);
    }
}
Also used : HashMap(java.util.HashMap) FileNotFoundException(java.io.FileNotFoundException) Time(com.ichi2.libanki.utils.Time) IOException(java.io.IOException) 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) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) Collection(com.ichi2.libanki.Collection) JsonReader(com.google.gson.stream.JsonReader) FileReader(java.io.FileReader) Resources(android.content.res.Resources) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap)

Example 23 with TaskData

use of com.ichi2.async.TaskData in project AnkiChinaAndroid by ankichinateam.

the class CollectionTask method doInBackgroundLoadDeck.

private TaskData doInBackgroundLoadDeck() {
    Timber.d("doInBackgroundLoadDeckCounts");
    Collection col = CollectionHelper.getInstance().getCol(mContext);
    try {
        // Get due tree
        Object[] o = new Object[] { col.getSched().quickDeckDueTree() };
        return new TaskData(o);
    } catch (RuntimeException e) {
        Timber.w(e, "doInBackgroundLoadDeckCounts - error");
        return null;
    }
}
Also used : Collection(com.ichi2.libanki.Collection) JSONObject(com.ichi2.utils.JSONObject)

Example 24 with TaskData

use of com.ichi2.async.TaskData in project AnkiChinaAndroid by ankichinateam.

the class CollectionTask method doInBackgroundConfRemove.

private TaskData doInBackgroundConfRemove(TaskData param) {
    Timber.d("doInBackgroundConfRemove");
    Collection col = getCol();
    Object[] data = param.getObjArray();
    DeckConfig conf = (DeckConfig) data[0];
    try {
        // Note: We do the actual removing of the options group in the main thread so that we
        // can ask the user to confirm if they're happy to do a full sync, and just do the resorting here
        // When a conf is deleted, all decks using it revert to the default conf.
        // Cards must be reordered according to the default conf.
        int order = conf.getJSONObject("new").getInt("order");
        int defaultOrder = col.getDecks().getConf(1).getJSONObject("new").getInt("order");
        if (order != defaultOrder) {
            conf.getJSONObject("new").put("order", defaultOrder);
            col.getSched().resortConf(conf);
        }
        col.save();
        return new TaskData(true);
    } catch (JSONException e) {
        return new TaskData(false);
    }
}
Also used : Collection(com.ichi2.libanki.Collection) JSONException(com.ichi2.utils.JSONException) JSONObject(com.ichi2.utils.JSONObject) DeckConfig(com.ichi2.libanki.DeckConfig)

Example 25 with TaskData

use of com.ichi2.async.TaskData in project AnkiChinaAndroid by ankichinateam.

the class CollectionTask method doInBackgroundImportAdd.

private TaskData doInBackgroundImportAdd(TaskData param) {
    Timber.d("doInBackgroundImportAdd");
    Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources();
    Collection col = getCol();
    String path = param.getString();
    AnkiPackageImporter imp = new AnkiPackageImporter(col, path);
    imp.setProgressCallback(new ProgressCallback(this, res));
    try {
        imp.run();
    } catch (ImportExportException e) {
        return new TaskData(e.getMessage(), true);
    }
    return new TaskData(new Object[] { imp });
}
Also used : AnkiPackageImporter(com.ichi2.libanki.importer.AnkiPackageImporter) ImportExportException(com.ichi2.anki.exception.ImportExportException) Collection(com.ichi2.libanki.Collection) Resources(android.content.res.Resources)

Aggregations

Collection (com.ichi2.libanki.Collection)67 TaskData (com.ichi2.async.TaskData)46 JSONObject (com.ichi2.utils.JSONObject)35 Card (com.ichi2.libanki.Card)16 JSONException (com.ichi2.utils.JSONException)15 ArrayList (java.util.ArrayList)14 JSONObject (org.json.JSONObject)13 Resources (android.content.res.Resources)12 HashMap (java.util.HashMap)12 SharedPreferences (android.content.SharedPreferences)11 Deck (com.ichi2.libanki.Deck)11 Intent (android.content.Intent)10 View (android.view.View)9 TextView (android.widget.TextView)9 ConfirmationDialog (com.ichi2.anki.dialogs.ConfirmationDialog)9 TaskListener (com.ichi2.async.TaskListener)9 Map (java.util.Map)9 VisibleForTesting (androidx.annotation.VisibleForTesting)8 CollectionTask (com.ichi2.async.CollectionTask)8 IOException (java.io.IOException)8