Search in sources :

Example 46 with Collection

use of com.ichi2.libanki.Collection 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 47 with Collection

use of com.ichi2.libanki.Collection 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)

Example 48 with Collection

use of com.ichi2.libanki.Collection in project Anki-Android by Ramblurr.

the class DeckTask method doInBackgroundConfReset.

private TaskData doInBackgroundConfReset(TaskData... params) {
    Log.i(AnkiDroidApp.TAG, "doInBackgroundConfReset");
    Object[] data = params[0].getObjArray();
    Collection col = (Collection) data[0];
    JSONObject conf = (JSONObject) data[1];
    col.getDecks().restoreToDefault(conf);
    return new TaskData(true);
}
Also used : JSONObject(org.json.JSONObject) Collection(com.ichi2.libanki.Collection) JSONObject(org.json.JSONObject)

Example 49 with Collection

use of com.ichi2.libanki.Collection in project Anki-Android by Ramblurr.

the class DeckTask method doInBackgroundOpenCollection.

private TaskData doInBackgroundOpenCollection(TaskData... params) {
    Log.i(AnkiDroidApp.TAG, "doInBackgroundOpenCollection");
    long time = Utils.intNow(1000);
    Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources();
    String collectionFile = params[0].getString();
    SharedPreferences prefs = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance().getBaseContext());
    // see, if a collection is still opened
    Collection oldCol = AnkiDroidApp.getCol();
    Collection col = null;
    publishProgress(new TaskData(res.getString(R.string.open_collection)));
    if (!(AnkiDroidApp.colIsOpen() && oldCol.getPath().equals(collectionFile))) {
        // android's delete db bug
        if (BackupManager.safetyBackupNeeded(collectionFile)) {
            publishProgress(new TaskData(res.getString(R.string.backup_collection)));
            BackupManager.performBackup(collectionFile);
        }
        publishProgress(new TaskData(res.getString(R.string.open_collection)));
        // load collection
        try {
            col = AnkiDroidApp.openCollection(collectionFile);
        } catch (RuntimeException e) {
            BackupManager.restoreCollectionIfMissing(collectionFile);
            Log.e(AnkiDroidApp.TAG, "doInBackgroundOpenCollection - RuntimeException on opening collection: " + e);
            AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundOpenCollection");
            return new TaskData(false);
        }
        // create tutorial deck if needed
        if (prefs.contains("createTutorial") && prefs.getBoolean("createTutorial", false)) {
            prefs.edit().remove("createTutorial").commit();
            publishProgress(new TaskData(res.getString(R.string.tutorial_load)));
            doInBackgroundLoadTutorial(new TaskData(col));
        }
    } else {
        Log.i(AnkiDroidApp.TAG, "doInBackgroundOpenCollection: collection still open - reusing it");
        col = oldCol;
    }
    Object[] counts = null;
    DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col));
    if (result != null) {
        counts = result.getObjArray();
    }
    if (prefs.getBoolean("splashScreen", false)) {
        long millies = Utils.intNow(1000) - time;
        if (millies < 1000) {
            try {
                Thread.sleep(1200 - millies);
            } catch (InterruptedException e) {
            }
        }
    }
    return new TaskData(col, counts);
}
Also used : SharedPreferences(android.content.SharedPreferences) Collection(com.ichi2.libanki.Collection) JSONObject(org.json.JSONObject) Resources(android.content.res.Resources)

Example 50 with Collection

use of com.ichi2.libanki.Collection in project Anki-Android by Ramblurr.

the class DeckTask method doInBackgroundDeleteDeck.

private TaskData doInBackgroundDeleteDeck(TaskData... params) {
    Log.i(AnkiDroidApp.TAG, "doInBackgroundDeleteDeck");
    Collection col = params[0].getCollection();
    long did = params[0].getLong();
    col.getDecks().rem(did, true);
    return doInBackgroundLoadDeckCounts(new TaskData(col));
}
Also used : Collection(com.ichi2.libanki.Collection)

Aggregations

Collection (com.ichi2.libanki.Collection)40 JSONObject (org.json.JSONObject)20 File (java.io.File)13 JSONException (org.json.JSONException)12 IOException (java.io.IOException)11 Resources (android.content.res.Resources)10 DialogInterface (android.content.DialogInterface)6 DeckTask (com.ichi2.async.DeckTask)6 TaskData (com.ichi2.async.DeckTask.TaskData)6 StyledDialog (com.ichi2.themes.StyledDialog)6 AnkiDb (com.ichi2.anki.AnkiDb)5 FileInputStream (java.io.FileInputStream)5 ArrayList (java.util.ArrayList)5 Intent (android.content.Intent)4 Note (com.ichi2.libanki.Note)4 FileNotFoundException (java.io.FileNotFoundException)4 FileOutputStream (java.io.FileOutputStream)4 InputStream (java.io.InputStream)4 JSONArray (org.json.JSONArray)4 OnCancelListener (android.content.DialogInterface.OnCancelListener)3