Esempio n. 1
0
        public async Task LoadChapterAsync(int index, CancellationToken token)
        {
            //wait till previous task is cancelled
            while (lastDownloadTask != null && lastDownloadTask.Status == TaskStatus.WaitingForActivation && !lastDownloadTask.IsCanceled)
            {
                Debug.WriteLine("Waiting for last task to cancel");

                //wait for 25ms
                await Task.Delay(25);
            }

            CheckVisibility = Visibility.Hidden;

            List <string> pagePaths;

            //downloaded chapter path
            string chapterPath = MainViewModel.Settings.mangaPath + MangaName + "/" + ChapterNames[index].Replace(' ', '_') + ".ch";

            //if chapter hasn't been downloaded, download
            if (!File.Exists(chapterPath))
            {
                //get current selected chapters url
                string currentUrl = _chapters[index].url;

                //get page paths
                pagePaths = await GetPagePaths(currentUrl);

                //set maximum of page downloads progress bar
                PageCount = pagePaths.Count;

                //reset downloaded value
                PagesDownloadValue = 0;

                //Itereate through pages
                for (int i = 0; i < pagePaths.Count; i++)
                {
                    BitmapImage imageSource;

                    //if chapter already downloaded
                    if (_chapters[(int)SelectedChapterIndex].imageTempPaths.Count >= i + 1 && _chapters[(int)SelectedChapterIndex].imageTempPaths[i] != null)
                    {
                        //load image from byte array on file
                        imageSource = LoadBitmapFromArrayFile(_chapters[(int)SelectedChapterIndex].imageTempPaths[i]);
                    }
                    else
                    {
                        WebClient web = new WebClient();
                        web.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                        byte[] byteArray = await web.DownloadDataTaskAsync(pagePaths[i]);

                        //Download the data to byte array
                        //byte[] byteArray = DataConversionHelper.DownloadToArray(pagePaths[i]);

                        //save byte array to temporary file
                        string tempPath = SaveByteArrayToTempFile(byteArray);

                        //record temporary path
                        _chapters[(int)SelectedChapterIndex].imageTempPaths.Add(tempPath);

                        //convert array to Bitmap
                        imageSource = byteArray.ToFreezedBitmapImage();
                    }

                    //check for cancellation before applying image
                    token.ThrowIfCancellationRequested();

                    //Call main thread to add to collection
                    Application.Current.Dispatcher.Invoke(() => { AddToReaderAsync(imageSource); });

                    //append downloaded chapter value
                    PagesDownloadValue += 1;
                }

                if (MainViewModel.Settings.autoDownloadReadChapters)
                {
                    if (!File.Exists(mangaSavePath))
                    {
                        MainViewModel.MangaViewModel.SaveMangaInfo();
                    }

                    //save the downloaded
                    SaveChapter((int)SelectedChapterIndex, chapterPath);
                }
            }
            else // read chapter from memory
            {
                //load data from chapter file
                imageData = SaveSystem.LoadBinary <ChSave>(chapterPath).Images;

                //set maximum of page downloads progress bar
                PageCount = imageData.Count;

                //reset downloaded value
                PagesDownloadValue = 0;

                //iterate through all data
                for (int i = 0; i < imageData.Count; i++)
                {
                    //Create image from byte array
                    BitmapImage image = imageData[i].ToFreezedBitmapImage();

                    //Call main thread to add to collection
                    Application.Current.Dispatcher.Invoke(() => { AddToReaderAsync(image); });

                    //append downloaded chapter value
                    PagesDownloadValue += 1;
                }
            }

            //Rise notification according to settings
            if (MainViewModel.Settings.chapterReaderLoadNotifications)
            {
                Application.Current.Dispatcher.Invoke(() => MainViewModel.NotificationsViewModel.AddNotification("Current chapter fully loaded", NotificationMode.Success));
            }

            CheckVisibility = Visibility.Visible;

            #region Download next chapter to temporary path

            //if next chapter doesnt exist exit method
            if (!NextChapterExists || !MainViewModel.Settings.autoDownloadNextChapter)
            {
                currentDownloadTask = null; return;
            }

            //Save path for Next chapter
            string NextchapterPath = MainViewModel.Settings.mangaPath + MangaName + "/" + ChapterNames[index + 1].Replace(' ', '_') + ".ch";

            //if next chapter downloaded exit method
            if (File.Exists(NextchapterPath))
            {
                currentDownloadTask = null; return;
            }

            //Next chapters url
            string NextUrl = _chapters[index + 1].url;

            //get page paths
            pagePaths = await GetPagePaths(NextUrl);

            //Itereate through pages
            for (int i = 0; i < pagePaths.Count; i++)
            {
                //check for cancellation before downloading image
                token.ThrowIfCancellationRequested();

                //if page of chapter havent been downloaded
                if (!(_chapters[(int)SelectedChapterIndex + 1].imageTempPaths.Count >= i + 1 && _chapters[(int)SelectedChapterIndex + 1].imageTempPaths[i] != null))
                {
                    //Download the data to byte array
                    byte[] byteArray = DataConversionHelper.DownloadToArray(pagePaths[i]);

                    //save byte array to temporary file
                    string tempPath = SaveByteArrayToTempFile(byteArray);

                    //record temporary path
                    _chapters[(int)SelectedChapterIndex + 1].imageTempPaths.Add(tempPath);
                }
            }

            if (MainViewModel.Settings.autoDownloadReadChapters)
            {
                //save the downloaded
                SaveChapter((int)SelectedChapterIndex + 1, NextchapterPath);
            }

            #endregion

            currentDownloadTask = null;
        }
        private async Task DownloadAsync()
        {
            isDownloading = true;

            while (_DownloadsPanel.Count > 0)
            {
                //get first Queued in list
                DownloadProgressViewModel item = null;
                for (int i = 0; i < _DownloadsPanel.Count; i++)
                {
                    if (_DownloadsPanel[i].DownloadState == DownloadState.Queued)
                    {
                        item = _DownloadsPanel[i];
                        break;
                    }
                }

                //if no items queued
                if (item == null)
                {
                    isDownloading = false; return;
                }

                //if download state is wait
                while (PlayPackIcon == PackIconKind.Play)
                {
                    await Task.Delay(1000);
                }

                //get all page paths of chapter
                List <string> pagePaths = await GetPagePaths(item.url);

                //set progress bar end
                item.Maximum = pagePaths.Count;

                //Change download State
                item.DownloadState = DownloadState.InProgress;

                //download all undownloaded files
                for (int i = 0; i < pagePaths.Count; i++)
                {
                    //if download state is wait
                    while (PlayPackIcon == PackIconKind.Play)
                    {
                        await Task.Delay(1000);
                    }

                    if (!(item.tempPaths.Count >= i + 1 && item.tempPaths[i] != null))
                    {
                        //Download data to a byte array
                        byte[] array = DataConversionHelper.DownloadToArray(pagePaths[i]);

                        //Save to a temporary file
                        string path = SaveByteArrayToTempFile(array);

                        //Remember path
                        item.tempPaths.Add(path);
                    }

                    //advance download progress
                    item.Progress += 1;
                }

                //Create new ch class
                ChSave chSave = new ChSave(LoadPaths(item.tempPaths));

                //create path for download
                string savePath = MainView.Settings.mangaPath + item.Header + "/" + item.Description.Replace(" ", "_") + ".ch";

                //Save file to path
                SaveSystem.SaveBinary(chSave, savePath);

                //dispose of save class
                chSave = null;

                //Set download status to complete
                item.DownloadState = DownloadState.Completed;

                //notify user according to settings
                Application.Current.Dispatcher.Invoke(() =>
                {
                    if (MainView.Settings.chapterDownloadNotifications)
                    {
                        MainView.NotificationsViewModel.AddNotification(item.Header + ": " + item.Description + " Download Complete.", NotificationMode.Success);
                    }
                    if (MainView.Settings.autoDeleteCompletedDownloads)
                    {
                        DownloadsPanel.Remove(item);
                    }
                });
            }

            isDownloading = false;
            if (MainView.Settings.downloadTaskNotifications)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    MainView.NotificationsViewModel.AddNotification("Download Task complete.", NotificationMode.Normal);
                });
            }
        }