Example #1
0
 public DownloadProgressObserver(IDownloadable downloadable)
 {
     this.callback   = downloadable.GetCallback();
     this.bundleName = downloadable.GetBundleName();
     this.assetName  = downloadable.GetAssetName();
     this.options    = downloadable.GetParams();
 }
Example #2
0
        /// <summary>
        /// Download a specific version.
        /// </summary>
        /// <param name="v">Version to download.</param>
        public static void DownloadVersion(IDownloadable v)
        {
            if (v is null)
            {
                throw new ArgumentNullException(nameof(v));
            }
            List <IDownloadable> queue = new List <IDownloadable>(new[] { v });

            if (v is VersionGameFiles)
            {
                VersionGameFiles vgf = v as VersionGameFiles;
                if (!Config.DisableAudioDownload && vgf?.MinimumAudioVersion != null && vgf.MinimumAudioVersion.GreaterThan(Config.CurrentVersion))
                {
                    DialogResult result = MessageBox.Show($"New audio version found: {vgf.MinimumAudioVersion}.\nDownload and install this update?\n(Note, audio updates are often large downloads)", "Audio Update Found", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        queue.Add(vgf.MinimumAudioVersion);
                    }
                }
            }

            downloadForm = new DownloadForm(queue);
            downloadForm.Show();
            downloadForm.StartDownload();
        }
        private async Task DeleteAppData(IDownloadable downloadable)
        {
            // Get all the files recursively as our total
            string directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Artemis");

            if (!Directory.Exists(directory))
            {
                downloadable.ReportProgress(0, 0, 100);
                return;
            }

            string source = Assembly.GetEntryAssembly().Location;

            string[] files = Directory.GetFiles(directory, "*", SearchOption.AllDirectories);

            // Delete all files
            await Task.Run(() =>
            {
                int index = 0;
                foreach (string file in files)
                {
                    if (file != source)
                    {
                        File.Delete(file);
                    }

                    index++;
                    downloadable.ReportProgress(index, files.Length, index / (float)files.Length * 100);
                }
            });

            downloadable.ReportProgress(0, 0, 100);
        }
Example #4
0
        /// <summary>
        ///     Get the total download size of all file operations
        /// </summary>
        /// <param name="updatePackageSearchResult">The search result</param>
        /// <returns>Return the total download size of all operations</returns>
        public static long GetTotalSize(this IDownloadable updatePackageSearchResult)
        {
            var result = 0L;

            if (updatePackageSearchResult.Instructions.FileOperations == null)
            {
                foreach (var fileInformation in updatePackageSearchResult.Instructions.TargetFiles)
                {
                    result += fileInformation.Length;
                }
            }
            else
            {
                foreach (var fileOperation in updatePackageSearchResult.Instructions.FileOperations)
                {
                    if (fileOperation is DeltaPatchOperation deltaPatchOperation)
                    {
                        result += deltaPatchOperation.Patches.Sum(x => (long)x.Length);
                    }
                    else if (fileOperation is INeedDownload needDownload)
                    {
                        result += needDownload.Target.Length;
                    }
                }
            }

            return(result);
        }
Example #5
0
        private async static Task <bool> DownloadTrack(IDownloadable download, string fileName, Action <double> progressChangedAction)
        {
            try
            {
                switch (download.DownloadMethod)
                {
                case DownloadMethod.SoundCloud:
                    await SoundCloudDownloader.DownloadSoundCloudTrack(download.DownloadParameter, fileName, progressChangedAction);

                    break;

                case DownloadMethod.youtube_dl:
                    await youtube_dl.Instance.Download(download.DownloadParameter, fileName, progressChangedAction);

                    break;

                default:
                    throw new ArgumentException();
                }
            }
            catch (Exception)
            {
                return(false);
            }
            return(true);
        }
Example #6
0
        private async static Task <bool> DownloadTrack(IDownloadable download, string fileName, Action <double> progressChangedAction)
        {
            try
            {
                switch (download.DownloadMethod)
                {
                case DownloadMethod.AnyListen:
                    if (AnyListenSettings.Instance.Config.UseXunlei)
                    {
                        await XunleiDownloader.DownloadAnyListenTrack(download.DownloadParameter, fileName, progressChangedAction);
                    }
                    else
                    {
                        await AnyListenDownloader.DownloadAnyListenTrack(download.DownloadParameter, fileName, progressChangedAction);
                    }
                    break;

                default:
                    throw new ArgumentException();
                }
            }
            catch (Exception)
            {
                return(false);
            }
            return(true);
        }
Example #7
0
        public async static Task <bool> DownloadAndConfigureTrack(IDownloadable downloadInformation, IMusicInformation musicInformation, string fileName, Action <double> progressChangedAction, DownloadSettings settings)
        {
            if (string.IsNullOrEmpty(CommonHelper.GetLocation(downloadInformation.DownloadParameter)))
            {
                return(false);
            }
            if (!await DownloadTrack(downloadInformation, fileName, progressChangedAction))
            {
                return(false);
            }

            if (settings.IsConverterEnabled)
            {
                var oldFile = new FileInfo(fileName);
                oldFile.MoveTo(GeneralHelper.GetFreeFileName(oldFile.Directory, oldFile.Extension).FullName); //We move the downloaded file to a temp location
                await ffmpeg.ConvertFile(oldFile.FullName, fileName, settings.Bitrate, settings.Format);
            }

            //TagLib# destroys all aac files...
            if (settings.AddTags && settings.Format != AudioFormat.AAC)
            {
                await AddTags(musicInformation, fileName);
            }
            return(true);
        }
        public static async Task DownloadAsync(this HttpClient client, string requestUri, Stream destination,
                                               IDownloadable downloadable = null, CancellationToken cancellationToken = default)
        {
            // Get the http headers first to examine the content length
            using (HttpResponseMessage response = await client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead))
            {
                long?contentLength = response.Content.Headers.ContentLength;

                using (Stream download = await response.Content.ReadAsStreamAsync())
                {
                    // Ignore progress reporting when no progress reporter was
                    // passed or when the content length is unknown
                    if (downloadable == null || !contentLength.HasValue)
                    {
                        await download.CopyToAsync(destination);

                        return;
                    }

                    // Convert absolute progress (bytes downloaded) into relative progress (0% - 100%)
                    Progress <long> relativeProgress = new Progress <long>(
                        totalBytes => downloadable.ReportProgress(totalBytes, contentLength.Value, totalBytes / (float)contentLength.Value * 100f)
                        );
                    // Use extension method to report progress while downloading
                    await download.CopyToAsync(destination, 81920, relativeProgress, cancellationToken);

                    downloadable.ReportProgress(contentLength.Value, contentLength.Value, 100f);
                }
            }
        }
        private bool StreamFile(HttpWebResponse fileresp, IDownloadable download)
        {
            bool succeeded = true;

            using (Stream dlstream = fileresp.GetResponseStream()) {
                FileStream outputStream;
                while (true)
                {
                    try {
                        outputStream = new FileStream(currentFilepath, FileMode.OpenOrCreate, FileAccess.Write);
                        break;
                    } catch (UnauthorizedAccessException e) {
                        DialogResult res = MessageBox.Show(
                            $"Couldn't get access to local file location at {currentFilepath}. Another program might be using it. Would you like to try again?",
                            "Download Error",
                            MessageBoxButtons.RetryCancel,
                            MessageBoxIcon.Error);
                        if (res == DialogResult.Cancel)
                        {
                            throw e;
                        }
                        Thread.Sleep(1000);
                    }
                }

                int buffersize = 10000;
                try {
                    long bytesRead = 0;
                    int  length    = 1;
                    while (length > 0)
                    {
                        byte[] buffer = new byte[buffersize];
                        length     = dlstream.Read(buffer, 0, buffersize);
                        bytesRead += length;
                        outputStream.Write(buffer, 0, length);
                        UpdateProgress(Convert.ToInt32(100F * bytesRead / fileresp.ContentLength));
                        UpdateProgressText(
                            $"Downloading {download} (Package {downloadQueue.IndexOf(download) + 1}/{downloadQueue.Count}) {bytesRead / 1048576}/{fileresp.ContentLength / 1048576} MB ({Convert.ToInt16(100 * (double)bytesRead / fileresp.ContentLength, Program.Culture)}%)...");
                    }
                } catch (WebException e) {
                    succeeded = false;
                    DialogResult res = MessageBox.Show(
                        "An error has occurred during your download. Please check your network connection and try again.\n" +
                        "If this error persists, please report this issue to the launcher's GitHub page. Click OK to copy the error details to your clipboard or CANCEL to ignore this message.",
                        "Download Error",
                        MessageBoxButtons.OKCancel,
                        MessageBoxIcon.Error);
                    if (res == DialogResult.OK)
                    {
                        Clipboard.SetText(e.ToString());
                    }
                    Aborted?.Invoke(this, new EventArgs());
                    CloseForm();
                } finally {
                    outputStream.Dispose();
                }
            }

            return(succeeded);
        }
Example #10
0
 public Task <bool> StartDownloadingAsync(IDownloadable item)
 {
     return(StartDownloadingAsync(new List <IDownloadable>(1)
     {
         item
     }));
 }
Example #11
0
        public static async void DownloadAsync(IDownloadable download, IDiskStorageProvider storage, string path, string fileName)
        {
            if (download == null || download.Uri == null)
            {
                throw new ArgumentNullException(nameof(download));
            }

            if (storage == null)
            {
                throw new ArgumentNullException(nameof(storage));
            }

            try
            {
                Stream stream = await DownloadAsync(download);

                storage.Put(path, fileName, stream);
            }
            catch (Exception e)
            {
                download.Status    = DownloadStatus.Failed;
                download.Exception = e;
                throw e;
            }
        }
        /// <summary>
        /// Checks if the blockhash is correctly computed
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool VerifyHash(this IDownloadable obj)
        {
            string oldHash = obj.Hash;

            obj.GenerateHash();

            return(oldHash.Equals(obj.Hash));
        }
 public DownloadSearchViewModel(INovaromaEngine engine, IExceptionHandler exceptionHandler, IDialogService dialogService, IDownloadable downloadable, string directory)
     : base(dialogService) {
     _engine = engine;
     _exceptionHandler = exceptionHandler;
     _downloadable = downloadable;
     _directory = directory;
     _searchCommand = new RelayCommand(DoSearch, CanSearch);
 }
Example #14
0
 public virtual void Download(IDownloadable format, string filename, bool overwrite = true)
 {
     if (File.Exists(filename) && overwrite == false)
     {
         return;
     }
     startTime = DateTime.Now;
 }
Example #15
0
        private IDownloadable CreateDownload()
        {
            IDownloadable download = A.Fake <IDownloadable>();

            download.Exception = null;
            A.CallTo(() => download.Uri).Returns(_sampleUri);
            return(download);
        }
 /// <inheritdoc/>
 public bool GreaterThan(IDownloadable other)
 {
     if (other == null)
     {
         return(true);
     }
     return(Number > other.Number);
 }
Example #17
0
 public void Init(IDownloadable downloadable, DownloadProgressObserver observer)
 {
     this.fileName        = downloadable.GetBundleName();
     this.serverUrl       = downloadable.GetServerUrl();
     this.observer        = observer;
     this.loadOnComplete  = downloadable.IsLoadOnComplete();
     this.downloadVersion = downloadable.GetVersion();
     this.priority        = downloadable.GetPriority();
 }
Example #18
0
        public static void Download(IDownloadable dlObj, string fileName)
        {
            IEnumerable <DownloadTask> tasks = dlObj.GetDownloadTasks(fileName);

            foreach (var task in tasks)
            {
                Download(task);
            }
        }
 public DownloadSearchViewModel(INovaromaEngine engine, IExceptionHandler exceptionHandler, IDialogService dialogService, IDownloadable downloadable, string directory)
     : base(dialogService)
 {
     _engine           = engine;
     _exceptionHandler = exceptionHandler;
     _downloadable     = downloadable;
     _directory        = directory;
     _searchCommand    = new RelayCommand(DoSearch, CanSearch);
 }
Example #20
0
 /// <summary>
 /// Возвращает файл, в который будет выполняться загрузка.
 /// </summary>
 /// <param name="item">Элемент, для которого требуется создать файл.</param>
 /// <param name="folder">Папка, в которой требуется создать файл.</param>
 private static async Task <StorageFile> GetFileForDownload(IDownloadable item, StorageFolder folder)
 {
     try
     {
         return(await folder.CreateFileAsync(GetSafeFileName(item.FileName) + item.Extension,
                                             CreationCollisionOption.GenerateUniqueName));
     }
     catch (Exception) { return(null); }
 }
        public ExhibitRouteDownloadPageViewModel(IDownloadable downloadable, IDownloadableListItemViewModel downloadableListItemViewModel)
        {
            Downloadable = downloadable;
            this.downloadableListItemViewModel = downloadableListItemViewModel;
            SetImage();

            StartDownload = new Command(DownloadData);
            CancelCommand = new Command(CancelDownload);
        }
Example #22
0
 public virtual Task DownloadAsync(IDownloadable format, string filename, bool overwrite = true)
 {
     if (File.Exists(filename) && overwrite == false)
     {
         return(Task.CompletedTask);
     }
     startTime = DateTime.Now;
     return(Task.CompletedTask);
 }
        private bool PatchDownload(IDownloadable download, string destination)
        {
            try {
                if (download is VersionGameFiles)
                {
                    VersionGameFiles vgf = download as VersionGameFiles;
                    if (vgf.IsPatch)
                    {
                        UpdateProgressText("Patching...");
                        string versionpath = Path.Combine(Config.InstallPath, "Versions", download.Prerequisite.ToString());
                        RecursiveCopy(versionpath, destination, false);
                    }
                }
                else if (download is VersionAudio)
                {
                    VersionAudio va          = download as VersionAudio;
                    string       versionpath = Path.Combine(Config.InstallPath, "Versions", mostRecent.ToString());
                    RecursiveCopy(destination, versionpath, true);
                }
            } catch (DirectoryNotFoundException) {
                MessageBox.Show(
                    $"Could not find download{Environment.NewLine}{destination}{Environment.NewLine}The file appears to be missing. It may have been quarantined by your antivirus software. Please check your antivirus settings and retry. If the issue persists, please report this error.",
                    "Apex Launcher Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Warning);
                return(false);
            }

            if (download == mostRecent && !(download is VersionAudio))
            {
                bool downloadingNewAudio = false;
                foreach (IDownloadable d in downloadQueue)
                {
                    if (d is VersionAudio)
                    {
                        downloadingNewAudio = true;
                        break;
                    }
                }

                if (!downloadingNewAudio)
                {
                    string versionpath      = Path.Combine(Config.InstallPath, "Versions", mostRecent.ToString());
                    string audioversionpath = Path.Combine(Config.InstallPath, "Versions", VersionAudio.GetMostRecentVersion().ToString());
                    RecursiveCopy(audioversionpath, versionpath, true);
                }
            }

            try {
                File.Delete(currentFilepath);
            } catch (IOException e) {
                MessageBox.Show($"Error encountered when trying to delete {currentFilepath} after patching. You may need to delete the file manually, but the program should otherwise work correctly. Details:{Environment.NewLine}{e.Message}");
            }

            return(true);
        }
Example #24
0
        public virtual async Task DownloadAsync(IDownloadable file, IProgress <ProgressInfo> progress)
        {
            cancellationSource = new CancellationTokenSource();

            await downloader
            .DownloadFileAsync(file.DownloadUri, file.FullPath, progress, cancellationSource.Token)
            .ConfigureAwait(false);

            cancellationSource.Dispose();
        }
Example #25
0
        public void LoadBundle(IDownloadable downloadable)
        {
            DownloadProgressObserver downloadProgressObserver = new DownloadProgressObserver(downloadable);
            //Create download Request
            DownloadRequest req = new DownloadRequest();

            //Instantiate req manager
            req.Init(downloadable, downloadProgressObserver);
            //Schedule download
            downloadRequestManager.EnqueueDownload(req);
        }
Example #26
0
        public static string GetExtension(IDownloadable track)
        {
            switch (track.DownloadMethod)
            {
            case DownloadMethod.AnyListen:
                return(CommonHelper.GetFormat(track.DownloadParameter));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Example #27
0
 public void Execute(IDownloadable parameter)
 {
     if (parameter != null && Directory.Exists(parameter.GetAbsoulteFolderPath()))
     {
         Process.Start(parameter.GetAbsoulteFolderPath());
     }
     else
     {
         Log.Info(Strings.Library_Status_FolderNotFound);
     }
 }
Example #28
0
 public void Execute(IDownloadable parameter)
 {
     if (parameter != null && Directory.Exists(parameter.GetAbsoluteFolderPath()))
     {
         Helper.StartUseShell(parameter.GetAbsoluteFolderPath());
     }
     else
     {
         Log.Info(string.Format(Strings.Library_Status_FolderNotFound, parameter?.Folder));
     }
 }
 public SubtitleSearchViewModel(INovaromaEngine engine, IExceptionHandler exceptionHandler, IDialogService dialogService, IDownloadable downloadable, FileInfo fileInfo)
     : base(dialogService) {
     _engine = engine;
     _exceptionHandler = exceptionHandler;
     _downloadable = downloadable;
     _fileInfo = fileInfo;
     _subtitleLanguages = new MultiCheckSelection<EnumInfo<Language>>(Constants.LanguagesEnumInfo);
     foreach (var subtitleLanguage in engine.SubtitleLanguages)
         _subtitleLanguages.Selections.First(s => s.Item.Item == subtitleLanguage).IsSelected = true;
     _searchCommand = new RelayCommand(DoSearch, CanSearch);
 }
Example #30
0
 public void Execute(IDownloadable parameter)
 {
     if (parameter != null && Directory.Exists(parameter.GetAbsoulteFolderPath()))
     {
         Process.Start(parameter.GetAbsoulteFolderPath());
     }
     else
     {
         Log.Info("Папка не найдена.");
     }
 }
Example #31
0
 public static void SetDownloadProperties(string downloadKey, IDownloadable downloadable)
 {
     if (!string.IsNullOrEmpty(downloadKey))
     {
         downloadable.BackgroundDownload = false;
         downloadable.DownloadKey        = downloadKey;
         downloadable.NotFound           = false;
     }
     else
     {
         downloadable.NotFound = true;
     }
 }
Example #32
0
        public override async Task DownloadAsync(IDownloadable format, string filename, bool overwrite = true)
        {
            await base.DownloadAsync(format, filename, overwrite);

            if (MultiThreadDownload)
            {
                await MultiThreadedDownload(format, filename).ConfigureAwait(false);
            }
            else
            {
                await SingleThreadedDownload(format, filename).ConfigureAwait(false);
            }
        }
        private void MkvPackage(IDownloadable media)
        {
            const string mergedString = "[merged]";

            var directory = Path.GetDirectoryName(media.FilePath);
            if (string.IsNullOrEmpty(directory)) return;

            var mediaFileNameWithoutExtension = Path.GetFileNameWithoutExtension(media.FilePath);
            if (!mediaFileNameWithoutExtension.Contains(mergedString)) mediaFileNameWithoutExtension += mergedString;
            var outputPath = Path.Combine(directory, mediaFileNameWithoutExtension + ".mkv");

            if (string.IsNullOrEmpty(media.FilePath) || !File.Exists(media.FilePath)) return;

            var mediafileName = Path.GetFileName(media.FilePath);
            if (string.IsNullOrEmpty(mediafileName)) return;

            var tempPath = Path.Combine(Path.GetTempPath(), "Novaroma Mkv Packager");
            if (!File.Exists(tempPath)) Directory.CreateDirectory(tempPath);

            var subtitleFilePath = Directory.GetFiles(directory).FirstOrDefault(Helper.IsSubtitleFile);
            if (string.IsNullOrEmpty(subtitleFilePath)) return;
            var subtitleFileName = Path.GetFileName(subtitleFilePath);

            new FileInfo(media.FilePath).MoveTo(Path.Combine(tempPath, mediafileName));
            new FileInfo(subtitleFilePath).MoveTo(Path.Combine(tempPath, subtitleFileName));

            var mediaFilePathNew = Path.Combine(tempPath, mediafileName);
            var subtitleFilePathNew = Path.Combine(tempPath, subtitleFileName);

            MkvMerge(mediaFilePathNew, subtitleFilePathNew, outputPath);

            media.FilePath = outputPath;
            media.BackgroundDownload = false;
            media.SubtitleDownloaded = false;

            File.Delete(mediaFilePathNew);
            File.Delete(subtitleFilePathNew);
        }
Example #34
0
        private static Task ManualDownload(INovaromaEngine engine, IExceptionHandler exceptionHandler, IDialogService dialogService, IDownloadable downloadable,
                                           string searchQuery, VideoQuality videoQuality, string excludeKeywords, int? minSize, int? maxSize, string directory) {
            var viewModel = new DownloadSearchViewModel(engine, exceptionHandler, dialogService, downloadable, directory);
            var window = new DownloadSearchWindow(viewModel);

            var t = viewModel.InitSearch(searchQuery, videoQuality, excludeKeywords, minSize, maxSize);
            window.ForceShow();
            return t;
        }
Example #35
0
 public string GetExtension(IDownloadable track)
 {
     return GetExtension(DownloadManager.GetExtension(track));
 }
Example #36
0
 public static Task ManualSubtitleDownload(INovaromaEngine engine, IExceptionHandler exceptionHandler, IDialogService dialogService, IDownloadable downloadable) {
     return ManualSubtitleDownload(engine, exceptionHandler, dialogService, new FileInfo(downloadable.FilePath), downloadable);
 }
Example #37
0
        private static Task ManualSubtitleDownload(INovaromaEngine engine, IExceptionHandler exceptionHandler, IDialogService dialogService, FileInfo fileInfo, IDownloadable downloadable) {
            var searchQuery = downloadable != null ? downloadable.GetSearchQuery() : fileInfo.NameWithoutExtension();

            var viewModel = new SubtitleSearchViewModel(engine, exceptionHandler, dialogService, downloadable, fileInfo);
            var window = new SubtitleSearchWindow(viewModel);

            var t = viewModel.InitSearch(searchQuery);
            window.ForceShow();
            return t;
        }