Ejemplo n.º 1
0
 private void HandleDownloadProgress(DownloadItemViewModel downloadItemViewModel, object progress)
 {
     if (progress is DownloadFileProgress downloadFileProgress)
     {
         downloadItemViewModel.UpdateProgress(downloadFileProgress.DownloadedBytes, downloadFileProgress.FileSize);
     }
 }
        public void Download(DownloadItemViewModel newDownload)
        {
            if (!AssetCatalog.TryParseDownloadUrl(newDownload.DownloadUrl, out DownloadLocationType type, out string location))
            {
                return;
            }

            switch (type)
            {
            case DownloadLocationType.Url:
                DownloadFileFromUrl(newDownload, location);
                break;


            case DownloadLocationType.GDrive:
                DownloadFileFromGDrive(newDownload, location);
                break;


            case DownloadLocationType.MegaFile:
                DownloadFileFromMega(newDownload, location);

                break;
            }

            newDownload.IsStarted = true;
        }
Ejemplo n.º 3
0
        private void ApplyDownloadManagerBatchEventArgs(ObservableCollection <DownloadItemViewModel> downloads,
                                                        DownloadManagerBatchEventArgs downloadManagerBatchEventArgs,
                                                        out bool selectionButtonStatesUpdateRequired, out bool nonSelectionButtonStatesUpdateRequired)
        {
            selectionButtonStatesUpdateRequired    = false;
            nonSelectionButtonStatesUpdateRequired = false;
            foreach (DownloadItemEventArgs downloadItemEventArgs in downloadManagerBatchEventArgs.BatchEvents)
            {
                switch (downloadItemEventArgs)
                {
                case DownloadItemAddedEventArgs downloadItemAddedEvent:
                    DownloadItemViewModel newDownloadItemViewModel = ToDownloadItemViewModel(downloadItemAddedEvent.AddedDownloadItem);
                    downloadDictionary[newDownloadItemViewModel.Id] = newDownloadItemViewModel;
                    downloads.Add(newDownloadItemViewModel);
                    nonSelectionButtonStatesUpdateRequired = true;
                    break;

                case DownloadItemChangedEventArgs downloadItemChangedEvent:
                    DownloadItem          changedDownloadItem          = downloadItemChangedEvent.ChangedDownloadItem;
                    DownloadItemViewModel changedDownloadItemViewModel = downloadDictionary[changedDownloadItem.Id];
                    bool statusChanged = changedDownloadItemViewModel.Status != changedDownloadItem.Status;
                    changedDownloadItemViewModel.Name = changedDownloadItem.FileName;
                    if (statusChanged)
                    {
                        changedDownloadItemViewModel.Status = changedDownloadItem.Status;
                    }
                    changedDownloadItemViewModel.ProgressText  = GetDownloadProgressText(changedDownloadItem);
                    changedDownloadItemViewModel.ProgressValue = GetDownloadProgressValue(changedDownloadItem);
                    if (statusChanged)
                    {
                        if (changedDownloadItemViewModel.IsSelected)
                        {
                            selectionButtonStatesUpdateRequired = true;
                        }
                        nonSelectionButtonStatesUpdateRequired = true;
                    }
                    break;

                case DownloadItemRemovedEventArgs downloadItemRemovedEvent:
                    DownloadItem          removedDownloadItem          = downloadItemRemovedEvent.RemovedDownloadItem;
                    DownloadItemViewModel removedDownloadItemViewModel = downloadDictionary[removedDownloadItem.Id];
                    bool wasSelected = removedDownloadItemViewModel.IsSelected;
                    downloads.Remove(removedDownloadItemViewModel);
                    if (wasSelected)
                    {
                        selectionButtonStatesUpdateRequired = true;
                    }
                    nonSelectionButtonStatesUpdateRequired = true;
                    break;

                case DownloadItemLogLineEventArgs downloadItemLogLineEvent:
                    DownloadItemViewModel downloadItemViewModel = downloadDictionary[downloadItemLogLineEvent.DownloadItemId];
                    if (downloadItemLogLineEvent.LineIndex >= downloadItemViewModel.Logs.Count)
                    {
                        downloadItemViewModel.Logs.Add(ToDownloadItemLogLineViewModel(downloadItemLogLineEvent.LogLine));
                    }
                    break;
                }
            }
        }
Ejemplo n.º 4
0
        public DownloadItemViewModel Download(string link, string saveFilePath, string description, Action onCancel, Action onComplete)
        {
            DownloadLocationType type;
            string location;

            if (!AssetCatalog.TryParseDownloadUrl(link, out type, out location))
            {
                return(null);
            }

            Action onError = () =>
            {
            };


            DownloadItemViewModel newDownload = new DownloadItemViewModel()
            {
                ItemName      = description,
                OnCancel      = onCancel,
                OnError       = onError,
                OnComplete    = onComplete,
                DownloadSpeed = "Calculating ...",
                DownloadType  = DownloadType.Asset
            };

            switch (type)
            {
            case DownloadLocationType.Url:
                using (var wc = new System.Net.WebClient())
                {
                    newDownload.PerformCancel = () =>
                    {
                        wc.CancelAsync();
                        newDownload.OnCancel?.Invoke();
                    };
                    wc.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_wc_DownloadProgressChanged);
                    wc.DownloadFileCompleted   += new AsyncCompletedEventHandler(_wc_DownloadFileCompleted);
                    wc.DownloadFileAsync(new Uri(location), saveFilePath, newDownload);
                }

                break;

            case DownloadLocationType.GDrive:
                var gd = new GDrive();
                newDownload.PerformCancel = () =>
                {
                    gd.CancelAsync();
                    newDownload.OnCancel?.Invoke();
                };
                gd.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_wc_DownloadProgressChanged);
                gd.DownloadFileCompleted   += new AsyncCompletedEventHandler(_wc_DownloadFileCompleted);
                gd.Download(location, saveFilePath, newDownload);
                break;
            }

            newDownload.IsStarted = true;
            return(newDownload);
        }
        void _wc_DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
        {
            DownloadItemViewModel item = (DownloadItemViewModel)e.UserState;
            int prog = e.ProgressPercentage;

            if ((e.TotalBytesToReceive < 0) && (sender is GDrive))
            {
                prog = (int)(100 * e.BytesReceived / (sender as GDrive).GetContentLength());
            }
            UpdateDownloadProgress(item, prog, e.BytesReceived);
        }
        private void menuItemCancelDownload_Click(object sender, RoutedEventArgs e)
        {
            DownloadItemViewModel downloadItem = lstDownloads.SelectedItem as DownloadItemViewModel;

            if (downloadItem == null)
            {
                return;
            }

            downloadItem.PerformCancel?.Invoke();
        }
Ejemplo n.º 7
0
 public void SelectDownload(Guid downloadId)
 {
     ExecuteInUiThread(() =>
     {
         DownloadItemViewModel downloadItemToSelect = Downloads.FirstOrDefault(downloadItemViewModel => downloadItemViewModel.Id == downloadId);
         if (downloadItemToSelect != null)
         {
             SelectedDownload = downloadItemToSelect;
             Events.RaiseEvent(ViewModelEvent.RegisteredEventId.SCROLL_TO_SELECTION);
         }
     });
 }
Ejemplo n.º 8
0
        private void menuItemCancelDownload_Click(object sender, RoutedEventArgs e)
        {
            DownloadItemViewModel downloadItem = lstDownloads.SelectedItem as DownloadItemViewModel;

            if (downloadItem == null)
            {
                return;
            }

            downloadItem.IsCanceled = true;
            ViewModel.CancelDownload(downloadItem);
        }
        private void DownloadFileFromGDrive(DownloadItemViewModel newDownload, string fileId)
        {
            GDrive gd = new GDrive();

            newDownload.PerformCancel = () =>
            {
                gd.CancelAsync();
                newDownload.OnCancel?.Invoke();
            };
            gd.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_wc_DownloadProgressChanged);
            gd.DownloadFileCompleted   += new AsyncCompletedEventHandler(_wc_DownloadFileCompleted);
            gd.Download(fileId, newDownload.SaveFilePath, newDownload);
        }
 private void DownloadFileFromUrl(DownloadItemViewModel newDownload, string url)
 {
     using (var wc = new System.Net.WebClient())
     {
         newDownload.PerformCancel = () =>
         {
             wc.CancelAsync();
             newDownload.OnCancel?.Invoke();
         };
         wc.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_wc_DownloadProgressChanged);
         wc.DownloadFileCompleted   += new AsyncCompletedEventHandler(_wc_DownloadFileCompleted);
         wc.DownloadFileAsync(new Uri(url), newDownload.SaveFilePath, newDownload);
     }
 }
Ejemplo n.º 11
0
        public void AddAndStart(string filepath, string url, int no, int type = 0)
        {
            var item = new DownloadItemViewModel(_downloadService)
            {
                FilePath = filepath,
                Url      = url,
                No       = no,
                Type     = type
            };

            Downloads.Add(item);

            item.Start();
        }
Ejemplo n.º 12
0
        private async Task DownloadNextItemAsync()
        {
            DownloadItemViewModel downloadItem = Downloads.FirstOrDefault(downloadItemViewModel => downloadItemViewModel.Status == DownloadItemStatus.QUEUED);

            if (downloadItem == null)
            {
                return;
            }
            string            dumpUrl                 = downloadItem.Collection.DownloadUrl;
            string            dumpFilePath            = downloadItem.Collection.DownloadFilePath;
            Progress <object> downloadProgressHandler = new Progress <object>(progress => HandleDownloadProgress(downloadItem, progress));

            DownloadUtils.DownloadResult downloadResult = default;
            bool error = false;

            downloadItem.UpdateStatus(DownloadItemStatus.DOWNLOADING);
            try
            {
                downloadResult = await MainModel.LibgenDumpDownloader.DownloadDumpAsync(dumpUrl, dumpFilePath, downloadProgressHandler,
                                                                                        downloadCancellationTokenSource.Token);
            }
            catch (Exception exception)
            {
                Logger.Exception(exception);
                error = true;
            }
            if (!error)
            {
                switch (downloadResult)
                {
                case DownloadUtils.DownloadResult.COMPLETED:
                    downloadItem.UpdateStatus(DownloadItemStatus.COMPLETED);
                    break;

                case DownloadUtils.DownloadResult.CANCELLED:
                    downloadItem.UpdateStatus(DownloadItemStatus.STOPPED);
                    break;

                case DownloadUtils.DownloadResult.INCOMPLETE:
                case DownloadUtils.DownloadResult.ERROR:
                    error = true;
                    break;
                }
            }
            if (error)
            {
                downloadItem.UpdateStatus(DownloadItemStatus.ERROR);
            }
        }
Ejemplo n.º 13
0
 private void DownloaderListBoxDoubleClick()
 {
     if (SelectedRows.Count == 1)
     {
         DownloadItemViewModel selectedDownload = SelectedDownloads.First();
         if (selectedDownload.Status == DownloadItemStatus.COMPLETED)
         {
             string downloadedFilePath = Path.Combine(selectedDownload.DownloadDirectory, selectedDownload.Name);
             if (File.Exists(downloadedFilePath))
             {
                 Process.Start(downloadedFilePath);
             }
             else
             {
                 ShowMessage(Localization.FileNotFoundErrorTitle, Localization.GetFileNotFoundErrorText(downloadedFilePath));
             }
         }
     }
 }
Ejemplo n.º 14
0
        public void Download(DownloadItemViewModel newDownload)
        {
            DownloadLocationType type;
            string location;

            if (!AssetCatalog.TryParseDownloadUrl(newDownload.DownloadUrl, out type, out location))
            {
                return;
            }

            switch (type)
            {
            case DownloadLocationType.Url:
                using (var wc = new System.Net.WebClient())
                {
                    newDownload.PerformCancel = () =>
                    {
                        wc.CancelAsync();
                        newDownload.OnCancel?.Invoke();
                    };
                    wc.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_wc_DownloadProgressChanged);
                    wc.DownloadFileCompleted   += new AsyncCompletedEventHandler(_wc_DownloadFileCompleted);
                    wc.DownloadFileAsync(new Uri(location), newDownload.SaveFilePath, newDownload);
                }

                break;

            case DownloadLocationType.GDrive:
                var gd = new GDrive();
                newDownload.PerformCancel = () =>
                {
                    gd.CancelAsync();
                    newDownload.OnCancel?.Invoke();
                };
                gd.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_wc_DownloadProgressChanged);
                gd.DownloadFileCompleted   += new AsyncCompletedEventHandler(_wc_DownloadFileCompleted);
                gd.Download(location, newDownload.SaveFilePath, newDownload);
                break;
            }

            newDownload.IsStarted = true;
        }
        private void UpdateDownloadProgress(DownloadItemViewModel item, int percentDone, long bytesReceived)
        {
            if (item.PercentComplete != percentDone)
            {
                item.PercentComplete = percentDone;
            }

            TimeSpan interval = DateTime.Now - item.LastCalc;

            if ((interval.TotalSeconds >= 5))
            {
                if (bytesReceived > 0)
                {
                    item.DownloadSpeed = (((bytesReceived - item.LastBytes) / 1024.0) / interval.TotalSeconds).ToString("0.0") + "KB/s";
                    item.LastBytes     = bytesReceived;
                }

                item.LastCalc = DateTime.Now;
            }
        }
Ejemplo n.º 16
0
        private void DownloadAllPreviewImagesAsync()
        {
            Task t = Task.Factory.StartNew(() =>
            {
                CreateRequiredFolders();

                foreach (AssetViewModel asset in AllAssets.ToList())
                {
                    string pathToThumbnail = Path.Combine(AbsolutePathToThumbnails, asset.Asset.IDWithoutExtension);

                    if (ImageCache.IsOutOfDate(pathToThumbnail) || ImageCache.IsSourceUrlDifferent(pathToThumbnail, asset.Asset.PreviewImage))
                    {
                        ImageCache.AddOrUpdate(pathToThumbnail, asset.Asset.PreviewImage);

                        Guid downloadId = Guid.NewGuid();
                        Action onCancel = () => { RemoveFromDownloads(downloadId); };
                        Action onError  = () => { RemoveFromDownloads(downloadId); };

                        Action onComplete = () =>
                        {
                            RemoveFromDownloads(downloadId);
                        };

                        string formattedUrl = "rsmm://Url/" + asset.Asset.PreviewImage.Replace("://", "$");
                        DownloadItemViewModel downloadItem = new DownloadItemViewModel()
                        {
                            UniqueId     = downloadId,
                            DownloadType = DownloadType.Image,
                            ItemName     = "Downloading preview image",
                            DownloadUrl  = formattedUrl,
                            SaveFilePath = pathToThumbnail,
                            OnCancel     = onCancel,
                            OnComplete   = onComplete,
                            OnError      = onError
                        };

                        AddToDownloads(downloadItem);
                    }
                }
            });
        }
        void _wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            DownloadItemViewModel item = (DownloadItemViewModel)e.UserState;

            if (e.Cancelled)
            {
                if (sender is System.Net.WebClient)
                {
                    (sender as System.Net.WebClient).Dispose();
                }
                item.OnCancel?.Invoke();
            }
            else if (e.Error != null)
            {
                item.OnError?.Invoke(e.Error);
            }
            else
            {
                item.OnComplete?.Invoke();
            }
        }
Ejemplo n.º 18
0
        public static void AddDownload(DownloadFileInfo downloadItem)
        {
            DownloadWindow tempWindow = null;

            lock (DownloadWindows)
            {
                if (!DownloadWindows.TryGetValue(downloadItem.Id, out tempWindow))//不在缓存列表
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.FileName = downloadItem.SuggestedFileName;
                    sfd.Filter   = "所有文件|*";

                    var res = sfd.ShowDialog();
                    if (res == DialogResult.OK)
                    {
                        tempWindow = new DownloadWindow();
                        var vm = new DownloadItemViewModel()
                        {
                            FullPath      = sfd.FileName,
                            ID            = downloadItem.Id,
                            ReceivedBytes = 0,
                            Url           = downloadItem.Url,
                            TotalBytes    = downloadItem.TotalBytes
                        };
                        tempWindow.Closed += (s, e) =>
                        {
                            tempWindow.DataContext = null;
                            tempWindow.Close();
                            DownloadWindows.TryRemove(downloadItem.Id, out tempWindow);
                        };
                        tempWindow.DataContext = vm;
                        tempWindow.Show();
                        tempWindow.Activate();

                        DownloadWindows.TryAdd(downloadItem.Id, tempWindow);
                    }
                }
            }
        }
Ejemplo n.º 19
0
        void _wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            DownloadItemViewModel item = (DownloadItemViewModel)e.UserState;

            if (e.Cancelled)
            {
                if (sender is System.Net.WebClient)
                {
                    (sender as System.Net.WebClient).Dispose();
                }
                item.OnCancel?.Invoke();
            }
            else if (e.Error != null)
            {
                item.OnError?.Invoke();
                string msg = $"Error {item.ItemName} - {e.Error.GetBaseException().Message}";
            }
            else
            {
                item.OnComplete?.Invoke();
            }
        }
Ejemplo n.º 20
0
        private void RemoveFromDownloads(DownloadItemViewModel download)
        {
            if (download == null)
            {
                return;
            }

            var currentList = CurrentDownloads.ToList();

            currentList.Remove(download);

            CurrentDownloads = currentList;

            if (CurrentDownloads.Count > 0)
            {
                int nextItemIndex = CurrentDownloads.FindIndex(d => !d.IsStarted);

                if (nextItemIndex >= 0)
                {
                    AssetDownloader.Instance.Download(CurrentDownloads[nextItemIndex]);
                }
            }
        }
Ejemplo n.º 21
0
        private void AddToDownloads(DownloadItemViewModel downloadItem)
        {
            if (downloadItem == null)
            {
                return;
            }

            var currentList = CurrentDownloads.ToList();

            // return if already added to download queue
            if (currentList.Any(d => d.SaveFilePath == downloadItem.SaveFilePath))
            {
                return;
            }

            currentList.Add(downloadItem);

            CurrentDownloads = currentList;

            if (CurrentDownloads.Count == 1)
            {
                // first item added to queue so start download
                AssetDownloader.Instance.Download(downloadItem);
            }
            else if (CurrentDownloads.Count > 1 && CurrentDownloads[0].IsStarted && CurrentDownloads[0].DownloadType == DownloadType.Asset)
            {
                // multiple items queued with the first item being an asset...
                // ... in this case start the next non-asset download
                int nextItemIndex = CurrentDownloads.FindIndex(d => d.DownloadType != DownloadType.Asset && !d.IsStarted);

                if (nextItemIndex >= 0)
                {
                    AssetDownloader.Instance.Download(CurrentDownloads[nextItemIndex]);
                }
            }
        }
Ejemplo n.º 22
0
        private void DownloaderEvent(object sender, EventArgs e)
        {
            switch (e)
            {
            case DownloadItemAddedEventArgs downloadItemAddedEvent:
                DownloadItemViewModel newDownloadItemViewModel = ToDownloadItemViewModel(downloadItemAddedEvent.AddedDownloadItem);
                downloadDictionary[newDownloadItemViewModel.Id] = newDownloadItemViewModel;
                ExecuteInUiThread(() =>
                {
                    Downloads.Add(newDownloadItemViewModel);
                    UpdateNonSelectionButtonStates();
                });
                break;

            case DownloadItemChangedEventArgs downloadItemChangedEvent:
                DownloadItem          changedDownloadItem          = downloadItemChangedEvent.ChangedDownloadItem;
                DownloadItemViewModel changedDownloadItemViewModel = downloadDictionary[changedDownloadItem.Id];
                bool statusChanged = changedDownloadItemViewModel.Status != changedDownloadItem.Status;
                ExecuteInUiThread(() =>
                {
                    changedDownloadItemViewModel.Name = changedDownloadItem.FileName;
                    if (statusChanged)
                    {
                        changedDownloadItemViewModel.Status = changedDownloadItem.Status;
                    }
                    changedDownloadItemViewModel.ProgressText  = GetDownloadProgressText(changedDownloadItem);
                    changedDownloadItemViewModel.ProgressValue = GetDownloadProgressValue(changedDownloadItem);
                    if (statusChanged)
                    {
                        if (changedDownloadItemViewModel.IsSelected)
                        {
                            UpdateSelectionButtonStates();
                        }
                        UpdateNonSelectionButtonStates();
                    }
                });
                break;

            case DownloadItemRemovedEventArgs downloadItemRemovedEvent:
                DownloadItem          removedDownloadItem          = downloadItemRemovedEvent.RemovedDownloadItem;
                DownloadItemViewModel removedDownloadItemViewModel = downloadDictionary[removedDownloadItem.Id];
                ExecuteInUiThread(() =>
                {
                    bool isSelected = removedDownloadItemViewModel.IsSelected;
                    Downloads.Remove(removedDownloadItemViewModel);
                    if (isSelected)
                    {
                        UpdateSelectionButtonStates();
                    }
                    UpdateNonSelectionButtonStates();
                });
                break;

            case DownloadItemLogLineEventArgs downloadItemLogLineEvent:
                DownloadItemViewModel downloadItemViewModel = downloadDictionary[downloadItemLogLineEvent.DownloadItemId];
                if (downloadItemLogLineEvent.LineIndex >= downloadItemViewModel.Logs.Count)
                {
                    ExecuteInUiThread(() => downloadItemViewModel.Logs.Add(ToDownloadItemLogLineViewModel(downloadItemLogLineEvent.LogLine)));
                }
                break;
            }
        }
Ejemplo n.º 23
0
        public void OnDownloadUpdated(IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback)
        {
            try
            {
                if (!string.IsNullOrEmpty(downloadItem.FullPath))
                {
                    DownloadWindow tempWindow = null;

                    if (DownloadWindows.TryGetValue(downloadItem.Id, out tempWindow))//存在缓存里
                    {
                        var vm = tempWindow.DataContext as DownloadItemViewModel;
                        vm.ReceivedBytes = downloadItem.ReceivedBytes;
                        vm.TotalBytes    = downloadItem.TotalBytes;

                        if (downloadItem.IsComplete)//删除完成删除
                        {
                            tempWindow.Close();
                            callback.Dispose();
                            DownloadWindows.TryRemove(downloadItem.Id, out tempWindow);
                        }
                    }
                    else
                    {
                        if (CacheList.Count(c => c.ID == downloadItem.Id) > 0)
                        {
                            return;
                        }

                        tempWindow = new DownloadWindow();
                        var vm = new DownloadItemViewModel()
                        {
                            FullPath      = downloadItem.FullPath,
                            ID            = downloadItem.Id,
                            ReceivedBytes = downloadItem.ReceivedBytes,
                            TotalBytes    = downloadItem.TotalBytes,
                            Url           = downloadItem.Url
                        };

                        tempWindow.Closed += (s, e) =>
                        {
                            CacheList.Add(new CacheModel()
                            {
                                ID = downloadItem.Id, AddTime = DateTime.Now
                            });
                            downloadItem.IsCancelled = true;
                            tempWindow.DataContext   = null;
                            tempWindow.Close();
                            callback.Dispose();
                            DownloadWindows.TryRemove(downloadItem.Id, out tempWindow);

                            Application.Current.Dispatcher.Invoke(new Action(() =>
                            {
                                if (hideWindow != null)
                                {
                                    hideWindow.Close();
                                }
                            }));
                        };
                        tempWindow.DataContext = vm;
                        tempWindow.Show();
                        tempWindow.Activate();

                        DownloadWindows.TryAdd(downloadItem.Id, tempWindow);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
Ejemplo n.º 24
0
        private void GetSelectedPreviewImageAsync()
        {
            if (SelectedAsset == null)
            {
                return;
            }

            IsLoadingImage = true;
            UserMessage    = "Fetching preview image ...";

            bool isDownloadingImage = false;

            Task t = Task.Factory.StartNew(() =>
            {
                CreateRequiredFolders();

                string pathToThumbnail = Path.Combine(AbsolutePathToThumbnails, SelectedAsset.Asset.IDWithoutExtension);

                if (ImageCache.IsOutOfDate(pathToThumbnail) || ImageCache.IsSourceUrlDifferent(pathToThumbnail, SelectedAsset.Asset.PreviewImage))
                {
                    ImageCache.AddOrUpdate(pathToThumbnail, SelectedAsset.Asset.PreviewImage);
                    Guid downloadGuid = Guid.NewGuid();

                    Action onCancel = () =>
                    {
                        RemoveFromDownloads(downloadGuid);
                    };

                    Action onError = () =>
                    {
                        RemoveFromDownloads(downloadGuid);
                    };

                    Action onComplete = () =>
                    {
                        RemoveFromDownloads(downloadGuid);
                        GetSelectedPreviewImageAsync();
                    };

                    isDownloadingImage  = true;
                    string formattedUrl = "rsmm://Url/" + SelectedAsset.Asset.PreviewImage.Replace("://", "$");
                    DownloadItemViewModel imageDownload = new DownloadItemViewModel()
                    {
                        UniqueId     = downloadGuid,
                        DownloadType = DownloadType.Image,
                        ItemName     = "Downloading preview image",
                        OnCancel     = onCancel,
                        OnComplete   = onComplete,
                        OnError      = onError,
                        DownloadUrl  = formattedUrl,
                        SaveFilePath = pathToThumbnail
                    };

                    AddToDownloads(imageDownload);
                    return;
                }
                else
                {
                    UserMessage = "";
                }

                if (PreviewImageSource != null)
                {
                    PreviewImageSource.Close();
                    PreviewImageSource = null;
                }

                using (FileStream stream = File.Open(pathToThumbnail, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    PreviewImageSource = new MemoryStream();
                    stream.CopyTo(PreviewImageSource);
                }

                PreviewImageSource = new MemoryStream(File.ReadAllBytes(pathToThumbnail));
            });

            t.ContinueWith((taskResult) =>
            {
                if (taskResult.IsFaulted)
                {
                    UserMessage        = "Failed to get preview image.";
                    PreviewImageSource = null;
                    Logger.Error(taskResult.Exception);
                }

                IsLoadingImage = isDownloadingImage;
            });
        }
Ejemplo n.º 25
0
        public Task CheckForCatalogUpdatesAsync(bool clearCache = true)
        {
            object countLock = new object();

            Task t = Task.Factory.StartNew(() =>
            {
                string catFile = AbsolutePathToCatalogSettingsJson;

                Directory.CreateDirectory(AbsolutePathToTempDownloads);

                CatalogSettings currentSettings = new CatalogSettings();

                if (File.Exists(catFile))
                {
                    currentSettings = JsonConvert.DeserializeObject <CatalogSettings>(File.ReadAllText(catFile));
                    currentSettings.CatalogUrls.RemoveAll(s => string.IsNullOrWhiteSpace(s.Url));
                }
                else
                {
                    CatalogSettings.AddDefaults(currentSettings);
                }


                if (currentSettings.CatalogUrls.Count == 0)
                {
                    if (File.Exists(catFile))
                    {
                        File.Delete(catFile);
                    }

                    _catalogCache = new AssetCatalog();
                    ReloadAllAssets();
                    RefreshFilteredAssetList();
                    return;
                }

                if (clearCache)
                {
                    lock (catalogCacheLock)
                    {
                        _catalogCache = new AssetCatalog();
                    }
                }

                foreach (CatalogSubscription sub in currentSettings.CatalogUrls.Where(c => c.IsActive).ToArray())
                {
                    Logger.Info($"Checking catalog {sub.Url}");

                    string uniqueFileName = $"cattemp{Path.GetRandomFileName()}.xml"; // save temp catalog update to unique filename so multiple catalog updates can download async
                    string path           = Path.Combine(AbsolutePathToTempDownloads, uniqueFileName);

                    Guid downloadId = Guid.NewGuid();

                    Action onCancel = () =>
                    {
                        RemoveFromDownloads(downloadId);
                    };

                    Action onError = () =>
                    {
                        RemoveFromDownloads(downloadId);
                    };

                    Action onComplete = () =>
                    {
                        RemoveFromDownloads(downloadId);

                        try
                        {
                            AssetCatalog c = JsonConvert.DeserializeObject <AssetCatalog>(File.ReadAllText(path));

                            lock (catalogCacheLock) // put a lock on the Catalog so multiple threads can only merge one at a time
                            {
                                _catalogCache = AssetCatalog.Merge(_catalogCache, c);
                                File.WriteAllText(AbsolutePathToCatalogJson, JsonConvert.SerializeObject(_catalogCache, Formatting.Indented));
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex);
                        }
                        finally
                        {
                            // delete temp catalog
                            if (File.Exists(path))
                            {
                                File.Delete(path);
                            }

                            ReloadAllAssets();
                            RefreshFilteredAssetList();
                        }
                    };

                    DownloadItemViewModel catalogDownload = new DownloadItemViewModel()
                    {
                        UniqueId     = downloadId,
                        DownloadType = DownloadType.Catalog,
                        ItemName     = $"Checking catalog {sub.Url}",
                        DownloadUrl  = AssetCatalog.FormatUrl(sub.Url),
                        SaveFilePath = path,
                        OnComplete   = onComplete,
                        OnError      = onError,
                        OnCancel     = onCancel
                    };

                    AddToDownloads(catalogDownload);
                }
            });

            return(t);
        }
Ejemplo n.º 26
0
        private void RemoveFromDownloads(Guid downloadID)
        {
            DownloadItemViewModel toRemove = CurrentDownloads.FirstOrDefault(d => d.UniqueId == downloadID);

            RemoveFromDownloads(toRemove);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Main method for downloading and installing the selected asset asynchronously.
        /// </summary>
        public void DownloadSelectedAssetAsync()
        {
            CreateRequiredFolders();

            AssetViewModel assetToDownload = SelectedAsset; // get the selected asset currently in-case user selection changes while download occurs

            string pathToDownload = Path.Combine(AbsolutePathToTempDownloads, assetToDownload.Asset.ID);
            Guid   downloadId     = Guid.NewGuid();

            Action onComplete = () =>
            {
                IsInstallingAsset = true;

                RemoveFromDownloads(downloadId);

                UserMessage = $"Installing asset: {assetToDownload.Name} ... ";
                Task installTask = Task.Factory.StartNew(() =>
                {
                    InstallDownloadedAsset(assetToDownload, pathToDownload);
                });

                installTask.ContinueWith((installResult) =>
                {
                    if (installResult.IsFaulted)
                    {
                        UserMessage = $"Failed to install asset ...";
                        Logger.Error(installResult.Exception);
                        IsInstallingAsset = false;
                        return;
                    }

                    // lastly delete downloaded file
                    if (DeleteDownloadAfterInstall && File.Exists(pathToDownload))
                    {
                        File.Delete(pathToDownload);
                    }

                    IsInstallingAsset = false;

                    RefreshPreviewForSelected();

                    // refresh list if filtering by installed or uninstalled
                    if (SelectedInstallStatus != defaultInstallStatusValue)
                    {
                        RefreshFilteredAssetList();
                    }

                    if (assetToDownload.AssetCategory == AssetCategory.Maps.Value)
                    {
                        HasDownloadedMap = true;
                    }
                });
            };

            Action onError = () =>
            {
                RemoveFromDownloads(downloadId);
                UserMessage = $"Failed to download {assetToDownload.Name}";
            };

            Action onCancel = () =>
            {
                RemoveFromDownloads(downloadId);
                UserMessage = $"Canceled downloading {assetToDownload.Name}";
            };

            DownloadItemViewModel downloadItem = new DownloadItemViewModel()
            {
                UniqueId     = downloadId,
                DownloadType = DownloadType.Asset,
                ItemName     = $"Downloading {assetToDownload.Name}",
                DownloadUrl  = assetToDownload.Asset.DownloadLink,
                SaveFilePath = pathToDownload,
                OnCancel     = onCancel,
                OnComplete   = onComplete,
                OnError      = onError,
            };

            AddToDownloads(downloadItem);
        }
        public void OnDownloadUpdated(IWebBrowser chromiumWebBrowser, IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback)
        {
            DownloadItemViewModel _item = null;

            //初始暂停
            if (string.IsNullOrWhiteSpace(downloadItem.FullPath))
            {
                callback.Pause();
            }
            else//初始化完毕
            {
                //插入记录
                if (!DownloadMap.ContainsKey(downloadItem.Id))
                {
                    _item = new DownloadItemViewModel();
                    _item.customDownloadHandler = this;
                    _item.UpDate(downloadItem);
                    DownloadMap.Add(downloadItem.Id, _item);
                    //Console.WriteLine("----insert {0}", _item.ID);
                }
                else
                {            //获取对应记录
                    _item = DownloadMap[downloadItem.Id];
                }
                //继续开始下载
                if (!_item.IsInitalized)
                {
                    _item.IsInitalized = true;
                    callback.Resume();
                }
            }


            if (_item != null && _item.IsInitalized)
            {
                _item.UpDate(downloadItem);
                //callback管理
                if (callback.IsDisposed)
                {
                    Console.WriteLine("Callback disposed");
                }
                else
                {
                    if (ControlMap.ContainsKey(_item.ID))
                    {
                        ControlMap[_item.ID] = callback;
                    }
                    else
                    {
                        ControlMap.Add(_item.ID, callback);
                    }
                }

                //更新
                OnUpdated?.BeginInvoke(this, _item, (o) =>
                {
                    if (_item.NeedPause)
                    {
                        try { GetControl(_item.ID)?.Pause(); } catch (Exception e) { Console.WriteLine("Cancel Error :{0}", e.Message); }
                        _item.NeedPause = false;
                        _item.IsPaused  = true;
                    }
                    if (_item.NeedCancel)
                    {
                        try { GetControl(_item.ID)?.Cancel(); } catch (Exception e) { Console.WriteLine("Cancel Error :{0}", e.Message); }
                        _item.NeedCancel  = false;
                        _item.IsCancelled = true;
                    }
                    if (_item.NeedResume)
                    {
                        try { GetControl(_item.ID)?.Resume(); } catch (Exception e) { Console.WriteLine("Resume Error :{0}", e.Message); }
                        _item.NeedResume = false;
                        _item.IsPaused   = false;
                    }

                    OnUpdated.Invoke(this, _item);
                }, null);
            }
        }
        private void DownloadFileFromMega(DownloadItemViewModel newDownload, string megaFileId)
        {
            bool wasCanceled = false;

            newDownload.PerformCancel = () =>
            {
                wasCanceled = true;

                try
                {
                    _megaDownloadCancelTokenSource?.Cancel();
                }
                catch (Exception dex)
                {
                    Logger.Error(dex);
                }
                finally
                {
                    _megaDownloadCancelTokenSource?.Dispose();
                    _megaDownloadCancelTokenSource = null;
                }

                newDownload.OnCancel?.Invoke();
            };

            var client = new MegaApiClient();

            client.LoginAnonymousAsync().ContinueWith((loginResult) =>
            {
                if (wasCanceled)
                {
                    return; // don't continue after async login since user already canceled download
                }

                if (loginResult.IsFaulted)
                {
                    newDownload.OnError?.Invoke(loginResult.Exception.GetBaseException());
                    return;
                }


                // get nodes from mega folder
                Uri fileLink   = new Uri($"https://mega.nz/file/{megaFileId}");
                INodeInfo node = client.GetNodeFromLink(fileLink);

                if (wasCanceled)
                {
                    return; // don't continue after async login since user already canceled download
                }

                if (node == null)
                {
                    newDownload.OnError?.Invoke(new Exception($"could not find node from link {fileLink}"));
                    client.LogoutAsync();
                    return;
                }

                if (File.Exists(newDownload.SaveFilePath))
                {
                    File.Delete(newDownload.SaveFilePath); //delete old temp file if it exists (throws exception otherwise)
                }


                IProgress <double> progressHandler = new Progress <double>(x =>
                {
                    double estimatedBytesReceived = (double)node.Size * (x / 100);
                    UpdateDownloadProgress(newDownload, (int)x, (long)estimatedBytesReceived);
                });

                _megaDownloadCancelTokenSource = new CancellationTokenSource();
                Task downloadTask = client.DownloadFileAsync(fileLink, newDownload.SaveFilePath, progressHandler, _megaDownloadCancelTokenSource.Token);

                downloadTask.ContinueWith((downloadResult) =>
                {
                    _megaDownloadCancelTokenSource?.Dispose();
                    _megaDownloadCancelTokenSource = null;
                    client.LogoutAsync();

                    if (downloadResult.IsCanceled)
                    {
                        return;
                    }

                    if (downloadResult.IsFaulted)
                    {
                        newDownload.OnError?.Invoke(downloadResult.Exception.GetBaseException());
                        return;
                    }

                    _wc_DownloadFileCompleted(client, new AsyncCompletedEventArgs(null, false, newDownload));
                });
            });
        }