Esempio n. 1
0
        /// <summary>
        /// Download actors' image for a movie
        /// </summary>
        /// <param name="movie">The movie to process</param>
        public async Task DownloadActorImageAsync(MovieFull movie)
        {
            var watch = Stopwatch.StartNew();

            if (movie.Actors == null)
            {
                return;
            }

            await
            movie.Actors.ForEachAsync(
                actor =>
                DownloadFileHelper.DownloadFileTaskAsync(actor.SmallImage,
                                                         Constants.ActorMovieDirectory + actor.Name + Constants.ImageFileExtension),
                (actor, t) =>
            {
                if (t.Item3 == null && !string.IsNullOrEmpty(t.Item2))
                {
                    actor.SmallImagePath = t.Item2;
                }
            });

            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            Logger.Debug(
                $"DownloadActorImageAsync ({movie.ImdbCode}) in {elapsedMs} milliseconds.");
        }
Esempio n. 2
0
        /// <summary>
        /// Download the movie's poster image
        /// </summary>
        /// <param name="movie">The movie to process</param>
        public async Task DownloadPosterImageAsync(MovieFull movie)
        {
            var watch = Stopwatch.StartNew();

            if (movie.Images == null)
            {
                return;
            }

            var posterPath = new List <string>
            {
                movie.Images.LargeCoverImage
            };

            await
            posterPath.ForEachAsync(
                poster =>
                DownloadFileHelper.DownloadFileTaskAsync(poster,
                                                         Constants.PosterMovieDirectory + movie.ImdbCode + Constants.ImageFileExtension),
                (poster, t) =>
            {
                if (t.Item3 == null && !string.IsNullOrEmpty(t.Item2))
                {
                    movie.PosterImagePath = t.Item2;
                }
            });

            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            Logger.Debug(
                $"DownloadPosterImageAsync ({movie.ImdbCode}) in {elapsedMs} milliseconds.");
        }
Esempio n. 3
0
        public AuthClient(Func <bool, Task <string> > getAccessToken, HttpClient httpClientFactory)
            : base(getAccessToken, httpClientFactory)
        {
            var user = DownloadFileHelper.ReadUser();

            deviceInfo = user?.DeviceInfo;
        }
Esempio n. 4
0
        /// <summary>
        /// Download a subtitle
        /// </summary>
        /// <param name="movie">The movie of which to retrieve its subtitles</param>
        /// <param name="progress">Report the progress of the download</param>
        /// <param name="ct">Cancellation token</param>
        public async Task DownloadSubtitleAsync(MovieFull movie, IProgress <long> progress, CancellationTokenSource ct)
        {
            if (movie.SelectedSubtitle == null)
            {
                return;
            }

            var watch = Stopwatch.StartNew();

            var filePath = Constants.Subtitles + movie.ImdbCode + "\\" + movie.SelectedSubtitle.Language.EnglishName +
                           ".zip";

            try
            {
                var result = await
                             DownloadFileHelper.DownloadFileTaskAsync(
                    Constants.YifySubtitles + movie.SelectedSubtitle.Url, filePath, progress : progress, ct : ct);

                if (result.Item3 == null && !string.IsNullOrEmpty(result.Item2))
                {
                    using (var archive = ZipFile.OpenRead(result.Item2))
                    {
                        foreach (var entry in archive.Entries)
                        {
                            if (entry.FullName.StartsWith("_") ||
                                !entry.FullName.EndsWith(".srt", StringComparison.OrdinalIgnoreCase))
                            {
                                continue;
                            }
                            var subtitlePath = Path.Combine(Constants.Subtitles + movie.ImdbCode,
                                                            entry.FullName);
                            if (!File.Exists(subtitlePath))
                            {
                                entry.ExtractToFile(subtitlePath);
                            }

                            movie.SelectedSubtitle.FilePath = subtitlePath;
                        }
                    }
                }
            }
            catch (Exception exception) when(exception is TaskCanceledException)
            {
                Logger.Debug(
                    "DownloadSubtitleAsync cancelled.");
            }
            catch (Exception exception)
            {
                Logger.Error(
                    $"DownloadSubtitleAsync: {exception.Message}");
                throw;
            }
            finally
            {
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Logger.Debug(
                    $"DownloadSubtitleAsync ({movie.ImdbCode}) in {elapsedMs} milliseconds.");
            }
        }
Esempio n. 5
0
        private void Download(HttpContext context)
        {
            string zipFile = context.Server.MapPath("~/#download.zip");

            string[]      fd    = context.Request["value1"].Split('|');
            List <string> files = new List <string>();
            List <string> dir   = new List <string>();

            foreach (string file in fd)
            {
                string f = context.Server.MapPath(file);

                if (File.Exists(f))
                {
                    files.Add(f);
                }
                else if (Directory.Exists(f))
                {
                    dir.Add(f);
                }
            }

            ZipHelper.Zip(Path.GetDirectoryName(zipFile) + "\\", zipFile, "", true, files.ToArray(), dir.ToArray());
            DownloadFileHelper.ResponseFile(zipFile, "down_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip", context);
        }
Esempio n. 6
0
        /// <summary>
        /// Download cover image for each of the movies provided
        /// </summary>
        /// <param name="movies">The movies to process</param>
        public async Task DownloadCoverImageAsync(IEnumerable <MovieShort> movies)
        {
            var watch = Stopwatch.StartNew();

            var moviesToProcess = movies.ToList();

            await
            moviesToProcess.ForEachAsync(
                movie =>
                DownloadFileHelper.DownloadFileTaskAsync(movie.MediumCoverImage,
                                                         Constants.CoverMoviesDirectory + movie.ImdbCode + Constants.ImageFileExtension,
                                                         int.MaxValue),
                (movie, t) =>
            {
                if (t.Item3 == null && !string.IsNullOrEmpty(t.Item2))
                {
                    movie.CoverImagePath = t.Item2;
                }
            });

            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            Logger.Debug(
                $"DownloadCoverImageAsync ({string.Join(";", moviesToProcess.Select(movie => movie.ImdbCode))}) in {elapsedMs} milliseconds.");
        }
Esempio n. 7
0
        private string GenerateExcel(FilterViewModel FilterViewModel)
        {
            this.oWB                    = Factory.GetWorkbook();
            this.OSHEET                 = this.oWB.Worksheets[0];
            this.OSHEET.Name            = "Report Filters";
            this.OSHEET.Cells.WrapText  = false;
            this.OSHEET.Cells.Font.Name = "Calibri";
            this.OSHEET.Cells.Font.Size = 11;

            AddExcelRow(this.OSHEET, "Sr No.", 0, 0, true, false, HAlign.Left, false, true, true, false, 10, "", "");
            AddExcelRow(this.OSHEET, "Project Name", 0, 1, true, false, HAlign.Center, false, true, true, false, 20, "", "");
            AddExcelRow(this.OSHEET, "Prime Contractor", 0, 2, true, false, HAlign.Center, false, true, true, false, 15, "", "");
            AddExcelRow(this.OSHEET, "Contract Number", 0, 3, true, false, HAlign.Center, false, true, true, false, 15, "", "");
            AddExcelRow(this.OSHEET, "Task Order", 0, 4, true, false, HAlign.Center, false, true, true, false, 15, "", "");
            AddExcelRow(this.OSHEET, "COR Name", 0, 5, true, false, HAlign.Center, false, true, true, false, 15, "", "");
            AddExcelRow(this.OSHEET, "Traveler Name", 0, 6, true, false, HAlign.Center, false, true, true, false, 15, "", "");
            AddExcelRow(this.OSHEET, "Traveler Cost", 0, 7, true, false, HAlign.Center, false, true, true, false, 15, "", "");
            AddExcelRow(this.OSHEET, "From State/City", 0, 8, true, false, HAlign.Center, false, true, true, false, 25, "", "");
            AddExcelRow(this.OSHEET, "To State/City", 0, 9, true, false, HAlign.Center, false, true, true, false, 25, "", "");
            int rowIndex = 0;

            foreach (var item in FilterViewModel.lstTravelDetailModel)
            {
                rowIndex++;
                AddExcelRow(this.OSHEET, rowIndex.ToString(), rowIndex, 0, false, false, HAlign.Left, false, false, true, false, 0, "", "");
                AddExcelRow(this.OSHEET, item.Summary_ProjectName, rowIndex, 1, false, false, HAlign.Left, false, false, true, false, 0, "", "");
                AddExcelRow(this.OSHEET, item.Summary_PrimeContractor, rowIndex, 2, false, false, HAlign.Left, false, false, true, false, 0, "", "");
                AddExcelRow(this.OSHEET, item.Summary_ContractNumber, rowIndex, 3, false, false, HAlign.Left, false, false, true, false, 0, "", "");
                AddExcelRow(this.OSHEET, item.Summary_TaskOrder, rowIndex, 4, false, false, HAlign.Left, false, false, true, false, 0, "", "");
                AddExcelRow(this.OSHEET, item.Summary_CorName, rowIndex, 5, false, false, HAlign.Left, false, false, true, false, 0, "", "");
                AddExcelRow(this.OSHEET, item.Summary_TravelerName, rowIndex, 6, false, false, HAlign.Left, false, false, true, false, 0, "", "");
                AddExcelRow(this.OSHEET, item.Cost_TotalExpense.ToString(), rowIndex, 7, false, false, HAlign.Left, false, false, true, false, 0, "", "");
                AddExcelRow(this.OSHEET, item.TravelState1.Name + "/" + item.TravelCity.Name, rowIndex, 8, false, false, HAlign.Left, false, false, true, false, 0, "", "");
                AddExcelRow(this.OSHEET, item.TravelState.Name + "/" + item.TravelCity1.Name, rowIndex, 9, false, false, HAlign.Left, false, false, true, false, 0, "", "");
            }

            IRange  range  = this.OSHEET.Range[FilterViewModel.lstTravelDetailModel.Count(), 0, FilterViewModel.lstTravelDetailModel.Count(), 9];
            IBorder border = range.Borders[SpreadsheetGear.BordersIndex.EdgeBottom];

            border.LineStyle = SpreadsheetGear.LineStyle.Continous;
            border.Color     = SpreadsheetGear.Drawing.Color.GetSpreadsheetGearColor(System.Drawing.Color.Black);
            border.Weight    = SpreadsheetGear.BorderWeight.Thin;

            DownloadFileHelper.CreateFolder("ReportData", "Excel");
            //delete old files
            DownloadFileHelper.DeleteOldExcelFiles(ExcelExportTypeEnum.ReportFilters);
            //delete old files
            //DownloadFileHelper.DeleteOldFiles();

            string path      = System.Web.HttpContext.Current.Server.MapPath("~\\ReportData\\Excel");
            string timestamp = Guid.NewGuid().ToString();
            string fileName  = "ReportFilters_" + timestamp + ".xlsx";
            string output    = path + "\\" + fileName;

            this.oWB.SaveAs(output, SpreadsheetGear.FileFormat.OpenXMLWorkbook);
            string filePath = output;

            return(fileName);
        }
Esempio n. 8
0
        public async Task Login()
        {
            var user = DownloadFileHelper.ReadUser();

            if (user != null)
            {
                Utils.WriteGreenText("You are already logged in.");
                return;
            }

            var authResponse = await api.Auth.Autheticate();

            if (!authResponse.Success)
            {
                Utils.WriteRedText($"Could not register the device. Error: {authResponse.Error.Message}");
                return;
            }

            var register = authResponse.Data;

            Utils.WriteYellowText($"Visit {register.AuthDeviceUrl}");
            Utils.WriteYellowText($"Enter Pin {register.Pin}");
            Utils.WriteYellowText($"Expires at: {register.ValidUntil:HH:mm} UTC");

            while (true)
            {
                Thread.Sleep(15000);

                if (register.ValidUntil <= DateTimeOffset.UtcNow)
                {
                    Utils.WriteRedText("Pin is no longer valid.");
                    break;
                }

                var statusResponse = await api.Auth.DeviceStatus();

                if (statusResponse.Success && statusResponse.Data.Status == "Valid")
                {
                    var authorizeResponse = await api.Auth.GetAccessToken();

                    if (!authorizeResponse.Success)
                    {
                        Utils.WriteRedText($"Could not get access token. Error: {authorizeResponse.Error.Message}");
                    }
                    else
                    {
                        Utils.WriteGreenText("You have successfully logged in");
                    }

                    break;
                }
                else if (!statusResponse.Success)
                {
                    Utils.WriteRedText($"Could not get device status. Error: {statusResponse.Error.Message}");
                }
            }
        }
Esempio n. 9
0
        public async Task <ApiResponse <User> > GetAccessToken()
        {
            var response = await PostHttp <User>($"user/authorization/{deviceInfo.DeviceId}", deviceInfo);

            if (response.Success)
            {
                var user = response.Data;
                user.DeviceInfo = deviceInfo;
                DownloadFileHelper.WriteUser(user);
            }

            return(response);
        }
Esempio n. 10
0
        /// <summary>
        /// Download the movie's background image
        /// </summary>
        /// <param name="movie">The movie to process</param>
        /// <param name="ct">Used to cancel downloading background image</param>
        public async Task DownloadBackgroundImageAsync(MovieFull movie, CancellationTokenSource ct)
        {
            var watch = Stopwatch.StartNew();

            try
            {
                await Task.Run(async() =>
                {
                    TmdbClient.GetConfig();
                    var tmdbMovie  = TmdbClient.GetMovie(movie.ImdbCode, MovieMethods.Images);
                    var remotePath = new List <string>
                    {
                        TmdbClient.GetImageUrl(Constants.BackgroundImageSizeTmDb,
                                               tmdbMovie.BackdropPath).AbsoluteUri
                    };

                    await
                    remotePath.ForEachAsync(
                        background =>
                        DownloadFileHelper.DownloadFileTaskAsync(background,
                                                                 Constants.BackgroundMovieDirectory + movie.ImdbCode + Constants.ImageFileExtension,
                                                                 ct: ct),
                        (background, t) =>
                    {
                        if (t.Item3 == null && !string.IsNullOrEmpty(t.Item2))
                        {
                            movie.BackgroundImagePath = t.Item2;
                        }
                    });
                }, ct.Token);
            }
            catch (Exception exception) when(exception is TaskCanceledException)
            {
                Logger.Debug(
                    "DownloadBackgroundImageAsync cancelled.");
            }
            catch (Exception exception)
            {
                Logger.Error(
                    $"DownloadBackgroundImageAsync: {exception.Message}");
                throw;
            }
            finally
            {
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Logger.Debug(
                    $"DownloadBackgroundImageAsync ({movie.ImdbCode}) in {elapsedMs} milliseconds.");
            }
        }
Esempio n. 11
0
        public async Task <(bool completed, int duration, int size, ApiError error)> Download()
        {
            var clipsResponse = await GetClipUrls();

            if (!clipsResponse.Success)
            {
                return(false, 0, 0, null);
            }

            var      completed = false;
            int      totalSize = 0;
            ApiError error     = null;
            int      duration  = Environment.TickCount;

            foreach (var item in clipsResponse.Data.RankedOptions)
            {
                var head = await HeadHttp(item.Url);

                if (!head.Success)
                {
                    continue;
                }

                using var fs = DownloadFileHelper.CreateFile(FilePath);
                var response = await GetFile(item.Url);

                if (response.Success)
                {
                    var buffer = new byte[4096 * 1024];
                    int read;
                    while ((read = await response.Data.ReadAsync(buffer, 0, buffer.Length)) != 0)
                    {
                        await fs.WriteAsync(buffer, 0, read);

                        totalSize += read;
                    }

                    response.Message.Dispose();
                    completed = true;
                    break;
                }
                else
                {
                    error = response.Error;
                }
            }

            duration = Environment.TickCount - duration;
            return(completed, duration, totalSize, error);
        }
Esempio n. 12
0
        /// <summary>
        /// Download the movie's poster image
        /// </summary>
        /// <param name="movie">The movie to process</param>
        /// <param name="ct">Used to cancel downloading poster image</param>
        public async Task DownloadPosterImageAsync(MovieFull movie, CancellationTokenSource ct)
        {
            if (movie.Images == null)
            {
                return;
            }

            var watch = Stopwatch.StartNew();

            var posterPath = new List <string>
            {
                movie.Images.LargeCoverImage
            };

            try
            {
                await
                posterPath.ForEachAsync(
                    poster =>
                    DownloadFileHelper.DownloadFileTaskAsync(poster,
                                                             Constants.PosterMovieDirectory + movie.ImdbCode + Constants.ImageFileExtension, ct: ct),
                    (poster, t) =>
                {
                    if (t.Item3 == null && !string.IsNullOrEmpty(t.Item2))
                    {
                        movie.PosterImagePath = t.Item2;
                    }
                });
            }
            catch (Exception exception) when(exception is TaskCanceledException)
            {
                Logger.Debug(
                    "DownloadPosterImageAsync cancelled.");
            }
            catch (Exception exception)
            {
                Logger.Error(
                    $"DownloadPosterImageAsync: {exception.Message}");
                throw;
            }
            finally
            {
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Logger.Debug(
                    $"DownloadPosterImageAsync ({movie.ImdbCode}) in {elapsedMs} milliseconds.");
            }
        }
Esempio n. 13
0
        private void DownFile(HttpContext context)
        {
            string fileString = context.Request["value1"];

            string[] files = fileString.Split('|');

            foreach (string file in files)
            {
                string path = context.Server.MapPath(file);

                if (File.Exists(path))
                {
                    DownloadFileHelper.ResponseFile(path, context);
                }
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Download a subtitle
        /// </summary>
        /// <param name="movie">The movie of which to retrieve its subtitles</param>
        /// <param name="progress">Report the progress of the download</param>
        /// <param name="ct">Cancellation token</param>
        public async Task DownloadSubtitleAsync(MovieFull movie, IProgress <long> progress, CancellationTokenSource ct)
        {
            if (movie.SelectedSubtitle == null)
            {
                return;
            }

            var filePath = Constants.Subtitles + movie.ImdbCode + "\\" + movie.SelectedSubtitle.Language.EnglishName +
                           ".zip";

            try
            {
                var result = await
                             DownloadFileHelper.DownloadFileTaskAsync(
                    Constants.YifySubtitles + movie.SelectedSubtitle.Url, filePath, 10000, progress, ct);

                if (result.Item3 == null && !string.IsNullOrEmpty(result.Item2))
                {
                    using (var archive = ZipFile.OpenRead(result.Item2))
                    {
                        foreach (var entry in archive.Entries)
                        {
                            if (!entry.FullName.StartsWith("_") &&
                                entry.FullName.EndsWith(".srt", StringComparison.OrdinalIgnoreCase))
                            {
                                var subtitlePath = Path.Combine(Constants.Subtitles + movie.ImdbCode,
                                                                entry.FullName);
                                if (!File.Exists(subtitlePath))
                                {
                                    entry.ExtractToFile(subtitlePath);
                                }

                                movie.SelectedSubtitle.FilePath = subtitlePath;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(
                    $"DownloadSubtitleAsync (failed): {movie.Title}. Additional informations : {ex.Message}");
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Download actors' image for a movie
        /// </summary>
        /// <param name="movie">The movie to process</param>
        /// <param name="ct">Used to cancel downloading actor image</param>
        public async Task DownloadCastImageAsync(MovieFull movie, CancellationTokenSource ct)
        {
            if (movie.Cast == null)
            {
                return;
            }

            var watch = Stopwatch.StartNew();

            try
            {
                await
                movie.Cast.ForEachAsync(
                    cast =>
                    DownloadFileHelper.DownloadFileTaskAsync(cast.SmallImage,
                                                             Constants.CastMovieDirectory + cast.Name + Constants.ImageFileExtension, ct: ct),
                    (cast, t) =>
                {
                    if (t.Item3 == null && !string.IsNullOrEmpty(t.Item2))
                    {
                        cast.SmallImagePath = t.Item2;
                    }
                });
            }
            catch (Exception exception) when(exception is TaskCanceledException)
            {
                Logger.Debug(
                    "DownloadCastImageAsync cancelled.");
            }
            catch (Exception exception)
            {
                Logger.Error(
                    $"DownloadCastImageAsync: {exception.Message}");
                throw;
            }
            finally
            {
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Logger.Debug(
                    $"DownloadCastImageAsync ({movie.ImdbCode}) in {elapsedMs} milliseconds.");
            }
        }
Esempio n. 16
0
        public async Task <ApiResponse <Course> > GetCourse(string courseName)
        {
            var course = DownloadFileHelper.ReadCourse(courseName);

            if (course == null)
            {
                var response = await GetHttp <Course>($"library/courses/{courseName}");

                if (response.Success)
                {
                    DownloadFileHelper.WriteCourse(response.Data);
                }
                return(response);
            }

            return(new ApiResponse <Course>
            {
                Data = course
            });
        }
Esempio n. 17
0
        public async Task <ApiResponse> Logout()
        {
            if (deviceInfo == null)
            {
                return(new ApiResponse
                {
                    Error = new ApiError {
                        Message = "You are not logged in."
                    }
                });
            }

            var response = await DeleteHttp($"user/device/{deviceInfo.DeviceId}");

            if (response.Success)
            {
                DownloadFileHelper.DeleteUser();
            }
            return(response);
        }
Esempio n. 18
0
        public async Task <bool> Download()
        {
            var clipsResponse = await GetClipUrls();

            if (!clipsResponse.Success)
            {
                return(false);
            }

            var completed = false;

            foreach (var item in clipsResponse.Data.RankedOptions)
            {
                var head = await HeadHttp(item.Url);

                if (!head.Success)
                {
                    continue;
                }

                var filePath = DownloadFileHelper.GetVideoPath(outputPath, course.Title, ModuleId, ModuleTitle, Clip);
                using var fs = DownloadFileHelper.CreateFile(filePath);

                var response = await GetFile(item.Url);

                if (response.Success)
                {
                    var buffer = new byte[0x2000];
                    int read;
                    while ((read = response.Data.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        fs.Write(buffer, 0, read);
                    }

                    completed = true;
                    break;
                }
            }

            return(completed);
        }
Esempio n. 19
0
        /// <summary>
        /// Download the movie's background image
        /// </summary>
        /// <param name="movie">The movie to process</param>
        public async Task DownloadBackgroundImageAsync(MovieFull movie)
        {
            var watch = Stopwatch.StartNew();
            await Task.Run(async() =>
            {
                try
                {
                    TmdbClient.GetConfig();
                    var tmdbMovie  = TmdbClient.GetMovie(movie.ImdbCode, MovieMethods.Images);
                    var remotePath = new List <string>
                    {
                        TmdbClient.GetImageUrl(Constants.BackgroundImageSizeTmDb,
                                               tmdbMovie.BackdropPath).AbsoluteUri
                    };

                    await
                    remotePath.ForEachAsync(
                        background =>
                        DownloadFileHelper.DownloadFileTaskAsync(background,
                                                                 Constants.BackgroundMovieDirectory + movie.ImdbCode + Constants.ImageFileExtension),
                        (background, t) =>
                    {
                        if (t.Item3 == null && !string.IsNullOrEmpty(t.Item2))
                        {
                            movie.BackgroundImagePath = t.Item2;
                        }
                    });
                }
                catch (Exception ex) when(ex is SocketException || ex is WebException)
                {
                    Messenger.Default.Send(new ManageExceptionMessage(ex));
                }
            });

            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            Logger.Debug(
                $"DownloadBackgroundImageAsync ({movie.ImdbCode}) in {elapsedMs} milliseconds.");
        }
Esempio n. 20
0
        /// <summary>
        /// Download cover image for each of the movies provided
        /// </summary>
        /// <param name="movies">The movies to process</param>
        /// <param name="ct">Used to cancel task</param>
        public async Task DownloadCoverImageAsync(IEnumerable <MovieShort> movies, CancellationTokenSource ct)
        {
            var watch = Stopwatch.StartNew();

            var moviesToProcess = movies.ToList();

            try
            {
                await
                moviesToProcess.ForEachAsync(
                    movie =>
                    DownloadFileHelper.DownloadFileTaskAsync(movie.MediumCoverImage,
                                                             Constants.CoverMoviesDirectory + movie.ImdbCode + Constants.ImageFileExtension, ct: ct),
                    (movie, t) =>
                {
                    if (t.Item3 == null && !string.IsNullOrEmpty(t.Item2))
                    {
                        movie.CoverImagePath = t.Item2;
                    }
                });
            }
            catch (Exception exception) when(exception is TaskCanceledException)
            {
                Logger.Debug(
                    "DownloadCoverImageAsync cancelled.");
            }
            catch (Exception exception)
            {
                Logger.Error(
                    $"DownloadCoverImageAsync: {exception.Message}");
                throw;
            }
            finally
            {
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Logger.Debug(
                    $"DownloadCoverImageAsync ({string.Join(";", moviesToProcess.Select(movie => movie.ImdbCode))}) in {elapsedMs} milliseconds.");
            }
        }
Esempio n. 21
0
 public Task <bool> ExecuteAsync()
 {
     return(DownloadFileHelper.DownloadFileAsync(Uri, DestinationPath, Overwrite, _cts.Token, TimeoutSeconds, Log));
 }
Esempio n. 22
0
        /// <summary>
        /// Download a movie asynchronously
        /// </summary>
        /// <param name="movie">The movie to download</param>
        /// <param name="downloadProgress">Report download progress</param>
        /// <param name="downloadRate">Report download rate</param>
        /// <param name="ct">Cancellation token</param>
        private async Task DownloadMovieAsync(MovieFull movie, IProgress <double> downloadProgress,
                                              IProgress <double> downloadRate,
                                              CancellationTokenSource ct)
        {
            await Task.Run(async() =>
            {
                using (var session = new session())
                {
                    Logger.Info(
                        $"Start downloading movie : {movie.Title}");

                    IsDownloadingMovie = true;

                    downloadProgress?.Report(0d);
                    downloadRate?.Report(0d);

                    session.listen_on(6881, 6889);
                    var torrentUrl = movie.WatchInFullHdQuality
                        ? movie.Torrents?.FirstOrDefault(torrent => torrent.Quality == "1080p")?.Url
                        : movie.Torrents?.FirstOrDefault(torrent => torrent.Quality == "720p")?.Url;

                    var result =
                        await
                        DownloadFileHelper.DownloadFileTaskAsync(torrentUrl,
                                                                 Constants.TorrentDownloads + movie.ImdbCode + ".torrent", ct: ct);
                    var torrentPath = string.Empty;
                    if (result.Item3 == null && !string.IsNullOrEmpty(result.Item2))
                    {
                        torrentPath = result.Item2;
                    }

                    var addParams = new add_torrent_params
                    {
                        save_path = Constants.MovieDownloads,
                        ti        = new torrent_info(torrentPath)
                    };

                    var handle = session.add_torrent(addParams);
                    handle.set_upload_limit(_settingsViewModel.DownloadLimit * 1024);
                    handle.set_download_limit(_settingsViewModel.UploadLimit * 1024);

                    // We have to download sequentially, so that we're able to play the movie without waiting
                    handle.set_sequential_download(true);
                    var alreadyBuffered = false;
                    while (IsDownloadingMovie)
                    {
                        var status   = handle.status();
                        var progress = status.progress * 100d;

                        downloadProgress?.Report(progress);
                        downloadRate?.Report(Math.Round(status.download_rate / 1024d, 0));

                        handle.flush_cache();
                        if (handle.need_save_resume_data())
                        {
                            handle.save_resume_data(1);
                        }

                        if (progress >= Constants.MinimumBufferingBeforeMoviePlaying && !alreadyBuffered)
                        {
                            // Get movie file
                            foreach (
                                var filePath in
                                Directory.GetFiles(status.save_path + handle.torrent_file().name(),
                                                   "*" + Constants.VideoFileExtension)
                                )
                            {
                                alreadyBuffered = true;
                                movie.FilePath  = new Uri(filePath);
                                Messenger.Default.Send(new PlayMovieMessage(movie));
                            }
                        }

                        try
                        {
                            await Task.Delay(1000, ct.Token);
                        }
                        catch (TaskCanceledException)
                        {
                            return;
                        }
                    }
                }
            }, ct.Token);
        }
Esempio n. 23
0
 public PluralSightApi(int timeout)
 {
     user         = DownloadFileHelper.ReadUser();
     this.timeout = timeout;
 }