Exemplo n.º 1
0
        public MovieModel(TMDbLib.Objects.Movies.Movie _movie)
        {
            TMDBID      = _movie.Id;
            ImgSource   = "https://image.tmdb.org/t/p/w500/" + _movie.PosterPath;
            Title       = _movie.Title;
            ReleaseDate = _movie.ReleaseDate.Value.ToLongDateString();
            //Genre = _movie.GenreIds
            Information = _movie.Overview;

            if (_movie.Credits.Cast.Count <= 10)
            {
                Cast = _movie.Credits.Cast;
            }
            else if (_movie.Credits.Cast.Count > 10)
            {
                Cast = _movie.Credits.Cast.GetRange(0, 10);
            }

            if (_movie.Videos != null)
            {
                foreach (Video vid in _movie.Videos.Results)
                {
                    if (vid.Type == "Trailer")
                    {
                        TrailerSource = "https://www.youtube.com/embed/" + vid.Key + "?controls=1";
                        break;
                    }
                }
            }
        }
Exemplo n.º 2
0
        //Adding movie to database or just to the current instance
        private MovieConnector.Movie addMovieToDisplay(SearchMovie movie)
        {
            TMDbLib.Objects.Movies.Movie movie2 = client.GetMovieAsync(movie.Id).Result;
            List <string> ourGenres             = new List <string>();

            List <MovieConnector.Cast> ourCasts = new List <MovieConnector.Cast>();

            foreach (Genre genre in movie2.Genres)
            {
                ourGenres.Add(genre.Name);
            }

            try
            {
                TMDbLib.Objects.Movies.Movie casts;  casts = getCasts(movie.Id);
                int castCount = casts.Credits.Cast.Capacity;
                if (castCount > 5)
                {
                    castCount = 5;
                }
                for (int i = 0; i < castCount; i++)
                {
                    ourCasts.Add(new MovieConnector.Cast(casts.Credits.Cast[i].Id, casts.Credits.Cast[i].Character, casts.Credits.Cast[i].Name, casts.Credits.Cast[i].ProfilePath));
                }
            }
            catch (Exception e) { }

            currentMovie = new MovieConnector.Movie(movie.Id, movie.Title, movie.Overview, movie.ReleaseDate.Value, movie.VoteAverage,
                                                    movie.PosterPath, ourCasts, string.Join(",", ourGenres.ToArray()), movie2.Runtime.Value);

            return(currentMovie);
        }
Exemplo n.º 3
0
        public static List <Models.Movie> SearchMovie(string title)
        {
            try
            {
                SearchContainer <SearchMovie> results = APIConfiguration.ConnectAPI().SearchMovie("star wars");
                List <Models.Movie>           mlist   = new List <Models.Movie>();

                if (!String.IsNullOrEmpty(title))
                {
                    results = APIConfiguration.ConnectAPI().SearchMovie(title);
                }

                foreach (SearchMovie result in results.Results)
                {
                    TMDbLib.Objects.Movies.Movie trial = APIConfiguration.ConnectAPI().GetMovie(result.Id, MovieMethods.Videos);

                    Models.Movie movie = new Models.Movie()
                    {
                        MovieID = result.Id,
                        Poster  = ConfigurationManager.AppSettings["PosterPath"] + result.PosterPath,
                        Summary = result.Overview,
                        Title   = result.Title,
                        URL     = trial.Videos.Results.Count > 0 ? ConfigurationManager.AppSettings["YouTubePath"] + trial.Videos.Results[0].Key : ConfigurationManager.AppSettings["YouTubePath"]
                    };
                    mlist.Add(movie);
                }
                return(mlist);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw;
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Get the link to the youtube trailer of a movie
        /// </summary>
        /// <param name="imdbCode">The unique identifier of a movie</param>
        public Tuple <Trailers, Exception> GetMovieTrailer(string imdbCode)
        {
            Exception ex       = null;
            Trailers  trailers = new Trailers();

            TMDbClient tmDbclient = new TMDbClient(Constants.TmDbClientId);

            tmDbclient.GetConfig();

            try
            {
                TMDbLib.Objects.Movies.Movie movie = tmDbclient.GetMovie(imdbCode);
                if (movie.ImdbId != null)
                {
                    trailers = tmDbclient.GetMovieTrailers(movie.Id);
                }
                else
                {
                    ex = new Exception();
                }
            }
            catch (Exception e)
            {
                ex = e;
            }

            return(new Tuple <Trailers, Exception>(trailers, ex));
        }
Exemplo n.º 5
0
        public List <GenreModel> GetGenres(Movie m)
        {
            List <GenreModel> genres =
                m.Genres.Select(genre => new GenreModel(_context).GetItemFromKey(genre.Id.ToString())).ToList();

            return(genres);
        }
Exemplo n.º 6
0
        public ActionResult GetDetailsFromApi(int id)
        {
            if (Session["user"] == null || (Session["user"] as User).Role != Role.Admin)
            {
                return(RedirectToAction("AccessDenied", "Users"));
            }
            TMDbLib.Objects.Movies.Movie result = client.GetMovie(id, MovieMethods.Videos);
            Crew Director = client.GetMovieCredits(id).Crew.Where(crew => crew.Job == "Director").FirstOrDefault();

            result.Homepage  = "";
            result.ImdbId    = Director.Name;
            result.VoteCount = Director.Id;
            Director dbDir = db.Directors.Where(d => d.Name.ToLower().Equals(Director.Name.ToLower())).FirstOrDefault();

            if (dbDir == null)
            {
                result.Homepage = "noDirector";
            }
            else
            {
                result.Homepage = dbDir.ID.ToString();
            }

            return(this.Json(result));
        }
Exemplo n.º 7
0
        private IEnumerable <MovieBase> FetchMovie(TMDbClient client)
        {
            SearchContainer <SearchMovie> results = client.SearchMovieAsync(query: Filter).Result;
            List <MovieBase> movies = new List <MovieBase>();

            foreach (SearchMovie result in results.Results)
            {
                TMDbLib.Objects.Movies.Movie movie = client.GetMovieAsync(result.Id, MovieMethods.Videos | MovieMethods.Credits).Result;
                Crew   crew  = movie.Credits.Crew.FirstOrDefault(job => job.Job.ToLower().Contains("director"));
                Cast   cast  = movie.Credits.Cast.FirstOrDefault(x => x.Name.ToLower().Contains(this.Actor.ToLower()));;
                string actor = "";
                actor = cast?.Name;
                if (string.IsNullOrEmpty(actor))
                {
                    if (cast == null)
                    {
                        continue;
                    }
                }

                int year = Convert.ToDateTime(movie.ReleaseDate).Year;

                if (From > 0 && To > 0)
                {
                    if (!(From <= year && To >= year))
                    {
                        continue;
                    }
                }

                var tmdb_movie = new MovieBase()
                {
                    ID          = movie.Id.ToString(),
                    Title       = movie.Title,
                    KeyQuery    = Filter,
                    Description = movie.Overview,
                    ReleaseDate = Convert.ToDateTime(movie.ReleaseDate),
                    ImageURI    = client.GetImageUrl("original", movie.PosterPath).ToString(),
                    Rating      = movie.VoteAverage / 2.0,
                    Director    = crew?.Name,
                    Actor       = actor,
                    SourceType  = DataSourceType.TMDB.Description()
                };

                try
                {
                    tmdb_movie.TrailerURI = string.Format(URL.Trim() + "{0}", movie.Videos.Results.FirstOrDefault().Key);
                }
                catch
                {
                    tmdb_movie.TrailerURI = "";
                }


                movies.Add(tmdb_movie);
            }

            return(movies);
        }
Exemplo n.º 8
0
        public void AddGenres(Movie movie, MovieModel importedMovie)
        {
            List <GenreModel> genres = GetGenres(movie);

            if (genres.Any())
            {
                importedMovie.Genres = genres.AsItemIDs();
            }
        }
Exemplo n.º 9
0
 public void AddBackdrop(Movie m, MovieModel movie)
 {
     if (m.Images != null && m.Images.Backdrops != null && m.Images.Backdrops.Any())
     {
         IOrderedEnumerable <ImageData> imageDatas = m.Images.Backdrops.OrderByDescending(i => i.VoteAverage);
         Guid posterId = AddImage(imageDatas.First());
         movie.Backdrop = GlassExtensions.GetImage(posterId, movie.Title);
     }
 }
Exemplo n.º 10
0
        public void Add(Movie m)
        {
            if (m == null)
            {
                return;
            }
            MovieModel movie = Mapper.Map <MovieModel>(m);

            movie.Save(_moviesRootFolder, _masterService);
        }
Exemplo n.º 11
0
        public void AddCrewToMovie(Movie movie, IMovie importedMovie)
        {
            List <Crew> crew = movie.Credits.Crew;

            if (crew.Any())
            {
                IEnumerable <ICrewMember> crewMembers = AddCrew(crew);
                importedMovie.Crews = crewMembers.AsItemIDs();
            }
        }
Exemplo n.º 12
0
        public void AddCastToMovie(Movie movie, IMovie importedMovie)
        {
            List <Cast> cast = movie.Credits.Cast;

            if (cast.Any())
            {
                IEnumerable <ICastMember> castMembers = AddCast(cast);
                importedMovie.Casts = castMembers.AsItemIDs();
            }
        }
Exemplo n.º 13
0
        public EntryInformation(int entryId)
        {
            this.entryId = entryId;

            //Media Api
            apiKey = "24db2192e9447969b597b0a6823f7e8e";
            client = new TMDbClient(apiKey);
            movie  = client.GetMovieAsync(entryId, MovieMethods.Credits).Result;
            tvshow = client.GetTvShowAsync(entryId, TvShowMethods.Credits).Result;
        }
Exemplo n.º 14
0
 private TMDbLib.Objects.Movies.Movie getCasts(int movieId)
 {
     try {
         TMDbLib.Objects.Movies.Movie casts = client.GetMovieAsync(movieId, MovieMethods.Credits | MovieMethods.Videos).Result;
         return(casts);
     }
     catch (AggregateException e)
     {
         throw e;
     }
 }
Exemplo n.º 15
0
        private static string GetYoutubeTrailer(TMDbLibMovies.Movie tmdbMovie)
        {
            var youtubeTrailer = string.Empty;

            if (tmdbMovie?.Videos.Results != null)
            {
                var youTubeId = tmdbMovie.Videos.Results.FirstOrDefault(video => video.Site == "YouTube" && video.Type == "Trailer")?.Key;
                if (youTubeId != null)
                {
                    youtubeTrailer = "https://www.youtube.com/watch?v=" + youTubeId;
                }
            }

            return(youtubeTrailer);
        }
Exemplo n.º 16
0
        public DetailedFilm GetMovie(Film film)
        {
            DetailedFilm detailedFilm = new DetailedFilm(film);

            TMDbLib.Objects.Movies.Movie movie = WaitForItDAL.Singleton.GetMovieFullDetails(film.Id);

            detailedFilm.Duree       = TimeSpan.FromMinutes(movie.Runtime ?? 0);
            detailedFilm.Genres      = string.Join(" / ", movie.Genres.Select(i => i.Name).ToArray());
            detailedFilm.Realisateur = movie.Credits.Crew.Find(i => i.Job == "Director")?.Name;
            detailedFilm.Acteurs     = string.Join(System.Environment.NewLine, movie.Credits.Cast.Select(i => i.Name).Take(4).ToArray());
            detailedFilm.VoteAverage = movie.VoteAverage;
            detailedFilm.VoteCount   = movie.VoteCount;


            return(detailedFilm);
        }
Exemplo n.º 17
0
        private MovieConnector.Movie addMovieToDatabase(SearchMovie movie)
        {
            if (dbController.checkIfMovieInDatabase(movie.Id))
            {
                currentMovie = dbController.getMovieContent(movie.Id);
            }
            else
            {
                TMDbLib.Objects.Movies.Movie movie2 = client.GetMovieAsync(movie.Id).Result;
                List <Genre>  genres    = movie2.Genres;
                List <string> ourGenres = new List <string>();

                TMDbLib.Objects.Movies.Movie casts;

                foreach (Genre genre in genres)
                {
                    ourGenres.Add(genre.Name);
                }

                currentMovie = dbController.insertToMovie(movie.Id, movie.Title, movie.Overview, movie.ReleaseDate.Value, movie.VoteAverage,
                                                          movie.PosterPath, string.Join(",", ourGenres.ToArray()), movie2.Runtime.Value);

                try
                {
                    casts = getCasts(movie.Id);
                    int castCount = casts.Credits.Cast.Capacity;
                    if (castCount > 5)
                    {
                        castCount = 5;
                    }
                    for (int i = 0; i < castCount; i++)
                    {
                        if (!dbController.checkIfCastInDatabase(casts.Credits.Cast[i].Id))
                        {
                            dbController.insertToCast(casts.Credits.Cast[i].Id, casts.Credits.Cast[i].Character, casts.Credits.Cast[i].Name, casts.Credits.Cast[i].ProfilePath);
                        }
                        dbController.insertCastToMovie(movie.Id, casts.Credits.Cast[i].Id);
                    }
                }
                catch (Exception e) { }
            }
            return(currentMovie);
        }
        public bool Populate(Movie movie, ImagesWithId imgs)
        {
            try
            {
                Images = new List<MovieDB_Image_Result>();

                MovieID = movie.Id;
                MovieName = movie.Title;
                OriginalName = movie.Title;
                Overview = movie.Overview;

                if (imgs != null && imgs.Backdrops != null)
                {
                    foreach (ImageData img in imgs.Backdrops)
                    {
                        MovieDB_Image_Result imageResult = new MovieDB_Image_Result();
                        if (imageResult.Populate(img, "backdrop"))
                            Images.Add(imageResult);
                    }
                }

                if (imgs != null && imgs.Posters != null)
                {
                    foreach (ImageData img in imgs.Posters)
                    {
                        MovieDB_Image_Result imageResult = new MovieDB_Image_Result();
                        if (imageResult.Populate(img, "poster"))
                            Images.Add(imageResult);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error( ex,ex.ToString());
                return false;
            }

            return true;
        }
Exemplo n.º 19
0
        public async Task <int> IMDB()
        {
            var              IMDB    = new TMDbClient("2c54085e8a7f520650d65cb78a48555a");
            OMDbClient       omdb    = new OMDbClient(true);
            int              counter = 0;
            List <BLL.Movie> rez     = new List <BLL.Movie>();

            // 54001
            for (int j = 64852; j <= 624852; j += 100)
            {
                for (int i = j; i < j + 100; i++)
                {
                    TMDbLib.Objects.Movies.Movie pom = new TMDbLib.Objects.Movies.Movie();
                    try
                    {
                        pom = await IMDB.GetMovieAsync(i, MovieMethods.Credits | MovieMethods.Similar | MovieMethods.Videos | MovieMethods.Reviews | MovieMethods.Keywords);

                        if (pom.ImdbId != "" && pom.ImdbId != null && pom.ImdbId.Length > 0)
                        {
                            var newMovie = new BLL.Movie
                            {
                                IMDbId      = pom.ImdbId,
                                Id          = pom.Id,
                                Title       = pom.Title,
                                Runtime     = pom.Runtime,
                                Credits     = pom.Credits,
                                Genres      = pom.Genres,
                                Keywords    = pom.Keywords,
                                Overview    = pom.Overview,
                                Popularity  = pom.Popularity,
                                PosterPath  = pom.PosterPath,
                                ReleaseDate = pom.ReleaseDate,
                                Reviews     = pom.Reviews,
                                Similar     = pom.Similar,
                                Status      = pom.Status,
                                Videos      = pom.Videos,
                                VoteAverage = pom.VoteAverage,
                                VoteCount   = pom.VoteCount
                            };
                            newMovie = movieRepo.OMDbData(newMovie);
                            newMovie = movieRepo.SubtitleData(newMovie);
                            rez.Add(newMovie);
                        }
                    }
                    catch
                    {
                        if (rez != null && rez.Count > 0)
                        {
                            baza.saveMovies(rez);
                            rez = new List <BLL.Movie>();
                        }
                    }
                }
                if (rez.Count > 0)
                {
                    baza.saveMovies(rez);
                    rez = new List <BLL.Movie>();
                }

                counter = j;
            }
            return(counter);
        }
Exemplo n.º 20
0
        public async Task <MovieMetadata> GetTmdbMetadataAsync(int tmdbId)
        {
            TMDbLib.Objects.Movies.Movie movie = null;
            Directory.CreateDirectory(this.AppSettings.TmdbCacheDirectoryPath);
            var cacheFilePath = $"{this.AppSettings.TmdbCacheDirectoryPath}/{tmdbId}.json";

            //if a cache file exists, and it's was updated less than a month ago, use it.
            if (File.Exists(cacheFilePath) && (DateTime.Now - File.GetLastWriteTime(cacheFilePath)).TotalDays < 30)
            {
                try
                {
                    movie = Newtonsoft.Json.JsonConvert.DeserializeObject <TMDbLib.Objects.Movies.Movie>(File.ReadAllText(cacheFilePath));
                }
                catch (Exception)
                {
                }
            }
            //if the movie could not be loaded from cache, retrieve a fresh copy from TMDB
            if (movie == null)
            {
                //only allow one thread to use the client at a time
                lock (Client)
                {
                    movie = Client.GetMovieAsync(tmdbId,
                                                 MovieMethods.AlternativeTitles |
                                                 MovieMethods.Credits |
                                                 MovieMethods.Images |
                                                 MovieMethods.Keywords |
                                                 MovieMethods.Releases |
                                                 MovieMethods.ReleaseDates |
                                                 MovieMethods.Videos
                                                 ).Result;
                }
                //save this result to disc
                var camelCaseFormatter = new JsonSerializerSettings();
                camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
                camelCaseFormatter.Formatting       = Formatting.Indented;

                var json = Newtonsoft.Json.JsonConvert.SerializeObject(movie, camelCaseFormatter);
                await File.WriteAllTextAsync(cacheFilePath, json);
            }

            var metadata = new MovieMetadata();

            metadata.AddCast(movie.Credits?.Cast);
            metadata.AddCrew(movie.Credits?.Crew);
            metadata.Collection = movie.BelongsToCollection?.Name;
            metadata.Summary    = movie.Overview;
            metadata.Genres     = movie.Genres?.Select(x => x.Name).ToList();
            metadata.Keywords   = movie.Keywords?.Keywords?.Select(x => x.Name).ToList();
            var release = movie.Releases?.Countries
                          ?.Where(x => x.Iso_3166_1.ToLower() == "us")
                          ?.OrderBy(x => x.ReleaseDate)
                          ?.First();

            //get the oldest US rating
            metadata.Rating      = release?.Certification;
            metadata.ReleaseYear = release?.ReleaseDate?.Year;
            //conver the runtime to seconds
            metadata.RuntimeSeconds = movie.Runtime * 60;
            metadata.Summary        = movie.Overview;
            metadata.Title          = movie.Title;
            metadata.SortTitle      = movie.Title;

            metadata.ExtraSearchText.AddRange(
                movie.AlternativeTitles?.Titles?.Where(x => x.Iso_3166_1.ToLower() == "us").Select(x => x.Title).ToList() ?? new List <string>()
                );
            metadata.ExtraSearchText.Add(movie.OriginalTitle);

            metadata.ExtraSearchText = metadata.ExtraSearchText.Distinct().ToList();

            metadata.TmdbId = movie.Id;


            if (movie.PosterPath != null)
            {
                metadata.PosterUrls.Add(Client.GetImageUrl("original", movie.PosterPath).ToString());
            }
            metadata.PosterUrls.AddRange(
                movie.Images?.Posters
                ?.Where(x => x.Iso_639_1?.ToLower() == "en")
                ?.Select(x => Client.GetImageUrl("original", x.FilePath).ToString())
                ?.ToList() ?? new List <string>()
                );
            metadata.PosterUrls = metadata.PosterUrls.Distinct().ToList();


            //add the marked backdrop path first
            if (movie.BackdropPath != null)
            {
                metadata.BackdropUrls.Add(Client.GetImageUrl("original", movie.BackdropPath).ToString());
            }
            //add all additional backdrops
            metadata.BackdropUrls.AddRange(
                movie.Images?.Backdrops
                //move the highest rated backdrops to the top
                ?.OrderByDescending(x => x.VoteAverage)
                ?.Where(x => x.Iso_639_1?.ToLower() == "en" || x.Iso_639_1 == null)
                ?.Select(x => Client.GetImageUrl("original", x.FilePath).ToString())
                ?.ToList() ?? new List <string>()
                );
            metadata.BackdropUrls = metadata.BackdropUrls.Distinct().ToList();
            return(metadata);
        }
Exemplo n.º 21
0
        public WriteMovieInfoToXML(Movie movie, string folder)
        {
            TMDbClient client = new TMDbClient("a8fab4f9461636422a8df05bf17065a8");
            var actors = movie.Credits.Cast;
            var crews = movie.Credits.Crew;
            string _year;

            string[] files = Directory.GetFiles(folder, "*", SearchOption.TopDirectoryOnly);
            List<string> videoFiles = new List<string>();
            foreach (var file in files)
            {
                if (file.EndsWith(".mp4"))
                {
                    videoFiles.Add(file);
                }
                if (file.EndsWith(".mkv"))
                {
                    videoFiles.Add(file);
                }
                if (file.EndsWith(".avi"))
                {
                    videoFiles.Add(file);
                }
            }
            string nfile = null;
            if (videoFiles.Count == 1)
            {
                int index = videoFiles[0].LastIndexOf("\\");
                nfile = videoFiles[0].Substring(index + 1);
                Console.WriteLine(nfile);
            }

            if (movie.ReleaseDate != null)
            {
                _year = ((DateTime)movie.ReleaseDate).Year.ToString();
            }
            else
            {
                _year = "Unkown year";
            }
            var settings = new XmlWriterSettings
            {
                Indent = true,
                OmitXmlDeclaration = true,
                NewLineOnAttributes = true
            };
            using (XmlWriter writer = XmlWriter.Create(folder + "\\"+ nfile.Substring(0,nfile.Length-4) + ".nfo", settings))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("movie");
                writer.WriteElementString("title", movie.Title);
                writer.WriteElementString("originaltitle", movie.OriginalTitle);
                writer.WriteElementString("rating", movie.VoteAverage.ToString());
                writer.WriteElementString("votes", movie.VoteCount.ToString());
                writer.WriteElementString("year", _year);
                writer.WriteElementString("plot", movie.Overview);
                writer.WriteElementString("tagline", movie.Tagline);
                writer.WriteElementString("runtime", movie.Runtime.ToString());
                writer.WriteElementString("thumb", "https://image.tmdb.org/t/p/original" + movie.PosterPath);
                writer.WriteElementString("filenameandpath", folder + "\\" + nfile);
                foreach (var genre in movie.Genres)
                {
                    writer.WriteElementString("genre", genre.Name);
                }
                foreach (var actor in actors)
                {
                    writer.WriteStartElement("actor");
                    writer.WriteElementString("name", actor.Name);
                    writer.WriteElementString("role", actor.Character);
                    writer.WriteEndElement();
                }
                foreach (var crew in crews)
                {
                    writer.WriteStartElement("crew");
                    writer.WriteElementString("name", crew.Name);
                    writer.WriteElementString("job", crew.Job);
                    writer.WriteEndElement();
                }
                writer.WriteElementString("dateadded", DateTime.Now.ToString());
                writer.WriteEndElement();
                writer.WriteEndDocument();
            }
        }
Exemplo n.º 22
0
 public void AddProductionCompany(Movie m, MovieModel movie)
 {
     AddProductionCompany(m.ProductionCompanies, movie);
 }
Exemplo n.º 23
0
        public void cacheVideo(Movie movie)
        {
            try
            {
                
                /*
                //check if exists
                bool exists = false;
               // var movieJson = Newtonsoft.Json.JsonConvert.SerializeObject(movie);
                string line;
               // StreamReader file = new StreamReader(videosCache);
               // while ((line = file.ReadLine()) != null)
                {
                    var myLine = Newtonsoft.Json.JsonConvert.SerializeObject(line);
                    if (myLine == movieJson)
                        exists = true;
                }
                file.Dispose();
                if (!exists) {
                    using (System.IO.StreamWriter file2 = new System.IO.StreamWriter(videosCache))
                    {
                        file2.WriteLine(movieJson);
                    }
                }
                */
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }

        }
Exemplo n.º 24
0
        public override MetadataFileResult MovieMetadata(Movie movie, MovieFile movieFile)
        {
            var xmlResult = string.Empty;

            if (Settings.MovieMetadata)
            {
                _logger.Debug("Generating Movie Metadata for: {0}", Path.Combine(movie.Path, movieFile.RelativePath));

                var movieMetadataLanguage    = (Settings.MovieMetadataLanguage == (int)Language.Original) ? (int)movie.OriginalLanguage : Settings.MovieMetadataLanguage;
                var selectedSettingsLanguage = Language.FindById(movieMetadataLanguage);
                var isoLanguage = IsoLanguages.Get(selectedSettingsLanguage);
                var isoLanguageTwoLetterCode = isoLanguage.TwoLetterCode;
                var countryCode = isoLanguage.CountryCode;

                if (TmdbClient == null)
                {
                    TmdbClient = new TMDbClient(Settings.ApiKey)
                    {
                        DefaultCountry     = countryCode,
                        DefaultLanguage    = isoLanguageTwoLetterCode,
                        ThrowApiExceptions = true
                    };
                }

                var extraMethods =
                    TMDbLibMovies.MovieMethods.Credits |
                    TMDbLibMovies.MovieMethods.Releases |
                    TMDbLibMovies.MovieMethods.Videos;

                TMDbLibMovies.Movie tmdbMovie = null;
                try
                {
                    tmdbMovie = TmdbClient.GetMovieAsync(movie.TmdbId, extraMethods).Result;
                }
                catch (Exception exception)
                {
                    _logger.Error(exception, "Fail to obtain Tmdb Movie Metadata for: {0}", Path.Combine(movie.Path, movieFile.RelativePath));
                }

                Collection tmdbMovieCollection = null;
                if (tmdbMovie.BelongsToCollection != null)
                {
                    try
                    {
                        tmdbMovieCollection = TmdbClient.GetCollectionAsync(tmdbMovie.BelongsToCollection.Id).Result;
                    }
                    catch (Exception exception)
                    {
                        _logger.Error(exception, "Fail to obtain Tmdb Movie Collection Metadata for: {0}", Path.Combine(movie.Path, movieFile.RelativePath));
                    }
                }

                var sb  = new StringBuilder();
                var xws = new XmlWriterSettings
                {
                    OmitXmlDeclaration = false,
                    Encoding           = Encoding.UTF8,
                    Indent             = false
                };

                if (tmdbMovie != null)
                {
                    using (var xw = XmlWriter.Create(sb, xws))
                    {
                        var doc = new XDocument();

                        var details = new XElement("movie");

                        details.Add(new XElement("title", tmdbMovie.Title));

                        details.Add(new XElement("originaltitle", tmdbMovie.OriginalTitle));

                        details.Add(new XElement("sorttitle", tmdbMovie.Title.ToLowerInvariant()));

                        if (tmdbMovie.VoteAverage > 0)
                        {
                            var setRating         = new XElement("ratings");
                            var setRatethemoviedb = new XElement("rating", new XAttribute("name", "themoviedb"), new XAttribute("max", "10"), new XAttribute("default", "true"));
                            setRatethemoviedb.Add(new XElement("value", tmdbMovie.VoteAverage));
                            setRatethemoviedb.Add(new XElement("votes", tmdbMovie.VoteCount));
                            setRating.Add(setRatethemoviedb);
                            details.Add(setRating);
                        }

                        details.Add(new XElement("rating", tmdbMovie.VoteAverage));

                        details.Add(new XElement("top250"));

                        var outlineEndPosition = tmdbMovie.Overview.IndexOf(". ");
                        details.Add(new XElement("outline", tmdbMovie.Overview.Substring(0, outlineEndPosition > 0 ? outlineEndPosition + 1 : tmdbMovie.Overview.Length)));

                        details.Add(new XElement("plot", tmdbMovie.Overview));

                        details.Add(new XElement("tagline", tmdbMovie.Tagline));

                        details.Add(new XElement("runtime", tmdbMovie.Runtime));

                        if (tmdbMovie.PosterPath != null)
                        {
                            details.Add(new XElement("thumb", new XAttribute("aspect", CoverType.poster), new XAttribute("preview", BaseImageUrl + "/w185" + tmdbMovie.PosterPath), BaseImageUrl + "/original" + tmdbMovie.PosterPath));
                        }

                        if (Settings.FanartApiKey.IsNotNullOrWhiteSpace())
                        {
                            string content = null;

                            try
                            {
                                var fanartRequest  = new HttpRequest($"http://webservice.fanart.tv/v3/movies/{movie.TmdbId}?api_key={Settings.FanartApiKey}", HttpAccept.Json);
                                var fanartResponse = _client.Execute(fanartRequest);

                                content = fanartResponse.Content;
                            }
                            catch (Exception e)
                            {
                                _logger.Error(e, "Can't obtain data from Fanart for Movie: {0}", Path.Combine(movie.Path, movieFile.RelativePath));
                            }

                            if (content.IsNotNullOrWhiteSpace())
                            {
                                var originalLanguageTwoLetterCode = tmdbMovie.OriginalLanguage;
                                var fanartMovie = Json.Deserialize <FanartMovie>(content);

                                if (fanartMovie != null)
                                {
                                    var moviebanner = GetBestOptionForFanartMovieArt(fanartMovie.moviebanner, isoLanguageTwoLetterCode, originalLanguageTwoLetterCode);
                                    if (moviebanner != null)
                                    {
                                        details.Add(new XElement("thumb", new XAttribute("aspect", CoverType.banner), new XAttribute("preview", moviebanner.url.Replace("/fanart/", "/preview/")), moviebanner.url));
                                    }

                                    var hdmovieclearart = GetBestOptionForFanartMovieArt(fanartMovie.hdmovieclearart, isoLanguageTwoLetterCode, originalLanguageTwoLetterCode);
                                    if (hdmovieclearart != null)
                                    {
                                        details.Add(new XElement("thumb", new XAttribute("aspect", CoverType.clearart), new XAttribute("preview", hdmovieclearart.url.Replace("/fanart/", "/preview/")), hdmovieclearart.url));
                                    }

                                    var hdmovielogo = GetBestOptionForFanartMovieArt(fanartMovie.hdmovielogo, isoLanguageTwoLetterCode, originalLanguageTwoLetterCode);
                                    if (hdmovielogo != null)
                                    {
                                        details.Add(new XElement("thumb", new XAttribute("aspect", CoverType.clearlogo), new XAttribute("preview", hdmovielogo.url.Replace("/fanart/", "/preview/")), hdmovielogo.url));
                                    }

                                    if (fanartMovie.moviedisc != null)
                                    {
                                        var moviedisc = GetBestOptionForFanartMovieArt(fanartMovie.moviedisc.Cast <FanartMovieArt>().ToList(), isoLanguageTwoLetterCode, originalLanguageTwoLetterCode);
                                        if (moviedisc != null)
                                        {
                                            details.Add(new XElement("thumb", new XAttribute("aspect", CoverType.discart), new XAttribute("preview", moviedisc.url.Replace("/fanart/", "/preview/")), moviedisc.url));
                                        }
                                    }

                                    var moviethumb = GetBestOptionForFanartMovieArt(fanartMovie.moviethumb, isoLanguageTwoLetterCode, originalLanguageTwoLetterCode);
                                    if (moviethumb != null)
                                    {
                                        details.Add(new XElement("thumb", new XAttribute("aspect", CoverType.landscape), new XAttribute("preview", moviethumb.url.Replace("/fanart/", "/preview/")), moviethumb.url));
                                    }
                                }
                            }
                        }

                        if (tmdbMovie.BackdropPath != null)
                        {
                            details.Add(new XElement("fanart", new XElement("thumb", new XAttribute("preview", BaseImageUrl + "/w300" + tmdbMovie.BackdropPath), BaseImageUrl + "/original" + tmdbMovie.BackdropPath)));
                        }

                        if (tmdbMovie.Releases?.Countries != null)
                        {
                            var releases   = tmdbMovie.Releases.Countries.Where(i => !string.IsNullOrWhiteSpace(i.Certification)).ToList();
                            var ourRelease = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, isoLanguageTwoLetterCode, StringComparison.OrdinalIgnoreCase));
                            var usRelease  = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, "US", StringComparison.OrdinalIgnoreCase));

                            if (ourRelease != null)
                            {
                                var ratingPrefix = string.Equals(isoLanguageTwoLetterCode, "US", StringComparison.OrdinalIgnoreCase) ? string.Empty : isoLanguageTwoLetterCode.ToUpperInvariant() + "-";
                                var newRating    = ratingPrefix + ourRelease.Certification.Replace("DE-", "FSK-");

                                details.Add(new XElement("mpaa", newRating));
                            }
                            else if (usRelease != null)
                            {
                                details.Add(new XElement("mpaa", usRelease.Certification));
                            }
                        }

                        var uniqueId = new XElement("uniqueid", tmdbMovie.Id);
                        uniqueId.SetAttributeValue("type", "tmdb");
                        uniqueId.SetAttributeValue("default", true);
                        details.Add(uniqueId);
                        details.Add(new XElement("tmdbid", tmdbMovie.Id));

                        if (tmdbMovie.ImdbId.IsNotNullOrWhiteSpace())
                        {
                            var imdbId = new XElement("uniqueid", tmdbMovie.ImdbId);
                            imdbId.SetAttributeValue("type", "imdb");
                            details.Add(imdbId);
                            details.Add(new XElement("imdbid", tmdbMovie.ImdbId));
                        }

                        foreach (var genre in tmdbMovie.Genres)
                        {
                            details.Add(new XElement("genre", genre.Name));
                        }

                        foreach (var country in tmdbMovie.ProductionCountries)
                        {
                            details.Add(new XElement("country", country.Name));
                        }

                        if (tmdbMovieCollection != null)
                        {
                            details.Add(new XElement("collectionnumber", tmdbMovieCollection.Id));

                            var setElement = new XElement("set");
                            setElement.SetAttributeValue("tmdbcolid", tmdbMovieCollection.Id);

                            setElement.Add(new XElement("name", tmdbMovieCollection.Name));
                            setElement.Add(new XElement("overview", tmdbMovieCollection.Overview));

                            details.Add(setElement);
                        }

                        foreach (var writer in tmdbMovie.Credits.Crew.Where(crew => (crew.Job == "Screenplay" || crew.Job == "Story" || crew.Job == "Novel" || crew.Job == "Writer") && crew.Name.IsNotNullOrWhiteSpace()))
                        {
                            details.Add(new XElement("credits", writer.Name));
                        }

                        foreach (var director in tmdbMovie.Credits.Crew.Where(crew => crew.Job == "Director" && crew.Name.IsNotNullOrWhiteSpace()))
                        {
                            details.Add(new XElement("director", director.Name));
                        }

                        if (tmdbMovie.ReleaseDate.HasValue)
                        {
                            details.Add(new XElement("releasedate", tmdbMovie.ReleaseDate.Value.ToString("yyyy-MM-dd")));
                            details.Add(new XElement("premiered", tmdbMovie.ReleaseDate.Value.ToString("yyyy-MM-dd")));
                            details.Add(new XElement("year", tmdbMovie.ReleaseDate.Value.Year));
                        }

                        details.Add(new XElement("status", tmdbMovie.Status));

                        foreach (var company in tmdbMovie.ProductionCompanies)
                        {
                            details.Add(new XElement("studio", company.Name));
                        }

                        details.Add(new XElement("trailer", GetYoutubeTrailer(tmdbMovie)));

                        if (movieFile.MediaInfo != null)
                        {
                            var sceneName = movieFile.GetSceneOrFileName();

                            var fileInfo      = new XElement("fileinfo");
                            var streamDetails = new XElement("streamdetails");

                            var video = new XElement("video");
                            video.Add(new XElement("aspect", movieFile.MediaInfo.Width / movieFile.MediaInfo.Height));
                            video.Add(new XElement("bitrate", movieFile.MediaInfo.VideoBitrate));
                            video.Add(new XElement("codec", MediaInfoFormatter.FormatVideoCodec(movieFile.MediaInfo, sceneName)));
                            video.Add(new XElement("framerate", movieFile.MediaInfo.VideoFps));
                            video.Add(new XElement("height", movieFile.MediaInfo.Height));
                            video.Add(new XElement("scantype", movieFile.MediaInfo.ScanType));
                            video.Add(new XElement("width", movieFile.MediaInfo.Width));

                            if (movieFile.MediaInfo.RunTime != default)
                            {
                                video.Add(new XElement("duration", movieFile.MediaInfo.RunTime.TotalMinutes));
                                video.Add(new XElement("durationinseconds", Math.Round(movieFile.MediaInfo.RunTime.TotalSeconds)));
                            }

                            streamDetails.Add(video);

                            var audio             = new XElement("audio");
                            var audioChannelCount = movieFile.MediaInfo.AudioChannels;
                            audio.Add(new XElement("bitrate", movieFile.MediaInfo.AudioBitrate));
                            audio.Add(new XElement("channels", audioChannelCount));
                            audio.Add(new XElement("codec", MediaInfoFormatter.FormatAudioCodec(movieFile.MediaInfo, sceneName)));
                            audio.Add(new XElement("language", movieFile.MediaInfo.AudioLanguages));
                            streamDetails.Add(audio);

                            if (movieFile.MediaInfo.Subtitles != null && movieFile.MediaInfo.Subtitles.Count > 0)
                            {
                                var subtitle = new XElement("subtitle");
                                subtitle.Add(new XElement("language", movieFile.MediaInfo.Subtitles));
                                streamDetails.Add(subtitle);
                            }

                            fileInfo.Add(streamDetails);
                            details.Add(fileInfo);

                            foreach (var cast in tmdbMovie.Credits.Cast)
                            {
                                if (cast.Name.IsNotNullOrWhiteSpace() && cast.Character.IsNotNullOrWhiteSpace())
                                {
                                    var actorElement = new XElement("actor");

                                    actorElement.Add(new XElement("name", cast.Name));
                                    actorElement.Add(new XElement("role", cast.Character));
                                    actorElement.Add(new XElement("order", cast.Order));

                                    if (cast.ProfilePath.IsNotNullOrWhiteSpace())
                                    {
                                        actorElement.Add(new XElement("thumb", BaseImageUrl + "/original" + cast.ProfilePath));
                                    }

                                    details.Add(actorElement);
                                }
                            }

                            details.Add(new XElement("dateadded", movieFile.DateAdded.ToString("s")));
                        }

                        doc.Add(details);
                        doc.Save(xw);

                        xmlResult += doc.ToString();
                        xmlResult += Environment.NewLine;
                    }
                }
            }

            if (Settings.MovieMetadataURL)
            {
                xmlResult += "https://www.themoviedb.org/movie/" + movie.TmdbId;
                xmlResult += Environment.NewLine;

                xmlResult += "https://www.imdb.com/title/" + movie.ImdbId;
                xmlResult += Environment.NewLine;
            }

            var metadataFileName = GetMovieMetadataFilename(movieFile.RelativePath);

            return(string.IsNullOrEmpty(xmlResult) ? null : new MetadataFileResult(metadataFileName, xmlResult.Trim(Environment.NewLine.ToCharArray())));
        }
Exemplo n.º 25
0
        public void Add(int id)
        {
            Movie movie = Get(id);

            Add(movie);
        }
Exemplo n.º 26
0
 public MovieModel GetMappedMovie(Movie movie)
 {
     return(Mapper.Map <MovieModel>(movie));
 }
Exemplo n.º 27
0
 public List <Cast> GetCast(Movie movie)
 {
     return(GetCast(movie.Id));
 }
Exemplo n.º 28
0
        /// <summary>
        /// Download the movie background image
        /// </summary>
        /// <param name="imdbCode">The unique identifier of a movie</param>
        /// <param name="cancellationToken">cancellationToken</param>
        public async Task <Tuple <string, IEnumerable <Exception> > > DownloadMovieBackgroundImageAsync(string imdbCode,
                                                                                                        CancellationTokenSource cancellationToken)
        {
            List <Exception> ex = new List <Exception>();
            string           backgroundImage = String.Empty;

            TMDbClient tmDbclient = new TMDbClient(Constants.TmDbClientId);

            tmDbclient.GetConfig();

            try
            {
                TMDbLib.Objects.Movies.Movie movie = tmDbclient.GetMovie(imdbCode, MovieMethods.Images);
                if (movie.ImdbId != null)
                {
                    Uri imageUri = tmDbclient.GetImageUrl(Constants.BackgroundImageSizeTmDb,
                                                          movie.Images.Backdrops.Aggregate((i1, i2) => i1.VoteAverage > i2.VoteAverage ? i1 : i2).FilePath);

                    try
                    {
                        Tuple <string, Exception> res =
                            await
                            DownloadFileAsync(imdbCode, imageUri, Constants.FileType.BackgroundImage,
                                              cancellationToken.Token);

                        if (res != null)
                        {
                            if (res.Item2 == null)
                            {
                                backgroundImage = Constants.BackgroundMovieDirectory + imdbCode +
                                                  Constants.ImageFileExtension;
                            }
                            else
                            {
                                ex.Add(res.Item2);
                            }
                        }
                        else
                        {
                            ex.Add(new Exception());
                        }
                    }
                    catch (WebException webException)
                    {
                        ex.Add(webException);
                    }
                    catch (TaskCanceledException e)
                    {
                        ex.Add(e);
                    }
                }
                else
                {
                    ex.Add(new Exception());
                }
            }
            catch (Exception e)
            {
                ex.Add(e);
            }

            return(new Tuple <string, IEnumerable <Exception> >(backgroundImage, ex));
        }
Exemplo n.º 29
0
        private void addToMyVideos(string Name, string Year, string Season, string Episode)
        {

            this.labelTotalMyVideos.Invoke(new UIUpdaterDelegate(() =>
            {
                this.labelTotalMyVideos.Text = "My Videos: " + MoviesManager.MyMoviesCount.ToString();
            }));

            TMDbLib.Objects.Movies.Movie aMovie = new TMDbLib.Objects.Movies.Movie();
            Name = MovieCleaner.justMovieName(Name, Year);
            aMovie = MyMovie.loadTMDbLib(Name);
            if (MyMovie.lastImage != null)
            {
                //MyMoviesCollection.Add(aMovie);
                if (aMovie != null)
                {
                    if (!File.Exists(MySettings + "//cache//"))
                        AddOneEntryToMyVideos(aMovie, MyMovie.lastImage);
                }
                else
                    return;
            }
            /*


            Season = Season.Replace("S", "");
            Episode = Episode.Replace("E", "");
            if (Season == "")
                Season = "01";
            string RunTime = "";
            string Rating = "";
            string Title = "";
            string Description = "";
            string SmallImage = "";
            string RegularImage =  "http://blogs.ncs-nj.org/k4stemlab/files/2013/04/image-unavailable.jpg";
            string URL = "";
            string number = "";
            string IMDBRating = "";
            string ComingSoon = "";
            string TheaterStatus = "";
            string Trailers = "";
            string TheAirDate = "";
            string TheEpisodeTitle = "";
            string SeasonCover = "";
            Int32 theYear = 0;
            string Genres = "";
            if (Episode == "")
                Episode = "0";

            Name = MovieCleaner.justMovieName(Name, Year);
            //locate the movie in the database 
            string postInfo = "Title=" + Name + "&Submit=QueryMovie";
            HTTP http = new HTTP();
            string response = http.DoPOST("https://secure2025.hostgator.com/~czzplnm/moviemanager.php", postInfo);

            string[] Data = response.Split('|');

            if (Data.Length >= 13)
            {
                createMyMovie(Data[5], Data[8], Data[2], Data[4], Convert.ToInt32(Data[3]), Convert.ToInt16(Data[0]), Data[7], Data[6], Data[1], Data[12], Data[11], Data[10], Data[9], Data[13], TheEpisodeTitle, TheAirDate, 0, 0, SeasonCover);
                this.labelTotalMyVideos.Invoke(new UIUpdaterDelegate(() =>
                    {
                        this.labelTotalMyVideos.Text = "My Videos: " + MoviesManager.MyMoviesCount.ToString();
                    }));
            }*/
            //aMovie.loadConfig();//search moviedb
            //  if (!aMovie.loadMyMovieFromFile(Name, Year, Season, Episode))
            //  {
            //  aMovie.loadTMDbLib(Name, this);
            //aMovie.loadMovieDB(Name);
            /*
            if (!aMovie.loadOMDB(Name))
            {

                if(!aMovie.loadTvShowID(Name))       
                    aMovie.loadMovieID(Name);




            }
            */


            //}
            /*
            if (checkBoxIgnoreMovies.Checked)
                if (aMovie.movieType == MyMovie.mType.themoviedbMovie)
                    return;

            if (checkBoxIgnoreTVShows.Checked)
                if (aMovie.movieType == MyMovie.mType.themoviedbTV)
                    return;
                        

            if (aMovie.Image != null)
            {
                MyMoviesCollection.Add(aMovie);
                AddOneEntryToMyVideos(aMovie);
            }
                  */

            /*
             
                JToken titleToken = token.SelectToken("Title");
                if (titleToken != null)
                {
                    Title = titleToken.ToString();
                    int itemYear = (int)token.SelectToken("Year");
                }
                Int16 IntSeason = Convert.ToInt16(Season);
                Int16 IntEpisode = Convert.ToInt16(Episode);
            */
            //   createMyMovie(SmallImage, number, Title, Description, MoviesManager.CleanYear(theYear.ToString()), MoviesManager.CleanRuntime(RunTime), URL, RegularImage, Rating, TheaterStatus, ComingSoon, IMDBRating, Genres, Trailers, TheEpisodeTitle, TheAirDate, IntSeason, IntEpisode, SeasonCover);

        }
Exemplo n.º 30
0
 public List <Crew> GetCrew(Movie movie)
 {
     return(GetCrew(movie.Id));
 }
Exemplo n.º 31
0
 public void AddTrailers(Movie m, MovieModel movie)
 {
     AddTrailers(m.Trailers, movie);
 }