Search in sources :

Example 1 with ServerBase

use of ar.rulosoft.mimanganu.servers.ServerBase in project MiMangaNu by raulhaag.

the class DownloadPoolService method initPool.

private void initPool() {
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DPS_wakelock");
    try {
        wakeLock.acquire();
    } catch (Exception e) {
        e.printStackTrace();
    }
    Util.getInstance().createNotificationWithProgressbar(getApplicationContext(), mNotifyID, getResources().getString(R.string.downloading), "");
    Manga manga = null;
    ServerBase s = null;
    String path = "";
    int lcId = -1;
    int n = -1;
    errors = 0;
    while (hasDownloadsPending()) {
        if (slots > 0) {
            slots--;
            ChapterDownload dc = null;
            int sig = 1;
            int idx = 0;
            while (idx < chapterDownloads.size()) {
                ChapterDownload d = chapterDownloads.get(idx);
                idx++;
                // start notification code
                if (n > chapterDownloads.size())
                    n = idx;
                if (n < idx)
                    n = idx;
                if (resetN) {
                    n = 0;
                    resetN = false;
                }
                if (resetE) {
                    errors = 0;
                    resetE = false;
                }
                // end notification code
                if (d.chapter.getPages() == 0) {
                    if (d.status != DownloadStatus.ERROR && d.status != DownloadStatus.PAUSED)
                        try {
                            ServerBase server;
                            Manga m = Database.getManga(getApplicationContext(), d.chapter.getMangaID());
                            server = ServerBase.getServer(m.getServerId(), getApplicationContext());
                            server.chapterInit(d.chapter);
                            d.reset();
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            if (d.chapter.getPages() == 0)
                                d.status = DownloadStatus.ERROR;
                        }
                    Database.updateChapter(getApplicationContext(), d.chapter);
                }
                if (d.getPagesStatusLength() == 0) {
                    d.reset();
                }
                if (d.status != DownloadStatus.ERROR && d.status != DownloadStatus.PAUSED) {
                    sig = d.getNext();
                    if (sig > -1) {
                        dc = d;
                        break;
                    }
                }
            }
            if (dc != null) {
                if (manga == null || manga.getId() != dc.chapter.getMangaID()) {
                    try {
                        manga = Database.getManga(actual.getApplicationContext(), dc.chapter.getMangaID());
                        s = ServerBase.getServer(manga.getServerId(), getApplicationContext());
                    } catch (Exception e) {
                        dc.status = DownloadStatus.ERROR;
                    }
                }
                if (lcId != dc.chapter.getId()) {
                    try {
                        lcId = dc.chapter.getId();
                        path = generateBasePath(s, manga, dc.chapter, getApplicationContext());
                        new File(path).mkdirs();
                    } catch (Exception e) {
                        dc.status = DownloadStatus.ERROR;
                    }
                }
                try {
                    if (errors < 1)
                        Util.getInstance().changeNotificationWithProgressbar(dc.getChapter().getPages(), sig, mNotifyID, getResources().getString(R.string.x_of_y_chapters_downloaded, (n - 1), chapterDownloads.size()), getResources().getString(R.string.downloading) + " " + dc.getChapter().getTitle(), true);
                    else {
                        Util.getInstance().changeNotificationWithProgressbar(dc.getChapter().getPages(), sig, mNotifyID, getResources().getString(R.string.x_of_y_chapters_downloaded, (n - 1), chapterDownloads.size()), "(" + getResources().getString(R.string.chapter_download_errors) + " " + errors + ")\n" + getResources().getString(R.string.downloading) + " " + dc.getChapter().getTitle(), true);
                    }
                    String source_file = s.getImageFrom(dc.chapter, sig);
                    String save_file = path + "/" + sig + ".jpg";
                    SingleDownload des;
                    des = new SingleDownload(getApplicationContext(), source_file, save_file, sig - 1, dc.chapter.getId(), dc, s.needRefererForImages());
                    des.setChangeListener(dc);
                    dc.setChangeListener(this);
                    new Thread(des).start();
                } catch (Exception e) {
                    dc.setErrorIdx(sig - 1);
                    slots++;
                }
            } else if (slots == 1) {
                break;
            } else {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                slots++;
            }
        } else {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    Util.getInstance().cancelNotification(mNotifyID);
    actual = null;
    stopSelf();
    try {
        if (wakeLock.isHeld())
            wakeLock.release();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : PowerManager(android.os.PowerManager) ServerBase(ar.rulosoft.mimanganu.servers.ServerBase) File(java.io.File) Manga(ar.rulosoft.mimanganu.componentes.Manga)

Example 2 with ServerBase

use of ar.rulosoft.mimanganu.servers.ServerBase in project MiMangaNu by raulhaag.

the class AsyncAddManga method doInBackground.

@Override
protected Void doInBackground(Void... params) {
    ServerBase serverBase = ServerBase.getServer(manga.getServerId(), mActivity);
    try {
        if (loadMangaInformation)
            serverBase.loadMangaInformation(manga, false);
        serverBase.loadChapters(manga, false);
        total = manga.getChapters().size();
        int mid = Database.addManga(mActivity, manga);
        if (mid > -1) {
            long initTime = System.currentTimeMillis();
            for (int i = 0; i < manga.getChapters().size(); i++) {
                if (System.currentTimeMillis() - initTime > 500) {
                    publishProgress(i);
                    initTime = System.currentTimeMillis();
                }
                Database.addChapter(mActivity, manga.getChapter(i), mid);
            }
            publishProgress(total);
        } else {
            allOk = false;
        }
    } catch (Exception e) {
        allOk = false;
        error = Log.getStackTraceString(e);
    }
    return null;
}
Also used : ServerBase(ar.rulosoft.mimanganu.servers.ServerBase)

Example 3 with ServerBase

use of ar.rulosoft.mimanganu.servers.ServerBase in project MiMangaNu by raulhaag.

the class MainFragment method onContextItemSelected.

@Override
public boolean onContextItemSelected(MenuItem item) {
    final Manga manga = ((MangasRecAdapter) recyclerView.getAdapter()).getItem(lastContextMenuIndex);
    if (item.getItemId() == R.id.delete) {
        new AlertDialog.Builder(getContext()).setTitle(R.string.app_name).setMessage(getString(R.string.manga_delete_confirm, manga.getTitle())).setNegativeButton(getString(android.R.string.no), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                DownloadPoolService.forceStop(manga.getId());
                ServerBase serverBase = ServerBase.getServer(manga.getServerId(), getContext());
                String path = Paths.generateBasePath(serverBase, manga, getActivity());
                Util.getInstance().deleteRecursive(new File(path));
                Database.deleteManga(getActivity(), manga.getId());
                mMAdapter.remove(manga);
                Util.getInstance().showFastSnackBar(getResources().getString(R.string.deleted, manga.getTitle()), getView(), getContext());
                dialog.dismiss();
            }
        }).show();
    } else if (item.getItemId() == R.id.noupdate) {
        if (manga.isFinished()) {
            manga.setFinished(false);
            Database.setUpgradable(getActivity(), manga.getId(), false);
        } else {
            manga.setFinished(true);
            Database.setUpgradable(getActivity(), manga.getId(), true);
        }
    } else if (item.getItemId() == R.id.download_all_chapters) {
        ArrayList<Chapter> chapters = Database.getChapters(getActivity(), manga.getId(), Database.COL_CAP_DOWNLOADED + " != 1", true);
        for (Chapter chapter : chapters) {
            try {
                DownloadPoolService.addChapterDownloadPool(getActivity(), chapter, false);
            } catch (Exception e) {
                Log.e(TAG, "Download add pool error", e);
            }
        }
        if (chapters.size() > 1)
            Util.getInstance().showFastSnackBar(getString(R.string.downloading) + " " + chapters.size() + " " + getString(R.string.chapters), getView(), getContext());
        else
            Util.getInstance().showFastSnackBar(getString(R.string.downloading) + " " + chapters.size() + " " + getString(R.string.chapter), getView(), getContext());
    }
    return super.onContextItemSelected(item);
}
Also used : AlertDialog(android.app.AlertDialog) ServerBase(ar.rulosoft.mimanganu.servers.ServerBase) DialogInterface(android.content.DialogInterface) Chapter(ar.rulosoft.mimanganu.componentes.Chapter) MangasRecAdapter(ar.rulosoft.mimanganu.adapters.MangasRecAdapter) File(java.io.File) Manga(ar.rulosoft.mimanganu.componentes.Manga)

Example 4 with ServerBase

use of ar.rulosoft.mimanganu.servers.ServerBase in project MiMangaNu by raulhaag.

the class MangaFragment method onActivityCreated.

@Override
public void onActivityCreated(final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    pm = PreferenceManager.getDefaultSharedPreferences(getActivity());
    super.onCreate(savedInstanceState);
    if (mMangaId == -1) {
        getActivity().onBackPressed();
    }
    mManga = Database.getManga(getActivity(), mMangaId);
    mServerBase = ServerBase.getServer(mManga.getServerId(), getContext());
    if (getView() == null) {
        try {
            finalize();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    } else {
        mListView = getView().findViewById(R.id.list);
        swipeReLayout = getView().findViewById(R.id.str);
        readerOptions = getView().findViewById(R.id.reader_options);
        mImageLoader = new ImageLoader(getActivity());
        final int[] colors = ThemeColors.getColors(pm);
        readerOptions.setBackgroundColor(colors[0]);
        readerOptions.setManga(mManga);
        swipeReLayout.setColorSchemeColors(colors[0], colors[1]);
        if (savedInstanceState != null) {
            if (searchForNewChapters.getStatus() == AsyncTask.Status.RUNNING) {
                swipeReLayout.post(new Runnable() {

                    @Override
                    public void run() {
                        swipeReLayout.setRefreshing(true);
                    }
                });
            }
        }
        swipeReLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                if ((searchForNewChapters.getStatus() != AsyncTask.Status.RUNNING)) {
                    searchForNewChapters = new SearchForNewChapters();
                    searchForNewChapters.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }
            }
        });
        mListView.setDivider(new ColorDrawable(colors[0]));
        mListView.setDividerHeight(1);
        mInfo = new ControlInfoNoScroll(getActivity());
        mListView.addHeaderView(mInfo);
        mInfo.setColor(MainActivity.darkTheme, colors[0]);
        mInfo.enableTitleCopy(getActivity(), mManga.getTitle());
        ChapterAdapter.setColor(MainActivity.darkTheme, colors[1], colors[0]);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Chapter c = (Chapter) mListView.getAdapter().getItem(position);
                getPagesTask = new GetPagesTask();
                getPagesTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, c);
            }
        });
        mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        mListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {

            @Override
            public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
                return false;
            }

            @Override
            public void onDestroyActionMode(android.view.ActionMode mode) {
                mChapterAdapter.clearSelection();
            }

            @Override
            public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) {
                MenuInflater inflater = getActivity().getMenuInflater();
                inflater.inflate(R.menu.listitem_capitulo_menu_cab, menu);
                return true;
            }

            @Override
            public boolean onActionItemClicked(final android.view.ActionMode mode, MenuItem item) {
                final SparseBooleanArray selection = mChapterAdapter.getSelection();
                final ServerBase serverBase = ServerBase.getServer(mManga.getServerId(), getContext());
                boolean finish = true;
                switch(item.getItemId()) {
                    case R.id.select_all:
                        mChapterAdapter.selectAll();
                        return true;
                    case R.id.unselect:
                        mChapterAdapter.clearSelection();
                        return true;
                    case R.id.select_from:
                        mChapterAdapter.selectFrom(selection.keyAt(0));
                        return true;
                    case R.id.select_to:
                        mChapterAdapter.selectTo(selection.keyAt(0));
                        return true;
                    case R.id.download_selection:
                        new AsyncAddChapters().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, mChapterAdapter.getSelectedChapters());
                        break;
                    case R.id.mark_as_read_and_delete_images:
                        markSelectedAsRead = new MarkSelectedAsRead(selection.size());
                        markSelectedAsRead.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        deleteImages = new DeleteImages(serverBase, selection.size());
                        deleteImages.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        break;
                    case R.id.delete_images:
                        deleteImages = new DeleteImages(serverBase, selection.size());
                        deleteImages.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        break;
                    case R.id.remove_chapter:
                        finish = false;
                        new AlertDialog.Builder(getContext()).setTitle(R.string.app_name).setMessage(R.string.delete_confirm).setNegativeButton(getString(android.R.string.no), new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (selection.size() < 8) {
                                    // Remove chapters on UI Thread
                                    for (int i = selection.size() - 1; i >= 0; i--) {
                                        Chapter chapter = mChapterAdapter.getItem(selection.keyAt(i));
                                        chapter.delete(getActivity(), mManga, serverBase);
                                        mChapterAdapter.remove(chapter);
                                        mode.finish();
                                    }
                                } else {
                                    removeChapters = new RemoveChapters(serverBase, selection.size(), mode);
                                    removeChapters.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                }
                                dialog.dismiss();
                            }
                        }).show();
                        break;
                    case R.id.reset_chapter:
                        resetChapters = new ResetChapters(serverBase, selection.size());
                        resetChapters.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        break;
                    case R.id.mark_selected_as_read:
                        markSelectedAsRead = new MarkSelectedAsRead(selection.size());
                        markSelectedAsRead.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        break;
                    case R.id.mark_selected_as_unread:
                        markSelectedAsUnread = new MarkSelectedAsUnread(selection.size());
                        markSelectedAsUnread.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        break;
                }
                mChapterAdapter.notifyDataSetChanged();
                if (finish)
                    mode.finish();
                return false;
            }

            @Override
            public void onItemCheckedStateChanged(android.view.ActionMode mode, int position, long id, boolean checked) {
                mChapterAdapter.setSelectedOrUnselected(position);
            }
        });
        getActivity().setTitle(mManga.getTitle());
        Database.updateMangaRead(getActivity(), mManga.getId());
        loadInfo(mManga);
        chapters_order = pm.getInt(CHAPTERS_ORDER, 1);
        hide_read = pm.getBoolean(CHAPTERS_HIDE_READ, false);
    }
}
Also used : ActionMode(android.view.ActionMode) DialogInterface(android.content.DialogInterface) SwipeRefreshLayout(android.support.v4.widget.SwipeRefreshLayout) SparseBooleanArray(android.util.SparseBooleanArray) Menu(android.view.Menu) ServerBase(ar.rulosoft.mimanganu.servers.ServerBase) MenuInflater(android.view.MenuInflater) Chapter(ar.rulosoft.mimanganu.componentes.Chapter) AbsListView(android.widget.AbsListView) MenuItem(android.view.MenuItem) View(android.view.View) AdapterView(android.widget.AdapterView) AbsListView(android.widget.AbsListView) ListView(android.widget.ListView) ControlInfoNoScroll(ar.rulosoft.mimanganu.componentes.ControlInfoNoScroll) ColorDrawable(android.graphics.drawable.ColorDrawable) AdapterView(android.widget.AdapterView) ImageLoader(com.fedorvlasov.lazylist.ImageLoader)

Example 5 with ServerBase

use of ar.rulosoft.mimanganu.servers.ServerBase in project MiMangaNu by raulhaag.

the class PreferencesFragment method onCreatePreferences.

@Override
public void onCreatePreferences(Bundle bundle, String s) {
    addPreferencesFromResource(R.xml.fragment_preferences);
    ColorListDialogPref primaryColor = (ColorListDialogPref) getPreferenceManager().findPreference("primario");
    primaryColor.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object o) {
            ((MainActivity) getActivity()).setColorToBars();
            return false;
        }
    });
    PreferenceGroup preferenceGroup = (PreferenceGroup) findPreference("account");
    ServerBase[] servers = ServerBase.getServers(getContext());
    for (final ServerBase sb : servers) {
        if (sb.needLogin()) {
            SwitchPreferenceCompat preference = new SwitchPreferenceCompat(getContext());
            preference.setTitle(sb.getServerName());
            preference.setSelectable(true);
            preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

                @Override
                public boolean onPreferenceClick(Preference preference) {
                    new LoginDialog(getContext(), sb).show();
                    return false;
                }
            });
            preferenceGroup.addPreference(preference);
        }
    }
    /* Once, create necessary Data */
    prefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
    final String current_filepath = prefs.getString("directorio", Environment.getExternalStorageDirectory().getAbsolutePath()) + "/MiMangaNu/";
    /* This enables to hide downloaded images from gallery, just a toggle */
    final SwitchPreferenceCompat cBoxPref = (SwitchPreferenceCompat) getPreferenceManager().findPreference("mostrar_en_galeria");
    // actuate the switch based on the existence of the .nomedia file
    final File noMedia = new File(current_filepath, ".nomedia");
    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
        cBoxPref.setChecked(noMedia.exists());
    } else {
        cBoxPref.setEnabled(false);
    }
    cBoxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            // reject change event in case the external storage is not available
            if (!android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
                return false;
            }
            try {
                if ((Boolean) newValue) {
                    if (!noMedia.createNewFile()) {
                        Log.w("PF", "failed to create .nomedia file");
                    }
                } else {
                    if (!noMedia.delete()) {
                        Log.w("PF", "failed to delete .nomedia file");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }
    });
    /* Set summary for Reader preference + seamless chapter transitions summary */
    // true: Paged Reader; false: Continuous Reader
    Boolean readType = prefs.getBoolean("reader_type", false);
    Preference reader_type = getPreferenceManager().findPreference("reader_type");
    Preference seamlessChapterTransitionsPref = getPreferenceManager().findPreference("seamless_chapter_transitions");
    if (readType) {
        reader_type.setTitle(getString(R.string.paged_reader));
        seamlessChapterTransitionsPref.setSummary(getString(R.string.seamless_chapter_transitions_paged_reader_subtitle));
    } else {
        reader_type.setTitle(getString(R.string.continuous_reader));
        seamlessChapterTransitionsPref.setSummary(getString(R.string.seamless_chapter_transitions_continuous_reader_subtitle));
    }
    final SwitchPreferenceCompat readerTypePref = (SwitchPreferenceCompat) getPreferenceManager().findPreference("reader_type");
    readerTypePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
            Boolean readType = prefs.getBoolean("reader_type", false);
            Preference reader_type = getPreferenceManager().findPreference("reader_type");
            Preference seamlessChapterTransitions = getPreferenceManager().findPreference("seamless_chapter_transitions");
            if (!readType) {
                reader_type.setTitle(getString(R.string.paged_reader));
                seamlessChapterTransitions.setSummary(getString(R.string.seamless_chapter_transitions_paged_reader_subtitle));
            } else {
                reader_type.setTitle(getString(R.string.continuous_reader));
                seamlessChapterTransitions.setSummary(getString(R.string.seamless_chapter_transitions_continuous_reader_subtitle));
            }
            return true;
        }
    });
    /* enable / disable seamless_chapter_transitions_delete_read depending on the state of seamless_chapter_transitions */
    Preference seamlessChapterTransitionsDeleteReadPreference = getPreferenceManager().findPreference("seamless_chapter_transitions_delete_read");
    if (prefs.getBoolean("seamless_chapter_transitions", false)) {
        seamlessChapterTransitionsDeleteReadPreference.setEnabled(true);
    } else {
        seamlessChapterTransitionsDeleteReadPreference.setEnabled(false);
    }
    final SwitchPreferenceCompat seamlessChapterTransitionsSPC = (SwitchPreferenceCompat) getPreferenceManager().findPreference("seamless_chapter_transitions");
    seamlessChapterTransitionsSPC.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
            Preference seamlessChapterTransitionsDeleteReadPreference = getPreferenceManager().findPreference("seamless_chapter_transitions_delete_read");
            if (!prefs.getBoolean("seamless_chapter_transitions", false)) {
                seamlessChapterTransitionsDeleteReadPreference.setEnabled(true);
            } else {
                seamlessChapterTransitionsDeleteReadPreference.setEnabled(false);
                SharedPreferences.Editor prefEdit = prefs.edit();
                prefEdit.putBoolean("seamless_chapter_transitions_delete_read", false);
                prefEdit.apply();
            }
            return true;
        }
    });
    /* enable / disable auto_import_path depending on the state of auto_import */
    Preference autoImportPath = getPreferenceManager().findPreference("auto_import_path");
    if (prefs.getBoolean("auto_import", false)) {
        autoImportPath.setEnabled(true);
    } else {
        autoImportPath.setEnabled(false);
    }
    final SwitchPreferenceCompat autoImportSPC = (SwitchPreferenceCompat) getPreferenceManager().findPreference("auto_import");
    autoImportSPC.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
            Preference autoImportPath = getPreferenceManager().findPreference("auto_import_path");
            if (!prefs.getBoolean("auto_import", false)) {
                autoImportPath.setEnabled(true);
            } else {
                autoImportPath.setEnabled(false);
            }
            return true;
        }
    });
    /* This sets the download threads (parallel downloads) */
    final SeekBarCustomPreference listPreferenceDT = (SeekBarCustomPreference) getPreferenceManager().findPreference("download_threads");
    listPreferenceDT.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            int threads = (int) newValue;
            int antes = DownloadPoolService.SLOTS;
            DownloadPoolService.SLOTS = threads;
            if (DownloadPoolService.actual != null)
                DownloadPoolService.actual.slots += (threads - antes);
            return true;
        }
    });
    /* This sets the maximum number of errors to tolerate */
    final SeekBarCustomPreference listPrefET = (SeekBarCustomPreference) getPreferenceManager().findPreference("error_tolerancia");
    listPrefET.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            ChapterDownload.MAX_ERRORS = (int) newValue;
            return true;
        }
    });
    /* This sets the number of retries to fetch images */
    SeekBarCustomPreference listPrefRT = (SeekBarCustomPreference) getPreferenceManager().findPreference("reintentos");
    listPrefRT.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            SingleDownload.RETRY = (int) newValue;
            return true;
        }
    });
    /* This sets the Update Interval of the mangas (i.e. once per week) */
    final ListPreference listPrefCU = (ListPreference) getPreferenceManager().findPreference("update_interval");
    listPrefCU.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            long time = Long.parseLong((String) newValue);
            JobManager.instance().cancelAllForTag(UpdateJobCreator.UPDATE_TAG);
            if (time > 0) {
                new JobRequest.Builder(UpdateJobCreator.UPDATE_TAG).setPeriodic(time, TimeUnit.MINUTES.toMillis(5)).setRequiresCharging(false).setRequiresDeviceIdle(false).setUpdateCurrent(true).build().schedule();
            }
            if (time < 0)
                MainActivity.coldStart = false;
            return true;
        }
    });
    /* This is for Custom language selection */
    final ListPreference listPrefBatotoLang = (ListPreference) getPreferenceManager().findPreference("batoto_lang_selection");
    listPrefBatotoLang.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (newValue.equals("Custom")) {
                LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View rootView = inflater.inflate(R.layout.simple_input_dialog, null);
                final EditText CustomLang = (EditText) rootView.findViewById(R.id.txtCustomLang);
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                dialogBuilder.setTitle(getString(R.string.custom_language));
                dialogBuilder.setView(rootView);
                dialogBuilder.setPositiveButton("Ok", null);
                dialogBuilder.setNegativeButton(getString(R.string.cancel), null);
                AlertDialog dialog = dialogBuilder.create();
                dialog.setOnShowListener(new DialogInterface.OnShowListener() {

                    @Override
                    public void onShow(final DialogInterface dialog) {
                        Button accept = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
                        accept.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View view) {
                                prefs.edit().putString("batoto_custom_lang", CustomLang.getText().toString()).apply();
                                Util.getInstance().toast(getContext(), getString(R.string.custom_language) + ": " + CustomLang.getText().toString());
                                dialog.dismiss();
                            }
                        });
                    }
                });
                dialog.show();
            }
            return true;
        }
    });
    /* This sets the Version Number, that's all */
    final Preference prefAbout = getPreferenceManager().findPreference("about_text");
    prefAbout.setSummary("v" + BuildConfig.VERSION_NAME);
    /* This will check how much storage is taken by the mangas */
    new calcStorage().execute(current_filepath);
    final Preference prefLicense = getPreferenceManager().findPreference("license_view");
    prefLicense.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            ((MainActivity) getActivity()).replaceFragment(new LicenseFragment(), "licence_fragment");
            return false;
        }
    });
    final SwitchPreferenceCompat onlyWifiUpdateSwitch = (SwitchPreferenceCompat) getPreferenceManager().findPreference("update_only_wifi");
    SwitchPreferenceCompat onlyWifiSwitch = (SwitchPreferenceCompat) getPreferenceManager().findPreference("only_wifi");
    onlyWifiSwitch.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object o) {
            NetworkUtilsAndReceiver.ONLY_WIFI = (Boolean) o;
            NetworkUtilsAndReceiver.connectionStatus = NetworkUtilsAndReceiver.ConnectionStatus.UNCHECKED;
            onlyWifiUpdateSwitch.setEnabled(!(Boolean) o);
            return true;
        }
    });
    if (onlyWifiSwitch.isChecked()) {
        onlyWifiUpdateSwitch.setEnabled(false);
    } else {
        onlyWifiUpdateSwitch.setEnabled(true);
    }
    final SeekBarCustomPreference seekBarConnectionRetry = (SeekBarCustomPreference) getPreferenceManager().findPreference("connection_retry");
    seekBarConnectionRetry.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Navigator.connectionRetry = Integer.parseInt(prefs.getString("connection_retry", "10"));
            return true;
        }
    });
    final SeekBarCustomPreference seekBarConnectionTimeout = (SeekBarCustomPreference) getPreferenceManager().findPreference("connection_timeout");
    seekBarConnectionTimeout.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Navigator.connectionTimeout = Integer.parseInt(prefs.getString("connection_timeout", "10"));
            return true;
        }
    });
    final SeekBarCustomPreference seekBarWriteTimeout = (SeekBarCustomPreference) getPreferenceManager().findPreference("write_timeout");
    seekBarWriteTimeout.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Navigator.writeTimeout = Integer.parseInt(prefs.getString("write_timeout", "10"));
            return true;
        }
    });
    final SeekBarCustomPreference seekBarReadTimeout = (SeekBarCustomPreference) getPreferenceManager().findPreference("read_timeout");
    seekBarReadTimeout.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Navigator.readTimeout = Integer.parseInt(prefs.getString("read_timeout", "30"));
            return true;
        }
    });
    Preference gridColumnsPref = getPreferenceManager().findPreference("grid_columns");
    if (prefs.getBoolean("grid_columns_automatic_detection", true)) {
        gridColumnsPref.setEnabled(false);
    } else {
        gridColumnsPref.setEnabled(true);
    }
    final SwitchPreferenceCompat gridColumnsAutomaticDetectionSPC = (SwitchPreferenceCompat) getPreferenceManager().findPreference("grid_columns_automatic_detection");
    gridColumnsAutomaticDetectionSPC.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
            Preference gridColumns = getPreferenceManager().findPreference("grid_columns");
            if (prefs.getBoolean("grid_columns_automatic_detection", true)) {
                gridColumns.setEnabled(true);
            } else {
                gridColumns.setEnabled(false);
            }
            return true;
        }
    });
    final Preference prefClearCache = getPreferenceManager().findPreference("clear_cache");
    prefClearCache.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            Preference clearCache = getPreferenceManager().findPreference("clear_cache");
            clearCache.setEnabled(false);
            Thread t0 = new Thread(new Runnable() {

                @Override
                public void run() {
                    new FileCache(getActivity()).clearCache();
                }
            });
            Thread t1 = new Thread(new Runnable() {

                @Override
                public void run() {
                    Util.getInstance().createNotificationWithProgressbar(getContext(), 69, getString(R.string.deleting_empty_directories), "");
                    Util.getInstance().deleteEmptyDirectoriesRecursive(new File(current_filepath));
                    Util.getInstance().cancelNotification(69);
                }
            });
            t0.start();
            t1.start();
            return true;
        }
    });
    final Preference prefClearSpecificCookies = getPreferenceManager().findPreference("clear_specific_cookies");
    prefClearSpecificCookies.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            Preference clearSpecificCookies = getPreferenceManager().findPreference("clear_specific_cookies");
            clearSpecificCookies.setEnabled(false);
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View rootView = inflater.inflate(R.layout.simple_input_dialog, null);
            final EditText SpecificCookiesToClear = (EditText) rootView.findViewById(R.id.txtCustomLang);
            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
            dialogBuilder.setTitle("Cookies to clear contain");
            dialogBuilder.setView(rootView);
            dialogBuilder.setPositiveButton("Ok", null);
            dialogBuilder.setNegativeButton(getString(R.string.cancel), null);
            AlertDialog dialog = dialogBuilder.create();
            dialog.setOnShowListener(new DialogInterface.OnShowListener() {

                @Override
                public void onShow(final DialogInterface dialog) {
                    Button accept = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
                    accept.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View view) {
                            Thread t0 = new Thread(new Runnable() {

                                @Override
                                public void run() {
                                    Util.getInstance().removeSpecificCookies(getContext(), SpecificCookiesToClear.getText().toString());
                                }
                            });
                            t0.start();
                            dialog.dismiss();
                        }
                    });
                    Button cancel = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEGATIVE);
                    cancel.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                        }
                    });
                }
            });
            dialog.show();
            return true;
        }
    });
    final Preference prefClearAllCookies = getPreferenceManager().findPreference("clear_all_cookies");
    prefClearAllCookies.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            Preference clearAllCookies = getPreferenceManager().findPreference("clear_all_cookies");
            clearAllCookies.setEnabled(false);
            Thread t0 = new Thread(new Runnable() {

                @Override
                public void run() {
                    Util.getInstance().removeAllCookies(getContext());
                }
            });
            t0.start();
            return true;
        }
    });
    final Preference prefResetServersToDefaults = getPreferenceManager().findPreference("reset_server_list_to_defaults");
    prefResetServersToDefaults.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            Preference resetServerListToDefaults = getPreferenceManager().findPreference("reset_server_list_to_defaults");
            resetServerListToDefaults.setEnabled(false);
            prefs.edit().putString("unused_servers", "").apply();
            return true;
        }
    });
    final Preference prefVacuumDatabase = getPreferenceManager().findPreference("vacuum_database");
    prefVacuumDatabase.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference preference) {
            Preference vacuumDatabase = getPreferenceManager().findPreference("vacuum_database");
            vacuumDatabase.setEnabled(false);
            Thread t0 = new Thread(new Runnable() {

                @Override
                public void run() {
                    Util.getInstance().createNotificationWithProgressbar(getContext(), 70, getString(R.string.vacuum_database_notification_text), "");
                    Database.vacuumDatabase(getContext());
                    Util.getInstance().cancelNotification(70);
                }
            });
            t0.start();
            return true;
        }
    });
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        getPreferenceManager().findPreference("update_sound").setVisible(false);
        getPreferenceManager().findPreference("update_vibrate").setVisible(false);
        getPreferenceManager().findPreference("update_notif_options").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

            @Override
            public boolean onPreferenceClick(Preference preference) {
                Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
                intent.putExtra(Settings.EXTRA_CHANNEL_ID, Util.channelIdNews);
                intent.putExtra(Settings.EXTRA_APP_PACKAGE, getContext().getPackageName());
                startActivity(intent);
                return true;
            }
        });
    } else {
        getPreferenceManager().findPreference("update_notif_options").setVisible(false);
    }
    setFirstRunDefaults();
}
Also used : AlertDialog(android.app.AlertDialog) DialogInterface(android.content.DialogInterface) ColorListDialogPref(ar.rulosoft.custompref.ColorListDialogPref) JobRequest(com.evernote.android.job.JobRequest) Button(android.widget.Button) ServerBase(ar.rulosoft.mimanganu.servers.ServerBase) EditText(android.widget.EditText) SwitchPreferenceCompat(android.support.v7.preference.SwitchPreferenceCompat) SharedPreferences(android.content.SharedPreferences) Intent(android.content.Intent) ListPreference(android.support.v7.preference.ListPreference) View(android.view.View) FileCache(com.fedorvlasov.lazylist.FileCache) SeekBarCustomPreference(ar.rulosoft.custompref.SeekBarCustomPreference) ListPreference(android.support.v7.preference.ListPreference) Preference(android.support.v7.preference.Preference) LayoutInflater(android.view.LayoutInflater) PreferenceGroup(android.support.v7.preference.PreferenceGroup) LoginDialog(ar.rulosoft.mimanganu.componentes.LoginDialog) File(java.io.File) SeekBarCustomPreference(ar.rulosoft.custompref.SeekBarCustomPreference)

Aggregations

ServerBase (ar.rulosoft.mimanganu.servers.ServerBase)10 DialogInterface (android.content.DialogInterface)4 View (android.view.View)4 Manga (ar.rulosoft.mimanganu.componentes.Manga)3 File (java.io.File)3 AlertDialog (android.app.AlertDialog)2 SharedPreferences (android.content.SharedPreferences)2 RecyclerView (android.support.v7.widget.RecyclerView)2 OnClickListener (android.view.View.OnClickListener)2 ImageView (android.widget.ImageView)2 Chapter (ar.rulosoft.mimanganu.componentes.Chapter)2 LoginDialog (ar.rulosoft.mimanganu.componentes.LoginDialog)2 Intent (android.content.Intent)1 ColorDrawable (android.graphics.drawable.ColorDrawable)1 Bundle (android.os.Bundle)1 PowerManager (android.os.PowerManager)1 SwipeRefreshLayout (android.support.v4.widget.SwipeRefreshLayout)1 ListPreference (android.support.v7.preference.ListPreference)1 Preference (android.support.v7.preference.Preference)1 PreferenceGroup (android.support.v7.preference.PreferenceGroup)1