GetSourceMovieInfo() публичный Метод

public GetSourceMovieInfo ( DBSourceInfo source ) : DBSourceMovieInfo
source DBSourceInfo
Результат DBSourceMovieInfo
        public bool GetArtwork(DBMovieInfo movie)
        {
            string myVideoCoversFolder = Config.GetFolder(Config.Dir.Thumbs) + "\\Videos\\Title";

            Regex cleaner = new Regex("[\\\\/:*?\"<>|]");
            string cleanTitle = cleaner.Replace(movie.Title, "_");
            string id = movie.GetSourceMovieInfo(SourceInfo).Identifier;
            string filename = myVideoCoversFolder + "\\" + cleanTitle + "{" + id + "}L.jpg";

            if (System.IO.File.Exists(filename))
                return movie.AddCoverFromFile(filename);

            return false;
        }
        private List<DBMovieInfo> getMoviesByTitle(string title)
        {
            int popularity = 100;

            List<DBMovieInfo> results = new List<DBMovieInfo>();
            Film[] films = Api.Search(title);
            if (films != null) {
                foreach (Film film in films) {
                    DBMovieInfo movie = new DBMovieInfo();
                    movie.Title = film.title.FromSortable();
                    movie.AlternateTitles.Add(film.alternative_title);
                    movie.GetSourceMovieInfo(SourceInfo).Identifier = film.filmId;
                    movie.Popularity = popularity--;

                    int year = 0;
                    if (int.TryParse(film.year, out year))
                        movie.Year = year;

                    // Add movie to the results
                    results.Add(movie);
                }
            }

            return results;
        }
 private string getMovieMeterID(DBMovieInfo movie)
 {
     string mmId = null;
     DBSourceMovieInfo idObj = movie.GetSourceMovieInfo(SourceInfo);
     if (idObj != null && idObj.Identifier != null) {
         mmId = idObj.Identifier;
     }
     else {
         // Translate IMDb code to MovieMeter ID
         string imdbId = movie.ImdbID.Trim();
         if (imdbId != string.Empty) {
             mmId = Api.GetMovieMeterId(imdbId);
             if (mmId != null)
                 movie.GetSourceMovieInfo(SourceInfo).Identifier = mmId;
         }
     }
     return mmId;
 }
        private DBMovieInfo getMovieDetails(string mmid)
        {
            FilmDetail film = Api.GetMovieDetails(mmid);
            if (film != null) {

                DBMovieInfo movie = new DBMovieInfo();
                movie.GetSourceMovieInfo(SourceInfo).Identifier = film.filmId.ToString();

                movie.Title = film.title.FromSortable();
                movie.Summary = film.plot;
                movie.ImdbID = "tt" + film.imdb;
                movie.DetailsURL = film.url;

                // Score (multiply by 2 to get the 1-10 scale)
                if (!String.IsNullOrEmpty(film.average))
                    movie.Score = (Convert.ToSingle(film.average, NumberFormatInfo.InvariantInfo) * 2);

                // Runtime
                int runtime = 0;
                if (int.TryParse(film.duration, out runtime))
                    movie.Runtime = runtime;

                // Year
                int year = 0;
                if (int.TryParse(film.year, out year))
                    movie.Year = year;

                // Try to add the alternative titles
                if (film.alternative_titles != null)
                    foreach (FilmDetail.Title alt in film.alternative_titles)
                        movie.AlternateTitles.Add(alt.title);

                // Try to add the genres
                if (film.genres != null)
                    foreach (string genre in film.genres)
                        movie.Genres.Add(genre);

                // Try to add the actors
                if (film.actors != null)
                    foreach (FilmDetail.Actor actor in film.actors)
                        movie.Actors.Add(actor.name);

                // Try to add the directors
                if (film.directors != null)
                    foreach (FilmDetail.Director director in film.directors)
                        movie.Directors.Add(director.name);

                return movie;
            }
            return null;
        }
        public bool GetBackdrop(DBMovieInfo movie)
        {
            if (movie == null)
                return false;

            // if we already have a backdrop move on for now
            if (movie.BackdropFullPath.Trim().Length > 0)
                return true;

            // do we have an id?
            string tmdbID = getTheMovieDbId(movie, true);
            if (tmdbID == null) {
                return false;
            }

            // Try to get movie information
            XmlNodeList xml = getXML(apiMovieGetInfo + tmdbID);
            if (xml == null) {
                return false;
            }

            // try to grab backdrops from the resulting xml doc
            string backdropURL = string.Empty;
            XmlNodeList backdropNodes = xml.Item(0).SelectNodes("//image[@type='backdrop']");
            foreach (XmlNode currNode in backdropNodes) {
                if (currNode.Attributes["size"].Value == "original") {
                    backdropURL = currNode.Attributes["url"].Value;
                    if (backdropURL.Trim().Length > 0) {
                        if (movie.AddBackdropFromURL(backdropURL) == ImageLoadResults.SUCCESS) {
                            movie.GetSourceMovieInfo(SourceInfo).Identifier = tmdbID;
                            return true;
                        }
                    }
                }
            }

            // if we get here we didn't manage to find a proper backdrop
            // so return false
            return false;
        }
        /// <summary>
        /// returns the tmdb id for a movie if its exists
        /// </summary>
        private string getTmdbId(DBMovieInfo movie)
        {
            // get source info, maybe already have it from poster or movieinfo
            var tmdbSource = DBSourceInfo.GetAll().Find(s => s.ToString() == "themoviedb.org");
            if (tmdbSource == null)
                return null;

            string id = movie.GetSourceMovieInfo(tmdbSource).Identifier;
            if (id == null || id.Trim() == string.Empty)
                return null;

            return id;
        }
        public bool GetArtwork(DBMovieInfo movie)
        {
            if (movie == null)
                return false;

            // do we have an id?
            string tmdbID = getTheMovieDbId(movie, true);
            if (tmdbID == null)
                return false;

            // try to get movie artwork
            var movieArtwork = TheMovieDbAPI.GetMovieImages(tmdbID);
            if (movieArtwork == null || movieArtwork.Posters == null || movieArtwork.Posters.Count == 0)
                return false;

            // filter out minimum size images
            int minWidth = MovingPicturesCore.Settings.MinimumCoverWidth;
            int minHeight = MovingPicturesCore.Settings.MinimumCoverHeight;

            movieArtwork.Posters.RemoveAll(p => p.Width < minWidth || p.Height < minHeight);
            if (movieArtwork.Posters.Count == 0)
                return false;

            // filter posters by language
            var langPosters = movieArtwork.Posters.Where(p => p.LanguageCode == MovingPicturesCore.Settings.DataProviderLanguageCode);
            if (MovingPicturesCore.Settings.DataProviderLanguageCode == "en") {
                // include no language posters with english (sometimes language is not assigned)
                langPosters = langPosters.Union(movieArtwork.Posters.Where(p => p.LanguageCode == null));
            }
            // if no localised posters available use all posters
            if (langPosters.Count() == 0) {
                langPosters = movieArtwork.Posters;
            }

            // sort by highest rated / most popular
            langPosters = langPosters.OrderByDescending(p => p.Score);

            // grab coverart loading settings
            int maxCovers = MovingPicturesCore.Settings.MaxCoversPerMovie;
            int maxCoversInSession = MovingPicturesCore.Settings.MaxCoversPerSession;
            int coversAdded = 0;

            // get the base url for images
            string baseImageUrl = getImageBaseUrl();
            if (string.IsNullOrEmpty(baseImageUrl))
                return false;

            // download posters
            foreach (var poster in langPosters) {
                // if we have hit our limit quit
                if (movie.AlternateCovers.Count >= maxCovers || coversAdded >= maxCoversInSession)
                    return true;

                // get url for cover and load it via the movie object
                string coverPath = baseImageUrl + poster.FilePath;
                if (coverPath.Trim() != string.Empty) {
                    if (movie.AddCoverFromURL(coverPath) == ImageLoadResults.SUCCESS)
                        coversAdded++;
                }
            }

            if (coversAdded > 0) {
                // Update source info
                movie.GetSourceMovieInfo(SourceInfo).Identifier = tmdbID;
                return true;
            }

            return false;
        }
        private DBMovieInfo getMovieInformation(string movieId)
        {
            if (string.IsNullOrEmpty(movieId))
                return null;

            // request the movie details by imdb id or tmdb id
            var movieDetails = TheMovieDbAPI.GetMovieInfo(movieId, MovingPicturesCore.Settings.DataProviderLanguageCode);
            if (movieDetails == null)
                return null;

            var movie = new DBMovieInfo();

            // get the tmdb id
            movie.GetSourceMovieInfo(SourceInfo).Identifier = movieDetails.Id.ToString();

            // get the localised title if available otherwise fallback to original title
            movie.Title = string.IsNullOrEmpty(movieDetails.Title) ? movieDetails.OriginalTitle : movieDetails.Title;

            // get alternative titles
            var altTitles = TheMovieDbAPI.GetAlternativeTitles(movieDetails.Id.ToString());
            if (altTitles != null && altTitles.Titles != null) {
                movie.AlternateTitles.AddRange(altTitles.Titles.Select(a => a.Title));
            }

            // get languages
            if (movieDetails.SpokenLanguages != null) {
                movie.Language = string.Join("|", movieDetails.SpokenLanguages.Select(l => l.Name).ToArray());
            }

            // get tagline
            movie.Tagline = movieDetails.Tagline;

            // get imdb id
            movie.ImdbID = movieDetails.ImdbId;

            // get homepage
            movie.DetailsURL = movieDetails.HomePage;

            // get movie overview
            movie.Summary = movieDetails.Overview;

            // get movie score
            movie.Score = movieDetails.Score;

            // get movie vote count
            movie.Popularity = movieDetails.Votes;

            // get runtime (mins)
            movie.Runtime = movieDetails.Runtime == null ? 0 : (int)movieDetails.Runtime;

            // get movie cast
            var castInfo = TheMovieDbAPI.GetCastInfo(movieDetails.Id.ToString());
            if (castInfo != null) {
                // add actors, sort by order field
                if (castInfo.Cast != null)
                    movie.Actors.AddRange(castInfo.Cast.OrderBy(a => a.Order).Select(a => a.Name));

                // add directors
                if (castInfo.Crew != null) {
                    movie.Directors.AddRange(castInfo.Crew.Where(c => c.Department == "Directing").Select(c => c.Name).Distinct());
                }

                // add writers
                if (castInfo.Crew != null) {
                    movie.Writers.AddRange(castInfo.Crew.Where(c => c.Department == "Writing").Select(c => c.Name).Distinct());
                }
            }

            // add genres
            if (movieDetails.Genres != null) {
                movie.Genres.AddRange(movieDetails.Genres.Select(g => g.Name).ToArray());
            }

            // add collection - only one supported by TMDb
            if (movieDetails.BelongsToCollection != null) {
                // remove 'Collection' from name
                string collection = movieDetails.BelongsToCollection.Name.Replace("Collection", "").Trim();
                movie.Collections.Add(collection);
            }

            // add production companies (studios)
            if (movieDetails.ProductionCompanies != null)  {
                movie.Studios.AddRange(movieDetails.ProductionCompanies.Select(p => p.Name));
            }

            // add release date and year
            DateTime date;
            if (DateTime.TryParse(movieDetails.ReleaseDate, out date))
            {
                movie.Year = date.Year;
                movie.ReleaseDate = date;
            }

            // add certification (US MPAA rating)
            var movieCertifications = TheMovieDbAPI.GetReleaseInfo(movieDetails.Id.ToString());
            if (movieCertifications != null && movieCertifications.Countries != null) {
                // this could also be a scraper setting to get certification and release date from preferred country
                var releaseInfo = movieCertifications.Countries.Find(c => c.CountryCode == "US");
                if (releaseInfo != null) {
                    movie.Certification = releaseInfo.Certification;
                    // todo: uncomment this later if we have a setting for preferred country, it will override the release date that was previously set
                    //if (DateTime.TryParse(releaseInfo.ReleaseDate, out date))
                    //{
                    //    movie.ReleaseDate = date;
                    //}
                }
            }

            // get plot keywords
            var plotKeywords = TheMovieDbAPI.GetPlotKeywords(movieDetails.Id.ToString());
            if (plotKeywords != null) {
                movie.PlotKeywords.AddRange(plotKeywords.Keywords.Select(k => k.Name).ToArray());
            }

            return movie;
        }
        public bool GetArtwork(DBMovieInfo movie)
        {
            if (scraper == null)
                return false;

            Dictionary<string, string> paramList = new Dictionary<string, string>();
            Dictionary<string, string> results;

            // grab coverart loading settings
            int maxCovers = MovingPicturesCore.Settings.MaxCoversPerMovie;
            int maxCoversInSession = MovingPicturesCore.Settings.MaxCoversPerSession;

            // if we have already hit our limit for the number of covers to load, quit
            if (movie.AlternateCovers.Count >= maxCovers)
                return true;

            // try to load the id for the movie for this script
            DBSourceMovieInfo idObj = movie.GetSourceMovieInfo(ScriptID);
            if (idObj != null && idObj.Identifier != null)
                paramList["movie.site_id"] = idObj.Identifier;

            // load params for scraper
            foreach (DBField currField in DBField.GetFieldList(typeof(DBMovieInfo)))
                if (currField.GetValue(movie) != null)
                    paramList["movie." + currField.FieldName] = currField.GetValue(movie).ToString().Trim();

            //set higher level settings for script to use
            paramList["settings.defaultuseragent"] = MovingPicturesCore.Settings.UserAgent;
            paramList["settings.mepo_data"] = Config.GetFolder(Config.Dir.Config);

            // run the scraper
            results = scraper.Execute("get_cover_art", paramList);
            if (results == null) {
                logger.Error(Name + " scraper script failed to execute \"get_cover_art\" node.");
                return false;
            }

            int coversAdded = 0;
            int count = 0;
            while (results.ContainsKey("cover_art[" + count + "].url") || results.ContainsKey("cover_art[" + count + "].file")) {
                // if we have hit our limit quit
                if (movie.AlternateCovers.Count >= maxCovers || coversAdded >= maxCoversInSession)
                    return true;

                // get url for cover and load it via the movie object
                if (results.ContainsKey("cover_art[" + count + "].url")) {
                    string coverPath = results["cover_art[" + count + "].url"];
                    if (coverPath.Trim() != string.Empty)
                        if (movie.AddCoverFromURL(coverPath) == ImageLoadResults.SUCCESS)
                            coversAdded++;
                }

                // get file for cover and load it via the movie object
                if (results.ContainsKey("cover_art[" + count + "].file")) {
                    string coverPath = results["cover_art[" + count + "].file"];
                    if (coverPath.Trim() != string.Empty)
                        if (movie.AddCoverFromFile(coverPath))
                            coversAdded++;
                }

                count++;
            }

            if (coversAdded > 0)
                return true;

            return false;
        }
        public List<DBMovieInfo> Get(MovieSignature movieSignature)
        {
            if (scraper == null)
                return null;

            List<DBMovieInfo> rtn = new List<DBMovieInfo>();
            Dictionary<string, string> paramList = new Dictionary<string, string>();
            Dictionary<string, string> results;

            if (movieSignature.Title != null) paramList["search.title"] = movieSignature.Title;
            if (movieSignature.Keywords != null) paramList["search.keywords"] = movieSignature.Keywords;
            if (movieSignature.Year != null) paramList["search.year"] = movieSignature.Year.ToString();
            if (movieSignature.ImdbId != null) paramList["search.imdb_id"] = movieSignature.ImdbId;
            if (movieSignature.DiscId != null) paramList["search.disc_id"] = movieSignature.DiscId;
            if (movieSignature.MovieHash != null) paramList["search.moviehash"] = movieSignature.MovieHash;
            if (movieSignature.Path != null) paramList["search.basepath"] = movieSignature.Path;
            if (movieSignature.Folder != null) paramList["search.foldername"] = movieSignature.Folder;
            if (movieSignature.File != null) paramList["search.filename"] = movieSignature.File;

            //set higher level settings for script to use
            paramList["settings.defaultuseragent"] = MovingPicturesCore.Settings.UserAgent;
            paramList["settings.mepo_data"] = Config.GetFolder(Config.Dir.Config);

            // this variable is the filename without extension (and a second one without stackmarkers)
            if (!String.IsNullOrEmpty(movieSignature.File)) {
                paramList["search.filename_noext"] = Path.GetFileNameWithoutExtension(movieSignature.File);
                paramList["search.clean_filename"] = Utility.GetFileNameWithoutExtensionAndStackMarkers(movieSignature.File);
            }

            results = scraper.Execute("search", paramList);
            if (results == null) {
                logger.Error(Name + " scraper script failed to execute \"search\" node.");
                return rtn;
            }

            int count = 0;
            // The movie result is only valid if the script supplies a unique site
            while (results.ContainsKey("movie[" + count + "].site_id")) {
                string siteId;
                string prefix = "movie[" + count + "].";
                count++;

                // if the result does not yield a site id it's not valid so skip it
                if (!results.TryGetValue(prefix + "site_id", out siteId))
                    continue;

                // if this movie was already added skip it
                if (rtn.Exists(delegate(DBMovieInfo item) { return item.GetSourceMovieInfo(ScriptID).Identifier == siteId; }))
                    continue;

                // if this movie does not have a valid title, don't bother
                if (!results.ContainsKey(prefix + "title"))
                    continue;

                // We passed all checks so create a new movie object
                DBMovieInfo newMovie = new DBMovieInfo();

                // store the site id in the new movie object
                newMovie.GetSourceMovieInfo(ScriptID).Identifier = siteId;

                // Try to store all other fields in the new movie object
                foreach (DBField currField in DBField.GetFieldList(typeof(DBMovieInfo))) {
                    string value;
                    if (results.TryGetValue(prefix + currField.FieldName, out value))
                        currField.SetValue(newMovie, value.Trim());
                }

                // add the movie to our movie results list
                rtn.Add(newMovie);
            }

            return rtn;
        }
        private DBMovieInfo getMovieInfo(string idMovie)
        {
            DBMovieInfo movieRes = new DBMovieInfo();
            try
            {
                SQLiteClient mp_db = new SQLiteClient(Config.GetFile(Config.Dir.Database, @"VideoDatabaseV5.db3"));
                SQLiteResultSet sqlResults = mp_db.Execute("SELECT * FROM movieinfo WHERE idMovie LIKE '" + idMovie + "'");

                SQLiteResultSet.Row sqlRow = sqlResults.GetRow(0);
                System.Collections.Hashtable columns = sqlResults.ColumnIndices;

                movieRes.Popularity = int.Parse(sqlResults.GetField(0, int.Parse(columns["strVotes"].ToString())));
                movieRes.Runtime = int.Parse(sqlResults.GetField(0, int.Parse(columns["runtime"].ToString())));
                movieRes.Score = float.Parse(sqlResults.GetField(0, int.Parse(columns["fRating"].ToString())));
                movieRes.Year = int.Parse(sqlResults.GetField(0, int.Parse(columns["iYear"].ToString())));

                string Title = sqlResults.GetField(0, int.Parse(columns["strTitle"].ToString()));
                if (!Title.Contains("unknown"))
                    movieRes.Title = Title;

                string Certification = sqlResults.GetField(0, int.Parse(columns["mpaa"].ToString()));
                if (!Certification.Contains("unknown"))
                    movieRes.Certification = Certification;

                string Tagline = sqlResults.GetField(0, int.Parse(columns["strTagLine"].ToString()));
                if (!Tagline.Contains("unknown"))
                    movieRes.Tagline = Tagline;

                string Summary = sqlResults.GetField(0, int.Parse(columns["strPlotOutline"].ToString()));
                if (!Summary.Contains("unknown"))
                    movieRes.Summary = Summary;

                string imdb_id = sqlResults.GetField(0, int.Parse(columns["IMDBID"].ToString()));
                if (!imdb_id.Contains("unknown"))
                    movieRes.ImdbID = imdb_id;

                string genreMain = sqlResults.GetField(0, int.Parse(columns["strGenre"].ToString()));
                if (!genreMain.Contains("unknown"))
                {
                    string[] genreSplit = genreMain.Split('/');
                    foreach (string genre in genreSplit)
                    {
                        movieRes.Genres.Add(genre.Trim());
                    }
                }

                string castMain = sqlResults.GetField(0, int.Parse(columns["strCast"].ToString()));
                if (!castMain.Contains("unknown"))
                {
                    string[] castSplit = castMain.Split('\n');
                    foreach (string cast in castSplit)
                    {
                        string castFinal = cast;
                        if (cast.Contains(" as "))
                            castFinal = cast.Remove(cast.IndexOf(" as "));
                        movieRes.Actors.Add(castFinal.Trim());
                    }
                }

                string idDirector = sqlResults.GetField(0, int.Parse(columns["idDirector"].ToString()));
                if (!castMain.Contains("unknown"))
                {
                    SQLiteResultSet sqlDirector = mp_db.Execute("SELECT strActor FROM actors WHERE idActor LIKE '" + idDirector + "'");
                    movieRes.Directors.Add(sqlDirector.GetField(0, 0));
                }

                string writers = sqlResults.GetField(0, int.Parse(columns["strCredits"].ToString()));
                if (!writers.Contains("unknown")) {
                    string[] writerArray = writers.Split(new string[] {"\n", "   "}, StringSplitOptions.None);
                    foreach (string writer in writerArray) {
                        if (!movieRes.Writers.Contains(writer.Trim()))
                            movieRes.Writers.Add(writer.Trim());
                    }
                }

                movieRes.GetSourceMovieInfo(SourceInfo).Identifier = sqlResults.GetField(0, int.Parse(columns["idMovie"].ToString())).ToString();

                mp_db.Close();
            }
            catch
            {
                return null;
            }

            return movieRes;
        }
        private static string GetTmdbID(DBMovieInfo movie)
        {
            if (tmdbSource == null)
            {
                tmdbSource = GetTmdbSourceInfo();
                if (tmdbSource == null) return null;
            }

            string id = movie.GetSourceMovieInfo(tmdbSource).Identifier;
            if (id == null || id.Trim() == string.Empty) return null;
            if (int.Parse(id.Trim()) <= 0) return null;

            return id;
        }
        private string getTheMovieDbId(DBMovieInfo movie, bool fuzzyMatch)
        {
            // check for internally stored ID
            DBSourceMovieInfo idObj = movie.GetSourceMovieInfo(SourceInfo);
            if (idObj != null && idObj.Identifier != null) {
                return idObj.Identifier;
            }

            // if available, lookup based on imdb ID
            else if (movie.ImdbID != null && movie.ImdbID.Trim().Length > 0) {
                string imdbId = movie.ImdbID.Trim();
                XmlNodeList xml = getXML(apiMovieImdbLookup + imdbId);
                if (xml != null && xml.Count > 0) {
                    // Get TMDB Id
                    XmlNodeList idNodes = xml.Item(0).SelectNodes("//id");
                    if (idNodes.Count != 0) {
                        return idNodes[0].InnerText;
                    }
                }
            }

            // if asked for, do a fuzzy match based on title
            else if (fuzzyMatch) {
                // grab possible matches by main title
                List<DBMovieInfo> results = Search(movie.Title, movie.Year);
                if (results.Count == 0) results = Search(movie.Title);

                // grab possible matches by alt titles
                foreach (string currAltTitle in movie.AlternateTitles) {
                    List<DBMovieInfo> tempResults = Search(movie.Title, movie.Year);
                    if (results.Count == 0) tempResults = Search(movie.Title);

                    results.AddRange(tempResults);
                }

                // pick a possible match if one meets our requirements
                foreach (DBMovieInfo currMatch in results) {
                    if (CloseEnough(currMatch, movie))
                        return currMatch.GetSourceMovieInfo(SourceInfo).Identifier;
                }
            }

            return null;
        }
        private DBMovieInfo getMovieInformation(XmlNode movieNode)
        {
            if (movieNode == null)
                return null;

            if (movieNode.ChildNodes.Count < 2 || movieNode.Name != "movie")
                return null;

            DBMovieInfo movie = new DBMovieInfo();
            foreach (XmlNode node in movieNode.ChildNodes) {
                string value = node.InnerText;
                switch (node.Name) {
                    case "id":
                        movie.GetSourceMovieInfo(SourceInfo).Identifier = value;
                        break;
                    case "name":
                        movie.Title = value;
                        break;
                    case "alternative_name":
                        // todo: remove this check when the api is fixed
                        if (value.Trim() != "None found." && value.Trim().Length > 0 )
                            movie.AlternateTitles.Add(value);
                        break;
                    case "released":
                        DateTime date;
                        if (DateTime.TryParse(value, out date))
                            movie.Year = date.Year;
                        break;
                    case "language":
                        try {
                            movie.Language = new CultureInfo(value).DisplayName;
                        } catch (Exception) { }
                        break;
                    case "tagline":
                        movie.Tagline = value;
                        break;
                    case "imdb_id":
                        movie.ImdbID = value;
                        break;
                    case "url":
                        movie.DetailsURL = value;
                        break;
                    case "overview":
                        movie.Summary = value;
                        break;
                    case "rating":
                        float rating = 0;
                        if (float.TryParse(value, out rating))
                            movie.Score = rating;
                        break;
                    case "votes":
                        int popularity;
                        if (int.TryParse(value, out popularity))
                            movie.Popularity = popularity;
                        break;
                    case "runtime":
                        int runtime = 0;
                        if (int.TryParse(value, out runtime))
                            movie.Runtime = runtime;
                        break;
                    case "cast": // Actors, Directors and Writers
                        foreach (XmlNode person in node.ChildNodes) {
                            string name = person.Attributes["name"].Value;
                            string job = person.Attributes["job"].Value;
                            switch (job) {
                                case "Director":
                                    movie.Directors.Add(name);
                                    break;
                                case "Actor":
                                    movie.Actors.Add(name);
                                    break;
                                case "Screenplay":
                                case "Author":
                                    movie.Writers.Add(name);
                                    break;
                            }
                        }
                        break;
                    case "categories":
                        foreach (XmlNode category in node.ChildNodes) {
                            string genre = category.Attributes["name"].Value;
                            string type = category.Attributes["type"].Value;
                            if (type == "genre") {
                                movie.Genres.Add(genre);
                            }
                        }
                        break;
                    case "studios":
                        foreach (XmlNode category in node.ChildNodes) {
                            movie.Studios.Add(category.Attributes["name"].Value);
                        }
                        break;
                    case "certification":
                        movie.Certification = value;
                        break;
                }
            }
            return movie;
        }
        public bool GetBackdrop(DBMovieInfo movie)
        {
            if (movie == null)
                return false;

            // if we already have a backdrop move on for now
            if (movie.BackdropFullPath.Trim().Length > 0)
                return true;

            // do we have an id?
            string tmdbID = getTheMovieDbId(movie, true);
            if (tmdbID == null)
                return false;

            // try to get movie artwork
            var movieArtwork = TheMovieDbAPI.GetMovieImages(tmdbID);
            if (movieArtwork == null || movieArtwork.Backdrops == null || movieArtwork.Backdrops.Count == 0)
                return false;

            // filter out minimum size images
            int minWidth = MovingPicturesCore.Settings.MinimumBackdropWidth;
            int minHeight = MovingPicturesCore.Settings.MinimumBackdropHeight;

            movieArtwork.Backdrops.RemoveAll(b => b.Width < minWidth || b.Height < minHeight);
            if (movieArtwork.Backdrops.Count == 0)
                return false;

            // sort by highest rated / most popular
            var backdrops = movieArtwork.Backdrops.OrderByDescending(p => p.Score);

            // get the base url for images
            string baseImageUrl = getImageBaseUrl();
            if (string.IsNullOrEmpty(baseImageUrl))
                return false;

            // moving pics currently only supports 1 backdrop per movie
            string backdropURL = baseImageUrl + backdrops.First().FilePath;
            if (backdropURL.Trim().Length > 0) {
                if (movie.AddBackdropFromURL(backdropURL) == ImageLoadResults.SUCCESS) {
                    movie.GetSourceMovieInfo(SourceInfo).Identifier = tmdbID;
                    return true;
                }
            }

            // if we get here we didn't manage to find a proper backdrop
            // so return false
            return false;
        }
        public bool GetBackdrop(DBMovieInfo movie)
        {
            if (scraper == null)
                return false;

            Dictionary<string, string> paramList = new Dictionary<string, string>();
            Dictionary<string, string> results;

            // if we already have a backdrop move on for now
            if (movie.BackdropFullPath.Trim().Length > 0)
                return true;

            // try to load the id for the movie for this script
            DBSourceMovieInfo idObj = movie.GetSourceMovieInfo(ScriptID);
            if (idObj != null && idObj.Identifier != null)
                paramList["movie.site_id"] = idObj.Identifier;

            // load params for scraper
            foreach (DBField currField in DBField.GetFieldList(typeof(DBMovieInfo)))
                if (currField.GetValue(movie) != null)
                    paramList["movie." + currField.FieldName] = currField.GetValue(movie).ToString().Trim();

            //set higher level settings for script to use
            paramList["settings.defaultuseragent"] = MovingPicturesCore.Settings.UserAgent;
            paramList["settings.mepo_data"] = Config.GetFolder(Config.Dir.Config);

            // run the scraper
            results = scraper.Execute("get_backdrop", paramList);
            if (results == null) {
                logger.Error(Name + " scraper script failed to execute \"get_backdrop\" node.");
                return false;
            }

            // Loop through all the results until a valid backdrop is found
            int count = 0;
            while (results.ContainsKey("backdrop[" + count + "].url") || results.ContainsKey("backdrop[" + count + "].file")) {

                // attempt to load via a URL
                if (results.ContainsKey("backdrop[" + count + "].url")) {
                    string backdropURL = results["backdrop[" + count + "].url"];
                    if (backdropURL.Trim().Length > 0)
                        if (movie.AddBackdropFromURL(backdropURL) == ImageLoadResults.SUCCESS)
                            return true;
                }

                // attempt to load via a file
                if (results.ContainsKey("backdrop[" + count + "].file")) {
                    string backdropFile = results["backdrop[" + count + "].file"];
                    if (backdropFile.Trim().Length > 0)
                        if (movie.AddBackdropFromFile(backdropFile))
                            return true;
                }

                count++;
            }

            // no valid backdrop found
            return false;
        }
        public UpdateResults Update(DBMovieInfo movie)
        {
            if (movie == null)
                return UpdateResults.FAILED;

            string tmdbId = getTheMovieDbId(movie, false);
            // check if TMDb id is still null, if so request id.
            if (string.IsNullOrEmpty(tmdbId))
                return UpdateResults.FAILED_NEED_ID;

            // Grab the movie using the TMDb ID
            DBMovieInfo newMovie = getMovieInformation(tmdbId);
            if (newMovie != null) {
                movie.GetSourceMovieInfo(SourceInfo).Identifier = tmdbId;
                movie.CopyUpdatableValues(newMovie);
                return UpdateResults.SUCCESS;
            }
            else {
                return UpdateResults.FAILED;
            }
        }
        public UpdateResults Update(DBMovieInfo movie)
        {
            if (scraper == null)
                return UpdateResults.FAILED;

            Dictionary<string, string> paramList = new Dictionary<string, string>();
            Dictionary<string, string> results;
            bool hasSiteId = false;

            // try to load the id for the movie for this script
            // if we have no site id still continue as we might still
            // be able to grab details using another identifier such as imdb_id
            DBSourceMovieInfo idObj = movie.GetSourceMovieInfo(ScriptID);
            if (idObj != null && idObj.Identifier != null) {
                paramList["movie.site_id"] = idObj.Identifier;
                hasSiteId = true;
            }

            // load params
            foreach (DBField currField in DBField.GetFieldList(typeof(DBMovieInfo))) {
                if (currField.AutoUpdate && currField.GetValue(movie) != null)
                    paramList["movie." + currField.FieldName] = currField.GetValue(movie).ToString().Trim();
            }

            //set higher level settings for script to use
            paramList["settings.defaultuseragent"] = MovingPicturesCore.Settings.UserAgent;
            paramList["settings.mepo_data"] = Config.GetFolder(Config.Dir.Config);

            // try to retrieve results
            results = scraper.Execute("get_details", paramList);
            if (results == null) {
                logger.Error(Name + " scraper script failed to execute \"get_details\" node.");
                return UpdateResults.FAILED;
            }

            if (!hasSiteId) {
                // if we started out without a site id
                // try to get it from the details response
                string siteId;
                if (results.TryGetValue("movie.site_id", out siteId))
                    movie.GetSourceMovieInfo(ScriptID).Identifier = siteId;
                else
                    // still no site id, so we are returning
                    return UpdateResults.FAILED_NEED_ID;
            }

            // get our new movie details
            DBMovieInfo newMovie = new DBMovieInfo();
            foreach (DBField currField in DBField.GetFieldList(typeof(DBMovieInfo))) {
                string value;
                bool success = results.TryGetValue("movie." + currField.FieldName, out value);

                if (success && value.Trim().Length > 0)
                    currField.SetValue(newMovie, value.Trim());
            }

            // and update as necessary
            movie.CopyUpdatableValues(newMovie);

            return UpdateResults.SUCCESS;
        }
        private string getTheMovieDbId(DBMovieInfo movie, bool fuzzyMatch)
        {
            // check for internally stored TMDb ID
            DBSourceMovieInfo idObj = movie.GetSourceMovieInfo(SourceInfo);
            if (idObj != null && idObj.Identifier != null) {
                return idObj.Identifier;
            }

            // if available, lookup based on IMDb ID
            else if (movie.ImdbID != null && movie.ImdbID.Trim().Length == 9) {
                string imdbId = movie.ImdbID.Trim();
                var movieInfo = TheMovieDbAPI.GetMovieInfo(imdbId);
                if (movieInfo != null) {
                    return movieInfo.Id.ToString();
                }
            }

            // if asked for, do a fuzzy match based on title and year
            else if (fuzzyMatch) {
                // grab possible matches by main title + year
                List<DBMovieInfo> results = Search(movie.Title, movie.Year);
                if (results.Count == 0) results = Search(movie.Title);

                // grab possible matches by alt titles
                foreach (string currAltTitle in movie.AlternateTitles) {
                    List<DBMovieInfo> tempResults = Search(movie.Title, movie.Year);
                    if (tempResults.Count == 0) tempResults = Search(movie.Title);

                    results.AddRange(tempResults);
                }

                // pick a possible match if one meets our requirements
                foreach (DBMovieInfo currMatch in results) {
                    if (CloseEnough(currMatch, movie))
                        return currMatch.GetSourceMovieInfo(SourceInfo).Identifier;
                }
            }

            return null;
        }
Пример #20
0
        public static string GetTmdbID(DBMovieInfo movie)
        {
            if (tmdbSource == null) return null;

            string id = movie.GetSourceMovieInfo(tmdbSource).Identifier;
            if (id == null || id.Trim() == string.Empty) return null;

            // TMDb ID must be an integer greater than zero
            int result = 0;
            if (!int.TryParse(id, out result))
                return null;

            if (result <= 0) return null;

            return id;
        }
        public bool GetBackdrop(DBMovieInfo movie)
        {
            if (movie == null)
                return false;

            // if we already have a backdrop move on for now
            if (movie.BackdropFullPath.Trim().Length > 0)
                return true;

            // do we have an id?
            string movieId = getMovieId(movie);
            if (string.IsNullOrEmpty(movieId))
                return false;

            string url = apiMovieArtwork;
            if (!string.IsNullOrWhiteSpace(MovingPicturesCore.Settings.FanartTVClientKey))
                url = url + "&client_key=" + MovingPicturesCore.Settings.FanartTVClientKey;

            string response = getJson(string.Format(url, movieId));
            if (response == null)
                return false;

            // de-serialize json response
            var movieImages = response.FromJson<Artwork>();
            if (movieImages == null)
                return false;

            // check if we have any backdrops
            if (movieImages.moviebackground == null || movieImages.moviebackground.Count == 0)
                return false;

            // get the 1st (highest rated) movie backdrop
            // only single backdrops are currently supported
            string backdropUrl = movieImages.moviebackground.First().url;
            if (backdropUrl.Trim().Length > 0) {
                if (movie.AddBackdropFromURL(backdropUrl) == ImageLoadResults.SUCCESS) {
                    // store either the imdb id or tmdb id of movie for identifier
                    // there is no per movie id from fanart.tv, only per image id
                    movie.GetSourceMovieInfo(SourceInfo).Identifier = movieId;
                    return true;
                }
            }

            // if we get here we didn't manage to find a proper backdrop
            return false;
        }
        public static string GetTmdbID(DBMovieInfo movie)
        {
            if (tmdbSource == null) return null;

            string id = movie.GetSourceMovieInfo(tmdbSource).Identifier;
            if (id == null || id.Trim() == string.Empty) return null;
            return id;
        }
        public bool GetArtwork(DBMovieInfo movie)
        {
            if (movie == null)
                return false;

            // do we have an id?
            string movieId = getMovieId(movie);
            if (string.IsNullOrEmpty(movieId))
                return false;

            string url = apiMovieArtwork;
            if (!string.IsNullOrEmpty(MovingPicturesCore.Settings.FanartTVClientKey))
                url = url + "&client_key=" + MovingPicturesCore.Settings.FanartTVClientKey;

            // try to get movie artwork
            string response = getJson(string.Format(apiMovieArtwork, movieId));
            if (response == null)
                return false;

            // de-serialize json response
            var movieImages = response.FromJson<Artwork>();
            if (movieImages == null)
                return false;

            // check if we have any posters
            if (movieImages.movieposter == null || movieImages.movieposter.Count == 0)
                return false;

            // filter posters by language
            var langPosters = movieImages.movieposter.Where(p => p.lang == MovingPicturesCore.Settings.DataProviderLanguageCode);

            // if no localised posters available use all posters
            if (langPosters.Count() == 0) {
                langPosters = movieImages.movieposter;
            }

            // sort by highest rated / most popular
            langPosters = langPosters.OrderByDescending(p => p.likes);

            // grab coverart loading settings
            int maxCovers = MovingPicturesCore.Settings.MaxCoversPerMovie;
            int maxCoversInSession = MovingPicturesCore.Settings.MaxCoversPerSession;
            int coversAdded = 0;

            // download posters
            foreach (var poster in langPosters) {
                // if we have hit our limit quit
                if (movie.AlternateCovers.Count >= maxCovers || coversAdded >= maxCoversInSession)
                    return true;

                // get url for cover and load it via the movie object
                string coverPath = poster.url;
                if (coverPath.Trim() != string.Empty) {
                    if (movie.AddCoverFromURL(coverPath) == ImageLoadResults.SUCCESS)
                        coversAdded++;
                }
            }

            if (coversAdded > 0) {
                // Update source info
                movie.GetSourceMovieInfo(SourceInfo).Identifier = movieId;
                return true;
            }

            return false;
        }
        public bool GetArtwork(DBMovieInfo movie)
        {
            if (movie == null)
                return false;

            // do we have an id?
            string tmdbID = getTheMovieDbId(movie, true);
            if (tmdbID == null) {
                return false;
            }

            // Tro to get movie information
            XmlNodeList xml = getXML(apiMovieGetInfo + tmdbID);
            if (xml == null) {
                return false;
            }

            // grab coverart loading settings
            int maxCovers = MovingPicturesCore.Settings.MaxCoversPerMovie;
            int maxCoversInSession = MovingPicturesCore.Settings.MaxCoversPerSession;

            int coversAdded = 0;
            int count = 0;

            // try to grab posters from the xml results
            XmlNodeList posterNodes = xml.Item(0).SelectNodes("//image[@type='poster']");
            foreach (XmlNode posterNode in posterNodes) {
                if (posterNode.Attributes["size"].Value == "original") {
                    // if we have hit our limit quit
                    if (movie.AlternateCovers.Count >= maxCovers || coversAdded >= maxCoversInSession)
                        return true;

                    // get url for cover and load it via the movie object
                    string coverPath = posterNode.Attributes["url"].Value;
                    if (coverPath.Trim() != string.Empty)
                        if (movie.AddCoverFromURL(coverPath) == ImageLoadResults.SUCCESS)
                            coversAdded++;

                    count++;
                }
            }

            if (coversAdded > 0) {
                // Update source info
                movie.GetSourceMovieInfo(SourceInfo).Identifier = tmdbID;
                return true;
            }

            return false;
        }