Search in sources :

Example 6 with Upgrade

use of com.ichi2.upgrade.Upgrade in project Anki-Android by Ramblurr.

the class Connection method doInBackgroundUpgradeDecks.

private Payload doInBackgroundUpgradeDecks(Payload data) {
    // Enable http request canceller
    mCancelCallback = new CancelCallback();
    String path = (String) data.data[0];
    File ankiDir = new File(path);
    if (!ankiDir.isDirectory()) {
        data.success = false;
        data.data = new Object[] { "wrong anki directory" };
        return data;
    }
    // step 1: gather all .anki files into a zip, without media.
    // we must store them as 1.anki, 2.anki and provide a map so we don't run into
    // encoding issues with the zip file.
    File[] fileList = ankiDir.listFiles(new OldAnkiDeckFilter());
    List<String> corruptFiles = new ArrayList<String>();
    JSONObject map = new JSONObject();
    byte[] buf = new byte[1024];
    String zipFilename = path + "/upload.zip";
    String colFilename = path + AnkiDroidApp.COLLECTION_PATH;
    try {
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilename));
        int n = 1;
        for (File f : fileList) {
            String deckPath = f.getAbsolutePath();
            // set journal mode to delete
            try {
                AnkiDb d = AnkiDatabaseManager.getDatabase(deckPath);
            } catch (SQLiteDatabaseCorruptException e) {
                // ignore invalid .anki files
                corruptFiles.add(f.getName());
                continue;
            } finally {
                AnkiDatabaseManager.closeDatabase(deckPath);
            }
            // zip file
            String tmpName = n + ".anki";
            FileInputStream in = new FileInputStream(deckPath);
            ZipEntry ze = new ZipEntry(tmpName);
            zos.putNextEntry(ze);
            int len;
            while ((len = in.read(buf)) >= 0) {
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            map.put(tmpName, f.getName());
            n++;
        }
        // if all .anki files were found corrupted, abort
        if (fileList.length == corruptFiles.size()) {
            data.success = false;
            data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) };
            return data;
        }
        ZipEntry ze = new ZipEntry("map.json");
        zos.putNextEntry(ze);
        InputStream in = new ByteArrayInputStream(Utils.jsonToString(map).getBytes("UTF-8"));
        int len;
        while ((len = in.read(buf)) >= 0) {
            zos.write(buf, 0, len);
        }
        zos.closeEntry();
        zos.close();
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    File zipFile = new File(zipFilename);
    // step 1.1: if it's over 50MB compressed, it must be upgraded by the user
    if (zipFile.length() > 50 * 1024 * 1024) {
        data.success = false;
        data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_exceeds) };
        return data;
    }
    // step 2: upload zip file to upgrade service and get token
    BasicHttpSyncer h = new BasicHttpSyncer(null, null);
    // note: server doesn't expect it to be gzip compressed, because the zip file is compressed
    // enable cancelling
    publishProgress(R.string.upgrade_decks_upload, null, true);
    try {
        HttpResponse resp = h.req("upgrade/upload", new FileInputStream(zipFile), 0, false, null, mCancelCallback);
        if (resp == null && !isCancelled()) {
            data.success = false;
            data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) };
            return data;
        }
        String result;
        String key = null;
        if (!isCancelled()) {
            result = h.stream2String(resp.getEntity().getContent());
            if (result != null && result.startsWith("ok:")) {
                key = result.split(":")[1];
            } else {
                data.success = false;
                data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) };
                return data;
            }
        }
        while (!isCancelled()) {
            result = h.stream2String(h.req("upgrade/status?key=" + key).getEntity().getContent());
            if (result.equals("error")) {
                data.success = false;
                data.data = new Object[] { "error" };
                return data;
            } else if (result.startsWith("waiting:")) {
                publishProgress(R.string.upgrade_decks_upload, result.split(":")[1]);
            } else if (result.equals("upgrading")) {
                publishProgress(new Object[] { R.string.upgrade_decks_upgrade_started });
            } else if (result.equals("ready")) {
                break;
            } else {
                data.success = false;
                data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) };
                return data;
            }
            Thread.sleep(1000);
        }
        // gzip compression if the client says it can handle it
        if (!isCancelled()) {
            publishProgress(new Object[] { R.string.upgrade_decks_downloading });
            resp = h.req("upgrade/download?key=" + key, null, 6, true, null, mCancelCallback);
        // uploads/downloads have finished so disable cancelling
        }
        publishProgress(R.string.upgrade_decks_downloading, null, false);
        if (isCancelled()) {
            return null;
        }
        if (resp == null) {
            data.success = false;
            data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) };
            return data;
        }
        // step 5: check the received file is valid
        InputStream cont = resp.getEntity().getContent();
        if (!h.writeToFile(cont, colFilename)) {
            data.success = false;
            data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_sdcard, new File(colFilename).length() / 1048576 + 1) };
            (new File(colFilename)).delete();
            return data;
        }
        // check the received file is ok
        publishProgress(new Object[] { R.string.sync_check_download_file });
        publishProgress(R.string.sync_check_download_file);
        try {
            AnkiDb d = AnkiDatabaseManager.getDatabase(colFilename);
            if (!d.queryString("PRAGMA integrity_check").equalsIgnoreCase("ok")) {
                data.success = false;
                data.data = new Object[] { sContext.getResources() };
                return data;
            }
        } finally {
            AnkiDatabaseManager.closeDatabase(colFilename);
        }
        Collection col = AnkiDroidApp.openCollection(colFilename);
        ArrayList<String> decks = col.getDecks().allNames(false);
        ArrayList<String> failed = new ArrayList<String>();
        ArrayList<File> mediaDirs = new ArrayList<File>();
        for (File f : fileList) {
            String name = f.getName().replaceFirst("\\.anki$", "");
            if (!decks.contains(name)) {
                failed.add(name);
            } else {
                mediaDirs.add(new File(f.getAbsolutePath().replaceFirst("\\.anki$", ".media")));
            }
        }
        File newMediaDir = new File(col.getMedia().getDir());
        // step 6. move media files to new media directory
        publishProgress(new Object[] { R.string.upgrade_decks_media });
        ArrayList<String> failedMedia = new ArrayList<String>();
        File curMediaDir = null;
        for (File mediaDir : mediaDirs) {
            curMediaDir = mediaDir;
            // Check if media directory exists and is local
            if (!curMediaDir.exists() || !curMediaDir.isDirectory()) {
                // If not try finding it in dropbox 1.2.x
                curMediaDir = new File(AnkiDroidApp.getDropboxDir(), mediaDir.getName());
                if (!curMediaDir.exists() || !curMediaDir.isDirectory()) {
                    // No media for this deck
                    continue;
                }
            }
            // Found media dir, copy files
            for (File m : curMediaDir.listFiles()) {
                try {
                    Utils.copyFile(m, new File(newMediaDir, m.getName()));
                } catch (IOException e) {
                    failedMedia.add(curMediaDir.getName().replaceFirst("\\.media$", ".anki"));
                    break;
                }
            }
        }
        data.data = new Object[] { failed, failedMedia, newMediaDir.getAbsolutePath() };
        data.success = true;
        return data;
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (IllegalStateException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        (new File(zipFilename)).delete();
    }
}
Also used : ZipEntry(java.util.zip.ZipEntry) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) SQLiteDatabaseCorruptException(android.database.sqlite.SQLiteDatabaseCorruptException) AnkiDb(com.ichi2.anki.AnkiDb) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) JSONException(org.json.JSONException) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) BasicHttpSyncer(com.ichi2.libanki.sync.BasicHttpSyncer) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipOutputStream(java.util.zip.ZipOutputStream) FileOutputStream(java.io.FileOutputStream) Collection(com.ichi2.libanki.Collection) JSONObject(org.json.JSONObject) File(java.io.File)

Example 7 with Upgrade

use of com.ichi2.upgrade.Upgrade in project Anki-Android by Ramblurr.

the class Storage method check.

/*
     * Upgrading ************************************************************
     */
// public void upgrade(String path) {
// // mPath = path;
// // _openDB(path);
// // upgradeSchema();
// // _openCol();
// // _upgradeRest();
// // return mCol;
// }
/*
     * Integrity checking ************************************************************
     */
public static boolean check(String path) {
    AnkiDb db = AnkiDatabaseManager.getDatabase(path);
    // corrupt?
    try {
        if (!db.queryString("PRAGMA integrity_check").equalsIgnoreCase("ok")) {
            return false;
        }
    } catch (SQLException _) {
        return false;
    }
    // old version?
    if (db.queryScalar("SELECT version FROM decks") < 65) {
        return false;
    }
    // ensure we have indices for checks below
    db.execute("create index if not exists ix_cards_factId on cards (factId)");
    db.execute("create index if not exists ix_fields_factId on fieldModels (factId)");
    db.execute("analyze");
    // fields missing a field model?
    if (db.queryColumn(Integer.class, "select id from fields where fieldModelId not in (" + "select distinct id from fieldModels)", 0).size() > 0) {
        return false;
    }
    // facts missing a field?
    if (db.queryColumn(Integer.class, "select distinct facts.id from facts, fieldModels where " + "facts.modelId = fieldModels.modelId and fieldModels.id not in " + "(select fieldModelId from fields where factId = facts.id)", 0).size() > 0) {
        return false;
    }
    // cards missing a fact?
    if (db.queryColumn(Integer.class, "select id from cards where factId not in (select id from facts)", 0).size() > 0) {
        return false;
    }
    // cards missing a card model?
    if (db.queryColumn(Integer.class, "select id from cards where cardModelId not in (select id from cardModels)", 0).size() > 0) {
        return false;
    }
    // cards with a card model from the wrong model?
    if (db.queryColumn(Integer.class, "select id from cards where cardModelId not in (select cm.id from " + "cardModels cm, facts f where cm.modelId = f.modelId and " + "f.id = cards.factId)", 0).size() > 0) {
        return false;
    }
    // facts missing a card?
    if (db.queryColumn(Integer.class, "select facts.id from facts " + "where facts.id not in (select distinct factId from cards)", 0).size() > 0) {
        return false;
    }
    // dangling fields?
    if (db.queryColumn(Integer.class, "select id from fields where factId not in (select id from facts)", 0).size() > 0) {
        return false;
    }
    // fields without matching interval
    if (db.queryColumn(Integer.class, "select id from fields where ordinal != (select ordinal from fieldModels " + "where id = fieldModelId)", 0).size() > 0) {
        return false;
    }
    // incorrect types
    if (db.queryColumn(Integer.class, "select id from cards where relativeDelay != (case " + "when successive then 1 when reps then 0 else 2 end)", 0).size() > 0) {
        return false;
    }
    if (db.queryColumn(Integer.class, "select id from cards where type != (case " + "when type >= 0 then relativeDelay else relativeDelay - 3 end)", 0).size() > 0) {
        return false;
    }
    return true;
}
Also used : AnkiDb(com.ichi2.anki.AnkiDb) SQLException(android.database.SQLException)

Example 8 with Upgrade

use of com.ichi2.upgrade.Upgrade in project Anki-Android by Ramblurr.

the class FullSyncer method download.

@Override
public Object[] download() {
    InputStream cont;
    try {
        HttpResponse ret = super.req("download");
        if (ret == null) {
            return null;
        }
        cont = ret.getEntity().getContent();
    } catch (IllegalStateException e1) {
        throw new RuntimeException(e1);
    } catch (IOException e1) {
        return null;
    }
    String path = AnkiDroidApp.getCollectionPath();
    if (mCol != null) {
        mCol.close(false);
        mCol = null;
    }
    String tpath = path + ".tmp";
    if (!super.writeToFile(cont, tpath)) {
        return new Object[] { "sdAccessError" };
    }
    // first check, if account needs upgrade (from 1.2)
    try {
        FileInputStream fis = new FileInputStream(tpath);
        if (super.stream2String(fis, 15).equals("upgradeRequired")) {
            return new Object[] { "upgradeRequired" };
        }
    } catch (FileNotFoundException e1) {
        throw new RuntimeException(e1);
    }
    // check the received file is ok
    mCon.publishProgress(R.string.sync_check_download_file);
    try {
        AnkiDb d = AnkiDatabaseManager.getDatabase(tpath);
        if (!d.queryString("PRAGMA integrity_check").equalsIgnoreCase("ok")) {
            Log.e(AnkiDroidApp.TAG, "Full sync - downloaded file corrupt");
            return new Object[] { "remoteDbError" };
        }
    } catch (SQLiteDatabaseCorruptException e) {
        Log.e(AnkiDroidApp.TAG, "Full sync - downloaded file corrupt");
        return new Object[] { "remoteDbError" };
    } finally {
        AnkiDatabaseManager.closeDatabase(tpath);
    }
    // overwrite existing collection
    File newFile = new File(tpath);
    if (newFile.renameTo(new File(path))) {
        return new Object[] { "success" };
    } else {
        return new Object[] { "overwriteError" };
    }
}
Also used : AnkiDb(com.ichi2.anki.AnkiDb) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) HttpResponse(org.apache.http.HttpResponse) SQLiteDatabaseCorruptException(android.database.sqlite.SQLiteDatabaseCorruptException) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 9 with Upgrade

use of com.ichi2.upgrade.Upgrade in project Anki-Android by Ramblurr.

the class Info method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    // Log.i(AnkiDroidApp.TAG, "Info - onCreate()");
    Themes.applyTheme(this);
    super.onCreate(savedInstanceState);
    Resources res = getResources();
    mType = getIntent().getIntExtra(TYPE_EXTRA, TYPE_ABOUT);
    setTitle(getTitleString());
    setContentView(R.layout.info);
    mWebView = (WebView) findViewById(R.id.info);
    mWebView.setBackgroundColor(res.getColor(Themes.getBackgroundColor()));
    Themes.setWallpaper((View) mWebView.getParent().getParent().getParent());
    Button continueButton = (Button) findViewById(R.id.info_continue);
    continueButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if (mType == TYPE_ABOUT) {
                Info.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.ichi2.anki")));
                return;
            }
            setResult(RESULT_OK);
            switch(mType) {
                case TYPE_WELCOME:
                    AnkiDroidApp.getSharedPrefs(Info.this.getBaseContext()).edit().putLong("lastTimeOpened", System.currentTimeMillis()).commit();
                    break;
                case TYPE_NEW_VERSION:
                    AnkiDroidApp.getSharedPrefs(Info.this.getBaseContext()).edit().putString("lastVersion", AnkiDroidApp.getPkgVersionName()).commit();
                    break;
                case TYPE_UPGRADE_DECKS:
                    break;
            }
            finishWithAnimation();
        }
    });
    StringBuilder sb = new StringBuilder();
    switch(mType) {
        case TYPE_ABOUT:
            String[] content = res.getStringArray(R.array.about_content);
            sb.append("<html><body text=\"#000000\" link=\"#E37068\" alink=\"#E37068\" vlink=\"#E37068\">");
            sb.append(String.format(content[0], res.getString(R.string.app_name), res.getString(R.string.link_anki))).append("<br/><br/>");
            sb.append(String.format(content[1], res.getString(R.string.link_issue_tracker), res.getString(R.string.link_wiki), res.getString(R.string.link_forum))).append("<br/><br/>");
            sb.append(String.format(content[2], res.getString(R.string.link_wikipedia_open_source), res.getString(R.string.link_contribution), res.getString(R.string.link_contribution_contributors))).append(" ");
            sb.append(String.format(content[3], res.getString(R.string.link_translation), res.getString(R.string.link_donation))).append("<br/><br/>");
            sb.append(String.format(content[4], res.getString(R.string.licence_wiki), res.getString(R.string.link_source))).append("<br/><br/>");
            sb.append("</body></html>");
            mWebView.loadDataWithBaseURL("", sb.toString(), "text/html", "utf-8", null);
            ((Button) findViewById(R.id.info_continue)).setText(res.getString(R.string.info_rate));
            break;
        case TYPE_WELCOME:
            // title
            sb.append("<html><body text=\"#000000\" link=\"#E37068\" alink=\"#E37068\" vlink=\"#E37068\">");
            sb.append("<big><b>");
            sb.append(res.getString(R.string.studyoptions_welcome_title));
            sb.append("</big></b><br><br>");
            // message
            sb.append(res.getString(R.string.welcome_message).replace("\n", "<br>"));
            sb.append("</body></html>");
            mWebView.loadDataWithBaseURL("", sb.toString(), "text/html", "utf-8", null);
            // add tutorial button
            Button tutBut = (Button) findViewById(R.id.info_tutorial);
            tutBut.setVisibility(View.VISIBLE);
            tutBut.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    setResult(RESULT_OK);
                    Editor edit = AnkiDroidApp.getSharedPrefs(Info.this.getBaseContext()).edit();
                    edit.putLong("lastTimeOpened", System.currentTimeMillis());
                    edit.putBoolean("createTutorial", true);
                    edit.commit();
                    finishWithAnimation();
                }
            });
            break;
        case TYPE_NEW_VERSION:
            sb.append(res.getString(R.string.new_version_message));
            sb.append("<ul>");
            String[] features = res.getStringArray(R.array.new_version_features);
            for (int i = 0; i < features.length; i++) {
                sb.append("<li>");
                sb.append(features[i]);
                sb.append("</li>");
            }
            sb.append("</ul>");
            sb.append("</body></html>");
            mWebView.loadDataWithBaseURL("", sb.toString(), "text/html", "utf-8", null);
            // reactivating ssl check for every new version
            AnkiDroidApp.getSharedPrefs(Info.this.getBaseContext()).edit().putBoolean("sslAcceptAll", false).commit();
            break;
        case TYPE_SHARED_DECKS:
            mLoadingLayer = (RelativeLayout) findViewById(R.id.info_loading_layer);
            mLoadingLayer.setVisibility(View.VISIBLE);
            try {
                mShareDecksTemplate = Utils.convertStreamToString(getAssets().open("shared_decks_template.html"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            mWebView.setWebViewClient(new MobileAnkiWebview());
            mWebView.loadUrl(res.getString(R.string.shared_decks_url));
            mWebView.getSettings().setJavaScriptEnabled(true);
            continueButton.setText(res.getString(R.string.download_button_return));
            break;
        case TYPE_UPGRADE_DECKS:
            setTitle(R.string.deck_upgrade_title);
            sb.append("<html><body>");
            // add upgrade button
            Button but = (Button) findViewById(R.id.info_tutorial);
            but.setVisibility(View.VISIBLE);
            // add sync button
            Button syncButton = (Button) findViewById(R.id.info_sync);
            syncButton.setVisibility(View.VISIBLE);
            mUpgradeStage = getIntent().getIntExtra(TYPE_UPGRADE_STAGE, -1);
            boolean reupgrading = false;
            switch(mUpgradeStage) {
                case UPGRADE_SCREEN_BASIC1:
                    sb.append(getString(R.string.deck_upgrade_major_warning));
                    but.setText(R.string.later);
                    but.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            Themes.showThemedToast(Info.this, getString(R.string.deck_upgrade_start_again_to_upgrade_toast), false);
                            setResult(RESULT_CANCELED);
                            finish();
                        }
                    });
                    syncButton.setText(R.string.more_options);
                    syncButton.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            Intent result = new Intent();
                            result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_MORE_OPTIONS);
                            setResult(RESULT_OK, result);
                            finishWithAnimation();
                        }
                    });
                    continueButton.setText(R.string.now);
                    continueButton.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            Intent result = new Intent();
                            result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_BASIC2);
                            setResult(RESULT_OK, result);
                            finishWithAnimation();
                        }
                    });
                    break;
                case UPGRADE_SCREEN_BASIC2:
                    sb.append(getString(R.string.deck_upgrade_recommended_method));
                    but.setText(R.string.back);
                    but.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            Intent result = new Intent();
                            result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_BASIC1);
                            result.putExtra(TYPE_ANIMATION_RIGHT, true);
                            setResult(RESULT_OK, result);
                            finishWithAnimation(false);
                        }
                    });
                    syncButton.setText(getString(R.string.internet));
                    syncButton.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            Intent result = new Intent();
                            result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_WEB_UPGRADE);
                            setResult(RESULT_OK, result);
                            finishWithAnimation();
                        }
                    });
                    continueButton.setText(getString(R.string.pc));
                    continueButton.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            Intent result = new Intent();
                            result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_PC_UPGRADE);
                            setResult(RESULT_OK, result);
                            finishWithAnimation();
                        }
                    });
                    break;
                case UPGRADE_SCREEN_MORE_OPTIONS:
                    // If re-upgrading a collection exists already, so don't offer to make a new one
                    if (new File(AnkiDroidApp.getCollectionPath()).exists()) {
                        setTitle(getString(R.string.exit_wizard));
                        reupgrading = true;
                        sb.append(getString(R.string.deck_upgrade_more_options_exit));
                    } else {
                        sb.append(getString(R.string.deck_upgrade_more_options_new_collection));
                    }
                    sb.append(getString(R.string.deck_upgrade_more_options_downgrade));
                    but.setText(R.string.upgrade_decks_button);
                    but.setText(R.string.back);
                    but.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            Intent result = new Intent();
                            result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_BASIC1);
                            result.putExtra(TYPE_ANIMATION_RIGHT, true);
                            setResult(RESULT_OK, result);
                            finishWithAnimation(false);
                        }
                    });
                    if (reupgrading) {
                        syncButton.setText(getString(R.string.upgrade_deck_dont_upgrade));
                        syncButton.setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View arg0) {
                                Intent result = new Intent();
                                result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_CONTINUE);
                                setResult(RESULT_OK, result);
                                finishWithAnimation();
                            }
                        });
                    } else {
                        syncButton.setText(R.string.deck_upgrade_create_new_collection);
                        syncButton.setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View arg0) {
                                StyledDialog.Builder builder = new StyledDialog.Builder(Info.this);
                                builder.setTitle(R.string.deck_upgrade_create_new_collection_title);
                                builder.setIcon(R.drawable.ic_dialog_alert);
                                builder.setMessage(R.string.deck_upgrade_not_import_warning);
                                builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent result = new Intent();
                                        result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_CONTINUE);
                                        setResult(RESULT_OK, result);
                                        finishWithAnimation();
                                    }
                                });
                                builder.setNegativeButton(R.string.no, null);
                                builder.show();
                            }
                        });
                    }
                    continueButton.setVisibility(View.GONE);
                    break;
                case UPGRADE_SCREEN_WEB_UPGRADE:
                    sb.append(getString(R.string.deck_upgrade_via_web));
                    but.setText(R.string.back);
                    but.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            Intent result = new Intent();
                            result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_BASIC2);
                            result.putExtra(TYPE_ANIMATION_RIGHT, true);
                            setResult(RESULT_OK, result);
                            finishWithAnimation(false);
                        }
                    });
                    syncButton.setVisibility(View.GONE);
                    continueButton.setText(R.string.yes);
                    continueButton.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            lockScreenOrientation();
                            Connection.upgradeDecks(mWebUpgradeListener, new Connection.Payload(new Object[] { AnkiDroidApp.getCurrentAnkiDroidDirectory() }));
                        }
                    });
                    break;
                case UPGRADE_SCREEN_PC_UPGRADE:
                    sb.append(getString(R.string.deck_upgrade_via_anki_desktop));
                    but.setText(R.string.back);
                    but.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            Intent result = new Intent();
                            result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_BASIC2);
                            result.putExtra(TYPE_ANIMATION_RIGHT, true);
                            setResult(RESULT_OK, result);
                            finishWithAnimation(false);
                        }
                    });
                    syncButton.setText(R.string.usb);
                    syncButton.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            Intent result = new Intent();
                            result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_MANUAL_UPGRADE);
                            setResult(RESULT_OK, result);
                            finishWithAnimation();
                        }
                    });
                    continueButton.setText(R.string.ankiweb);
                    continueButton.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            Intent result = new Intent();
                            result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_AUTO_UPGRADE);
                            setResult(RESULT_OK, result);
                            finishWithAnimation();
                        }
                    });
                    break;
                case UPGRADE_SCREEN_MANUAL_UPGRADE:
                    sb.append(getString(R.string.deck_upgrade_manual));
                    but.setText(R.string.back);
                    but.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            Intent result = new Intent();
                            result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_BASIC2);
                            result.putExtra(TYPE_ANIMATION_RIGHT, true);
                            setResult(RESULT_OK, result);
                            finishWithAnimation(false);
                        }
                    });
                    syncButton.setText(R.string._import);
                    syncButton.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            File apkgFile = new File(AnkiDroidApp.getCurrentAnkiDroidDirectory(), DeckPicker.IMPORT_REPLACE_COLLECTION_NAME);
                            List<File> importables = Utils.getImportableDecks();
                            if (importables == null || !importables.contains(apkgFile)) {
                                Themes.showThemedToast(Info.this, getResources().getString(R.string.upgrade_import_no_file_found, DeckPicker.IMPORT_REPLACE_COLLECTION_NAME), false);
                            } else {
                                lockScreenOrientation();
                                DeckTask.launchDeckTask(DeckTask.TASK_TYPE_IMPORT_REPLACE, mUpgradeImportListener, new DeckTask.TaskData(AnkiDroidApp.getCol(), apkgFile.getAbsolutePath()));
                            }
                        }
                    });
                    continueButton.setVisibility(View.GONE);
                    break;
                case UPGRADE_SCREEN_AUTO_UPGRADE:
                    sb.append(getString(R.string.deck_upgrade_auto_upgrade));
                    but.setText(R.string.back);
                    but.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            Intent result = new Intent();
                            result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_PC_UPGRADE);
                            result.putExtra(TYPE_ANIMATION_RIGHT, true);
                            setResult(RESULT_OK, result);
                            finishWithAnimation(false);
                        }
                    });
                    syncButton.setText(getString(R.string.upgrade_deck_sync_from_ankiweb));
                    syncButton.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            StyledDialog.Builder builder = new StyledDialog.Builder(Info.this);
                            builder.setTitle(R.string.upgrade_deck_sync_from_ankiweb);
                            builder.setIcon(R.drawable.ic_dialog_alert);
                            builder.setMessage(getString(R.string.upgrade_deck_have_you_synced));
                            builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    lockScreenOrientation();
                                    downloadCollection();
                                }
                            });
                            builder.setNegativeButton(R.string.back, null);
                            builder.show();
                        }
                    });
                    continueButton.setVisibility(View.GONE);
                    break;
            }
            // File[] fileList = (new File(AnkiDroidApp.getCurrentAnkiDroidDirectory())).listFiles(new OldAnkiDeckFilter());
            // StringBuilder fsb = new StringBuilder();
            // fsb.append("<ul>");
            // for (File f : fileList) {
            // fsb.append("<li>").append(f.getName().replace(".anki", "")).append("</li>");
            // }
            // fsb.append("</ul>");
            // sb.append(res.getString(R.string.upgrade_decks_message, fsb.toString()));
            // sb.append("<ul><li>");
            // sb.append(res.getString(R.string.upgrade_decks_message_pos1,
            // AnkiDroidApp.getCurrentAnkiDroidDirectory()));
            // sb.append("</li><li>");
            // sb.append(res.getString(R.string.upgrade_decks_message_pos2, res.getString(R.string.link_anki)));
            // sb.append("</li><li>");
            // sb.append(res.getString(R.string.upgrade_decks_message_pos3));
            // sb.append("</li></ul>");
            // sb.append(res.getString(R.string.upgrade_decks_message_finish));
            sb.append("</body></html>");
            mWebView.loadDataWithBaseURL("", sb.toString(), "text/html", "utf-8", null);
            StyledDialog.Builder builder2 = new StyledDialog.Builder(this);
            builder2.setTitle(res.getString(R.string.connection_error_title));
            builder2.setIcon(R.drawable.ic_dialog_alert);
            builder2.setMessage(res.getString(R.string.connection_needed));
            builder2.setPositiveButton(res.getString(R.string.ok), null);
            mNoConnectionAlert = builder2.create();
            break;
        default:
            finish();
            break;
    }
}
Also used : DialogInterface(android.content.DialogInterface) StyledDialog(com.ichi2.themes.StyledDialog) Intent(android.content.Intent) IOException(java.io.IOException) View(android.view.View) WebView(android.webkit.WebView) Button(android.widget.Button) OnClickListener(android.view.View.OnClickListener) Payload(com.ichi2.async.Connection.Payload) List(java.util.List) ArrayList(java.util.ArrayList) Resources(android.content.res.Resources) Editor(android.content.SharedPreferences.Editor) File(java.io.File)

Example 10 with Upgrade

use of com.ichi2.upgrade.Upgrade in project Anki-Android by Ramblurr.

the class DeckPicker method showStartupScreensAndDialogs.

private void showStartupScreensAndDialogs(SharedPreferences preferences, int skip) {
    if (skip < 1 && preferences.getLong("lastTimeOpened", 0) == 0) {
        Intent infoIntent = new Intent(this, Info.class);
        infoIntent.putExtra(Info.TYPE_EXTRA, Info.TYPE_WELCOME);
        startActivityForResult(infoIntent, SHOW_INFO_WELCOME);
        if (skip != 0 && AnkiDroidApp.SDK_VERSION > 4) {
            ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.LEFT);
        }
    } else if (skip < 2 && !preferences.getString("lastVersion", "").equals(AnkiDroidApp.getPkgVersionName())) {
        preferences.edit().putBoolean("showBroadcastMessageToday", true).commit();
        Intent infoIntent = new Intent(this, Info.class);
        infoIntent.putExtra(Info.TYPE_EXTRA, Info.TYPE_NEW_VERSION);
        startActivityForResult(infoIntent, SHOW_INFO_NEW_VERSION);
        if (skip != 0 && AnkiDroidApp.SDK_VERSION > 4) {
            ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.LEFT);
        }
    } else if (skip < 3 && upgradeNeeded()) {
        // Note that the "upgrade needed" refers to upgrading Anki 1.x decks, not to newer
        // versions of AnkiDroid.
        AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance().getBaseContext()).edit().putInt("lastUpgradeVersion", AnkiDroidApp.getPkgVersionCode()).commit();
        showUpgradeScreen(skip != 0, Info.UPGRADE_SCREEN_BASIC1);
    } else if (skip < 4 && hasErrorFiles()) {
        Intent i = new Intent(this, Feedback.class);
        startActivityForResult(i, REPORT_ERROR);
        if (skip != 0 && AnkiDroidApp.SDK_VERSION > 4) {
            ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.LEFT);
        }
    } else if (!AnkiDroidApp.isSdCardMounted()) {
        showDialog(DIALOG_SD_CARD_NOT_MOUNTED);
    } else if (!BackupManager.enoughDiscSpace(mPrefDeckPath)) {
        // && !preferences.getBoolean("dontShowLowMemory",
        // false)) {
        showDialog(DIALOG_NO_SPACE_LEFT);
    } else if (preferences.getBoolean("noSpaceLeft", false)) {
        showDialog(DIALOG_BACKUP_NO_SPACE_LEFT);
        preferences.edit().putBoolean("noSpaceLeft", false).commit();
    } else if (mImportPath != null && AnkiDroidApp.colIsOpen()) {
        showDialog(DIALOG_IMPORT);
    } else {
        // AnkiDroid is being updated and a collection already exists. We check if we are upgrading
        // to a version that contains additions to the database integrity check routine that we would
        // like to run on all collections. A missing version number is assumed to be a fresh
        // installation of AnkiDroid and we don't run the check.
        int current = AnkiDroidApp.getPkgVersionCode();
        int previous;
        if (!preferences.contains("lastUpgradeVersion")) {
            // Fresh install
            previous = current;
        } else {
            try {
                previous = preferences.getInt("lastUpgradeVersion", current);
            } catch (ClassCastException e) {
                // Previous versions stored this as a string.
                String s = preferences.getString("lastUpgradeVersion", "");
                // check.
                if (s.equals("2.0.2")) {
                    previous = 40;
                } else {
                    previous = 0;
                }
            }
        }
        preferences.edit().putInt("lastUpgradeVersion", current).commit();
        if (previous < AnkiDroidApp.CHECK_DB_AT_VERSION) {
            DeckTask.launchDeckTask(DeckTask.TASK_TYPE_OPEN_COLLECTION, new Listener() {

                @Override
                public void onPostExecute(DeckTask task, TaskData result) {
                    mOpenCollectionHandler.onPostExecute(result);
                    integrityCheck();
                }

                @Override
                public void onPreExecute(DeckTask task) {
                }

                @Override
                public void onProgressUpdate(DeckTask task, TaskData... values) {
                }
            }, new DeckTask.TaskData(AnkiDroidApp.getCollectionPath()));
        } else {
            loadCollection();
        }
    }
}
Also used : OnGlobalLayoutListener(android.view.ViewTreeObserver.OnGlobalLayoutListener) OnCancelListener(android.content.DialogInterface.OnCancelListener) SimpleOnGestureListener(android.view.GestureDetector.SimpleOnGestureListener) Listener(com.ichi2.async.DeckTask.Listener) OnClickListener(android.view.View.OnClickListener) Intent(android.content.Intent) ActivityInfo(android.content.pm.ActivityInfo) ContextMenuInfo(android.view.ContextMenu.ContextMenuInfo) DeckTask(com.ichi2.async.DeckTask) TaskData(com.ichi2.async.DeckTask.TaskData)

Aggregations

File (java.io.File)7 Intent (android.content.Intent)6 SharedPreferences (android.content.SharedPreferences)6 View (android.view.View)6 Resources (android.content.res.Resources)5 Bundle (android.os.Bundle)5 TextView (android.widget.TextView)5 Collection (com.ichi2.libanki.Collection)5 JSONException (com.ichi2.utils.JSONException)5 SQLiteDatabaseCorruptException (android.database.sqlite.SQLiteDatabaseCorruptException)4 Message (android.os.Message)4 NonNull (androidx.annotation.NonNull)4 SearchView (androidx.appcompat.widget.SearchView)4 ConfirmModSchemaException (com.ichi2.anki.exception.ConfirmModSchemaException)4 FileInputStream (java.io.FileInputStream)4 FileNotFoundException (java.io.FileNotFoundException)4 IOException (java.io.IOException)4 InputStream (java.io.InputStream)4 List (java.util.List)4 BroadcastReceiver (android.content.BroadcastReceiver)3