public void AddAllMissing(string path, DatabaseBuilderType type)
        {
            var files = Directory.GetFileSystemEntries(path).ToList();

            if (type == DatabaseBuilderType.Movies)
            {
                BasicLogger.Log("Adding all or any missing movies to the database.", Verbosity.Information);
                BasicLogger.Log("Year of each movie in parentheses is expected to appear on each movie's name. Directory will otherwise be ignored.", Verbosity.Information);
                BasicLogger.Log("Accurate Movie Name is expected for each directory. Movie will not be added otherwise.", Verbosity.Information);
                foreach (var file in files)
                {
                    FileAttributes attr = File.GetAttributes(file);
                    if (!attr.HasFlag(FileAttributes.Directory))
                    {
                        continue;
                    }
                    string name = Path.GetFileName(file);
                    if (name == null)
                    {
                        continue;
                    }
                    if (name.Contains("[1080p]"))
                    {
                        name = name.Remove(name.IndexOf("[1080p]", StringComparison.Ordinal)).Trim();
                    }
                    if (name.Contains("(") && name.Contains(")"))
                    {
                        var year = name.Substring(name.LastIndexOf('(') + 1);
                        name = name.Remove(name.LastIndexOf('(')).Trim();
                        year = year.Remove(year.IndexOf(')')).Trim();
                        name = name.Replace("310 to Yuma", "3:10 to Yuma"); //Hardcoded, can't figure out any other way. Unique case.
                        var movie = _moviesRepository.Query(x => x.Title == name && x.Year == year).FirstOrDefault();
                        if (movie != null)
                        {
                            BasicLogger.Log("Conflicting entry: " + name + " (" + year + ")", Verbosity.Warning);
                            continue;
                        }
                        var   obtainedMovieTask = _omdbApiHandler.GetRequestedMovie(name, year: year);
                        Movie obtainedMovieToCheck;
                        try
                        {
                            Task.WaitAll(obtainedMovieTask);
                            obtainedMovieToCheck = obtainedMovieTask.Result;
                            if (obtainedMovieToCheck == null)
                            {
                                throw new Exception();
                            }
                        }
                        catch (Exception)
                        {
                            obtainedMovieTask = _omdbApiHandler.GetRequestedMovie(name); //year might be causing trouble
                            try
                            {
                                Task.WaitAll(obtainedMovieTask);
                                obtainedMovieToCheck = obtainedMovieTask.Result;
                                if (obtainedMovieToCheck == null)
                                {
                                    throw new Exception();
                                }
                                BasicLogger.Log(name + " was searched for without the year (" + year +
                                                "). Please confirm entry.", Verbosity.Warning);
                            }
                            catch (Exception)
                            {
                                if (name.Contains(" and ") || name.Contains(" And "))
                                {
                                    name = name.Replace(" and ", "&");
                                    name = name.Replace(" And ", "&");
                                }
                                obtainedMovieTask = _omdbApiHandler.GetRequestedMovie(name, year: year);
                                try
                                {
                                    Task.WaitAll(obtainedMovieTask);
                                    obtainedMovieToCheck = obtainedMovieTask.Result;
                                    if (obtainedMovieToCheck == null)
                                    {
                                        throw new Exception();
                                    }
                                }
                                catch (Exception)
                                {
                                    if (name.Contains(" and ") || name.Contains(" And "))
                                    {
                                        name = name.Replace(" and ", "&");
                                        name = name.Replace(" And ", "&");
                                    }
                                    obtainedMovieTask = _omdbApiHandler.GetRequestedMovie(name);
                                    try
                                    {
                                        Task.WaitAll(obtainedMovieTask);
                                        BasicLogger.Log(name + " was searched for without the year (" + year +
                                                        "). Please confirm entry.", Verbosity.Warning);
                                    }
                                    catch (Exception ex)
                                    {
                                        BasicLogger.Log(ex.Message + " " + name + " (" + year + ")", Verbosity.Error);
                                        continue;
                                    }
                                }
                            }
                        }
                        var obtainedMovie = obtainedMovieTask.Result;
                        if (obtainedMovie == null)
                        {
                            BasicLogger.Log("Something went wrong with: " + name + " (" + year + ")", Verbosity.Error);
                            continue;
                        }
                        movie = _moviesRepository.Query(x => x.ImdbId == obtainedMovie.ImdbId).FirstOrDefault();
                        if (movie != null)
                        {
                            BasicLogger.Log("Conflicting entries: " + name + " (" + year + "), " + movie.Title + " (" +
                                            movie.Year + ")", Verbosity.Warning);
                            continue;
                        }
                        UpdateDatabaseWithWatchable(obtainedMovie, type, file);
                    }
                    else
                    {
                        BasicLogger.Log("Skipped: " + name, Verbosity.Warning);
                    }
                }
            }
        }
Ejemplo n.º 2
0
        //Returns a Movie based on the information provided. If no movie was found, returns null. No dependencies are modified or added to the TheaterContext.
        public async Task <Movie> GetRequestedMovie(string name = "-1", string imdbId = "-1", string year = "-1", PlotVersion plotVersion = PlotVersion.Both)
        {
            if (name == "-1" && imdbId == "-1")
            {
                throw new InvalidOperationException("While name and ImdbId are both optional, at least one must be provided.");
            }
            var movieToReturn = new Movie();
            var searchBy      = new[] { "", "" };

            if (name == "-1")
            {
                searchBy[0] = "i";
                searchBy[1] = imdbId;
                year        = "-1";
            }
            else
            {
                searchBy[0] = "t";
                searchBy[1] = name;
            }
            var valuesList = new List <Dictionary <string, string> >();

            if (year == "-1")
            {
                if (plotVersion == PlotVersion.Short || plotVersion == PlotVersion.Both)
                {
                    var values = new Dictionary <string, string>
                    {
                        { searchBy[0], searchBy[1] },
                        { "r", "xml" },
                        { "plot", "short" }
                    };
                    valuesList.Add(values);
                }
                if (plotVersion == PlotVersion.Full || plotVersion == PlotVersion.Both)
                {
                    var values = new Dictionary <string, string>
                    {
                        { searchBy[0], searchBy[1] },
                        { "r", "xml" },
                        { "plot", "full" }
                    };
                    valuesList.Add(values);
                }
            }
            else
            {
                if (plotVersion == PlotVersion.Short || plotVersion == PlotVersion.Both)
                {
                    var values = new Dictionary <string, string>
                    {
                        { searchBy[0], searchBy[1] },
                        { "y", year },
                        { "r", "xml" },
                        { "plot", "short" }
                    };
                    valuesList.Add(values);
                }
                if (plotVersion == PlotVersion.Full || plotVersion == PlotVersion.Both)
                {
                    var values = new Dictionary <string, string>
                    {
                        { searchBy[0], searchBy[1] },
                        { "y", year },
                        { "r", "xml" },
                        { "plot", "full" }
                    };
                    valuesList.Add(values);
                }
            }
            var client = new HttpClient();

            var requestUrls = new List <string>();

            foreach (var valuesDictionary in valuesList)
            {
                var omdbUrl = "http://www.omdbapi.com/?";
                for (var i = 0; i < valuesList.ElementAt(0).Count; i++)
                {
                    omdbUrl += (i == 0 ? "" : "&") + valuesDictionary.Keys.ElementAt(i) + "=" + valuesDictionary[valuesDictionary.Keys.ElementAt(i)];
                }
                requestUrls.Add(omdbUrl);
            }
            var responseNodes = new List <XmlNode>();

            for (int i = 0; i < requestUrls.Count; i++)
            {
                var responseString = await client.GetStringAsync(requestUrls.ElementAt(i));

                var doc = new XmlDocument();
                doc.LoadXml(responseString);
                var rootNode = doc.SelectSingleNode("root");
                if (rootNode == null)
                {
                    BasicLogger.Log("Something went wrong while obtaining rootnode from document for " + requestUrls.ElementAt(i).Clone(), Verbosity.Error);
                    requestUrls.Remove(requestUrls.ElementAt(i));
                    i = -1;
                    continue;
                }
                if (rootNode.Attributes != null && rootNode.Attributes.GetNamedItem("response").Value == "False")
                {
                    BasicLogger.Log("Invalid Identifier for " + requestUrls.ElementAt(i), Verbosity.Error);
                    requestUrls.Remove(requestUrls.ElementAt(i));
                    i = -1;
                    continue;
                }
                var docNode = rootNode.SelectSingleNode("movie");
                if (docNode == null)
                {
                    BasicLogger.Log("Empty XML for " + requestUrls.ElementAt(i), Verbosity.Error);
                    requestUrls.Remove(requestUrls.ElementAt(i));
                    i = -1;
                    continue;
                }
                responseNodes.Add(docNode);
            }
            for (var i = 0; i < responseNodes.Count; i++)
            {
                var xmlAttributeCollection = responseNodes.ElementAt(i).Attributes;
                if (xmlAttributeCollection == null)
                {
                    continue;
                }
                if (xmlAttributeCollection.GetNamedItem("type").Value != "movie")
                {
                    BasicLogger.Log("Element " + xmlAttributeCollection.GetNamedItem("imdbID").Value + " is not a movie!", Verbosity.Warning);
                    continue;
                }
                if (i == 0)
                {
                    movieToReturn.Title      = xmlAttributeCollection.GetNamedItem("title").Value;
                    movieToReturn.ImdbId     = xmlAttributeCollection.GetNamedItem("imdbID").Value;
                    movieToReturn.ImdbRating =
                        decimal.Parse(xmlAttributeCollection.GetNamedItem("imdbRating").Value);
                    var runtime = xmlAttributeCollection.GetNamedItem("runtime").Value;
                    if (runtime.Contains("min"))
                    {
                        runtime = runtime.Remove(runtime.IndexOf("min", StringComparison.Ordinal)).Trim();
                    }
                    movieToReturn.RunTime     = short.Parse(runtime);
                    movieToReturn.Language    = xmlAttributeCollection.GetNamedItem("language").Value;
                    movieToReturn.Rating      = xmlAttributeCollection.GetNamedItem("rated").Value;
                    movieToReturn.Year        = xmlAttributeCollection.GetNamedItem("year").Value;
                    movieToReturn.ReleaseDate =
                        DateTime.Parse(xmlAttributeCollection.GetNamedItem("released").Value);
                    movieToReturn.Actors = new List <Actor>();
                    var actorsString = xmlAttributeCollection.GetNamedItem("actors").Value;
                    while (actorsString.Contains("("))
                    {
                        actorsString = actorsString.Remove(actorsString.IndexOf("(", StringComparison.Ordinal),
                                                           actorsString.IndexOf(")", StringComparison.Ordinal) + 1 - actorsString.IndexOf("(", StringComparison.Ordinal));
                    }
                    var actorsList = actorsString.Split(',').ToList();
                    foreach (var actor in actorsList)
                    {
                        if (actor.Trim() == "")
                        {
                            continue;
                        }
                        var act = _actorsRepository.Query(x => x.Name == actor.Trim()).FirstOrDefault() ?? new Actor
                        {
                            Name = actor.Trim()
                        };
                        act.Portrait = _defaultAvatar.ToArray();
                        movieToReturn.Actors.Add(act);
                    }
                    movieToReturn.Directors = new List <Director>();
                    var directorsString = xmlAttributeCollection.GetNamedItem("director").Value;
                    while (directorsString.Contains("("))
                    {
                        directorsString = directorsString.Remove(directorsString.IndexOf("(", StringComparison.Ordinal),
                                                                 directorsString.IndexOf(")", StringComparison.Ordinal) + 1 - directorsString.IndexOf("(", StringComparison.Ordinal));
                    }
                    var directorsList = directorsString.Split(',').ToList();
                    foreach (var director in directorsList)
                    {
                        if (director.Trim() == "")
                        {
                            continue;
                        }
                        var dir = _directorsRepository.Query(x => x.Name == director.Trim()).FirstOrDefault() ?? new Director
                        {
                            Name = director.Trim()
                        };
                        dir.Portrait = _defaultAvatar.ToArray();
                        movieToReturn.Directors.Add(dir);
                    }
                    movieToReturn.Writers = new List <Writer>();
                    var writersString = xmlAttributeCollection.GetNamedItem("writer").Value;
                    while (writersString.Contains("("))
                    {
                        writersString = writersString.Remove(writersString.IndexOf("(", StringComparison.Ordinal),
                                                             writersString.IndexOf(")", StringComparison.Ordinal) + 1 - writersString.IndexOf("(", StringComparison.Ordinal));
                    }
                    var writersList = writersString.Split(',').ToList();
                    foreach (var writer in writersList)
                    {
                        if (writer.Trim() == "")
                        {
                            continue;
                        }
                        var wri = _writersRepository.Query(x => x.Name == writer.Trim()).FirstOrDefault() ?? new Writer
                        {
                            Name = writer.Trim()
                        };
                        wri.Portrait = _defaultAvatar.ToArray();
                        movieToReturn.Writers.Add(wri);
                    }
                    movieToReturn.Genres = new List <Genre>();
                    var genresString = xmlAttributeCollection.GetNamedItem("genre").Value;
                    while (genresString.Contains("("))
                    {
                        genresString = genresString.Remove(genresString.IndexOf("(", StringComparison.Ordinal),
                                                           genresString.IndexOf(")", StringComparison.Ordinal) + 1 - genresString.IndexOf("(", StringComparison.Ordinal));
                    }
                    var genresList = genresString.Split(',').ToList();
                    foreach (var genre in genresList)
                    {
                        var gen = _genresRepository.Query(x => x.Name == genre.Trim()).FirstOrDefault() ?? new Genre
                        {
                            Name = genre.Trim()
                        };
                        movieToReturn.Genres.Add(gen);
                    }
                    var stringImage =
                        client.GetStreamAsync(xmlAttributeCollection.GetNamedItem("poster").Value);
                    await stringImage;
                    var   reader     = new BinaryReader(stringImage.Result);
                    var   imagebytes = reader.ReadAllBytes();
                    movieToReturn.Poster = imagebytes;
                }
                if (requestUrls.ElementAt(i).Contains("plot=short"))
                {
                    movieToReturn.ShortPlot = responseNodes.ElementAt(i).Attributes.GetNamedItem("plot").Value;
                }
                else
                {
                    movieToReturn.LongPlot = responseNodes.ElementAt(i).Attributes.GetNamedItem("plot").Value;
                }
            }
            return(String.IsNullOrEmpty(movieToReturn.ImdbId) ? null : movieToReturn);
        }
 private void UpdateDatabaseWithWatchable(CompleteWatchable watchable, DatabaseBuilderType type, string path = "")
 {
     if (type == DatabaseBuilderType.Movies)
     {
         var files     = Directory.GetFileSystemEntries(path).ToList();
         var actors    = new List <Actor>(watchable.Actors);
         var writers   = new List <Writer>(watchable.Writers);
         var directors = new List <Director>(watchable.Directors);
         var genres    = new List <Genre>(watchable.Genres);
         watchable.Actors.Clear();
         watchable.Writers.Clear();
         watchable.Directors.Clear();
         watchable.Genres.Clear();
         _moviesRepository.Create((Movie)watchable);
         foreach (var file in files)
         {
             if (file.EndsWith("srt"))
             {
                 if (files.Count > 2)
                 {
                     BasicLogger.Log(watchable.Title +
                                     "'s subtitles not added due to more than 2 files being present in the directory.", Verbosity.Error);
                 }
                 else
                 {
                     var subs = new Subtitles
                     {
                         Language  = SubtitleLanguage.English,
                         Path      = file,
                         Watchable = watchable
                     };
                     _subtitlesRepository.Create(subs);
                 }
             }
             else if (file.EndsWith("mp4") || file.EndsWith("avi") || file.EndsWith("mkv") || file.EndsWith("wmv"))
             {
                 watchable.Path = file;
                 _moviesRepository.Update((Movie)watchable);
             }
         }
         foreach (var actor in actors)
         {
             var databaseActor = _actorsRepository.Query(x => x.Name == actor.Name).FirstOrDefault();
             if (databaseActor == null)
             {
                 actor.Watchables = new List <Watchable> {
                     watchable
                 };
                 _actorsRepository.Create(actor);
             }
             else
             {
                 if (databaseActor.Watchables == null)
                 {
                     databaseActor.Watchables = new List <Watchable>();
                 }
                 if (databaseActor.Watchables.Contains(watchable))
                 {
                     continue;
                 }
                 databaseActor.Watchables.Add(watchable);
                 _actorsRepository.Update(databaseActor);
             }
         }
         foreach (var writer in writers)
         {
             var databaseWriter = _writersRepository.Query(x => x.Name == writer.Name).FirstOrDefault();
             if (databaseWriter == null)
             {
                 writer.Watchables = new List <Watchable> {
                     watchable
                 };
                 _writersRepository.Create(writer);
             }
             else
             {
                 if (databaseWriter.Watchables == null)
                 {
                     databaseWriter.Watchables = new List <Watchable>();
                 }
                 if (databaseWriter.Watchables.Contains(watchable))
                 {
                     continue;
                 }
                 databaseWriter.Watchables.Add(watchable);
                 _writersRepository.Update(databaseWriter);
             }
         }
         foreach (var director in directors)
         {
             var databaseDirector = _directorsRepository.Query(x => x.Name == director.Name).FirstOrDefault();
             if (databaseDirector == null)
             {
                 director.Watchables = new List <Watchable> {
                     watchable
                 };
                 _directorsRepository.Create(director);
             }
             else
             {
                 if (databaseDirector.Watchables == null)
                 {
                     databaseDirector.Watchables = new List <Watchable>();
                 }
                 if (databaseDirector.Watchables.Contains(watchable))
                 {
                     continue;
                 }
                 databaseDirector.Watchables.Add(watchable);
                 _directorsRepository.Update(databaseDirector);
             }
         }
         foreach (var genre in genres)
         {
             var databaseGenre = _genresRepository.Query(x => x.Name == genre.Name).FirstOrDefault();
             if (databaseGenre == null)
             {
                 genre.Watchables = new List <Watchable> {
                     watchable
                 };
                 _genresRepository.Create(genre);
             }
             else
             {
                 if (databaseGenre.Watchables == null)
                 {
                     databaseGenre.Watchables = new List <Watchable>();
                 }
                 if (databaseGenre.Watchables.Contains(watchable))
                 {
                     continue;
                 }
                 databaseGenre.Watchables.Add(watchable);
                 _genresRepository.Update(databaseGenre);
             }
         }
     }
 }