示例#1
0
        public void GetHashCode_DifferentMovies_ReturnsDifferentHashCode()
        {
            var fixture = new Fixture();

            var id1 = fixture.Create <string>();
            var dateUploadedUnix1 = fixture.Create <int>();

            var id2 = fixture.Create <string>();
            var dateUploadedUnix2 = fixture.Create <int>();

            var movie1 = new MovieJson
            {
                ImdbCode         = id1,
                DateUploadedUnix = dateUploadedUnix1
            };

            var movie2 = new MovieJson
            {
                ImdbCode         = id2,
                DateUploadedUnix = dateUploadedUnix2
            };

            Assert.AreNotEqual(
                _comparer.GetHashCode(movie1), _comparer.GetHashCode(movie2));
        }
示例#2
0
        public void Equals_DifferentMovies_ReturnsFalse()
        {
            var fixture = new Fixture();

            var id1 = fixture.Create <string>();
            var dateUploadedUnix1 = fixture.Create <int>();

            var id2 = fixture.Create <string>();
            var dateUploadedUnix2 = fixture.Create <int>();

            var movie1 = new MovieJson
            {
                ImdbCode         = id1,
                DateUploadedUnix = dateUploadedUnix1
            };

            var movie2 = new MovieJson
            {
                ImdbCode         = id2,
                DateUploadedUnix = dateUploadedUnix2
            };

            Assert.AreEqual(
                _comparer.Equals(movie1, movie2), false);

            Assert.AreEqual(
                _comparer.Equals(movie1, null), false);

            Assert.AreEqual(
                _comparer.Equals(movie2, null), false);
        }
示例#3
0
        /// <summary>
        /// Translate movie informations (title, description, ...)
        /// </summary>
        /// <param name="movieToTranslate">Movie to translate</param>
        /// <returns>Task</returns>
        public async Task TranslateMovieAsync(MovieJson movieToTranslate)
        {
            if (!MustRefreshLanguage)
            {
                return;
            }
            var watch = Stopwatch.StartNew();

            try
            {
                var movie = await TmdbClient.GetMovieAsync(movieToTranslate.ImdbCode,
                                                           MovieMethods.Credits);

                movieToTranslate.Title           = movie?.Title;
                movieToTranslate.Genres          = movie?.Genres?.Select(a => a.Name).ToList();
                movieToTranslate.DescriptionFull = movie?.Overview;
            }
            catch (Exception exception) when(exception is TaskCanceledException)
            {
                Logger.Debug(
                    "TranslateMovieAsync cancelled.");
            }
            catch (Exception exception)
            {
                Logger.Error(
                    $"TranslateMovieAsync: {exception.Message}");
            }
            finally
            {
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Logger.Debug(
                    $"TranslateMovieAsync ({movieToTranslate.ImdbCode}) in {elapsedMs} milliseconds.");
            }
        }
示例#4
0
        public async Task <Metadata> GetMetadata(string id)
        {
            try
            {
                _logger.LogInformation($"Attempting to get movie metadata for track {id}.");
                HttpRequestMessage request = new HttpRequestMessage();
                request.Method     = HttpMethod.Get;
                request.RequestUri = new Uri($"{_endpoint}{id}");

                HttpResponseMessage response = await _client.SendAsync(request);

                response.EnsureSuccessStatusCode();
                string responseJson = await response.Content.ReadAsStringAsync();

                _logger.LogInformation($"Movie information recieved for movie {id}");

                MovieJson movie = JsonConvert.DeserializeObject <MovieJson>(responseJson);

                return(new Movie
                {
                    Title = movie.result.mv_title,
                    Artist = movie.result.mv_main_artist_nm
                });
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Exception occured trying to download the file.");
                return(null);
            }
        }
示例#5
0
        /// <summary>
        /// Get the link to the youtube trailer of a movie
        /// </summary>
        /// <param name="movie">The movie</param>
        /// <param name="ct">Used to cancel loading trailer</param>
        /// <returns>Video trailer</returns>
        public async Task <ResultContainer <Video> > GetMovieTrailerAsync(MovieJson movie, CancellationToken ct)
        {
            var watch = Stopwatch.StartNew();

            var trailers = new ResultContainer <Video>();

            try
            {
                await Task.Run(
                    async() => trailers = (await TmdbClient.GetMovieAsync(movie.ImdbCode, MovieMethods.Videos))
                    ?.Videos,
                    ct);
            }
            catch (Exception exception) when(exception is TaskCanceledException)
            {
                Logger.Debug(
                    "GetMovieTrailerAsync cancelled.");
            }
            catch (Exception exception)
            {
                Logger.Error(
                    $"GetMovieTrailerAsync: {exception.Message}");
                throw;
            }
            finally
            {
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Logger.Debug(
                    $"GetMovieTrailerAsync ({movie.ImdbCode}) in {elapsedMs} milliseconds.");
            }

            return(trailers);
        }
示例#6
0
 /// <summary>
 /// Initialize a new instance of PlayMovieMessage class
 /// </summary>
 /// <param name="movie">The movie</param>
 /// <param name="bufferProgress">The buffer progress</param>
 /// <param name="bandwidthRate">The bandwidth rate</param>
 /// <param name="playingProgress">The playing progress</param>
 public PlayMovieMessage(MovieJson movie, Progress <double> bufferProgress, Progress <BandwidthRate> bandwidthRate, IProgress <double> playingProgress)
 {
     Movie           = movie;
     BufferProgress  = bufferProgress;
     BandwidthRate   = bandwidthRate;
     PlayingProgress = playingProgress;
 }
示例#7
0
        /// <summary>
        /// Get movies similar async
        /// </summary>
        /// <param name="movie">Movie</param>
        /// <returns>Movies</returns>
        public async Task <IEnumerable <MovieLightJson> > GetMoviesSimilarAsync(MovieJson movie)
        {
            var watch = Stopwatch.StartNew();

            (IEnumerable <MovieLightJson> movies, int nbMovies)similarMovies = (new List <MovieLightJson>(), 0);
            try
            {
                if (movie.Similars != null && movie.Similars.Any())
                {
                    similarMovies = await GetSimilarAsync(0, Utils.Constants.MaxMoviesPerPage, movie.Similars,
                                                          CancellationToken.None)
                                    .ConfigureAwait(false);
                }
            }
            catch (Exception exception)
            {
                Logger.Error(
                    $"GetMoviesSimilarAsync: {exception.Message}");
                throw;
            }
            finally
            {
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Logger.Debug(
                    $"GetMoviesSimilarAsync in {elapsedMs} milliseconds.");
            }

            return(similarMovies.movies.Where(
                       a => a.ImdbCode != movie.ImdbCode));
        }
示例#8
0
        /// <summary>
        /// Get movies similar async
        /// </summary>
        /// <param name="movie">Movie</param>
        /// <returns>Movies</returns>
        public async Task <List <MovieJson> > GetMoviesSimilarAsync(MovieJson movie)
        {
            var watch  = Stopwatch.StartNew();
            var movies = new List <MovieJson>();

            try
            {
                if (movie.Similars != null && movie.Similars.Any())
                {
                    await movie.Similars.ParallelForEachAsync(async imdbCode =>
                    {
                        var similar = await GetMovieAsync(imdbCode);
                        if (similar != null)
                        {
                            movies.Add(similar);
                        }
                    });
                }
            }
            catch (Exception exception)
            {
                Logger.Error(
                    $"GetMoviesSimilarAsync: {exception.Message}");
                throw;
            }
            finally
            {
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Logger.Debug(
                    $"GetMoviesSimilarAsync in {elapsedMs} milliseconds.");
            }

            return(movies);
        }
        /// <summary>
        /// Load the movie's subtitles asynchronously
        /// </summary>
        /// <param name="movie">The movie</param>
        private async Task LoadSubtitles(MovieJson movie)
        {
            Logger.Debug(
                $"Load subtitles for movie: {movie.Title}");
            Movie            = movie;
            LoadingSubtitles = true;
            await Task.Run(() =>
            {
                try
                {
                    var languages = _subtitlesService.GetSubLanguages().ToList();

                    var imdbId = 0;
                    if (int.TryParse(new string(movie.ImdbCode
                                                .SkipWhile(x => !char.IsDigit(x))
                                                .TakeWhile(char.IsDigit)
                                                .ToArray()), out imdbId))
                    {
                        var subtitles = _subtitlesService.SearchSubtitlesFromImdb(
                            languages.Select(lang => lang.SubLanguageID).Aggregate((a, b) => a + "," + b),
                            imdbId.ToString());
                        DispatcherHelper.CheckBeginInvokeOnUI(() =>
                        {
                            movie.AvailableSubtitles =
                                new ObservableCollection <Subtitle>(subtitles.OrderBy(a => a.LanguageName)
                                                                    .Select(sub => new Subtitle
                            {
                                Sub = sub
                            }).GroupBy(x => x.Sub.LanguageName,
                                       (k, g) =>
                                       g.Aggregate(
                                           (a, x) =>
                                           (Convert.ToDouble(x.Sub.Rating, CultureInfo.InvariantCulture) >=
                                            Convert.ToDouble(a.Sub.Rating, CultureInfo.InvariantCulture))
                                                        ? x
                                                        : a)));
                            movie.AvailableSubtitles.Insert(0, new Subtitle
                            {
                                Sub = new OSDBnet.Subtitle
                                {
                                    LanguageName = LocalizationProviderHelper.GetLocalizedValue <string>("NoneLabel")
                                }
                            });

                            movie.SelectedSubtitle = movie.AvailableSubtitles.FirstOrDefault();
                            LoadingSubtitles       = false;
                        });
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(
                        $"Failed loading subtitles for : {movie.Title}. {ex.Message}");
                    DispatcherHelper.CheckBeginInvokeOnUI(() =>
                    {
                        LoadingSubtitles = false;
                    });
                }
            });
        }
示例#10
0
        /// <summary>
        /// Set a movie as seen
        /// </summary>
        /// <param name="movie">Seen movie</param>
        public async Task SetHasBeenSeenMovieAsync(MovieJson movie)
        {
            if (movie == null)
            {
                throw new ArgumentNullException(nameof(movie));
            }
            var watch = Stopwatch.StartNew();

            try
            {
                using (var context = new ApplicationDbContext())
                {
                    var movieHistory = await context.MovieHistory.FirstOrDefaultAsync();

                    if (movieHistory == null)
                    {
                        await CreateMovieHistoryAsync();

                        movieHistory = await context.MovieHistory.FirstOrDefaultAsync();
                    }

                    if (movieHistory.Movies == null)
                    {
                        movieHistory.Movies = new List <Entity.Movie.MovieEntity>
                        {
                            MovieJsonToEntity(movie)
                        };

                        context.MovieHistory.AddOrUpdate(movieHistory);
                    }
                    else
                    {
                        var movieFull = movieHistory.Movies.FirstOrDefault(p => p.ImdbCode == movie.ImdbCode);
                        if (movieFull == null)
                        {
                            movieHistory.Movies.Add(MovieJsonToEntity(movie));
                        }
                        else
                        {
                            movieFull.HasBeenSeen = movie.HasBeenSeen;
                        }
                    }

                    await context.SaveChangesAsync();
                }
            }
            catch (Exception exception)
            {
                Logger.Error(
                    $"SetHasBeenSeenMovieAsync: {exception.Message}");
            }
            finally
            {
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Logger.Debug(
                    $"SetHasBeenSeenMovieAsync ({movie.ImdbCode}) in {elapsedMs} milliseconds.");
            }
        }
示例#11
0
        /// <summary>
        /// Get movie by its Imdb code
        /// </summary>
        /// <param name="imdbCode">Movie's Imdb code</param>
        /// <param name="ct">Cancellation</param>
        /// <returns>The movie</returns>
        public async Task <MovieJson> GetMovieAsync(string imdbCode, CancellationToken ct)
        {
            var timeoutPolicy =
                Policy.TimeoutAsync(Constants.DefaultRequestTimeoutInSecond, TimeoutStrategy.Optimistic);

            try
            {
                return(await timeoutPolicy.ExecuteAsync(async cancellation =>
                {
                    var watch = Stopwatch.StartNew();

                    var restClient = new RestClient(Constants.PopcornApi);
                    var request = new RestRequest("/{segment}/{movie}", Method.GET);
                    request.AddUrlSegment("segment", "movies");
                    request.AddUrlSegment("movie", imdbCode);
                    var movie = new MovieJson();

                    try
                    {
                        var response = await restClient.ExecuteTaskAsync(request, cancellation);
                        if (response.ErrorException != null)
                        {
                            throw response.ErrorException;
                        }

                        movie = JsonSerializer.Deserialize <MovieJson>(response.RawBytes);
                        movie.TranslationLanguage = (await _tmdbService.GetClient).DefaultLanguage;
                        movie.TmdbId =
                            (await(await _tmdbService.GetClient).GetMovieAsync(movie.ImdbId,
                                                                               cancellationToken: cancellation)).Id;
                    }
                    catch (Exception exception) when(exception is TaskCanceledException)
                    {
                        Logger.Debug(
                            "GetMovieAsync cancelled.");
                    }
                    catch (Exception exception)
                    {
                        Logger.Error(
                            $"GetMovieAsync: {exception.Message}");
                        throw;
                    }
                    finally
                    {
                        watch.Stop();
                        var elapsedMs = watch.ElapsedMilliseconds;
                        Logger.Trace(
                            $"GetMovieAsync ({imdbCode}) in {elapsedMs} milliseconds.");
                    }

                    return movie;
                }, ct));
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw;
            }
        }
示例#12
0
 /// <summary>
 /// Initialize a new instance of PlayMovieMessage class
 /// </summary>
 /// <param name="movie">The movie</param>
 /// <param name="bufferProgress">The buffer progress</param>
 /// <param name="bandwidthRate">The bandwidth rate</param>
 /// <param name="playingProgress">The playing progress</param>
 /// <param name="pieceAvailability">The piece availability progress</param>
 public PlayMovieMessage(MovieJson movie, Progress <double> bufferProgress, Progress <BandwidthRate> bandwidthRate, IProgress <double> playingProgress, Progress <PieceAvailability> pieceAvailability)
 {
     Movie             = movie;
     BufferProgress    = bufferProgress;
     BandwidthRate     = bandwidthRate;
     PlayingProgress   = playingProgress;
     PieceAvailability = pieceAvailability;
 }
示例#13
0
        /// <summary>
        /// Get the link to the youtube trailer of a movie
        /// </summary>
        /// <param name="movie">The movie</param>
        /// <param name="ct">Used to cancel loading trailer</param>
        /// <returns>Video trailer</returns>
        public async Task <string> GetMovieTrailerAsync(MovieJson movie, CancellationToken ct)
        {
            var timeoutPolicy =
                Policy.TimeoutAsync(Constants.DefaultRequestTimeoutInSecond, TimeoutStrategy.Optimistic);

            try
            {
                return(await timeoutPolicy.ExecuteAsync(async cancellation =>
                {
                    var watch = Stopwatch.StartNew();
                    var uri = string.Empty;
                    try
                    {
                        var tmdbMovie =
                            await(await _tmdbService.GetClient).GetMovieAsync(movie.ImdbId, MovieMethods.Videos);
                        var trailers = tmdbMovie?.Videos;
                        if (trailers != null && trailers.Results.Any())
                        {
                            var trailer = trailers.Results
                                          .First()
                                          .Key;
                            var video = await GetVideoFromYtVideoId(trailer);
                            uri = await video.GetUriAsync();
                        }
                        else
                        {
                            throw new PopcornException("No trailer found.");
                        }
                    }
                    catch (Exception exception) when(exception is TaskCanceledException)
                    {
                        Logger.Debug(
                            "GetMovieTrailerAsync cancelled.");
                    }
                    catch (Exception exception)
                    {
                        Logger.Error(
                            $"GetMovieTrailerAsync: {exception.Message}");
                        throw;
                    }
                    finally
                    {
                        watch.Stop();
                        var elapsedMs = watch.ElapsedMilliseconds;
                        Logger.Trace(
                            $"GetMovieTrailerAsync ({movie.ImdbId}) in {elapsedMs} milliseconds.");
                    }

                    return uri;
                }, ct));
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw;
            }
        }
示例#14
0
        /// <summary>
        /// Get the link to the youtube trailer of a movie
        /// </summary>
        /// <param name="movie">The movie</param>
        /// <param name="ct">Used to cancel loading trailer</param>
        /// <returns>Video trailer</returns>
        public async Task <string> GetMovieTrailerAsync(MovieJson movie, CancellationToken ct)
        {
            var watch = Stopwatch.StartNew();
            var uri   = string.Empty;

            try
            {
                var tmdbMovie = await TmdbClient.GetMovieAsync(movie.ImdbCode, MovieMethods.Videos)
                                .ConfigureAwait(false);

                var trailers = tmdbMovie?.Videos;
                if (trailers != null && trailers.Results.Any())
                {
                    using (var service = Client.For(YouTube.Default))
                    {
                        var videos =
                            (await service.GetAllVideosAsync("https://youtube.com/watch?v=" + trailers.Results
                                                             .FirstOrDefault()
                                                             .Key).ConfigureAwait(false))
                            .ToList();
                        if (videos.Any())
                        {
                            var settings = SimpleIoc.Default.GetInstance <ApplicationSettingsViewModel>();
                            var maxRes   = settings.DefaultHdQuality ? 1080 : 720;
                            uri =
                                await videos.Where(a => !a.Is3D && a.Resolution <= maxRes &&
                                                   a.Format == VideoFormat.Mp4 && a.AudioBitrate > 0)
                                .Aggregate((i1, i2) => i1.Resolution > i2.Resolution ? i1 : i2).GetUriAsync();
                        }
                    }
                }
                else
                {
                    throw new PopcornException("No trailer found.");
                }
            }
            catch (Exception exception) when(exception is TaskCanceledException)
            {
                Logger.Debug(
                    "GetMovieTrailerAsync cancelled.");
            }
            catch (Exception exception)
            {
                Logger.Error(
                    $"GetMovieTrailerAsync: {exception.Message}");
                throw;
            }
            finally
            {
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Logger.Debug(
                    $"GetMovieTrailerAsync ({movie.ImdbCode}) in {elapsedMs} milliseconds.");
            }

            return(uri);
        }
示例#15
0
        /// <summary>
        /// Load movie's trailer asynchronously
        /// </summary>
        /// <param name="movie">The movie</param>
        /// <param name="ct">Cancellation token</param>
        public async Task LoadTrailerAsync(MovieJson movie, CancellationToken ct)
        {
            try
            {
                var trailer = await _movieService.GetMovieTrailerAsync(movie, ct);

                var trailerUrl = await _movieService.GetVideoTrailerUrlAsync(trailer.Results.FirstOrDefault()?.Key, ct);

                if (string.IsNullOrEmpty(trailerUrl))
                {
                    Logger.Error(
                        $"Failed loading movie's trailer: {movie.Title}");
                    Messenger.Default.Send(
                        new ManageExceptionMessage(
                            new Exception(
                                LocalizationProviderHelper.GetLocalizedValue <string>("TrailerNotAvailable"))));
                    Messenger.Default.Send(new StopPlayingTrailerMessage());
                    return;
                }

                if (!ct.IsCancellationRequested)
                {
                    Logger.Debug(
                        $"Movie's trailer loaded: {movie.Title}");
                    Messenger.Default.Send(new PlayTrailerMessage(trailerUrl, movie.Title, () =>
                    {
                        Messenger.Default.Send(new StopPlayingTrailerMessage());
                    },
                                                                  () =>
                    {
                        Messenger.Default.Send(new StopPlayingTrailerMessage());
                    }));
                }
            }
            catch (Exception exception) when(exception is TaskCanceledException)
            {
                Logger.Debug(
                    "GetMovieTrailerAsync cancelled.");
                Messenger.Default.Send(new StopPlayingTrailerMessage());
            }
            catch (Exception exception)
            {
                Logger.Error(
                    $"GetMovieTrailerAsync: {exception.Message}");
                Messenger.Default.Send(
                    new ManageExceptionMessage(
                        new Exception(
                            LocalizationProviderHelper.GetLocalizedValue <string>(
                                "TrailerNotAvailable"))));
                Messenger.Default.Send(new StopPlayingTrailerMessage());
            }
        }
示例#16
0
        public async Task <IActionResult> Add([FromBody] MovieViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Dados invalidos!"));
            }

            var movie = await _movieService.CreateMovie(model);

            var movieJson = new MovieJson(movie);

            return(StatusCode(201, movieJson));
        }
示例#17
0
 /// <summary>
 /// Initializes a new instance of the MovieDetailsViewModel class.
 /// </summary>
 /// <param name="movieService">Service used to interact with movies</param>
 /// <param name="movieTrailerService">The movie trailer service</param>
 /// <param name="subtitlesService">The subtitles service</param>
 public MovieDetailsViewModel(IMovieService movieService, IMovieTrailerService movieTrailerService,
                              ISubtitlesService subtitlesService)
 {
     _movieTrailerService = movieTrailerService;
     _movieService        = movieService;
     Movie                           = new MovieJson();
     SimilarMovies                   = new ObservableCollection <MovieLightJson>();
     SubtitlesService                = subtitlesService;
     CancellationLoadingToken        = new CancellationTokenSource();
     CancellationLoadingTrailerToken = new CancellationTokenSource();
     DownloadMovie                   = new DownloadMovieViewModel(subtitlesService, new DownloadMovieService <MovieJson>());
     RegisterMessages();
     RegisterCommands();
 }
示例#18
0
        /// <summary>
        /// Get the link to the youtube trailer of a movie
        /// </summary>
        /// <param name="movie">The movie</param>
        /// <param name="ct">Used to cancel loading trailer</param>
        /// <returns>Video trailer</returns>
        public async Task <string> GetMovieTrailerAsync(MovieJson movie, CancellationToken ct)
        {
            var watch = Stopwatch.StartNew();

            var uri = string.Empty;

            try
            {
                var tmdbMovie = await TmdbClient.GetMovieAsync(movie.ImdbCode, MovieMethods.Videos);

                var trailers = tmdbMovie?.Videos;
                if (trailers != null && trailers.Results.Any())
                {
                    var restClient = new RestClient(Utils.Constants.PopcornApi);
                    var request    = new RestRequest("/{segment}/{key}", Method.GET);
                    request.AddUrlSegment("segment", "trailer");
                    request.AddUrlSegment("key", trailers.Results.FirstOrDefault().Key);
                    var response = await restClient.ExecuteGetTaskAsync <TrailerResponse>(request, ct);

                    if (response.ErrorException != null)
                    {
                        throw response.ErrorException;
                    }

                    uri = response.Data?.TrailerUrl ?? string.Empty;
                }
            }
            catch (Exception exception) when(exception is TaskCanceledException)
            {
                Logger.Debug(
                    "GetMovieTrailerAsync cancelled.");
            }
            catch (Exception exception)
            {
                Logger.Error(
                    $"GetMovieTrailerAsync: {exception.Message}");
                throw;
            }
            finally
            {
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Logger.Debug(
                    $"GetMovieTrailerAsync ({movie.ImdbCode}) in {elapsedMs} milliseconds.");
            }

            return(uri);
        }
        /// <summary>
        /// Load the requested movie
        /// </summary>
        /// <param name="movie">The movie to load</param>
        private void LoadMovie(MovieJson movie)
        {
            var watch = Stopwatch.StartNew();

            Messenger.Default.Send(new LoadMovieMessage());
            IsMovieLoading = true;

            Movie                 = movie;
            IsMovieLoading        = false;
            Movie.FullHdAvailable = movie.Torrents.Any(torrent => torrent.Quality == "1080p");
            LoadSubtitles(Movie);

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

            Logger.Debug($"LoadMovie ({movie.ImdbCode}) in {elapsedMs} milliseconds.");
        }
示例#20
0
        // GET: Pick
        //Get
        public ActionResult Index()
        {
            var movies = MovieJson.GetMovies();

            if (movies.Count > 0)
            {
                var movie = movies.OrderBy(x => Guid.NewGuid()).FirstOrDefault();
                if (movie != null)
                {
                    movie.Details = Api.SearchOmdb(movie.Const);
                }
                return(View(movie));
            }
            else
            {
                throw new FileLoadException();
            }
        }
示例#21
0
        /// <summary>
        /// Get movies similar async
        /// </summary>
        /// <param name="movie">Movie</param>
        /// <param name="ct">Cancellation</param>
        /// <returns>Movies</returns>
        public async Task <IEnumerable <MovieLightJson> > GetMoviesSimilarAsync(MovieJson movie, CancellationToken ct)
        {
            var timeoutPolicy =
                Policy.TimeoutAsync(Utils.Constants.DefaultRequestTimeoutInSecond, TimeoutStrategy.Pessimistic);

            try
            {
                return(await timeoutPolicy.ExecuteAsync(async cancellation =>
                {
                    var watch = Stopwatch.StartNew();
                    (IEnumerable <MovieLightJson> movies, int nbMovies)similarMovies = (new List <MovieLightJson>(), 0);
                    try
                    {
                        if (movie.Similars != null && movie.Similars.Any())
                        {
                            similarMovies = await GetSimilarAsync(0, Utils.Constants.MaxMoviesPerPage, movie.Similars,
                                                                  CancellationToken.None)
                                            .ConfigureAwait(false);
                        }
                    }
                    catch (Exception exception)
                    {
                        Logger.Error(
                            $"GetMoviesSimilarAsync: {exception.Message}");
                        throw;
                    }
                    finally
                    {
                        watch.Stop();
                        var elapsedMs = watch.ElapsedMilliseconds;
                        Logger.Debug(
                            $"GetMoviesSimilarAsync in {elapsedMs} milliseconds.");
                    }

                    return similarMovies.movies.Where(
                        a => a.ImdbCode != movie.ImdbCode);
                }, ct).ConfigureAwait(false));
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return(new List <MovieLightJson>());
            }
        }
示例#22
0
        /// <summary>
        /// Get movie by its Imdb code
        /// </summary>
        /// <param name="imdbCode">Movie's Imdb code</param>
        /// <returns>The movie</returns>
        public async Task <MovieJson> GetMovieAsync(string imdbCode)
        {
            var watch = Stopwatch.StartNew();

            var restClient = new RestClient(Utils.Constants.PopcornApi);
            var request    = new RestRequest("/{segment}/{movie}", Method.GET);

            request.AddUrlSegment("segment", "movies");
            request.AddUrlSegment("movie", imdbCode);
            var movie = new MovieJson();

            try
            {
                var response = await restClient.ExecuteTaskAsync <MovieJson>(request).ConfigureAwait(false);

                if (response.ErrorException != null)
                {
                    throw response.ErrorException;
                }

                movie = response.Data;
            }
            catch (Exception exception) when(exception is TaskCanceledException)
            {
                Logger.Debug(
                    "GetMovieAsync cancelled.");
            }
            catch (Exception exception)
            {
                Logger.Error(
                    $"GetMovieAsync: {exception.Message}");
                throw;
            }
            finally
            {
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Logger.Debug(
                    $"GetMovieAsync ({imdbCode}) in {elapsedMs} milliseconds.");
            }

            return(movie);
        }
示例#23
0
        /// <summary>
        /// Get movies similar async
        /// </summary>
        /// <param name="movie">Movie</param>
        /// <param name="similars">Similars</param>
        /// <returns>Movies</returns>
        public async Task GetMoviesSimilarAsync(MovieJson movie, IList <MovieLightJson> similars)
        {
            var watch = Stopwatch.StartNew();

            try
            {
                if (movie.Similars != null && movie.Similars.Any())
                {
                    foreach (var imdbCode in movie.Similars)
                    {
                        try
                        {
                            var similar = await GetMovieLightAsync(imdbCode).ConfigureAwait(false);

                            if (similar != null)
                            {
                                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                                {
                                    similars.Add(similar);
                                });
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.Error(
                    $"GetMoviesSimilarAsync: {exception.Message}");
                throw;
            }
            finally
            {
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Logger.Debug(
                    $"GetMoviesSimilarAsync in {elapsedMs} milliseconds.");
            }
        }
示例#24
0
        public void Equals_SameMovie_ReturnsTrue()
        {
            var fixture = new Fixture();

            var movie1 = new MovieJson();
            var movie2 = new MovieJson();

            var imdbCode         = fixture.Create <string>();
            var dateUploadedUnix = fixture.Create <int>();

            movie1.ImdbCode         = imdbCode;
            movie2.ImdbCode         = imdbCode;
            movie1.DateUploadedUnix = dateUploadedUnix;
            movie2.DateUploadedUnix = dateUploadedUnix;

            Assert.AreEqual(
                _comparer.Equals(movie1, movie1), true);

            Assert.AreEqual(
                _comparer.Equals(movie1, movie2), true);
        }
示例#25
0
        public void GetHashCode_SameMovie_ReturnsSameHashCode()
        {
            var fixture = new Fixture();

            var movie1 = new MovieJson();
            var movie2 = new MovieJson();

            var id = fixture.Create <string>();
            var dateUploadedUnix = fixture.Create <int>();

            movie1.ImdbCode         = id;
            movie2.ImdbCode         = id;
            movie1.DateUploadedUnix = dateUploadedUnix;
            movie2.DateUploadedUnix = dateUploadedUnix;

            Assert.AreEqual(
                _comparer.GetHashCode(movie1), _comparer.GetHashCode(movie1));

            Assert.AreEqual(
                _comparer.GetHashCode(movie1), _comparer.GetHashCode(movie2));
        }
        /// <summary>
        /// Load the requested movie
        /// </summary>
        /// <param name="movie">The movie to load</param>
        private async Task LoadMovie(MovieJson movie)
        {
            var watch = Stopwatch.StartNew();

            Messenger.Default.Send(new LoadMovieMessage());
            IsMovieLoading = true;

            Movie                 = movie;
            IsMovieLoading        = false;
            Movie.FullHdAvailable = movie.Torrents.Any(torrent => torrent.Quality == "1080p");
            ComputeTorrentHealth();

            var similarTask = Task.Run(async() =>
            {
                try
                {
                    LoadingSimilar = true;
                    SimilarMovies  = new ObservableCollection <MovieJson>(await _movieService.GetMoviesSimilarAsync(Movie));
                    AnySimilar     = SimilarMovies.Any();
                    LoadingSimilar = false;
                }
                catch (Exception ex)
                {
                    Logger.Error(
                        $"Failed loading similar movies for : {movie.Title}. {ex.Message}");
                }
            });

            await Task.WhenAll(new List <Task>
            {
                LoadSubtitles(Movie),
                similarTask
            });

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

            Logger.Debug($"LoadMovie ({movie.ImdbCode}) in {elapsedMs} milliseconds.");
        }
示例#27
0
        /// <summary>
        /// Set the movie
        /// </summary>
        /// <param name="movie">Movie</param>
        public async Task SetMovieAsync(MovieJson movie)
        {
            if (movie == null) throw new ArgumentNullException(nameof(movie));
            var watch = Stopwatch.StartNew();

            try
            {
                var movieToUpdate = User.MovieHistory.FirstOrDefault(a => a.ImdbId == movie.ImdbCode);
                if (movieToUpdate == null)
                {
                    User.MovieHistory.Add(new MovieHistoryJson
                    {
                        ImdbId = movie.ImdbCode,
                        Favorite = movie.IsFavorite,
                        Seen = movie.HasBeenSeen
                    });
                }
                else
                {
                    movieToUpdate.Seen = movie.HasBeenSeen;
                    movieToUpdate.Favorite = movie.IsFavorite;
                }

                await UpdateHistoryAsync();
            }
            catch (Exception exception)
            {
                Logger.Error(
                    $"SetFavoriteMovieAsync: {exception.Message}");
            }
            finally
            {
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                Logger.Debug(
                    $"SetFavoriteMovieAsync ({movie.ImdbCode}) in {elapsedMs} milliseconds.");
            }
        }
示例#28
0
 /// <summary>
 /// Initialize a new instance of DownloadMovieMessage class
 /// </summary>
 /// <param name="movie">The movie to download</param>
 public DownloadMovieMessage(MovieJson movie)
 {
     Movie = movie;
 }
        /// <summary>
        /// Load movie's trailer asynchronously
        /// </summary>
        /// <param name="movie">The movie</param>
        /// <param name="ct">Cancellation token</param>
        public async Task LoadTrailerAsync(MovieJson movie, CancellationToken ct)
        {
            var timeoutPolicy =
                Policy.TimeoutAsync(Utils.Constants.DefaultRequestTimeoutInSecond, TimeoutStrategy.Pessimistic);

            try
            {
                await timeoutPolicy.ExecuteAsync(async cancellation =>
                {
                    try
                    {
                        var trailer = await MovieService.GetMovieTrailerAsync(movie, cancellation);
                        if (!cancellation.IsCancellationRequested && string.IsNullOrEmpty(trailer))
                        {
                            Logger.Error(
                                $"Failed loading movie's trailer: {movie.Title}");
                            Messenger.Default.Send(
                                new ManageExceptionMessage(
                                    new TrailerNotAvailableException(
                                        LocalizationProviderHelper.GetLocalizedValue <string>("TrailerNotAvailable"))));
                            Messenger.Default.Send(new StopPlayingTrailerMessage(Utils.MediaType.Movie));
                            return;
                        }

                        if (!cancellation.IsCancellationRequested)
                        {
                            Logger.Info(
                                $"Movie's trailer loaded: {movie.Title}");
                            Messenger.Default.Send(new PlayTrailerMessage(trailer, movie.Title, () =>
                            {
                                Messenger.Default.Send(new StopPlayingTrailerMessage(Utils.MediaType.Movie));
                            },
                                                                          () =>
                            {
                                Messenger.Default.Send(new StopPlayingTrailerMessage(Utils.MediaType.Movie));
                            }, Utils.MediaType.Movie));
                        }
                    }
                    catch (Exception exception) when(exception is TaskCanceledException)
                    {
                        Logger.Debug(
                            "GetMovieTrailerAsync cancelled.");
                        Messenger.Default.Send(new StopPlayingTrailerMessage(Utils.MediaType.Movie));
                    }
                    catch (Exception exception)
                    {
                        Logger.Error(
                            $"GetMovieTrailerAsync: {exception.Message}");
                        Messenger.Default.Send(
                            new ManageExceptionMessage(
                                new TrailerNotAvailableException(
                                    LocalizationProviderHelper.GetLocalizedValue <string>(
                                        "TrailerNotAvailable"))));
                        Messenger.Default.Send(new StopPlayingTrailerMessage(Utils.MediaType.Movie));
                    }
                }, ct);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
示例#30
0
        /// <summary>
        /// Convert a json movie to an entity
        /// </summary>
        /// <param name="movie">The movie to convert</param>
        /// <returns>Full movie entity</returns>
        private static MovieEntity MovieJsonToEntity(MovieJson movie)
        {
            if (movie == null)
            {
                throw new ArgumentNullException(nameof(movie));
            }
            var torrents = movie.Torrents.Select(torrent => new Torrent
            {
                DateUploaded     = torrent.DateUploaded,
                Url              = torrent.Url,
                Quality          = torrent.Quality,
                DateUploadedUnix = torrent.DateUploadedUnix,
                Hash             = torrent.Hash,
                Peers            = torrent.Peers,
                Seeds            = torrent.Seeds,
                Size             = torrent.Size,
                SizeBytes        = torrent.SizeBytes
            });

            var genres = movie.Genres.Select(genre => new Genre
            {
                Name = genre
            });

            var cast = movie.Cast.Select(actor => new Cast
            {
                CharacterName = actor.CharacterName,
                Name          = actor.Name,
                SmallImage    = actor.SmallImage,
                ImdbCode      = actor.ImdbCode
            });

            var movieFull = new MovieEntity
            {
                Year                   = movie.Year,
                Language               = movie.Language,
                ImdbCode               = movie.ImdbCode,
                Title                  = movie.Title,
                DateUploaded           = movie.DateUploaded,
                Runtime                = movie.Runtime,
                Url                    = movie.Url,
                TitleLong              = movie.TitleLong,
                Torrents               = torrents.ToList(),
                Genres                 = genres.ToList(),
                DateUploadedUnix       = movie.DateUploadedUnix,
                MpaRating              = movie.MpaRating,
                Rating                 = movie.Rating,
                DescriptionFull        = movie.DescriptionFull,
                Cast                   = cast.ToList(),
                DescriptionIntro       = movie.DescriptionIntro,
                DownloadCount          = movie.DownloadCount,
                LikeCount              = movie.LikeCount,
                YtTrailerCode          = movie.YtTrailerCode,
                HasBeenSeen            = movie.HasBeenSeen,
                IsFavorite             = movie.IsFavorite,
                BackgroundImage        = movie.BackgroundImage,
                MediumCoverImage       = movie.MediumCoverImage,
                SmallCoverImage        = movie.SmallCoverImage,
                LargeCoverImage        = movie.LargeCoverImage,
                LargeScreenshotImage1  = movie.LargeScreenshotImage1,
                LargeScreenshotImage2  = movie.LargeScreenshotImage2,
                LargeScreenshotImage3  = movie.MediumScreenshotImage3,
                MediumScreenshotImage3 = movie.MediumScreenshotImage3,
                MediumScreenshotImage1 = movie.MediumScreenshotImage1,
                MediumScreenshotImage2 = movie.MediumScreenshotImage2,
                Slug                   = movie.Slug,
                BackdropImage          = movie.BackdropImage,
                PosterImage            = movie.PosterImage
            };

            return(movieFull);
        }