Search in sources :

Example 26 with TaskData

use of com.ichi2.async.DeckTask.TaskData in project Anki-Android by Ramblurr.

the class DeckTask method doInBackgroundLoadDeckCounts.

private TaskData doInBackgroundLoadDeckCounts(TaskData... params) {
    Log.i(AnkiDroidApp.TAG, "doInBackgroundLoadDeckCounts");
    Collection col = params[0].getCollection();
    if (col == null) {
        return null;
    }
    try {
        return new TaskData(col.getSched().deckCounts());
    } catch (RuntimeException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundLoadDeckCounts - error: " + e);
        return null;
    }
}
Also used : Collection(com.ichi2.libanki.Collection)

Example 27 with TaskData

use of com.ichi2.async.DeckTask.TaskData in project Anki-Android by Ramblurr.

the class DeckTask method doInBackgroundUndo.

private TaskData doInBackgroundUndo(TaskData... params) {
    Sched sched = params[0].getSched();
    Collection col = sched.getCol();
    try {
        col.getDb().getDatabase().beginTransaction();
        Card newCard;
        try {
            long cid = col.undo();
            if (cid != 0) {
                // a review was undone,
                newCard = col.getCard(cid);
                col.reset();
                col.getSched().decrementCounts(newCard);
                sHadCardQueue = true;
            } else {
                // TODO: do not fetch new card if a non review operation has
                // been undone
                col.reset();
                newCard = getCard(sched);
            }
            // TODO: handle leech undoing properly
            publishProgress(new TaskData(newCard, 0));
            col.getDb().getDatabase().setTransactionSuccessful();
        } finally {
            col.getDb().getDatabase().endTransaction();
        }
    } catch (RuntimeException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundUndo - RuntimeException on undoing: " + e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundUndo");
        return new TaskData(false);
    }
    return new TaskData(true);
}
Also used : Sched(com.ichi2.libanki.Sched) Collection(com.ichi2.libanki.Collection) Card(com.ichi2.libanki.Card)

Example 28 with TaskData

use of com.ichi2.async.DeckTask.TaskData in project Anki-Android by Ramblurr.

the class DeckTask method doInBackgroundConfRemove.

private TaskData doInBackgroundConfRemove(TaskData... params) {
    Log.i(AnkiDroidApp.TAG, "doInBackgroundConfRemove");
    Object[] data = params[0].getObjArray();
    Collection col = (Collection) data[0];
    JSONObject conf = (JSONObject) data[1];
    try {
        // 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.getDecks().remConf(conf.getLong("id"));
        return new TaskData(true);
    } catch (JSONException e) {
        return new TaskData(false);
    }
}
Also used : JSONObject(org.json.JSONObject) Collection(com.ichi2.libanki.Collection) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject)

Example 29 with TaskData

use of com.ichi2.async.DeckTask.TaskData in project Anki-Android by Ramblurr.

the class DeckTask method doInBackgroundImportReplace.

private TaskData doInBackgroundImportReplace(TaskData... params) {
    Log.i(AnkiDroidApp.TAG, "doInBackgroundImportReplace");
    Collection col = params[0].getCollection();
    String path = params[0].getString();
    Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources();
    // extract the deck from the zip file
    String fileDir = AnkiDroidApp.getCurrentAnkiDroidDirectory() + "/tmpzip";
    File dir = new File(fileDir);
    if (dir.exists()) {
        BackupManager.removeDir(dir);
    }
    publishProgress(new TaskData(res.getString(R.string.import_unpacking)));
    // from anki2.py
    String colFile = fileDir + "/collection.anki2";
    ZipFile zip;
    try {
        zip = new ZipFile(new File(path), ZipFile.OPEN_READ);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - Error while unzipping: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace0");
        return new TaskData(false);
    }
    if (!Utils.unzipFiles(zip, fileDir, new String[] { "collection.anki2", "media" }, null) || !(new File(colFile)).exists()) {
        return new TaskData(-2, null, false);
    }
    Collection tmpCol = null;
    try {
        tmpCol = Storage.Collection(colFile);
        if (!tmpCol.validCollection()) {
            tmpCol.close();
            return new TaskData(-2, null, false);
        }
    } finally {
        if (tmpCol != null) {
            tmpCol.close();
        }
    }
    publishProgress(new TaskData(res.getString(R.string.importing_collection)));
    String colPath;
    if (col != null) {
        // unload collection and trigger a backup
        colPath = col.getPath();
        AnkiDroidApp.closeCollection(true);
        BackupManager.performBackup(colPath, true);
    }
    // overwrite collection
    colPath = AnkiDroidApp.getCollectionPath();
    File f = new File(colFile);
    f.renameTo(new File(colPath));
    int addedCount = -1;
    try {
        col = AnkiDroidApp.openCollection(colPath);
        // 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<String, String>();
        HashMap<String, String> numToName = new HashMap<String, String>();
        File mediaMapFile = new File(fileDir, "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 = col.getMedia().getDir();
        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);
        publishProgress(new TaskData(res.getString(R.string.import_update_counts)));
        // Update the counts
        DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col));
        if (result == null) {
            return null;
        }
        return new TaskData(addedCount, result.getObjArray(), true);
    } catch (RuntimeException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - RuntimeException: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace1");
        return new TaskData(false);
    } catch (FileNotFoundException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - FileNotFoundException: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace2");
        return new TaskData(false);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - IOException: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace3");
        return new TaskData(false);
    }
}
Also used : HashMap(java.util.HashMap) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) ZipFile(java.util.zip.ZipFile) Collection(com.ichi2.libanki.Collection) JsonReader(com.google.gson.stream.JsonReader) FileReader(java.io.FileReader) Resources(android.content.res.Resources) ZipFile(java.util.zip.ZipFile) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 30 with TaskData

use of com.ichi2.async.DeckTask.TaskData in project Anki-Android by Ramblurr.

the class DeckTask method doInBackgroundLoadTutorial.

private TaskData doInBackgroundLoadTutorial(TaskData... params) {
    Log.i(AnkiDroidApp.TAG, "doInBackgroundLoadTutorial");
    Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources();
    Collection col = params[0].getCollection();
    col.getDb().getDatabase().beginTransaction();
    String title = res.getString(R.string.help_tutorial);
    try {
        // get deck or create it
        long did = col.getDecks().id(title);
        // reset todays counts
        JSONObject d = col.getDecks().get(did);
        for (String t : new String[] { "new", "rev", "lrn", "time" }) {
            String k = t + "Today";
            JSONArray ja = new JSONArray();
            ja.put(col.getSched().getToday());
            ja.put(0);
            d.put(k, ja);
        }
        // save deck
        col.getDecks().save(d);
        if (col.getSched().cardCount("(" + did + ")") > 0) {
            // deck does already exist. Remove all cards and recreate them
            // to ensure the correct order
            col.remCards(col.getDecks().cids(did));
        }
        JSONObject model = col.getModels().byName(title);
        // }
        if (model == null) {
            model = col.getModels().addBasicModel(col, title);
        }
        model.put("did", did);
        String[] questions = res.getStringArray(R.array.tutorial_questions);
        String[] answers = res.getStringArray(R.array.tutorial_answers);
        String[] sampleQuestions = res.getStringArray(R.array.tutorial_capitals_questions);
        String[] sampleAnswers = res.getStringArray(R.array.tutorial_capitals_answers);
        int len = Math.min(questions.length, answers.length);
        for (int i = 0; i < len + Math.min(sampleQuestions.length, sampleAnswers.length); i++) {
            Note note = col.newNote(model);
            if (note.values().length < 2) {
                return new TaskData(false);
            }
            note.values()[0] = (i < len) ? questions[i] : sampleQuestions[i - len];
            note.values()[1] = (i < len) ? answers[i] : sampleAnswers[i - len];
            col.addNote(note);
        }
        // deck.setSessionTimeLimit(0);
        if (col.getSched().cardCount("(" + did + ")") == 0) {
            // error, delete deck
            col.getDecks().rem(did, true);
            return new TaskData(false);
        } else {
            col.save();
            col.getDecks().select(did);
            col.getDb().getDatabase().setTransactionSuccessful();
            return new TaskData(true);
        }
    } catch (SQLException e) {
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundLoadTutorial");
        return new DeckTask.TaskData(false);
    } catch (JSONException e) {
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundLoadTutorial");
        return new DeckTask.TaskData(false);
    } finally {
        col.getDb().getDatabase().endTransaction();
    }
}
Also used : SQLException(android.database.SQLException) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) Note(com.ichi2.libanki.Note) Collection(com.ichi2.libanki.Collection) Resources(android.content.res.Resources)

Aggregations

Collection (com.ichi2.libanki.Collection)24 JSONObject (org.json.JSONObject)13 JSONException (org.json.JSONException)8 TaskData (com.ichi2.async.DeckTask.TaskData)7 Resources (android.content.res.Resources)6 Sched (com.ichi2.libanki.Sched)6 AnkiDb (com.ichi2.anki.AnkiDb)5 Card (com.ichi2.libanki.Card)5 Note (com.ichi2.libanki.Note)5 File (java.io.File)5 DeckTask (com.ichi2.async.DeckTask)4 Intent (android.content.Intent)3 SharedPreferences (android.content.SharedPreferences)3 NotFoundException (android.content.res.Resources.NotFoundException)3 SQLException (android.database.SQLException)3 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 ZipFile (java.util.zip.ZipFile)3 DialogInterface (android.content.DialogInterface)2 OnCancelListener (android.content.DialogInterface.OnCancelListener)2