/// <summary>
        /// This method downloads the package represented by the PackageDownloadHandle,
        ///
        /// </summary>
        /// <param name="packageDownloadHandle">package download handle</param>
        internal virtual Task <(PackageDownloadHandle handle, string downloadPath)> Download(PackageDownloadHandle packageDownloadHandle)
        {
            // We only want to display the last 3 downloaded packages to the user
            // in the form of toast notifications.

            // We remove all but the last 2 packages and add the most recently-downloaded package
            if (Downloads.Count > 2)
            {
                Downloads.RemoveRange(index: 0, count: Downloads.Count - 2);
            }
            Downloads.Add(packageDownloadHandle);

            packageDownloadHandle.DownloadState = PackageDownloadHandle.State.Downloading;

            return(Task.Factory.StartNew(() =>
            {
                // Attempt to download package
                string pathDl;
                var res = Model.DownloadPackage(packageDownloadHandle.Id, packageDownloadHandle.VersionName, out pathDl);

                // if you fail, update download handle and return
                if (!res.Success)
                {
                    packageDownloadHandle.Error(res.Error);
                    pathDl = string.Empty;
                }

                return (handle: packageDownloadHandle, downloadPath: pathDl);
            }));
        }
Example #2
0
        private void DownloadSort(TransferObjectModel transferObject)
        {
            if (Downloads.Contains(transferObject))
            {
                if (!Downloads.Remove(transferObject))
                {
                    return;
                }
            }

            var inserted = false;

            for (var i = 0; i <= Downloads.Count - 1; i++)
            {
                if ((int)transferObject.Status <= (int)Downloads[i].Status)
                {
                    Downloads.Insert(i, transferObject);
                    inserted = true;
                    break;
                }
            }

            if (!inserted)
            {
                Downloads.Add(transferObject);
            }
        }
Example #3
0
        private async Task LoadDownloads()
        {
            Downloads.Clear();
            DownloadsState = ContentState.Loading;

            while (_downloadsService.IsLoading)
            {
                await Task.Delay(1000);
            }

            var downloads = _downloadsService.GetAllDownloads();

            if (downloads == null)
            {
                DownloadsState = ContentState.NoData;
                return;
            }

            for (int i = 0; i < downloads.Length; i++)
            {
                Downloads.Add(new TransferItemViewModel(downloads[i], _locService));
            }

            DownloadsState = ContentState.Normal;
        }
Example #4
0
 /// <summary>
 /// ダウンロード待ちリストに追加します。
 /// </summary>
 /// <param name="v">追加するデータ</param>
 public void AddDownload(VideoModel v)
 {
     if (!Downloads.Any(d => d.VideoId == v.VideoId))
     {
         Downloads.Add(v);
     }
 }
Example #5
0
        public void RefreshDownloads()
        {
            var downloads = DownloadManager.GetDownloads();

            foreach (var download in downloads)
            {
                var existingDownload = Downloads.FirstOrDefault(d => d.Id == download.Id);

                if (existingDownload != null)
                {
                    existingDownload.UpdateValues(download);
                }
                else
                {
                    Downloads.Add(new DownloadViewModel(download));
                }
            }

            var nonExistantDownloads = new List <DownloadViewModel>();

            foreach (var nonExistantDownload in Downloads.Where(d => !downloads.Any(existinDownload => existinDownload.Id == d.Id)))
            {
                nonExistantDownloads.Add(nonExistantDownload);
            }

            foreach (var toRemove in nonExistantDownloads)
            {
                Downloads.Remove(toRemove);
            }
        }
Example #6
0
 public void AddDownload(Download download)
 {
     lock (Downloads)
     {
         Downloads.Add(download);
         Refresh();
     }
 }
Example #7
0
        internal void AddToDownloadFolder(Image image)
        {
            Downloads.Read();
            Entity en = new Entity(image, ActiveFolder);

            Downloads.Add(en);
            Downloads.Save();
        }
Example #8
0
        protected override async Task LoadExistingDownloads()
        {
            IReadOnlyList <DownloadOperation> oldDownloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

            foreach (var d in oldDownloads)
            {
                Downloads.Add(await Models.DownloadItem.Create(d));
            }
        }
Example #9
0
 public void Add(string filepath, string url, int no)
 {
     Downloads.Add(new DownloadItemViewModel(_downloadService)
     {
         FilePath = filepath,
         Url      = url,
         No       = no
     });
 }
Example #10
0
        public bool AddDownload(Download download)
        {
            if (download == null)
            {
                return(true);
            }

            foreach (Download dl in Downloads)
            {
                if (dl.Url == download.Url)
                {
                    return(false);
                }
            }

            if (download.Status == DownloadStatus.Downloading || download.Status == DownloadStatus.Processing)
            {
                download.Status = preferencesManager.Preferences.ResumeDownloads ? DownloadStatus.Queued : DownloadStatus.Stopped;
            }

            download.PropertyChanged += Download_PropertyChanged;

            download.Index = Downloads.Count + 1;

            Downloads.Add(download);

            // Get the video title, but dont download the video yet, even if the download is 'Waiting' or 'Stopped'
            if (preferencesManager.Preferences.FetchTitle && download.Title == null)
            {
                YdlArguments args = new YdlArguments();
                args.General.IgnoreConfig      = true;
                args.General.FlatPlaylist      = true;
                args.VideoSelection.NoPlaylist = true;
                args.Verbosity.Simulate        = true;
                args.Verbosity.GetTitle        = true;

                args.Url = download.Url;

                string            strArgs      = Download.ArgumentSerializer.Serialize(args, true);
                ExecutableProcess titleProcess = new ExecutableProcess(YdlPath, strArgs, download.DownloadDirectory);

                titleProcess.OnReceived += (sender, data) => {
                    if (download.Title == null && !string.IsNullOrWhiteSpace(data?.Trim()))
                    {
                        download.Title = data.Trim();
                    }
                };
#if DEBUG
                titleProcess.OnExited += (sender, code) => Logger.Instance.Debug(nameof(DownloadManager), $"Title process has exited: {code}");
#endif
                titleProcess.Start();
            }

            FirePropertyChanged(nameof(TotalDownloads));
            return(true);
        }
 /// <summary>
 /// Потокобезопасная функция добавления в список загрузок
 /// </summary>
 /// <param name="downloadInfo">обьект описания загрузки</param>
 /// <returns></returns>
 private static int AddToDownloads(DownloadInfo downloadInfo)
 {
     lock (DownloadLocker)
     {
         Downloads.Add(downloadInfo);
         var id = Downloads.Count - 1;
         downloadInfo.Id = id;
         DownloadItemCollectionUpdated?.Invoke(downloadInfo);
         return(id);
     }
 }
Example #12
0
        public async Task AddDownload(DownloadDefinition downloadDefinition)
        {
            DownloadItem download = new DownloadItem(downloadDefinition, _appContext);

            Downloads.Add(download);
            await download.Start();

            await PersistDownloads();

            download.StatusChanged += downloadItem_StatusChanged;
        }
        public void AddDownload(string nxmLink)
        {
            Log.Information($@"Queueing nxmlink {nxmLink}");
            var dl = new ModDownload(nxmLink);

            dl.OnInitialized      += ModInitialized;
            dl.OnModDownloaded    += ModDownloaded;
            dl.OnModDownloadError += DownloadError;

            Downloads.Add(dl);
            dl.Initialize();
        }
Example #14
0
        public async Task StartDownload(string url)
        {
            IDownloadItem item = await downloadItemFactory(url);

            Downloads.Add(item);
            await item.Start();

            if (Downloads.Count > 0)
            {
                IsCancelAllEnabled = true;
            }
        }
Example #15
0
        /// <summary>
        /// This method downloads the package represented by the PackageDownloadHandle,
        /// uninstalls its current installation if necessary, and installs the package.
        ///
        /// Note that, if the package is already installed, it must be uninstallable
        /// </summary>
        /// <param name="packageDownloadHandle">package download handle</param>
        /// <param name="downloadPath">package download path</param>
        internal void DownloadAndInstall(PackageDownloadHandle packageDownloadHandle, string downloadPath)
        {
            Downloads.Add(packageDownloadHandle);

            packageDownloadHandle.DownloadState = PackageDownloadHandle.State.Downloading;

            Task.Factory.StartNew(() =>
            {
                // Attempt to download package
                string pathDl;
                var res = Model.DownloadPackage(packageDownloadHandle.Id, packageDownloadHandle.VersionName, out pathDl);

                // if you fail, update download handle and return
                if (!res.Success)
                {
                    packageDownloadHandle.Error(res.Error);
                    return;
                }

                // if success, proceed to install the package
                DynamoViewModel.UIDispatcher.BeginInvoke((Action)(() =>
                {
                    try
                    {
                        packageDownloadHandle.Done(pathDl);
                        var pmExtension = DynamoViewModel.Model.GetPackageManagerExtension();
                        var firstOrDefault = pmExtension.PackageLoader.LocalPackages.FirstOrDefault(pkg => pkg.ID == packageDownloadHandle.Id);
                        if (firstOrDefault != null)
                        {
                            var dynModel = DynamoViewModel.Model;
                            try
                            {
                                firstOrDefault.UninstallCore(dynModel.CustomNodeManager, pmExtension.PackageLoader, dynModel.PreferenceSettings);
                            }
                            catch
                            {
                                MessageBox.Show(String.Format(Resources.MessageFailToUninstallPackage,
                                                              DynamoViewModel.BrandingResourceProvider.ProductName,
                                                              packageDownloadHandle.Name),
                                                Resources.UninstallFailureMessageBoxTitle,
                                                MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                        }
                        SetPackageState(packageDownloadHandle, downloadPath);
                    }
                    catch (Exception e)
                    {
                        packageDownloadHandle.Error(e.Message);
                    }
                }));
            });
        }
Example #16
0
        public void Download(IChapterRecord chapter, string outputPath, IDownloadFormatProvider formatProvider)
        {
            var downloadViewModel = new DownloadViewModel(new DownloadedChapterInfo(chapter), _downloadsSemaphore);

            downloadViewModel.RemoveFromCollection += DownloadViewModel_RemoveFromCollection;
            downloadViewModel.DownloadStarted      += DownloadViewModel_DownloadStarted;

            Downloads.Add(downloadViewModel);

            downloadViewModel.DownloadChapter(outputPath, formatProvider);

            OnPropertyChanged(() => HasActiveDownloads);
        }
Example #17
0
 public void UpdateDownloads()
 {
     foreach (IUpdate bundle in Entry.BundledUpdates)
     {
         foreach (IUpdateDownloadContent udc in bundle.DownloadContents)
         {
             if (String.IsNullOrEmpty(udc.DownloadUrl))
             {
                 continue; // sanity check
             }
             Downloads.Add(udc.DownloadUrl);
         }
     }
 }
Example #18
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();
        }
Example #19
0
        private async void OnDownloadProgressChanged(object sender, TransferItem e)
        {
            await _dispatcherWrapper.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                if (DownloadsState == ContentState.Loading)
                {
                    return;
                }

                DownloadsState = ContentState.Normal;
                var item       = Downloads.FirstOrDefault(d => d.OperationGuid == e.OperationGuid);
                if (item == null)
                {
                    if (e.Status != BackgroundTransferStatus.Completed &&
                        e.Status != BackgroundTransferStatus.Canceled)
                    {
                        return;
                    }

                    Downloads.Add(new TransferItemViewModel(e, _locService));
                    item = Downloads.FirstOrDefault(d => d.OperationGuid == e.OperationGuid);
                    if (item == null)
                    {
                        return;
                    }
                }
                else
                {
                    item.Operation = e;
                }

                if (item.Status == BackgroundTransferStatus.Completed ||
                    item.Status == BackgroundTransferStatus.Canceled)
                {
                    Downloads.Remove(item);
                }

                if (Downloads.Count == 0)
                {
                    DownloadsState = ContentState.NoData;
                }
                else
                {
                    Downloads.OrderBy(d => d.Status, new TransferStatusComparer());
                }

                CancelAllDownloadsCommand.RaiseCanExecuteChanged();
            });
        }
Example #20
0
 private void AddUpdates(IUpdateDownloadContentCollection content)
 {
     foreach (IUpdateDownloadContent2 udc in content)
     {
         if (udc.IsDeltaCompressedContent)
         {
             continue;
         }
         if (String.IsNullOrEmpty(udc.DownloadUrl))
         {
             continue; // sanity check
         }
         Downloads.Add(udc.DownloadUrl);
     }
 }
Example #21
0
        public static void AddDownload(Download dl)
        {
            dl.DownloadStatusChanged += Dl_DownloadStatusChanged;
            Downloads.Add(dl);

            if (Downloads.Where(x => x.Status == DownloadStatus.Downloading).Count() < MaxParallelDownloads)
            {
                dl.Start();
                Trace.TraceInformation("Starting download '{0}'.", dl.Title);
            }
            else
            {
                Trace.TraceInformation("Putting '{0}' into queue.", dl.Title);
            }
        }
        public async Task AddDownload(Uri from, string As, string At, string installAt, string modN,
                                      string modFileN, Mod m)
        {
            Download            newDl   = new Download(from, As, At, installAt, modN, modFileN);
            ModDownload_Control control = new ModDownload_Control(ViewControl, newDl, AddToGUI, m);

            newDl.AssociatedDownloadControl = control;

            Downloads.Add(newDl);
            DownloadControls.Add(control);
            await ViewControl.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() =>
            {
                ViewControl.Items.Refresh();
                newDl.Start();
            }));
        }
Example #23
0
        private void DownloadCommandExecute()
        {
            var item = new DownloadItem(
                DownloadUri.Value,
                Path.GetRandomFileName()
                );

            Downloads.Add(item);
            try {
                item.StartDownload();
            } catch (Exception ex) {
                _dialogService.Error($"Error: {ex.Message}", "Download error");
                Downloads.Remove(item);
            }

            DownloadUri.Value = null;
        }
Example #24
0
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            var downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

            foreach (var item in downloads)
            {
                var download = new WtDownloadOperation
                {
                    Name              = item.ResultFile.Name,
                    Extension         = item.ResultFile.FileType,
                    DownloadOperation = item
                };
                Downloads.Add(download);
                await download.DownloadOperation
                .AttachAsync()
                .AsTask(CancellationToken.None, new Progress <DownloadOperation>(ProgressChanged));
            }
        }
Example #25
0
        public GraphSetup Add <T>() where T : GraphItem
        {
            async Task <List <GraphItem> > Download()
            {
                var query       = new ReadAllQuery <T>();
                var batchQuery  = new OrientQueryBatch(Connection, query.Query);
                var batch       = new Batch <List <T> >(batchQuery, Client);
                var batchResult = await batch.Execute();

                var result = batchResult switch
                {
                    Result <List <T>, Exception> .OkCase ok => ok.Payload,
                    Result <List <T>, Exception> .ErrCase err => throw err.Payload,
                          _ => throw new InvalidOperationException()
                };

                return(result.Cast <GraphItem>().ToList());
            }

            Downloads.Add(typeof(T), Download());
            return(this);
        }
Example #26
0
        public async void AddDownload()
        {
            var validFileName = await _urlService.GetValideDownloadFile(Url);

            if (validFileName == null)
            {
                _show.Message(Ressources.DownloaderViewModel.WrongURL);
                return;
            }

            var download = Download.NewDownload(_selectFile.ShowSaveFileDialog(Path.GetFileName(validFileName)), Url);

            if (download == null)
            {
                _show.Message(Ressources.DownloaderViewModel.ErrorCreateDownload);
                return;
            }
            var neu = new DownloadViewModel(download, _createEngine.For(SelectedEngine));

            AreDownloadListShow      = true;
            AreDownloadStartpossible = true;
            Downloads.Add(neu);
        }
Example #27
0
        /// <summary>
        /// Download button click event
        /// </summary>
        public async void Start()
        {
            if (!Directory.Exists(OutputPath))
            {
                OutputPath = "Not a valid directory!";
                return;
            }

            CanLoad = false;
            ProgressCircleVisibility = Visibility.Visible;
            List <string> urls;

            try
            {
                urls = await scraper.ScrapeForBzip2(SelectedValue.FastDlUrl);
            }
            catch (Exception e)
            {
                OutputPath = e.Message;
                return;
            }

            foreach (string url in urls)
            {
                if (File.Exists($@"{OutputPath}\{Path.GetFileNameWithoutExtension(url)}"))
                {
                    continue;
                }

                Downloads.Add(new FileDownload($"{SelectedValue.FastDlUrl}/{url}", $@"{OutputPath}\"));
            }

            ProgressCircleVisibility = Visibility.Collapsed;

            CanDownload = true;
        }
Example #28
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;
            }
        }
Example #29
0
        /// <summary>
        /// Callback method called when the "Download" method returns from an HTTPWebRequest.
        /// </summary>
        /// <param name="result">The result of the asynchronous operation.</param>
        private void ResponseCallback(IAsyncResult result)
        {
            RequestState state = (RequestState)result.AsyncState;

            try
            {
                HttpWebRequest request = state.Request as HttpWebRequest;
                if (null != request)
                {
                    // Retrieve response.
                    using (HttpWebResponse response = request.EndGetResponse(result) as HttpWebResponse)
                    {
                        if (null != response && response.StatusCode == HttpStatusCode.OK)
                        {
                            using (XmlReader reader = XmlReader.Create(response.GetResponseStream()))
                            {
                                Feed parentFeed = state.Argument as Feed;

                                if (null != parentFeed)
                                {
                                    // Collection to store all articles
                                    Collection <Article> parsedArticles = _parser.ParseItems(reader, parentFeed);

                                    // Raise event for a single feed downloaded.
                                    if (null != SingleDownloadFinished)
                                    {
                                        SingleDownloadFinished(this, new SingleDownloadFinishedEventArgs(parentFeed, parsedArticles));
                                    }

                                    // Add to all downloads dictionary and raise AllDownloadsFinished if all async requests have finished.
                                    Downloads.Add(parentFeed, parsedArticles);

                                    lock (_lockObject)
                                    {
                                        IsDownloading = ((--_numOfRequests) > 0);
                                    }
                                    if (_numOfRequests <= 0 && null != AllDownloadsFinished)
                                    {
                                        AllDownloadsFinished(this, new AllDownloadsFinishedEventArgs(Downloads));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (WebException we)
            {
                if (null != DownloadFailed)
                {
                    DownloadFailed(this, new DownloadFailedEventArgs(we)
                    {
                        BadConnectionException = true
                    });
                }
                return;
            }
            catch (XmlException e)
            {
                if (null != DownloadFailed)
                {
                    DownloadFailed(this, new DownloadFailedEventArgs(e));
                }
                return;
            }
        }
        private void CheckSteamForNewMods()
        {
            status_toolstrip_label.Text = "Checking for new mods...";

            ulong[] subscribedIDs;
            try
            {
                subscribedIDs = Workshop.GetSubscribedItems();
            }
            catch (InvalidOperationException)
            {
                // Steamworks not initialized?
                // Game taking over?
                status_toolstrip_label.Text = "Error checking for new mods.";
                return;
            }

            var change = false;

            foreach (var id in subscribedIDs)
            {
                var status = Workshop.GetDownloadStatus(id);

                if (status.HasFlag(EItemState.k_EItemStateInstalled))
                {
                    // already installed
                    continue;
                }

                if (Downloads.Any(d => d.WorkshopID == (long)id))
                {
                    // already observing
                    continue;
                }

                // Get info
                var detailsRequest = new ItemDetailsRequest(id).Send().WaitForResult();
                var details        = detailsRequest.Result;
                var link           = detailsRequest.GetPreviewURL();

                var downloadMod = new ModEntry
                {
                    Name        = details.m_rgchTitle,
                    DateCreated = DateTimeOffset.FromUnixTimeSeconds(details.m_rtimeCreated).DateTime,
                    DateUpdated = DateTimeOffset.FromUnixTimeSeconds(details.m_rtimeUpdated).DateTime,
                    Path        = Path.Combine(Settings.GetWorkshopPath(), "" + id),
                    Image       = link,
                    Source      = ModSource.SteamWorkshop,
                    WorkshopID  = (int)id,
                    State       = ModState.New | ModState.NotInstalled
                };

                // Start download
                Workshop.DownloadItem(id);
                //
                Downloads.Add(downloadMod);
                change = true;
            }

            if (change)
            {
                RefreshModList();
            }

            status_toolstrip_label.Text = StatusBarIdleString;
        }