/// <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."); } }
static async Task Main(string[] _args) { var client = TmdbClient.Default(); var populator = new MoviePopulator("./data/movie_ids_10_01_2020.json", client); var ingester = new IngestTmdb(populator); await ingester.Ingest(); }
/// <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); }
/// <summary> /// Translate movie informations (title, description, ...) /// </summary> /// <param name="movieToTranslate">Movie to translate</param> /// <returns>Task</returns> public async Task TranslateMovieAsync(IMovie movieToTranslate) { if (!MustRefreshLanguage) { return; } var watch = Stopwatch.StartNew(); try { var movie = await TmdbClient.GetMovieAsync(movieToTranslate.ImdbCode, MovieMethods.Credits).ConfigureAwait(false); var refMovie = movieToTranslate as MovieJson; if (refMovie != null) { refMovie.Title = movie?.Title; refMovie.Genres = movie?.Genres?.Select(a => a.Name).ToList(); refMovie.DescriptionFull = movie?.Overview; return; } var refMovieLight = movieToTranslate as MovieLightJson; if (refMovieLight != null) { refMovieLight.Title = movie?.Title; refMovieLight.Genres = movie?.Genres != null ? string.Join(", ", movie.Genres?.Select(a => a.Name)) : string.Empty; } } 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."); } }
/// <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.ExecuteTaskAsync <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> /// Get recommendations by page /// </summary> /// <param name="page"></param> /// <returns></returns> public async Task <(IEnumerable <MovieLightJson>, int nbMovies)> Discover(int page) { var discover = TmdbClient.DiscoverMoviesAsync(); var result = await discover.Query(page); var movies = new ConcurrentBag <MovieLightJson>(); await result.Results.ParallelForEachAsync(async movie => { var imdbMovie = await TmdbClient.GetMovieAsync(movie.Id); if (imdbMovie?.ImdbId == null) { return; } var fetch = await GetMovieLightAsync(imdbMovie.ImdbId); if (fetch != null) { movies.Add(fetch); } }); return(movies, result.TotalResults); }
public void InitializeAsync() { mdb = new TmdbClient("00bd97eb398972b1934ecaa963822fc8"); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); services.AddMiniProfiler(options => { options.RouteBasePath = "/profiler"; options.EnableDebugMode = true; }).AddEntityFramework(); services.AddControllers(); services.AddDbContext <ApplicationDbContext>(options => ApplicationDbContext.UseDefaultOptions(options)); services.AddScoped <ISessionRepository, SessionRepository>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <IGenreRepository, GenreRepository>(); services.AddScoped <ITitleRepository, TitleRepository>(); services.AddScoped <ICurrentUserAccessor, CurrentUserAccessor>(); services.AddSingleton(services => TmdbClient.Default(services.GetService <IMemoryCache>())); services.AddSingleton <MovieClient>(); services.AddSingleton <MovieMeta>(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddIdentity <ApplicationUser, IdentityRole>(options => { options.User.RequireUniqueEmail = false; }) .AddEntityFrameworkStores <ApplicationDbContext>() .AddDefaultTokenProviders(); // https://docs.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-3.1 services.AddControllersWithViews(options => { options.Filters.Add(new ValidationErrorHandler()); options.Filters.Add(new NotificationHandler()); }); services.AddRazorPages(); services.AddMediatR(typeof(Core.UseCases.Session.Create)); AssemblyScanner.FindValidatorsInAssembly(typeof(Core.UseCases.Session.Create).Assembly) .ForEach(item => services.AddScoped(item.InterfaceType, item.ValidatorType)); services.AddTransient(typeof(IPipelineBehavior <,>), typeof(ValidationPipelineBehavior <,>)); _ = services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { In = ParameterLocation.Header, Description = "Please insert JWT with Bearer into field", Name = "Authorization", Type = SecuritySchemeType.ApiKey }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, Array.Empty <string>() } }); }); }
public Handler(TmdbClient client) { Client = client; }
public Handler(TmdbClient client, Database database, IClock clock) { Client = client; Database = database; Clock = clock; }