예제 #1
0
        internal static void Add(MovieInfo movieInfo)
        {
            string commandText = @"INSERT INTO MOVIE_DATA (
                                    LOCATION, FILE_DATA_X, FILE_DATA_Y, FILE_DATA_DURATION, RAW_TITLE_PATH)
                                    VALUES (@location, @file_data_x, @file_data_y, @file_duration, @raw_title_path)";

            using (FbConnection connection = new FbConnection (string.Format (CONNECTION_STRING_FORMAT_FIREBIRD, DB_FILENAME)))
            {
                connection.Open ();

                using (FbTransaction transaction = connection.BeginTransaction ())
                {
                    using (FbCommand cmd = new FbCommand (commandText, connection, transaction))
                    {
                        cmd.Parameters.Add (new FbParameter ("@location", movieInfo.DvdName));
                        cmd.Parameters.Add (new FbParameter ("@file_data_x", movieInfo.FileData.X));
                        cmd.Parameters.Add (new FbParameter ("@file_data_y", movieInfo.FileData.Y));
                        cmd.Parameters.Add (new FbParameter ("@file_duration", movieInfo.FileData.Duration));
                        cmd.Parameters.Add (new FbParameter ("@raw_title_path", movieInfo.RawTitlePath));

                        cmd.ExecuteNonQuery ();
                    }
                    transaction.Commit ();
                }
            }
        }
        public void CompleteFromDatabase(MovieInfo movieInfo)
        {
            string searchTitle = movieInfo.Title;
            IList<MoviePage> searchResults = TryFindPossibleMoviePages (ref searchTitle);
            if (searchResults == null)
                return;

            MoviePage selectedResult = UserSelectSearchResult (searchTitle, searchResults.OrderBy (x => x.Match).ToList ());
            if (selectedResult == null)
                return;

            movieInfo.Year = selectedResult.Year;
            string detailsPage = GetMovieDetailsPage (selectedResult.RelativeLink);
        }
예제 #3
0
        /* -------------------------------------------------------------------------------------
         * Name:        getInfo
         * Goal:        Use the 'omdbapi' site to retrieve information on the movie with the indicated @imdbId
         * Parameters:  sImdbId     - The ImdbId of the movie we are interested in
         * History:
         * 24/feb/2016 ERK Created
           ------------------------------------------------------------------------------------- */
        public MovieInfo getInfo(String sImdbId)
        {
            try {
            // Create the object we will return
            MovieInfo oBack = new MovieInfo();
            // Create the imdbid string: "tt" + exactly 7 numbers, possibly prepended by '0'
            int iImdbId = Convert.ToInt32(sImdbId);
            sImdbId = "tt" + iImdbId.ToString("D7");

            // Create the request string
            String sRequest = sApiStart.Replace("@tt", sImdbId);
            // Make the request
            WebRequest request = WebRequest.Create(sRequest);
            request.Method = "GET";
            WebResponse response = request.GetResponse();
            StringBuilder sbReply = new StringBuilder();
            // Process the result
            using (Stream strResponse = response.GetResponseStream())
            using (StreamReader rdThis = new StreamReader(strResponse)) {
              Char[] readBuff = new Char[iBufSize];
              int iCount = rdThis.Read(readBuff, 0, iBufSize);
              while (iCount > 0) {
            // Append the information to the stringbuilder
            sbReply.Append(new String(readBuff, 0, iCount));
            // Make a follow-up request
            iCount = rdThis.Read(readBuff, 0, iBufSize);
              }
            }
            // Convert the XML reply to a processable object
            XmlDocument pdxReply = new XmlDocument();
            pdxReply.LoadXml(sbReply.ToString());
            // Get to the information
            XmlNode ndxInfo = pdxReply.SelectSingleNode("./descendant-or-self::movie");
            if (ndxInfo == null) return null;
            // Fill the object we will return
            // Iterate over all the properties of object 'MovieInfo'
            //    NOTE: they have to be implemented as 'properties' of the class...
            foreach(PropertyInfo prop in typeof(MovieInfo).GetProperties()) {
              // Set the value of oBack's property using the information in the Xml node
              prop.SetValue(oBack, ndxInfo.Attributes[prop.Name].Value);
            }

            // Read the reply as a
            return oBack;
              } catch (Exception ex) {
            errHandle.DoError("oprConv/getInfo", ex);
            return null;
              }
        }
예제 #4
0
        public static Task<Model.Epg> GetMetadata(Model.Epg epg, CancellationToken cancellationToken)
        {
            return Task.Run(async () =>
            {
                var movieItem = new MediaBrowser.Controller.Entities.Movies.Movie();

                try
                {
                    var movieInfo = new MovieInfo
                    {
                        Name = epg.Title,
                        MetadataLanguage = "en",
                    };

                    if (Cache[epg.Title] == null)
                    {
                        MetadataResult<MediaBrowser.Controller.Entities.Movies.Movie> omdbMovie;

                        var omdbItemProvider = new OmdbItemProvider(LiveTvService.JsonSerializer,
                            LiveTvService.HttpClient, LiveTvService.Logger, LiveTvService.LibraryManager, LiveTvService.FileSystem, LiveTvService.Config);

                        omdbMovie = await omdbItemProvider.GetMetadata(movieInfo, cancellationToken);

                        var imdbId = omdbMovie.Item.GetProviderId(MetadataProviders.Imdb);

                        Cache.Add(epg.Title, movieItem, DateTimeOffset.Now.AddDays(1));
                    }
                    else movieItem = Cache[epg.Title] as MediaBrowser.Controller.Entities.Movies.Movie;
                }
                catch (Exception exception)
                {
                    epg = null;

                    //Logger.Error("Series provider error: " + exception.Message);
                    //Logger.ErrorException("Movie provider error", exception);
                }

                return epg;
            });
        }
예제 #5
0
        internal static void Delete(MovieInfo movieInfo)
        {
            string commandText = @"DELETE FROM MOVIE_DATA
                                    WHERE LOCATION = @location AND RAW_TITLE_PATH = @raw_title_path";

            using (FbConnection connection = new FbConnection (string.Format (CONNECTION_STRING_FORMAT_FIREBIRD, DB_FILENAME)))
            {
                connection.Open ();

                using (FbTransaction transaction = connection.BeginTransaction ())
                {
                    using (FbCommand cmd = new FbCommand (commandText, connection, transaction))
                    {
                        cmd.Parameters.Add (new FbParameter ("@location", movieInfo.DvdName));
                        cmd.Parameters.Add (new FbParameter ("@raw_title_path", movieInfo.RawTitlePath));

                        cmd.ExecuteNonQuery ();
                    }
                    transaction.Commit ();
                }
            }
        }
예제 #6
0
        private void button1_Click(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog();
            dialog.Filter = "视频文件|*.avi;*.rmvb;*.rm";
            if (dialog.ShowDialog() == DialogResult.OK) {
                var file = dialog.FileName;
                capture = CvInvoke.cvCreateFileCapture(file);

                movieInfo = new MovieInfo(file, capture);
                trackBar.SetRange(0, movieInfo.frameCount);
                if (myTimer != null) {
                    myTimer.Stop();
                    myTimer.Dispose();
                }
                myTimer = new Timer();
                myTimer.Interval = 1000 / Convert.ToInt32(movieInfo.fps);
                myTimer.Tick += new EventHandler(MyTimer_Tick);

                MovieHandlers(this, new MovieEvent(MovieEvent.State.NewMovie));

                myTimer.Start();
            }
        }
        /// <summary>
        /// Downloads the JSON from the given URI and parses this into a dictionary
        /// </summary>
        /// <param name="url">The URI to download</param>
        /// <param name="movieInfo">The reference object to store the resulting MovieInfo object in</param>
        /// <returns>The result status code for this service call</returns>
        ServiceResultStatus LoadMovieData(string url, out MovieInfo movieInfo)
        {
            movieInfo = null;

            // Download JSON
            var client = new WebClient();
            string json;
            try {
                json = client.DownloadString(url);
            }
            catch (System.Net.WebException e) {
                Log("Could not load JSON: " + e.Message);
                return ServiceResultStatus.TemporaryError;
            }

            // Parse JSON and build object
            Dictionary<string, object> data;
            try {
                data = _serializer.DeserializeObject(json) as Dictionary<string, object>;
            }
            catch(Exception e) {
                Log("Could not parse JSON: " + e.Message);
                return ServiceResultStatus.InvalidResponse;
            }

            // Check response
            if (data["Response"].ToString().ToLower() == "false") {
                Log(data["Error"].ToString());
                return ServiceResultStatus.NoResult;
            }

            // Build object
            try {
                movieInfo = MovieInfo.Build(data);
                return ServiceResultStatus.Success;
            }
            catch (Exception) {
                Log("Could not build MovieInfo object");
                return ServiceResultStatus.InvalidResponse;
            }
        }
예제 #8
0
        public void SetUp()
        {
            _movie = new MovieInfo
            {
                MovieName    = "Test Movie",
                OriginalName = "Original Movie Name",
                Budget       = 100000,
                Awards       = new List <string> {
                    "Oscar"
                },
                AllocinebId   = 100,
                Actors        = new List <PersonInfo>(),
                CinePassionId = 200,
                Genres        = new List <GenreInfo>(),
                Rating        = new SimpleRating(5, 10),
                Runtime       = 120,
                Thumbnail     = new byte[] { 0x01, 0x02, 0x03 },
                Writers       = new List <PersonInfo>(),
                Characters    = new List <CharacterInfo>(),
                Languages     = new List <string> {
                    "en-US"
                },
                Directors           = new List <PersonInfo>(),
                ProductionCompanies = new List <CompanyInfo>(),
            };
            _movie.Actors.Add(new PersonInfo
            {
                Name        = "Actor Name Long",
                DateOfBirth = DateTime.Now,
                ImdbId      = "nm00000",
                AudioDbId   = 123,
                IsGroup     = false,
                Occupation  = "Actor",
            });
            _movie.Actors.Add(new PersonInfo
            {
                Name        = "Actor Name Long 2",
                DateOfBirth = DateTime.Now,
                ImdbId      = "nm00001",
                AudioDbId   = 124,
                IsGroup     = false,
                Occupation  = "Actor",
            });
            _movie.Genres.Add(new GenreInfo
            {
                Id   = 1,
                Name = "Action"
            });

            _movieSearch = new MovieInfo
            {
                MovieName = "Test Movie Long",
                Budget    = 100000,
                Awards    = new List <string> {
                    "Oscar", "Emmy"
                },
                ImdbId              = "tt0000",
                Actors              = new List <PersonInfo>(),
                CollectionName      = "Test Collection",
                CollectionMovieDbId = 122,
                CollectionNameId    = "testcollection",
                MovieDbId           = 222,
                Genres              = new List <GenreInfo>(),
                Rating              = new SimpleRating(7, 100),
                Runtime             = 125,
                Thumbnail           = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 },
                Writers             = new List <PersonInfo>(),
                Characters          = new List <CharacterInfo>(),
                Languages           = new List <string> {
                    "de"
                },
                Directors           = new List <PersonInfo>(),
                ProductionCompanies = new List <CompanyInfo>(),
                MovieNameSort       = "Movie Sort Name",
                Summary             = "Movie Summery",
                Tagline             = "Movie Tagline",
                Revenue             = 500000,
                Certification       = "PG-13"
            };
            _movieSearch.Actors.Add(new PersonInfo
            {
                Name          = "Actor Name 2",
                DateOfBirth   = DateTime.Now,
                ImdbId        = "nm00001",
                AudioDbId     = 124,
                IsGroup       = false,
                Biography     = "Actor Biography",
                DateOfDeath   = DateTime.Now,
                AlternateName = "Alternate Name",
                MusicBrainzId = "7F1E039D-480E-4076-BD02-11F215C79C89",
                Occupation    = "Actor",
                TvdbId        = 324
            });
            _movieSearch.ProductionCompanies.Add(new CompanyInfo
            {
                Name          = "Company Name",
                ImdbId        = "cc10001",
                AudioDbId     = 333,
                MusicBrainzId = "A19A198B-BBC2-426F-ACD1-EE545F16B2BC",
                Type          = "Film Studio",
                TvdbId        = 444
            });
            _movieSearch.Genres.Add(new GenreInfo
            {
                Id   = 2,
                Name = "Adventure"
            });
        }
 public override bool UpdateCharacters(MovieInfo movieInfo, bool importOnly)
 {
     return(false);
 }
예제 #10
0
        static List <Tuple <int, List <MovieInfo> > > GetMovies()
        {
            List <MovieInfo> moviesInfo = new List <MovieInfo>();

            List <int> ids = Extensions.Extensions.GetEmptyFieldsInGoogleTab(6502, 6730);

            bool flag = false;

            for (int i = 0; i < lines.Length; i++)
            {
                if (i > 3500)
                {
                    int id = Convert.ToInt32(IdMatch.Match(lines[i]).Groups[1].Value);
                    if (ids.Contains(id))
                    {
                        flag = true;
                        resultLines.Add(lines[i]);
                    }
                    if (flag && id > ids[ids.Count - 1] && id != 495)
                    {
                        resultLines.Add(lines[i]);
                    }
                }
            }

            //foreach (string x in lines)
            //{
            //    if (x.Contains(pattern))
            //    {
            //        resultLines.Add(x);
            //    }

            //}
            foreach (string x in resultLines)
            {
                Match     idMatch   = IdMatch.Match(x);
                int[]     numbers   = Regex.Matches(seasonNumMatch.Match(x).Groups[0].Value, "(-?[0-9]+)").OfType <Match>().Select(m => int.Parse(m.Value)).ToArray();
                string[]  forResult = x.Split(new string[] { "-->" }, StringSplitOptions.None);
                Match     nameMatch = new Regex(@"(?<=/in/)(.*)(?=.avi)").Match(forResult[0]);
                MovieInfo info      = new MovieInfo(x, Convert.ToInt32(idMatch.Groups[1].Value), nameOfSerial, numbers[0], numbers[1], "/hlsvodnew/" + forResult[1].Trim() + "/playlist.m3u8", nameMatch.Groups[1].Value);
                moviesInfo.Add(info);
            }

            var list = new List <Tuple <int, List <MovieInfo> > >();
            //moviesInfo.Sort((x, y) =>
            //    x.Season.CompareTo(y.Season));
            var maxSeason = moviesInfo.OrderByDescending(item => item.Season).First().Season;

            for (int i = 1; i < maxSeason; i++)
            {
                var tempList = moviesInfo.Where(a => a.Season == i).ToList();
                tempList.Sort((x, y) => x.Episode.CompareTo(y.Episode));
                //var count = 1;
                //for (int j = 0; j < tempList.Count; j++)
                //{
                //    tempList[j].Episode = count;
                //    count++;
                //}

                list.Add(new Tuple <int, List <MovieInfo> >(i, tempList));
            }

            return(list);
        }
예제 #11
0
        internal static void Update(MovieInfo movieInfo)
        {
            SqlCommand command = new SqlCommand ();
            command.CommandText = @"INSERT INTO MOVIE_DATA (
                                    LOCATION, FILE_DATA_X, FILE_DATA_Y, FILE_DATA_DURATION, RAW_TITLE_PATH)
                                    VALUES ('Los Angeles', 900, '10.Jan.1999')";
            command.Parameters.Add (new SqlParameter ("@PROD_ID", 100));

            //JpegBitmapEncoder encoder = new JpegBitmapEncoder ();
            //encoder.Frames.Add (BitmapFrame.Create (bmSource));
            //MemoryStream stream = new MemoryStream ();
            //encoder.Save (stream);
        }
        /// <summary>
        /// Asynchronously tries to extract metadata for the given <param name="mediaItemAccessor"></param>
        /// </summary>
        /// <param name="mediaItemAccessor">Points to the resource for which we try to extract metadata</param>
        /// <param name="extractedAspectData">Dictionary of <see cref="MediaItemAspect"/>s with the extracted metadata</param>
        /// <param name="forceQuickMode">If <c>true</c>, nothing is downloaded from the internet</param>
        /// <returns><c>true</c> if metadata was found and stored into <param name="extractedAspectData"></param>, else <c>false</c></returns>
        private async Task <bool> TryExtractMovieMetadataAsync(IResourceAccessor mediaItemAccessor, IDictionary <Guid, IList <MediaItemAspect> > extractedAspectData, bool forceQuickMode)
        {
            // Get a unique number for this call to TryExtractMetadataAsync. We use this to make reading the debug log easier.
            // This MetadataExtractor is called in parallel for multiple MediaItems so that the respective debug log entries
            // for one call are not contained one after another in debug log. We therefore prepend this number before every log entry.
            var  miNumber = Interlocked.Increment(ref _lastMediaItemNumber);
            bool isStub   = extractedAspectData.ContainsKey(StubAspect.ASPECT_ID);

            try
            {
                _debugLogger.Info("[#{0}]: Start extracting metadata for resource '{1}' (forceQuickMode: {2})", miNumber, mediaItemAccessor, forceQuickMode);

                // This MetadataExtractor only works for MediaItems accessible by an IFileSystemResourceAccessor.
                // Otherwise it is not possible to find a nfo-file in the MediaItem's directory.
                if (!(mediaItemAccessor is IFileSystemResourceAccessor))
                {
                    _debugLogger.Info("[#{0}]: Cannot extract metadata; mediaItemAccessor is not an IFileSystemResourceAccessor", miNumber);
                    return(false);
                }

                // We only extract metadata with this MetadataExtractor, if another MetadataExtractor that was applied before
                // has identified this MediaItem as a video and therefore added a VideoAspect.
                if (!extractedAspectData.ContainsKey(VideoAspect.ASPECT_ID))
                {
                    _debugLogger.Info("[#{0}]: Cannot extract metadata; this resource is not a video", miNumber);
                    return(false);
                }

                // Here we try to find an IFileSystemResourceAccessor pointing to the nfo-file.
                // If we don't find one, we cannot extract any metadata.
                IFileSystemResourceAccessor nfoFsra;
                if (!TryGetNfoSResourceAccessor(miNumber, mediaItemAccessor as IFileSystemResourceAccessor, out nfoFsra))
                {
                    return(false);
                }

                // Now we (asynchronously) extract the metadata into a stub object.
                // If there is an error parsing the nfo-file with XmlNfoReader, we at least try to parse for a valid IMDB-ID.
                // If no metadata was found, nothing can be stored in the MediaItemAspects.
                NfoMovieReader nfoReader = new NfoMovieReader(_debugLogger, miNumber, false, forceQuickMode, isStub, _httpClient, _settings);
                using (nfoFsra)
                {
                    if (!await nfoReader.TryReadMetadataAsync(nfoFsra).ConfigureAwait(false) &&
                        !await nfoReader.TryParseForImdbId(nfoFsra).ConfigureAwait(false))
                    {
                        _debugLogger.Warn("[#{0}]: No valid metadata found", miNumber);
                        return(false);
                    }
                    else if (isStub)
                    {
                        Stubs.MovieStub movie = nfoReader.GetMovieStubs().FirstOrDefault();
                        if (movie != null)
                        {
                            IList <MultipleMediaItemAspect> providerResourceAspects;
                            if (MediaItemAspect.TryGetAspects(extractedAspectData, ProviderResourceAspect.Metadata, out providerResourceAspects))
                            {
                                MultipleMediaItemAspect providerResourceAspect = providerResourceAspects.First(pa => pa.GetAttributeValue <int>(ProviderResourceAspect.ATTR_TYPE) == ProviderResourceAspect.TYPE_STUB);
                                string mime = null;
                                if (movie.FileInfo != null && movie.FileInfo.Count > 0)
                                {
                                    mime = MimeTypeDetector.GetMimeTypeFromExtension("file" + movie.FileInfo.First().Container);
                                }
                                if (mime != null)
                                {
                                    providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_MIME_TYPE, mime);
                                }
                            }

                            MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_TITLE, movie.Title);
                            MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_SORT_TITLE, movie.SortTitle != null ? movie.SortTitle : BaseInfo.GetSortTitle(movie.Title));
                            MediaItemAspect.SetAttribute(extractedAspectData, MediaAspect.ATTR_RECORDINGTIME, movie.Premiered.HasValue ? movie.Premiered.Value : movie.Year.HasValue ? movie.Year.Value : (DateTime?)null);

                            if (movie.FileInfo != null && movie.FileInfo.Count > 0)
                            {
                                extractedAspectData.Remove(VideoStreamAspect.ASPECT_ID);
                                extractedAspectData.Remove(VideoAudioStreamAspect.ASPECT_ID);
                                extractedAspectData.Remove(SubtitleAspect.ASPECT_ID);
                                StubParser.ParseFileInfo(extractedAspectData, movie.FileInfo, movie.Title, movie.Fps);
                            }
                        }
                    }
                }

                //Check reimport
                if (extractedAspectData.ContainsKey(ReimportAspect.ASPECT_ID))
                {
                    MovieInfo reimport = new MovieInfo();
                    reimport.FromMetadata(extractedAspectData);
                    if (!VerifyMovieReimport(nfoReader, reimport))
                    {
                        ServiceRegistration.Get <ILogger>().Info("NfoMovieMetadataExtractor: Nfo movie metadata from resource '{0}' ignored because it does not match reimport {1}", mediaItemAccessor, reimport);
                        return(false);
                    }
                }

                // Then we store the found metadata in the MediaItemAspects. If we only found metadata that is
                // not (yet) supported by our MediaItemAspects, this MetadataExtractor returns false.
                if (!nfoReader.TryWriteMetadata(extractedAspectData))
                {
                    _debugLogger.Warn("[#{0}]: No metadata was written into MediaItemsAspects", miNumber);
                    return(false);
                }

                _debugLogger.Info("[#{0}]: Successfully finished extracting metadata", miNumber);
                ServiceRegistration.Get <ILogger>().Debug("NfoMovieMetadataExtractor: Assigned nfo movie metadata for resource '{0}'", mediaItemAccessor);
                return(true);
            }
            catch (Exception e)
            {
                ServiceRegistration.Get <ILogger>().Warn("NfoMovieMetadataExtractor: Exception while extracting metadata for resource '{0}'; enable debug logging for more details.", mediaItemAccessor);
                _debugLogger.Error("[#{0}]: Exception while extracting metadata", e, miNumber);
                return(false);
            }
        }
예제 #13
0
 public MovieBuildedEventArgs(MovieInfo movieInfo)
 {
     this.MovieInfo = movieInfo;
 }
예제 #14
0
 public void AddToMovieInfo(MovieInfo movieInfo)
 {
     base.AddObject("MovieInfo", movieInfo);
 }
예제 #15
0
 public static MovieInfo CreateMovieInfo(int id)
 {
     MovieInfo movieInfo = new MovieInfo();
     movieInfo.id = id;
     return movieInfo;
 }
예제 #16
0
        internal static string GetMovieInfo(string name)
        {
            name = name.ToLower();
            string json = string.Empty;
            if (!CacheManager.TryGet<string>(CacheConstants.MovieInfoJson + name, out json))
            {

                try
                {
                    var tableMgr = new TableManager();

                    // get single movie object form database by its unique name
                    var movie = tableMgr.GetMovieByUniqueName(name);

                    if (movie != null)
                    {
                        MovieInfo movieInfo = new MovieInfo();
                        movieInfo.movieId = movie.MovieId;
                        movieInfo.Movie = movie;

                        // get reviews for movie by movie id
                        var reviewList = tableMgr.GetReviewsByMovieId(movie.MovieId);

                        // if reviews not null then add review to review list.
                        var userReviews = (reviewList != null) ?
                            reviewList.Select(review =>
                            {
                                ReviewerEntity reviewer = tableMgr.GetReviewerById(review.Value.ReviewerId);
                                ReviewEntity objReview = review.Value as ReviewEntity;

                                objReview.ReviewerName = reviewer.ReviewerName;
                                objReview.CriticsRating = objReview.SystemRating == 0 ? "" : (objReview.SystemRating == -1 ? 0 : 100).ToString();

                                //objReview.OutLink = reviewer.ReviewerImage;
                                return objReview;
                            }) :
                            Enumerable.Empty<ReviewEntity>();

                        //add reviewlist to movieinfo reviews
                        movieInfo.MovieReviews = userReviews.ToList();

                        // serialize movie object and return.
                        json = jsonSerializer.Value.Serialize(movieInfo);
                    }
                    else
                    {
                        // if movie not found then return empty string
                        json = string.Empty;
                    }

                    CacheManager.Add<string>(CacheConstants.MovieInfoJson + name, json);
                }
                catch (Exception ex)
                {
                    // if any error occured then return User friendly message with system error message
                    // use jsonError here because more custumizable
                    json = jsonSerializer.Value.Serialize(
                    new
                    {
                        Status = "Error",
                        UserMessage = "Unable to find " + name + " movie.",
                        ActualError = ex.Message
                    });
                }
            }
            return json;
        }
예제 #17
0
        internal static List<MovieInfo> LoadMovies()
        {
            if (!File.Exists (DB_FILENAME))
            {
                CreateDatabase ();
                return new List<MovieInfo> ();
            }

            List<MovieInfo> result = new List<MovieInfo> ();

            string commandText = @"SELECT * FROM MOVIE_DATA;";

            using (FbConnection connection = new FbConnection (string.Format (CONNECTION_STRING_FORMAT_FIREBIRD, DB_FILENAME)))
            {
                connection.Open ();

                using (FbTransaction transaction = connection.BeginTransaction ())
                {
                    using (FbCommand cmd = new FbCommand (commandText, connection, transaction))
                    {
                        FbDataReader reader = cmd.ExecuteReader ();
                        while (reader.Read ())
                        {
                            MovieFileData fileData = new MovieFileData ()
                            {
                                Duration = reader.GetDouble (7),
                                X = reader.GetInt32 (5),
                                Y = reader.GetInt32 (6)
                            };

                            string rawTitlePath = reader.GetString (8);
                            string dvdName = reader.GetString (4);
                            MovieInfo info = new MovieInfo (rawTitlePath, dvdName, fileData)
                            {
                                CoverImage = null,// BitmapSource.Create (reader.GetBytes (3))
                                Description = reader.GetString (1),
                                Genres = reader.GetString (0),
                                Rating = reader.GetString (2)
                            };

                            result.Add (info);
                        }
                    }
                    transaction.Commit ();
                }
            }

            // Write into the new database structure
            //CreateDatabase ();
            //foreach (MovieInfo info in result)
            //{
            //    Add (info);
            //}

            return result;
        }
예제 #18
0
        // get : api/MovieInfo?q={movieId}
        protected override string ProcessRequest()
        {
            JavaScriptSerializer json = new JavaScriptSerializer();

            try
            {
                var tableMgr = new TableManager();
                MovieInfo movieInfo = new MovieInfo();

                // get query string parameters
                var qpParams = HttpUtility.ParseQueryString(this.Request.RequestUri.Query);

                if (string.IsNullOrEmpty(qpParams["q"]))
                {
                    throw new ArgumentException(Constants.API_EXC_MOVIE_NAME_NOT_EXIST);
                }

                string name = qpParams["q"].ToString();

                // get single movie object form database by its uinque name
                var movie = tableMgr.GetMovieByUniqueName(name);

                if (movie != null)
                {
                    List<ReviewEntity> userReviews = new List<ReviewEntity>();

                    movieInfo.movieId = movie.MovieId;

                    // get reviews for movie by movie id
                    var reviewList = tableMgr.GetReviewsByMovieId(movie.MovieId);

                    if (reviewList != null)
                    {
                        // if reviews not null then add review to review list.
                        foreach (var review in reviewList)
                        {
                            ReviewerEntity reviewer = tableMgr.GetReviewerById(review.Value.ReviewerId);
                            ReviewEntity objReview = review.Value as ReviewEntity;

                            objReview.Affiliation = reviewer.Affilation;
                            objReview.ReviewerName = reviewer.ReviewerName;
                            objReview.OutLink = reviewer.ReviewerImage;
                            userReviews.Add(objReview);
                        }
                    }

                    //add reviewlist to movieinfo reviews
                    movieInfo.MovieReviews = userReviews;

                    // serialize movie object and return.
                    return json.Serialize(movieInfo);
                }
                else
                {
                    // if movie not found then return empty string
                    return string.Empty;
                }
            }
            catch (Exception ex)
            {
                // if any error occured then return User friendly message with system error message
                return json.Serialize(new { Status = "Error", UserMessage = Constants.UM_WHILE_GETTING_MOVIE, ActualError = ex.Message });
            }
        }
예제 #19
0
        protected async Task <ApiWrapperImageCollection <FanArtMovieThumb> > GetMovieFanArtAsync(MovieInfo movie, string language)
        {
            if (movie == null || movie.MovieDbId < 1)
            {
                return(null);
            }
            // Download all image information, filter later!
            FanArtMovieThumbs thumbs = await _fanArtTvHandler.GetMovieThumbsAsync(movie.MovieDbId.ToString()).ConfigureAwait(false);

            if (thumbs == null)
            {
                return(null);
            }
            ApiWrapperImageCollection <FanArtMovieThumb> images = new ApiWrapperImageCollection <FanArtMovieThumb>();

            images.Id = movie.MovieDbId.ToString();
            if (thumbs.MovieFanArt != null)
            {
                images.Backdrops.AddRange(SortByLanguageAndLikes(thumbs.MovieFanArt));
            }
            if (thumbs.MovieBanners != null)
            {
                images.Banners.AddRange(SortByLanguageAndLikes(thumbs.MovieBanners));
            }
            if (thumbs.MoviePosters != null)
            {
                images.Posters.AddRange(SortByLanguageAndLikes(thumbs.MoviePosters));
            }
            if (thumbs.MovieCDArt != null)
            {
                images.DiscArt.AddRange(SortByLanguageAndLikes(thumbs.MovieCDArt));
            }
            if (thumbs.HDMovieClearArt != null)
            {
                images.ClearArt.AddRange(SortByLanguageAndLikes(thumbs.HDMovieClearArt));
            }
            if (thumbs.HDMovieLogos != null)
            {
                images.Logos.AddRange(SortByLanguageAndLikes(thumbs.HDMovieLogos));
            }
            if (thumbs.MovieThumbnails != null)
            {
                images.Thumbnails.AddRange(SortByLanguageAndLikes(thumbs.MovieThumbnails));
            }
            return(images);
        }
예제 #20
0
        /// <summary>
        /// 获取影视地址
        /// </summary>
        /// <param name="qs"></param>
        /// <param name="cls"></param>
        /// <returns></returns>
        public string GetMovieUrl(MovieInfo b, Class cls)
        {
            string result = "";
            string fileName = TitleFilter(b.Title);

            string sitrurl = "/Movie/";

            result = string.Format("{0}{1}/{2}/index{3}",
                sitrurl,
                cls.ClassForder,
                fileName,
                BasePage.SystemSetting.ExtName
                );

            result = Regex.Replace(result, "[/]{2,}", "/");
            result = result.Replace(":", "_");
            result = result.Replace(">", "");
            result = result.Replace("<", "");
            result = result.Replace("*", "");
            result = result.Replace("?", "");
            result = result.Replace("|", "_");
            return result;
        }
예제 #21
0
 public Task <MetadataResult <Movie> > GetMetadata(MovieInfo info, CancellationToken cancellationToken)
 {
     return(GetMovieResult <Movie>(info, cancellationToken));
 }
예제 #22
0
        public void MovieInfoToMovieViewModel(MovieInfo vm)
        {
            var result = MockHelper.Mapper.Value.Map <MovieViewModel>(vm);

            result.Should().BeOfType <MovieViewModel>();
        }
예제 #23
0
 public override Task <bool> UpdatePersonsAsync(MovieInfo movieInfo, string occupation)
 {
     return(Task.FromResult(false));
 }
예제 #24
0
        private void getRentals()
        {
            Log.Info("HeadWeb: getRentals()");
              try
              {
            isGenre = false;
            isGenreContent = false;
            int runtime_hours = 0;
            int runtime_minutes = 0;
            XmlDocument doc = new XmlDocument();
            string requestUrl = Utils.constructUrl("user/rentals", "fields=name,plot,year,rating,genre,stream,cover,director&limit=40");
            string rootXML = Utils.GetWebData(requestUrl, HeadWebSettings.Instance.s_cc, null, null, false, false, null, "GET", null, false, false);
            doc.LoadXml(rootXML);
            XmlElement root = doc.DocumentElement;
            facadeLayout.Clear();
            mInfo.Clear();
            GUIListItem item = null;
            MovieInfo movieinfo = null;
            XmlNodeList list = root.SelectNodes("/response/list/item");
            foreach (XmlNode elm in list)
            {
              XmlNode node = elm.SelectSingleNode("content");
              string best = Utils.getBestCover(node);
              item = new GUIListItem();
              item.ItemId = Int32.Parse(node.Attributes["id"].Value);
              movieinfo = new MovieInfo();
              movieinfo.MovieID = item.ItemId;

              if (HeadWebSettings.Instance.s_useoriginalname)
              {
            try
            {
              item.Label = elm["originalname"].InnerText;
              if (item.Label.Length <= 0)
              {
                item.Label = elm["name"].InnerText;
              }
              HeadWebSettings.Instance.s_movietitle = Utils.makeSafeFilename(item.Label);
            }
            catch
            {
              try { item.Label = elm["name"].InnerText; HeadWebSettings.Instance.s_movietitle = Utils.makeSafeFilename(item.Label); }
              catch { }
            }
              }
              else
              {
            try { item.Label = elm["name"].InnerText; HeadWebSettings.Instance.s_movietitle = Utils.makeSafeFilename(item.Label); }
            catch { }
              }

              item.ThumbnailImage = best;

              item.Label2 = Translation.Expired;
              try
              {
            DateTime utcDateTime_rentalexpires = DateTime.Parse(elm["expires"].InnerText);
            DateTime utcDateTime_now = DateTime.Now;
            if (utcDateTime_rentalexpires > utcDateTime_now)
            {
              int time = Int32.Parse(elm["timeleft"].InnerText);
              runtime_hours = (time / 3600);
              runtime_minutes = ((time / 60) % 60);
              item.Label2 = runtime_hours.ToString() + "h " + runtime_minutes.ToString() + "m";
            }
              }
              catch { }

              try { item.Year = Int32.Parse(node["year"].InnerText); }
              catch { }

              XmlNode runtimenode = node.SelectSingleNode("stream/runtime");
              string runtime = string.Empty;

              try { item.Duration = Int32.Parse(runtimenode.InnerText); }
              catch { }

              XmlNode ratingnode = elm.SelectSingleNode("content/rating");
              string rating = string.Empty;
              try { item.Rating = float.Parse(ratingnode.InnerText); }
              catch { }

              XmlNode plotnode = elm.SelectSingleNode("content/plot");
              string plot = string.Empty;
              try { movieinfo.Plot = plotnode.InnerText; }
              catch { }

              try
              {
            string finalDirector = string.Empty;
            string[] list_directors = new string[] { };
            List<string> directorlist = new List<string>();

            XmlNodeList directornode = node.SelectNodes("director/person");
            foreach (XmlNode directorelm in directornode)
            {
              string newDirector = directorelm.InnerText;
              directorlist.Add(newDirector);
            }
            list_directors = directorlist.ToArray();
            if (list_directors.Length > 0)
            {
              finalDirector = string.Join(", ", list_directors);
            }
            movieinfo.Directors = finalDirector;
              }
              catch { }

              try
              {
            string finalGenre = string.Empty;
            string[] list_genres = new string[] { };
            List<string> genrelist = new List<string>();

            XmlNodeList genrenode = node.SelectNodes("genre");
            foreach (XmlNode genreelm in genrenode)
            {
              string newGenre = genreelm.InnerText;
              genrelist.Add(newGenre);
            }
            list_genres = genrelist.ToArray();
            if (list_genres.Length > 0)
            {
              finalGenre = string.Join(", ", list_genres);
            }
            movieinfo.Genres = finalGenre;
              }
              catch { }

              facadeLayout.Add(item);
              mInfo.Add(movieinfo);
            }
            int iTotalItems = facadeLayout.Count;
            GUIPropertyManager.SetProperty("#itemcount", iTotalItems.ToString());
            if (rememberIndex > -1)
            {
              GUIControl.SelectItemControl(GetID, facadeLayout.GetID, rememberIndex);
            }
            else
            {
              GUIControl.SelectItemControl(GetID, facadeLayout.GetID, 0);
            }
              }
              catch (Exception e)
              {
            Log.Error("HeadWeb: getRentals() caused an exception " + e.Message);
              }
        }
예제 #25
0
 public override Task <bool> UpdateCharactersAsync(MovieInfo movieInfo)
 {
     return(Task.FromResult(false));
 }
예제 #26
0
 public Task <IEnumerable <RemoteSearchResult> > GetSearchResults(MovieInfo searchInfo, CancellationToken cancellationToken)
 {
     return(GetSearchResults(searchInfo, "movie", cancellationToken));
 }
예제 #27
0
        public void getFavorites(bool storeOnly)
        {
            Log.Info("HeadWeb: getFavorites()");
              try
              {
            isGenre = false;
            isGenreContent = false;
            XmlDocument doc = new XmlDocument();
            string requestUrl = Utils.constructUrl("user/watchlist", "");

            // Clear web-cache by setting cache to 0
            int tempCacheTime = HeadWebSettings.Instance.CacheTimeout;
            HeadWebSettings.Instance.CacheTimeout = 0;

            string rootXML = Utils.GetWebData(requestUrl, HeadWebSettings.Instance.s_cc, null, null, false, false, null, "GET", null);
            doc.LoadXml(rootXML);
            XmlElement root = doc.DocumentElement;
            mInfo.Clear();
            if (!storeOnly)
            {
              facadeLayout.Clear();
            }
              GUIListItem item = null;
              MovieInfo movieinfo = null;
            XmlNodeList list = root.SelectNodes("/response/list/content");
            foreach (XmlNode elm in list)
            {
              string best = Utils.getBestCover(elm);
              item = new GUIListItem();
              movieinfo = new MovieInfo();
              item.ItemId = Int32.Parse(elm.Attributes["id"].Value);
              if (!storeOnly)
              {

            if (HeadWebSettings.Instance.s_useoriginalname)
            {
              try
              {
                item.Label = elm["originalname"].InnerText;
                if (item.Label.Length <= 0)
                {
                  item.Label = elm["name"].InnerText;
                }
                HeadWebSettings.Instance.s_movietitle = Utils.makeSafeFilename(item.Label);
              }
              catch
              {
                try { item.Label = elm["name"].InnerText; HeadWebSettings.Instance.s_movietitle = Utils.makeSafeFilename(item.Label); }
                catch { }
              }
            }
            else
            {
              try { item.Label = elm["name"].InnerText; HeadWebSettings.Instance.s_movietitle = Utils.makeSafeFilename(item.Label); }
              catch { }
            }

            item.ThumbnailImage = best;

            XmlNode streamnode_type = elm.SelectSingleNode("stream/type");
            string stream_type = string.Empty;
            try { stream_type = streamnode_type.InnerText; }
            catch { }

            XmlNode pricenode = elm.SelectSingleNode("stream/price");
            try { item.Label2 = pricenode.InnerText; }
            catch { }

            try { item.Year = Int32.Parse(elm["year"].InnerText); }
            catch { }

            XmlNode runtimenode = elm.SelectSingleNode("stream/runtime");
            string runtime = string.Empty;
            try { item.Duration = Int32.Parse(runtimenode.InnerText); }
            catch { }

            try { item.Rating = float.Parse(elm["rating"].InnerText); }
            catch { }

            try { movieinfo.Plot = elm["plot"].InnerText; }
            catch { }

            facadeLayout.Add(item);
            mInfo.Add(movieinfo);
              }
              HeadWebSettings.Instance.s_favorit.Add(item.ItemId);
            }
            int iTotalItems = facadeLayout.Count;
            GUIPropertyManager.SetProperty("#itemcount", iTotalItems.ToString());
            if (rememberIndex > -1)
            {
              GUIControl.SelectItemControl(GetID, facadeLayout.GetID, rememberIndex);
            }
            else
            {
              GUIControl.SelectItemControl(GetID, facadeLayout.GetID, 0);
            }
              }
              catch (Exception e)
              {
            Log.Error("HeadWeb: getFavorites() caused an exception " + e.Message);
              }
        }
예제 #28
0
        public static bool ExtractFromTags(ILocalFsResourceAccessor folderOrFileLfsra, MovieInfo movieInfo)
        {
            // Calling EnsureLocalFileSystemAccess not necessary; only string operation
            string extensionUpper = StringUtils.TrimToEmpty(Path.GetExtension(folderOrFileLfsra.LocalFileSystemPath)).ToUpper();

            // Try to get extended information out of MP4 files)
            if (extensionUpper != ".MP4" || extensionUpper != ".M4V")
            {
                return(false);
            }

            using (folderOrFileLfsra.EnsureLocalFileSystemAccess())
            {
                TagLib.File mp4File = TagLib.File.Create(folderOrFileLfsra.LocalFileSystemPath);
                if (ReferenceEquals(mp4File, null) || ReferenceEquals(mp4File.Tag, null))
                {
                    return(false);
                }

                TagLib.Tag tag = mp4File.Tag;

                if (!ReferenceEquals(tag.Genres, null) && tag.Genres.Length > 0)
                {
                    List <GenreInfo> genreList = tag.Genres.Where(s => !string.IsNullOrEmpty(s?.Trim())).Select(s => new GenreInfo {
                        Name = s.Trim()
                    }).ToList();
                    movieInfo.HasChanged |= MetadataUpdater.SetOrUpdateList(movieInfo.Genres, genreList, movieInfo.Genres.Count == 0);
                }

                if (!ReferenceEquals(tag.Performers, null) && tag.Performers.Length > 0)
                {
                    movieInfo.HasChanged |= MetadataUpdater.SetOrUpdateList(movieInfo.Actors,
                                                                            tag.Performers.Select(t => new PersonInfo()
                    {
                        Name = t, Occupation = PersonAspect.OCCUPATION_ACTOR, MediaName = movieInfo.MovieName.Text
                    }).ToList(), false);
                }

                //Clean up memory
                mp4File.Dispose();

                return(true);
            }
        }
예제 #29
0
        // Get movies in a list
        private void getContent(string cPath = "")
        {
            List<String> filters = new List<String>();
              string finalfilters = string.Empty;

              filters.Add("stream[flash]");

              if (OnlyFree)
              {
            filters.Add("maxprice[0.0]");
              }
              if (OnlyHD)
              {
            filters.Add("hd");
              }
              if (HeadWebSettings.Instance.s_disableadultmovies)
              {
            filters.Add("-adult");
              }
            string s = string.Join(",", filters.ToArray() as string[]);
            finalfilters = "/filter(" + s + ")";

              Log.Info("HeadWeb: getContent() for " + cPath + finalfilters);
              try
              {
            isGenre = false;
            isGenreContent = false;
            XmlDocument doc = new XmlDocument();
            string requestUrl = Utils.constructUrl(cPath + finalfilters, "fields=name,plot,year,rating,genre,stream,cover,director&limit=40");
            string rootXML = Utils.GetWebData(requestUrl, HeadWebSettings.Instance.s_cc, null, null, false, false, null, "GET", null);
            doc.LoadXml(rootXML);
            XmlElement root = doc.DocumentElement;
            facadeLayout.Clear();
            mInfo.Clear();
            GUIListItem item = null;
            MovieInfo movieinfo = null;

            XmlNodeList list = root.SelectNodes("/response/list/content");
            foreach (XmlNode elm in list)
            {
              string best = Utils.getBestCover(elm);
              item = new GUIListItem();
              item.ItemId = Int32.Parse(elm.Attributes["id"].Value);
              movieinfo = new MovieInfo();
              movieinfo.MovieID = item.ItemId;
              if (HeadWebSettings.Instance.s_useoriginalname)
              {
            try
            {
              item.Label = elm["originalname"].InnerText;
              if (item.Label.Length <= 0)
              {
                item.Label = elm["name"].InnerText;
              }
              HeadWebSettings.Instance.s_movietitle = Utils.makeSafeFilename(item.Label);
            }
            catch
            {
              try { item.Label = elm["name"].InnerText; HeadWebSettings.Instance.s_movietitle = Utils.makeSafeFilename(item.Label); }
              catch { }
            }
              }
              else
              {
            try { item.Label = elm["name"].InnerText; HeadWebSettings.Instance.s_movietitle = Utils.makeSafeFilename(item.Label); }
            catch { }
              }

              item.ThumbnailImage = best;

              XmlNode streamnode_type = elm.SelectSingleNode("stream/type");
              string stream_type = string.Empty;
              try { stream_type = streamnode_type.InnerText; }
              catch { }

              XmlNode pricenode = elm.SelectSingleNode("stream/price");
              try { item.Label2 = pricenode.InnerText; }
              catch { }

              try { item.Year = Int32.Parse(elm["year"].InnerText); }
              catch { }

              XmlNode runtimenode = elm.SelectSingleNode("stream/runtime");
              string runtime = string.Empty;
              try { item.Duration = Int32.Parse(runtimenode.InnerText); }
              catch { }

              try { item.Rating = float.Parse(elm["rating"].InnerText); }
              catch { }

              try { movieinfo.Plot = elm["plot"].InnerText; }
              catch { }

              try
              {
            string finalDirector = string.Empty;
            string[] list_directors = new string[] { };
            List<string> directorlist = new List<string>();

            XmlNodeList directornode = elm.SelectNodes("director/person");
            foreach (XmlNode directorelm in directornode)
            {
              string newDirector = directorelm.InnerText;
              directorlist.Add(newDirector);
            }
            list_directors = directorlist.ToArray();
            finalDirector = string.Join(", ", list_directors);
            movieinfo.Directors = finalDirector;
              }
              catch { }

              try
              {
            string finalGenre = string.Empty;
            string[] list_genres = new string[] { };
            List<string> genrelist = new List<string>();

            XmlNodeList genrenode = elm.SelectNodes("genre");
            foreach (XmlNode genreelm in genrenode)
            {
              string newGenre = genreelm.InnerText;
              genrelist.Add(newGenre);
            }
            list_genres = genrelist.ToArray();
            finalGenre = string.Join(", ", list_genres);
            movieinfo.Genres = finalGenre;
              }
              catch { }

              if (stream_type == "flash")
              {
            facadeLayout.Add(item);
            mInfo.Add(movieinfo);

              }
            }
            int iTotalItems = facadeLayout.Count;
            GUIPropertyManager.SetProperty("#itemcount", iTotalItems.ToString());
            if (rememberIndex > -1)
            {
              GUIControl.SelectItemControl(GetID, facadeLayout.GetID, rememberIndex);
            }
            else
            {
              GUIControl.SelectItemControl(GetID, facadeLayout.GetID, 0);
            }

              }
              catch (Exception e)
              {
            Log.Error("HeadWeb: getContent() caused an exception " + e.Message);
              }
        }
예제 #30
0
 public override Task <bool> UpdateCompaniesAsync(MovieInfo movieInfo, string companyType)
 {
     return(Task.FromResult(false));
 }
예제 #31
0
        public void ShouldWriteMovieInfo()
        {
            // TODO: Break this up into standalone tests.
            MovieInfo movieInfo = new MovieInfo();
            movieInfo.Cast.Add("Jimmy Bear");
            movieInfo.Directors.Add("Orson Welles");
            movieInfo.Producers.Add("Jim Evans");
            movieInfo.Screenwriters.Add("Herman J. Manciewicz");
            movieInfo.Studio = "WonderBoy Productions";

            this.file.Tags.MovieInfo = movieInfo;
            this.file.Save();

            this.file.Load();
            Assert.That(file.Tags.MovieInfo.Cast, Is.EquivalentTo(new List<string>() { "Jimmy Bear" }));
            Assert.That(file.Tags.MovieInfo.Directors, Is.EquivalentTo(new List<string>() { "Orson Welles" }));
            Assert.That(file.Tags.MovieInfo.Producers, Is.EquivalentTo(new List<string>() { "Jim Evans" }));
            Assert.That(file.Tags.MovieInfo.Screenwriters, Is.EquivalentTo(new List<string>() { "Herman J. Manciewicz" }));
            Assert.AreEqual("WonderBoy Productions", file.Tags.MovieInfo.Studio);

            // Test can have a null part of the MovieInfo
            file.Tags.MovieInfo.RemoveCast();
            this.file.Save();
            this.file.Load();
            Assert.IsFalse(file.Tags.MovieInfo.HasCast);

            // Touch the Cast property; it should be recreated.
            // Test can have a zero-length list for the MovieInfo.
            int count = this.file.Tags.MovieInfo.Cast.Count;
            this.file.Save();
            this.file.Load();
            Assert.IsTrue(file.Tags.MovieInfo.HasCast);
            Assert.AreEqual(0, file.Tags.MovieInfo.Cast.Count);

            // Test the null case.
            this.file.Tags.MovieInfo = null;
            this.file.Save();
            this.file.Load();
            Assert.IsNull(this.file.Tags.MovieInfo);
        }
 public override bool UpdatePersons(MovieInfo movieInfo, string occupation, bool importOnly)
 {
     return(false);
 }
예제 #33
0
 public Task DeleteTaskAsync(MovieInfo item)
 {
     return(restService.DeleteMovieInfoAsync("placeholder"));
 }
 public override bool UpdateCompanies(MovieInfo movieInfo, string companyType, bool importOnly)
 {
     return(false);
 }
        public bool TryExtractRelationships(IDictionary <Guid, IList <MediaItemAspect> > aspects, bool importOnly, out IList <RelationshipItem> extractedLinkedAspects)
        {
            extractedLinkedAspects = null;

            if (importOnly)
            {
                return(false);
            }

            if (MovieMetadataExtractor.OnlyLocalMedia)
            {
                return(false);
            }

            MovieCollectionInfo collectionInfo = new MovieCollectionInfo();

            if (!collectionInfo.FromMetadata(aspects))
            {
                return(false);
            }

            if (CheckCacheContains(collectionInfo))
            {
                return(false);
            }

            if (!MovieMetadataExtractor.SkipOnlineSearches && collectionInfo.HasExternalId)
            {
                OnlineMatcherService.Instance.UpdateCollection(collectionInfo, true, importOnly);
            }

            if (collectionInfo.Movies.Count == 0)
            {
                return(false);
            }

            if (BaseInfo.CountRelationships(aspects, LinkedRole) < collectionInfo.Movies.Count)
            {
                collectionInfo.HasChanged = true; //Force save for new movies
            }
            else
            {
                return(false);
            }

            if (!collectionInfo.HasChanged)
            {
                return(false);
            }

            AddToCheckCache(collectionInfo);

            extractedLinkedAspects = new List <RelationshipItem>();
            for (int i = 0; i < collectionInfo.Movies.Count; i++)
            {
                MovieInfo movieInfo = collectionInfo.Movies[i];
                movieInfo.CollectionNameId = collectionInfo.NameId;

                IDictionary <Guid, IList <MediaItemAspect> > movieAspects = new Dictionary <Guid, IList <MediaItemAspect> >();
                movieInfo.SetMetadata(movieAspects);
                MediaItemAspect.SetAttribute(movieAspects, MediaAspect.ATTR_ISVIRTUAL, true);

                if (movieAspects.ContainsKey(ExternalIdentifierAspect.ASPECT_ID))
                {
                    extractedLinkedAspects.Add(new RelationshipItem(movieAspects, Guid.Empty));
                }
            }
            return(extractedLinkedAspects.Count > 0);
        }
예제 #36
0
        private bool ExtractMovieData(ILocalFsResourceAccessor lfsra, IDictionary <Guid, MediaItemAspect> extractedAspectData)
        {
            // Calling EnsureLocalFileSystemAccess not necessary; only string operation
            string[] pathsToTest = new[] { lfsra.LocalFileSystemPath, lfsra.CanonicalLocalResourcePath.ToString() };
            string   title;

            // VideoAspect must be present to be sure it is actually a video resource.
            if (!extractedAspectData.ContainsKey(VideoAspect.ASPECT_ID))
            {
                return(false);
            }

            if (!MediaItemAspect.TryGetAttribute(extractedAspectData, MediaAspect.ATTR_TITLE, out title) || string.IsNullOrEmpty(title))
            {
                return(false);
            }

            MovieInfo movieInfo = new MovieInfo
            {
                MovieName = title,
            };

            // Allow the online lookup to choose best matching language for metadata
            ICollection <string> movieLanguages;

            if (MediaItemAspect.TryGetAttribute(extractedAspectData, VideoAspect.ATTR_AUDIOLANGUAGES, out movieLanguages) && movieLanguages.Count > 0)
            {
                movieInfo.Languages.AddRange(movieLanguages);
            }

            // Try to use an existing IMDB id for exact mapping
            string imdbId;

            if (MediaItemAspect.TryGetAttribute(extractedAspectData, MovieAspect.ATTR_IMDB_ID, out imdbId) ||
                pathsToTest.Any(path => ImdbIdMatcher.TryMatchImdbId(path, out imdbId)) ||
                MatroskaMatcher.TryMatchImdbId(lfsra, out imdbId))
            {
                movieInfo.ImdbId = imdbId;
            }

            // Also test the full path year, using a dummy. This is useful if the path contains the real name and year.
            foreach (string path in pathsToTest)
            {
                MovieInfo dummy = new MovieInfo {
                    MovieName = path
                };
                if (NamePreprocessor.MatchTitleYear(dummy))
                {
                    movieInfo.MovieName = dummy.MovieName;
                    movieInfo.Year      = dummy.Year;
                    break;
                }
            }

            // When searching movie title, the year can be relevant for multiple titles with same name but different years
            DateTime recordingDate;

            if (MediaItemAspect.TryGetAttribute(extractedAspectData, MediaAspect.ATTR_RECORDINGTIME, out recordingDate))
            {
                movieInfo.Year = recordingDate.Year;
            }

            if (MovieTheMovieDbMatcher.Instance.FindAndUpdateMovie(movieInfo))
            {
                if (!_onlyFanArt)
                {
                    movieInfo.SetMetadata(extractedAspectData);
                }
                if (_onlyFanArt && movieInfo.MovieDbId > 0)
                {
                    MediaItemAspect.SetAttribute(extractedAspectData, MovieAspect.ATTR_TMDB_ID, movieInfo.MovieDbId);
                }
                if (_onlyFanArt && movieInfo.CollectionMovieDbId > 0)
                {
                    MediaItemAspect.SetAttribute(extractedAspectData, MovieAspect.ATTR_COLLECTION_ID, movieInfo.CollectionMovieDbId);
                }
                return(true);
            }
            return(false);
        }
예제 #37
0
 public async Task <IEnumerable <RemoteSearchResult> > GetSearchResults(MovieInfo searchInfo, CancellationToken cancellationToken)
 {
     return(new List <RemoteSearchResult>());
 }
        private async Task <Tuple <Movie, RemoteSearchResult> > AutoDetectMovie(string movieName, int?movieYear, FileOrganizationResult result, MovieFileOrganizationOptions options, CancellationToken cancellationToken)
        {
            if (options.AutoDetectMovie)
            {
                var parsedName = _libraryManager.ParseName(movieName.AsSpan());

                var yearInName      = parsedName.Year;
                var nameWithoutYear = parsedName.Name;

                if (string.IsNullOrWhiteSpace(nameWithoutYear))
                {
                    nameWithoutYear = movieName;
                }

                if (!yearInName.HasValue)
                {
                    yearInName = movieYear;
                }

                string   metadataLanguage    = null;
                string   metadataCountryCode = null;
                BaseItem targetFolder        = null;

                if (!string.IsNullOrEmpty(options.DefaultMovieLibraryPath))
                {
                    targetFolder = _libraryManager.FindByPath(options.DefaultMovieLibraryPath, true);
                }

                if (targetFolder != null)
                {
                    metadataLanguage    = targetFolder.GetPreferredMetadataLanguage();
                    metadataCountryCode = targetFolder.GetPreferredMetadataCountryCode();
                }

                var movieInfo = new MovieInfo
                {
                    Name = nameWithoutYear,
                    Year = yearInName,
                    MetadataCountryCode = metadataCountryCode,
                    MetadataLanguage    = metadataLanguage
                };

                var searchResultsTask = await _providerManager.GetRemoteSearchResults <Movie, MovieInfo>(new RemoteSearchQuery <MovieInfo>
                {
                    SearchInfo = movieInfo
                }, cancellationToken);

                var finalResult = searchResultsTask.FirstOrDefault();

                if (finalResult != null)
                {
                    // We are in the good position, we can create the item
                    var organizationRequest = new MovieFileOrganizationRequest
                    {
                        NewMovieName        = finalResult.Name,
                        NewMovieProviderIds = finalResult.ProviderIds,
                        NewMovieYear        = finalResult.ProductionYear,
                        TargetFolder        = options.DefaultMovieLibraryPath
                    };

                    var movie = CreateNewMovie(organizationRequest, targetFolder, result, options, cancellationToken);

                    return(new Tuple <Movie, RemoteSearchResult>(movie, finalResult));
                }
            }

            return(null);
        }
예제 #39
0
 /// <summary>
 /// 获取影视地址
 /// </summary>
 /// <param name="qs"></param>
 /// <param name="cls"></param>
 /// <returns></returns>
 public string GetMovieUrl(MovieInfo b, Class cls)
 {
     return(string.Format("/Dynamic/Movie/?a=content&id={0}", b.id));
 }
예제 #40
0
 public override Task <bool> UpdateFromOnlineMovieAsync(MovieInfo movie, string language, bool cacheOnly)
 {
     return(Task.FromResult(movie.MovieDbId > 0 || !string.IsNullOrEmpty(movie.ImdbId)));
 }
예제 #41
0
        private async Task <bool> ExtractMovieData(ILocalFsResourceAccessor lfsra, IDictionary <Guid, IList <MediaItemAspect> > extractedAspectData)
        {
            // VideoAspect must be present to be sure it is actually a video resource.
            if (!extractedAspectData.ContainsKey(VideoAspect.ASPECT_ID) && !extractedAspectData.ContainsKey(SubtitleAspect.ASPECT_ID))
            {
                return(false);
            }

            // Calling EnsureLocalFileSystemAccess not necessary; only string operation
            string[] pathsToTest = new[] { lfsra.LocalFileSystemPath, lfsra.CanonicalLocalResourcePath.ToString() };
            string   title       = null;
            string   sortTitle   = null;
            bool     isReimport  = extractedAspectData.ContainsKey(ReimportAspect.ASPECT_ID);

            MovieInfo movieInfo = new MovieInfo();

            if (extractedAspectData.ContainsKey(MovieAspect.ASPECT_ID))
            {
                movieInfo.FromMetadata(extractedAspectData);
            }

            if (movieInfo.MovieName.IsEmpty)
            {
                //Try to get title
                if (MediaItemAspect.TryGetAttribute(extractedAspectData, MediaAspect.ATTR_TITLE, out title) &&
                    !string.IsNullOrEmpty(title) && !lfsra.ResourceName.StartsWith(title, StringComparison.InvariantCultureIgnoreCase))
                {
                    //The title may still contain tags and other noise, try and parse it for a title and year.
                    MovieNameMatcher.MatchTitleYear(title, movieInfo);
                }
            }
            if (movieInfo.MovieNameSort.IsEmpty)
            {
                //Try to get sort title
                if (MediaItemAspect.TryGetAttribute(extractedAspectData, MediaAspect.ATTR_SORT_TITLE, out sortTitle) && !string.IsNullOrEmpty(sortTitle))
                {
                    movieInfo.MovieNameSort = sortTitle;
                }
            }

            if (!isReimport) //Ignore tags or file based information for reimport because they might be the cause of the wrong import
            {
                if (movieInfo.MovieDbId == 0)
                {
                    try
                    {
                        // Try to use an existing TMDB id for exact mapping
                        string tmdbId = await MatroskaMatcher.TryMatchTmdbIdAsync(lfsra).ConfigureAwait(false);

                        if (!string.IsNullOrEmpty(tmdbId))
                        {
                            movieInfo.MovieDbId = Convert.ToInt32(tmdbId);
                        }
                    }
                    catch (Exception ex)
                    {
                        ServiceRegistration.Get <ILogger>().Debug("MoviesMetadataExtractor: Exception reading TMDB ID for '{0}'", ex, lfsra.CanonicalLocalResourcePath);
                    }
                }

                if (string.IsNullOrEmpty(movieInfo.ImdbId))
                {
                    try
                    {
                        // Try to use an existing IMDB id for exact mapping
                        string imdbId = await MatroskaMatcher.TryMatchImdbIdAsync(lfsra).ConfigureAwait(false);

                        if (!string.IsNullOrEmpty(imdbId))
                        {
                            movieInfo.ImdbId = imdbId;
                        }
                        else if (pathsToTest.Any(path => ImdbIdMatcher.TryMatchImdbId(path, out imdbId)))
                        {
                            movieInfo.ImdbId = imdbId;
                        }
                    }
                    catch (Exception ex)
                    {
                        ServiceRegistration.Get <ILogger>().Debug("MoviesMetadataExtractor: Exception reading IMDB ID for '{0}'", ex, lfsra.CanonicalLocalResourcePath);
                    }
                }

                if (!movieInfo.IsBaseInfoPresent || !movieInfo.ReleaseDate.HasValue)
                {
                    // Also test the full path year. This is useful if the path contains the real name and year.
                    foreach (string path in pathsToTest)
                    {
                        if (MovieNameMatcher.MatchTitleYear(path, movieInfo))
                        {
                            break;
                        }
                    }
                    //Fall back to MediaAspect.ATTR_TITLE
                    if (movieInfo.MovieName.IsEmpty && !string.IsNullOrEmpty(title))
                    {
                        movieInfo.MovieName = title;
                    }

                    /* Clear the names from unwanted strings */
                    MovieNameMatcher.CleanupTitle(movieInfo);
                }

                if (!movieInfo.ReleaseDate.HasValue && !movieInfo.HasExternalId)
                {
                    // When searching movie title, the year can be relevant for multiple titles with same name but different years
                    DateTime recordingDate;
                    if (MediaItemAspect.TryGetAttribute(extractedAspectData, MediaAspect.ATTR_RECORDINGTIME, out recordingDate))
                    {
                        movieInfo.ReleaseDate = recordingDate;
                    }
                }

                try
                {
                    await MatroskaMatcher.ExtractFromTagsAsync(lfsra, movieInfo).ConfigureAwait(false);

                    MP4Matcher.ExtractFromTags(lfsra, movieInfo);
                }
                catch (Exception ex)
                {
                    ServiceRegistration.Get <ILogger>().Debug("MoviesMetadataExtractor: Exception reading tags for '{0}'", ex, lfsra.CanonicalLocalResourcePath);
                }
            }

            // Allow the online lookup to choose best matching language for metadata
            if (movieInfo.Languages.Count == 0)
            {
                IList <MultipleMediaItemAspect> audioAspects;
                if (MediaItemAspect.TryGetAspects(extractedAspectData, VideoAudioStreamAspect.Metadata, out audioAspects))
                {
                    foreach (MultipleMediaItemAspect aspect in audioAspects)
                    {
                        string language = (string)aspect.GetAttributeValue(VideoAudioStreamAspect.ATTR_AUDIOLANGUAGE);
                        if (!string.IsNullOrEmpty(language) && !movieInfo.Languages.Contains(language))
                        {
                            movieInfo.Languages.Add(language);
                        }
                    }
                }
            }

            if (SkipOnlineSearches && !SkipFanArtDownload)
            {
                MovieInfo tempInfo = movieInfo.Clone();
                if (await OnlineMatcherService.Instance.FindAndUpdateMovieAsync(tempInfo).ConfigureAwait(false))
                {
                    movieInfo.CopyIdsFrom(tempInfo);
                    movieInfo.HasChanged = tempInfo.HasChanged;
                }
            }
            else if (!SkipOnlineSearches)
            {
                await OnlineMatcherService.Instance.FindAndUpdateMovieAsync(movieInfo).ConfigureAwait(false);
            }

            //Asign genre ids
            if (movieInfo.Genres.Count > 0)
            {
                IGenreConverter converter = ServiceRegistration.Get <IGenreConverter>();
                foreach (var genre in movieInfo.Genres)
                {
                    if (!genre.Id.HasValue && converter.GetGenreId(genre.Name, GenreCategory.Movie, null, out int genreId))
                    {
                        genre.Id             = genreId;
                        movieInfo.HasChanged = true;
                    }
                }
            }

            //Send it to the videos section
            if (!SkipOnlineSearches && !movieInfo.HasExternalId)
            {
                return(false);
            }

            //Create custom collection (overrides online collection)
            MovieCollectionInfo collectionInfo = movieInfo.CloneBasicInstance <MovieCollectionInfo>();
            string collectionName;

            if (string.IsNullOrEmpty(collectionInfo.NameId) && CollectionFolderHasFanArt(lfsra, out collectionName))
            {
                collectionInfo = new MovieCollectionInfo();
                collectionInfo.CollectionName = collectionName;
                if (!collectionInfo.CollectionName.IsEmpty)
                {
                    movieInfo.CollectionName = collectionInfo.CollectionName;
                    movieInfo.CopyIdsFrom(collectionInfo); //Reset ID's
                    movieInfo.HasChanged = true;
                }
            }

            if (movieInfo.MovieNameSort.IsEmpty)
            {
                if (!movieInfo.CollectionName.IsEmpty && movieInfo.ReleaseDate.HasValue)
                {
                    movieInfo.MovieNameSort = $"{movieInfo.CollectionName.Text} {movieInfo.ReleaseDate.Value.Year}-{movieInfo.ReleaseDate.Value.Month.ToString("00")}";
                }
                else if (!movieInfo.MovieName.IsEmpty)
                {
                    movieInfo.MovieNameSort = BaseInfo.GetSortTitle(movieInfo.MovieName.Text);
                }
                else
                {
                    movieInfo.MovieNameSort = BaseInfo.GetSortTitle(title);
                }
            }
            movieInfo.SetMetadata(extractedAspectData);

            return(movieInfo.IsBaseInfoPresent);
        }
예제 #42
0
        public override bool UpdateFromOnlineMovie(MovieInfo movie, string language, bool cacheOnly)
        {
            try
            {
                OmDbMovie movieDetail = null;
                if (!string.IsNullOrEmpty(movie.ImdbId))
                {
                    movieDetail = _omDbHandler.GetMovie(movie.ImdbId, cacheOnly);
                }
                if (movieDetail == null)
                {
                    return(false);
                }

                movie.ImdbId        = movieDetail.ImdbID;
                movie.MovieName     = new SimpleTitle(movieDetail.Title, true);
                movie.Summary       = new SimpleTitle(movieDetail.Plot, true);
                movie.Certification = movieDetail.Rated;

                movie.Revenue     = movieDetail.Revenue.HasValue ? movieDetail.Revenue.Value : 0;
                movie.Runtime     = movieDetail.Runtime.HasValue ? movieDetail.Runtime.Value : 0;
                movie.ReleaseDate = movieDetail.Released;

                List <string> awards = new List <string>();
                if (!string.IsNullOrEmpty(movieDetail.Awards))
                {
                    if (movieDetail.Awards.IndexOf("Won ", StringComparison.InvariantCultureIgnoreCase) >= 0 ||
                        movieDetail.Awards.IndexOf(" Oscar", StringComparison.InvariantCultureIgnoreCase) >= 0)
                    {
                        awards.Add("Oscar");
                    }
                    if (movieDetail.Awards.IndexOf("Won ", StringComparison.InvariantCultureIgnoreCase) >= 0 ||
                        movieDetail.Awards.IndexOf(" Golden Globe", StringComparison.InvariantCultureIgnoreCase) >= 0)
                    {
                        awards.Add("Golden Globe");
                    }
                    movie.Awards = awards;
                }

                if (movieDetail.ImdbRating.HasValue)
                {
                    MetadataUpdater.SetOrUpdateRatings(ref movie.Rating, new SimpleRating(movieDetail.ImdbVotes, movieDetail.ImdbVotes));
                }
                if (movieDetail.TomatoRating.HasValue)
                {
                    MetadataUpdater.SetOrUpdateRatings(ref movie.Rating, new SimpleRating(movieDetail.TomatoRating, movieDetail.TomatoTotalReviews));
                }
                if (movieDetail.TomatoUserRating.HasValue)
                {
                    MetadataUpdater.SetOrUpdateRatings(ref movie.Rating, new SimpleRating(movieDetail.TomatoUserRating, movieDetail.TomatoUserTotalReviews));
                }

                movie.Genres = movieDetail.Genres.Select(s => new GenreInfo {
                    Name = s
                }).ToList();

                //Only use these if absolutely necessary because there is no way to ID them
                if (movie.Actors.Count == 0)
                {
                    movie.Actors = ConvertToPersons(movieDetail.Actors, PersonAspect.OCCUPATION_ACTOR, movieDetail.Title);
                }
                if (movie.Writers.Count == 0)
                {
                    movie.Writers = ConvertToPersons(movieDetail.Writers, PersonAspect.OCCUPATION_WRITER, movieDetail.Title);
                }
                if (movie.Directors.Count == 0)
                {
                    movie.Directors = ConvertToPersons(movieDetail.Directors, PersonAspect.OCCUPATION_DIRECTOR, movieDetail.Title);
                }

                return(true);
            }
            catch (Exception ex)
            {
                ServiceRegistration.Get <ILogger>().Debug("OmDbWrapper: Exception while processing movie {0}", ex, movie.ToString());
                return(false);
            }
        }
예제 #43
0
        public async Task <IList <MediaItemSearchResult> > SearchForMatchesAsync(IDictionary <Guid, IList <MediaItemAspect> > searchAspectData, ICollection <string> searchCategories)
        {
            try
            {
                if (!(searchCategories?.Contains(MEDIA_CATEGORY_NAME_MOVIE) ?? true))
                {
                    return(null);
                }

                string searchData     = null;
                var    reimportAspect = MediaItemAspect.GetAspect(searchAspectData, ReimportAspect.Metadata);
                if (reimportAspect != null)
                {
                    searchData = reimportAspect.GetAttributeValue <string>(ReimportAspect.ATTR_SEARCH);
                }

                ServiceRegistration.Get <ILogger>().Debug("MovieMetadataExtractor: Search aspects to use: '{0}'", string.Join(",", searchAspectData.Keys));

                //Prepare search info
                MovieInfo movieSearchinfo = null;
                List <MediaItemSearchResult> searchResults = new List <MediaItemSearchResult>();
                if (!string.IsNullOrEmpty(searchData))
                {
                    if (searchAspectData.ContainsKey(VideoAspect.ASPECT_ID))
                    {
                        movieSearchinfo = new MovieInfo();
                        if (searchData.StartsWith("tt", StringComparison.InvariantCultureIgnoreCase) && !searchData.Contains(" ") && int.TryParse(searchData.Substring(2), out int id))
                        {
                            movieSearchinfo.ImdbId = searchData;
                        }
                        else if (!searchData.Contains(" ") && int.TryParse(searchData, out int movieDbId))
                        {
                            movieSearchinfo.MovieDbId = movieDbId;
                        }
                        else //Fallabck to name search
                        {
                            searchData = searchData.Trim();
                            if (!MovieNameMatcher.MatchTitleYear(searchData, movieSearchinfo))
                            {
                                movieSearchinfo.MovieName = searchData;
                            }
                        }

                        ServiceRegistration.Get <ILogger>().Debug("MovieMetadataExtractor: Searching for movie matches on search: '{0}'", searchData);
                    }
                }
                else
                {
                    if (searchAspectData.ContainsKey(VideoAspect.ASPECT_ID))
                    {
                        movieSearchinfo = new MovieInfo();
                        movieSearchinfo.FromMetadata(searchAspectData);

                        ServiceRegistration.Get <ILogger>().Debug("MovieMetadataExtractor: Searching for movie matches on aspects");
                    }
                }

                //Perform online search
                if (movieSearchinfo != null)
                {
                    var matches = await OnlineMatcherService.Instance.FindMatchingMoviesAsync(movieSearchinfo).ConfigureAwait(false);

                    ServiceRegistration.Get <ILogger>().Debug("MoviesMetadataExtractor: Movie search returned {0} matches", matches.Count());
                    foreach (var match in matches)
                    {
                        var result = new MediaItemSearchResult
                        {
                            Name = $"{match.MovieName.Text}{(match.ReleaseDate == null ? "" : $" ({match.ReleaseDate.Value.Year})")}" +
                                   $"{(string.IsNullOrWhiteSpace(match.OriginalName) || string.Compare(match.MovieName.Text, match.OriginalName, true) == 0 ? "" : $" [{match.OriginalName}]")}",
                            Description = match.Summary.IsEmpty ? "" : match.Summary.Text,
                        };

                        //Add external Ids
                        if (!string.IsNullOrEmpty(match.ImdbId))
                        {
                            result.ExternalIds.Add("imdb.com", match.ImdbId);
                        }
                        if (match.MovieDbId > 0)
                        {
                            result.ExternalIds.Add("themoviedb.org", match.MovieDbId.ToString());
                        }

                        //Assign aspects and remove unwanted aspects
                        match.SetMetadata(result.AspectData, true);
                        CleanReimportAspects(result.AspectData);

                        searchResults.Add(result);
                    }
                    return(searchResults);
                }
예제 #44
0
        public bool TryMerge(IDictionary <Guid, IList <MediaItemAspect> > extractedAspects, IDictionary <Guid, IList <MediaItemAspect> > existingAspects)
        {
            try
            {
                MovieInfo existing  = new MovieInfo();
                MovieInfo extracted = new MovieInfo();

                //Extracted aspects
                IList <MultipleMediaItemAspect> providerResourceAspects;
                if (!MediaItemAspect.TryGetAspects(extractedAspects, ProviderResourceAspect.Metadata, out providerResourceAspects))
                {
                    return(false);
                }

                //Existing aspects
                IList <MultipleMediaItemAspect> existingProviderResourceAspects;
                MediaItemAspect.TryGetAspects(existingAspects, ProviderResourceAspect.Metadata, out existingProviderResourceAspects);

                //Don't merge virtual resources
                if (!providerResourceAspects.Where(p => p.GetAttributeValue <int>(ProviderResourceAspect.ATTR_TYPE) == ProviderResourceAspect.TYPE_VIRTUAL).Any())
                {
                    //Replace if existing is a virtual resource
                    if (existingProviderResourceAspects.Where(p => p.GetAttributeValue <int>(ProviderResourceAspect.ATTR_TYPE) == ProviderResourceAspect.TYPE_VIRTUAL).Any())
                    {
                        //Don't allow merge of subtitles into virtual item
                        if (extractedAspects.ContainsKey(SubtitleAspect.ASPECT_ID) && !extractedAspects.ContainsKey(VideoStreamAspect.ASPECT_ID))
                        {
                            return(false);
                        }

                        MediaItemAspect.SetAttribute(existingAspects, MediaAspect.ATTR_ISVIRTUAL, false);
                        MediaItemAspect.SetAttribute(existingAspects, MediaAspect.ATTR_ISSTUB,
                                                     providerResourceAspects.Where(p => p.GetAttributeValue <int>(ProviderResourceAspect.ATTR_TYPE) == ProviderResourceAspect.TYPE_STUB).Any());
                        var now = DateTime.Now;
                        MediaItemAspect.SetAttribute(existingAspects, ImporterAspect.ATTR_DATEADDED, now);
                        MediaItemAspect.SetAttribute(existingAspects, ImporterAspect.ATTR_LAST_IMPORT_DATE, now);
                        existingAspects.Remove(ProviderResourceAspect.ASPECT_ID);
                        foreach (Guid aspect in extractedAspects.Keys)
                        {
                            if (!existingAspects.ContainsKey(aspect))
                            {
                                existingAspects.Add(aspect, extractedAspects[aspect]);
                            }
                        }

                        existing.FromMetadata(existingAspects);
                        extracted.FromMetadata(extractedAspects);

                        existing.MergeWith(extracted, true);
                        existing.SetMetadata(existingAspects);
                        return(true);
                    }

                    //Merge
                    if (providerResourceAspects.Where(p => p.GetAttributeValue <int>(ProviderResourceAspect.ATTR_TYPE) == ProviderResourceAspect.TYPE_STUB).Any() ||
                        existingProviderResourceAspects.Where(p => p.GetAttributeValue <int>(ProviderResourceAspect.ATTR_TYPE) == ProviderResourceAspect.TYPE_STUB).Any())
                    {
                        MediaItemAspect.SetAttribute(existingAspects, MediaAspect.ATTR_ISVIRTUAL, false);
                        MediaItemAspect.SetAttribute(existingAspects, MediaAspect.ATTR_ISSTUB, true);
                        if (!ResourceAspectMerger.MergeVideoResourceAspects(extractedAspects, existingAspects))
                        {
                            return(false);
                        }
                    }
                }

                existing.FromMetadata(existingAspects);
                extracted.FromMetadata(extractedAspects);

                existing.MergeWith(extracted, true);
                existing.SetMetadata(existingAspects);
                if (!ResourceAspectMerger.MergeVideoResourceAspects(extractedAspects, existingAspects))
                {
                    return(false);
                }

                return(true);
            }
            catch (Exception e)
            {
                // Only log at the info level here - And simply return false. This lets the caller know that we
                // couldn't perform our task here.
                ServiceRegistration.Get <ILogger>().Info("MovieMergeHandler: Exception merging resources (Text: '{0}')", e.Message);
                return(false);
            }
        }
예제 #45
0
        public async Task <IEnumerable <RemoteSearchResult> > GetSearchResults(MovieInfo searchInfo, CancellationToken cancellationToken)
        {
            var results = await GetSearchResultsFromInfoAsync(searchInfo, "movie", cancellationToken).ConfigureAwait(false);

            return(results.Select(GetSearchResultFromMedia));
        }
예제 #46
0
        /// <summary>
        /// Asynchronously tries to extract movie characters for the given <param name="mediaItemAccessor"></param>
        /// </summary>
        /// <param name="mediaItemAccessor">Points to the resource for which we try to extract metadata</param>
        /// <param name="extractedAspects">List of MediaItemAspect dictionaries to update with metadata</param>
        /// <param name="reimport">During reimport only allow if nfo is for same media as this</param>
        /// <returns><c>true</c> if metadata was found and stored into the <paramref name="extractedAspects"/>, else <c>false</c></returns>
        protected async Task <bool> TryExtractMovieCharactersMetadataAsync(IResourceAccessor mediaItemAccessor, IList <IDictionary <Guid, IList <MediaItemAspect> > > extractedAspects, MovieInfo reimport)
        {
            NfoMovieReader movieNfoReader = await TryGetNfoMovieReaderAsync(mediaItemAccessor, false).ConfigureAwait(false);

            if (movieNfoReader != null)
            {
                if (reimport != null && !VerifyMovieReimport(movieNfoReader, reimport))
                {
                    return(false);
                }

                return(movieNfoReader.TryWriteCharacterMetadata(extractedAspects));
            }
            return(false);
        }
 public IActionResult Create(MovieInfo movie)
 {
     movie.Id = _movies.Max(x => x.Id) + 1;
     _movies.Add(movie);
     return(RedirectToAction(nameof(Index)));
 }
예제 #48
0
 public Task <int> DeleteMovieInfoAsync(MovieInfo movieInfo)
 {
     return(database.DeleteAsync(movieInfo));
 }
 public void ParseTest()
 {
     MovieInfo info = new MovieInfo();
     byte[] data = Encoding.UTF8.GetBytes(this.testAtom);
     info.Populate(data);
 }