Inheritance: IComparable
        public bool Contains(DatabaseTable obj)
        {
            if (obj == null || cache[obj.GetType()] == null)
                return false;

            return cache[obj.GetType()].ContainsValue(obj);
        }
        // Shoudl really only be called if an item has been deleted from the database
        public void Remove(DatabaseTable obj)
        {
            if (obj == null || obj.ID == null)
                return;

            cache[obj.GetType()].Remove((int)obj.ID);
        }
        // create the dictionary to map variables to the correct values for this movie
        public static Dictionary<string, string> getVariableMapping(DatabaseTable obj)
        {
            // add fields from primary object
            Dictionary<string, string> replacementStrings = new Dictionary<string, string>();
            foreach (DBField currField in DBField.GetFieldList(obj.GetType())) {
                if (currField.Filterable && currField.GetValue(obj) != null)
                    replacementStrings[currField.FieldName] = currField.GetValue(obj).ToString().Trim();
            }

            // add fields from secondary types
            foreach (DBRelation currRelation in DBRelation.GetRelations(obj.GetType())) {
                if (!currRelation.Filterable)
                    continue;

                if (currRelation.GetRelationList(obj).Count > 0) {
                    DatabaseTable subObj = (DatabaseTable)currRelation.GetRelationList(obj)[0];

                    foreach (DBField currField in DBField.GetFieldList(currRelation.SecondaryType)) {
                        if (currField.Filterable && currField.GetValue(subObj) != null)
                            replacementStrings[currField.FieldName] = currField.GetValue(subObj).ToString().Trim();
                    }
                }
            }

            return replacementStrings;
        }
        // remove the existing object with the same ID from the cache and store this one instead.
        public void Replace(DatabaseTable obj)
        {
            if (obj == null || obj.ID == null)
                return;

            if (!cache.ContainsKey(obj.GetType()))
                cache[obj.GetType()] = new Dictionary<int, DatabaseTable>();

            cache[obj.GetType()][(int)obj.ID] = obj;
        }
        // Adds the given element to the cacheing system
        public DatabaseTable Add(DatabaseTable obj)
        {
            if (obj == null || obj.ID == null)
                return obj;

            if (!cache.ContainsKey(obj.GetType()))
                cache[obj.GetType()] = new Dictionary<int,DatabaseTable>();

            if (!cache[obj.GetType()].ContainsKey((int)obj.ID))
                cache[obj.GetType()][(int)obj.ID] = obj;

            return cache[obj.GetType()][(int)obj.ID];
        }
        /// <summary>
        /// Fired when an object is inserted in the Moving Pictures Database
        /// </summary>
        private void DatabaseManager_ObjectInserted(DatabaseTable obj)
        {
            // check connection state
            if (TraktSettings.AccountStatus != ConnectionState.Connected)
                return;

            if (obj.GetType() == typeof(DBWatchedHistory))
            {
                // movie has just been watched
                DBWatchedHistory watchedEvent = (DBWatchedHistory)obj;
                if (!TraktSettings.BlockedFilenames.Contains(watchedEvent.Movie.LocalMedia[0].FullPath) && !TraktSettings.BlockedFolders.Any(f => watchedEvent.Movie.LocalMedia[0].FullPath.ToLowerInvariant().Contains(f.ToLowerInvariant())))
                {
                    TraktLogger.Info("Watched History updated in MovingPictures. Title = '{0}', Year = '{1}', IMDb ID = '{2}', TMDb ID = '{3}'", watchedEvent.Movie.Title, watchedEvent.Movie.Year, watchedEvent.Movie.ImdbID ?? "<empty>", GetTmdbID(watchedEvent.Movie) ?? "<empty>");
                    ShowRateDialog(watchedEvent.Movie);
                    StopMovieScrobble(watchedEvent.Movie);

                    // remove from watchlist and recommendation categories and filters menu
                    // watched items are auto-removed online for these lists so we can do this now locally
                    RemoveMovieCriteriaFromRecommendationsNode(watchedEvent.Movie.ImdbID);
                    RemoveMovieCriteriaFromWatchlistNode(watchedEvent.Movie.ImdbID);
                }
                else
                {
                    TraktLogger.Info("Movie was blocked and not added to watched history on trakt.tv. Title = '{0}', Year = '{1}', IMDb ID = '{2}', TMDb ID = '{3}'", watchedEvent.Movie.Title, watchedEvent.Movie.Year, watchedEvent.Movie.ImdbID ?? "<empty>", GetTmdbID(watchedEvent.Movie) ?? "<empty>");
                }
            }
            else if (obj.GetType() == typeof(DBMovieInfo) && TraktSettings.SyncLibrary)
            {
                // movie was inserted into the database
                var insertedMovie = obj as DBMovieInfo;
                if (!TraktSettings.BlockedFilenames.Contains(insertedMovie.LocalMedia[0].FullPath) && !TraktSettings.BlockedFolders.Any(f => insertedMovie.LocalMedia[0].FullPath.ToLowerInvariant().Contains(f.ToLowerInvariant())))
                {
                    var syncThread = new Thread((objMovie) =>
                    {
                        // wait for import to be 100% complete including MediaInfo
                        Thread.Sleep(30000);

                        var tMovie = objMovie as DBMovieInfo;

                        var traktMovie = new TraktSyncMovieCollected
                        {
                            Ids = new TraktMovieId { Imdb = tMovie.ImdbID, Tmdb = GetTmdbID(tMovie).ToNullableInt32() },
                            Title = tMovie.Title,
                            Year = tMovie.Year,
                            CollectedAt = DateTime.UtcNow.ToISO8601(),
                            MediaType = GetMovieMediaType(tMovie),
                            Resolution = GetMovieResolution(tMovie),
                            AudioCodec = GetMovieAudioCodec(tMovie),
                            AudioChannels = GetMovieAudioChannels(tMovie),
                            Is3D = IsMovie3D(tMovie)
                        };

                        TraktLogger.Info("New movie added into MovingPictures, adding to trakt.tv collection. Title = '{0}', Year = '{1}', IMDb ID = '{2}', TMDb ID = '{3}', Date Added = '{4}', MediaType = '{5}', Resolution = '{6}', Audio Codec = '{7}', Audio Channels = '{8}'",
                                            traktMovie.Title, traktMovie.Year.HasValue ? traktMovie.Year.ToString() : "<empty>", traktMovie.Ids.Imdb ?? "<empty>", traktMovie.Ids.Tmdb.HasValue ? traktMovie.Ids.Tmdb.ToString() : "<empty>",
                                            traktMovie.CollectedAt, traktMovie.MediaType ?? "<empty>", traktMovie.Resolution ?? "<empty>", traktMovie.AudioCodec ?? "<empty>", traktMovie.AudioChannels ?? "<empty>");

                        // check if we already have the movie collected online
                        if (traktMovie.IsCollected())
                        {
                            TraktLogger.Info("Skipping movie addition to trakt.tv collection, movie already exists in online collection.");
                            return;
                        }

                        // insert movie into local cache - with title/year
                        TraktCache.AddMovieToCollection(traktMovie);

                        // check for valid IDs
                        if (TraktSettings.SkipMoviesWithNoIdsOnSync)
                        {
                            traktMovie.Title = null;
                            traktMovie.Year = null;
                            if (!BasicHandler.IsValidImdb(traktMovie.Ids.Imdb) && traktMovie.Ids.Tmdb == null)
                            {
                                TraktLogger.Info("Skipping movie addition to trakt.tv collection, movie has no valid online ID's.");
                                return;
                            }
                        }

                        // insert online
                        var response = TraktAPI.TraktAPI.AddMovieToCollection(traktMovie);
                        TraktLogger.LogTraktResponse(response);
                    })
                    {
                        IsBackground = true,
                        Name = "Sync"
                    };

                    syncThread.Start(insertedMovie);
                }
                else
                {
                    TraktLogger.Info("Movie was blocked and not added to collection on trakt.tv. Title = '{0}', Year = '{1}', IMDb ID = '{2}', TMDb ID = '{3}'", insertedMovie.Title, insertedMovie.Year, insertedMovie.ImdbID ?? "<empty>", GetTmdbID(insertedMovie) ?? "<empty>");
                }
            }
        }
        /// <summary>
        /// Fired when an object is updated in the Moving Pictures Database
        /// </summary>
        /// <param name="obj"></param>
        private void DatabaseManager_ObjectUpdatedEx(DatabaseTable dbObject, TableUpdateInfo ui)
        {
            // check connection state
            if (TraktSettings.AccountStatus != ConnectionState.Connected)
                return;

            // If it is user settings for a movie
            if (dbObject.GetType() != typeof(DBUserMovieSettings))
                return;

            // if we are syncing, we maybe manually setting state from trakt
            // in this case we dont want to resend to trakt
            if (SyncLibraryInProgress) return;

            DBUserMovieSettings userMovieSettings = (DBUserMovieSettings)dbObject;
            DBMovieInfo movie = userMovieSettings.AttachedMovies[0];

            // don't do anything if movie is blocked
            if (TraktSettings.BlockedFilenames.Contains(movie.LocalMedia[0].FullPath) || TraktSettings.BlockedFolders.Any(f => movie.LocalMedia[0].FullPath.ToLowerInvariant().Contains(f.ToLowerInvariant())))
            {
                TraktLogger.Info("Movie is on the blocked list so we didn't update trakt.tv. Title = '{0}', Year = '{1}', IMDB ID = '{2}', TMDb ID = '{3}'", movie.Title, movie.Year, movie.ImdbID ?? "<empty>", GetTmdbID(movie) ?? "<empty>");
                return;
            }

            // we check the watched flag and update Trakt respectfully
            // ignore if movie is the current movie being scrobbled, this will be set to watched automatically
            if (ui.WatchedCountChanged() && movie != currentMovie)
            {
                if (userMovieSettings.WatchedCount == 0)
                {
                    #region Unwatched Event
                    TraktLogger.Info("Received Un-Watched event in MovingPictures for movie. Title = '{0}', Year = '{1}', IMDB ID = '{2}', TMDb ID = '{3}'", movie.Title, movie.Year, movie.ImdbID ?? "<empty>", GetTmdbID(movie) ?? "<empty>");

                    var syncThread = new Thread((objMovie) =>
                    {
                        var tMovie = objMovie as DBMovieInfo;

                        var traktMovie = new TraktMovie
                        {
                            Ids = new TraktMovieId { Imdb = tMovie.ImdbID, Tmdb = GetTmdbID(tMovie).ToNullableInt32() },
                            Title = tMovie.Title,
                            Year = tMovie.Year
                        };

                        // update local cache
                        TraktCache.RemoveMovieFromWatchHistory(traktMovie);

                        var response = TraktAPI.TraktAPI.RemoveMovieFromWatchedHistory(traktMovie);
                        TraktLogger.LogTraktResponse(response);
                    })
                    {
                        IsBackground = true,
                        Name = "Sync"
                    };

                    syncThread.Start(movie);
                    #endregion
                }
                else
                {
                    #region Watched Event
                    TraktLogger.Info("Received Watched event in MovingPictures for movie. Title = '{0}', Year = '{1}', IMDB ID = '{2}', TMDb ID = '{3}'", movie.Title, movie.Year, movie.ImdbID ?? "<empty>", GetTmdbID(movie) ?? "<empty>");
                    if (!g_Player.IsVideo)
                    {
                        var syncThread = new Thread((objMovie) =>
                        {
                            var tMovie = objMovie as DBMovieInfo;

                            var traktMovie = new TraktSyncMovieWatched
                            {
                                Ids = new TraktMovieId { Imdb = tMovie.ImdbID, Tmdb = GetTmdbID(tMovie).ToNullableInt32() },
                                Title = tMovie.Title,
                                Year = tMovie.Year,
                                WatchedAt = DateTime.UtcNow.ToISO8601()
                            };

                            var response = TraktAPI.TraktAPI.AddMovieToWatchedHistory(traktMovie);
                            TraktLogger.LogTraktResponse(response);

                            if (response != null && response.NotFound != null && response.NotFound.Movies.Count == 0)
                            {
                                // update internal cache
                                TraktCache.AddMovieToWatchHistory(traktMovie);
                            }

                            // don't need to keep this movie anymore in categories/filter menu if it's watched
                            RemoveMovieCriteriaFromRecommendationsNode(tMovie.ImdbID);
                            RemoveMovieCriteriaFromWatchlistNode(tMovie.ImdbID);
                        })
                        {
                            IsBackground = true,
                            Name = "Sync"
                        };

                        syncThread.Start(movie);
                    }
                    #endregion
                }
            }

            // we will update the Trakt rating of the Movie
            // ignore if we rated using trakt rate dialog
            if (ui.RatingChanged() && userMovieSettings.UserRating > 0 && !TraktRateSent)
            {
                TraktLogger.Info("Received Rate event in MovingPictures for movie. Rating = '{0}/5', Title = '{1}', Year = '{2}', IMDB ID = '{3}', TMDb ID = '{4}'", userMovieSettings.UserRating, movie.Title, movie.Year, movie.ImdbID ?? "<empty>", GetTmdbID(movie) ?? "<empty>");

                var syncThread = new Thread((objMovie) =>
                {
                    var tMovie = objMovie as DBMovieInfo;

                    var traktMovie = new TraktSyncMovieRated
                    {
                        Ids = new TraktMovieId { Imdb = tMovie.ImdbID, Tmdb = GetTmdbID(tMovie).ToNullableInt32() },
                        Title = tMovie.Title,
                        Year = tMovie.Year,
                        RatedAt = DateTime.UtcNow.ToISO8601(),
                        Rating = (int)userMovieSettings.UserRating * 2
                    };

                    var response = TraktAPI.TraktAPI.AddMovieToRatings(traktMovie);
                    TraktLogger.LogTraktResponse(response);
                })
                {
                    IsBackground = true,
                    Name = "Sync"
                };
                syncThread.Start(movie);
            }
        }
 void movieDetailsList_FieldChanged(DatabaseTable obj, DBField field, object value)
 {
     movieDetailsList.RepopulateValues();
     if (FieldChanged != null) FieldChanged(obj, field, value);
 }
        /// <summary>
        /// Publishes standard object details to the skin
        /// </summary>
        /// <param name="obj">any object derived from databasetable</param>
        /// <param name="prefix">prefix for the generated skin properties</param>
        /// <param name="forceLogging">indicate wether to log all properties</param>
        private void PublishDetails(DatabaseTable obj, string prefix, bool forceLogging)
        {
            if (obj == null)
                return;

            int maxStringListElements = MovingPicturesCore.Settings.MaxElementsToDisplay;

            Type tableType = obj.GetType();
            foreach (DBField currField in DBField.GetFieldList(tableType)) {
                string propertyStr;
                string valueStr;

                // for string lists, lets do some nice formating
                object value = currField.GetValue(obj);
                if (value == null) {
                    propertyStr = "#MovingPictures." + prefix + "." + currField.FieldName;
                    SetProperty(propertyStr, "", forceLogging);
                }
                else if (currField.FieldName == "user" && tableType == typeof(DBUserMovieSettings)) {
                    // rename the "user" field to "username" to prevent overlapping variable names
                    propertyStr = "#MovingPictures." + prefix + ".username";
                    valueStr = currField.GetValue(obj).ToString().Trim();
                    SetProperty(propertyStr, valueStr, forceLogging);
                }
                else if (value.GetType() == typeof(StringList)) {

                    // make sure we dont go overboard with listing elements :P
                    StringList valueStrList = (StringList)value;
                    int max = maxStringListElements;
                    if (max > valueStrList.Count)
                        max = valueStrList.Count;

                    // add the coma seperated string
                    propertyStr = "#MovingPictures." + prefix + "." + currField.FieldName;
                    valueStr = valueStrList.ToPrettyString(max);
                    SetProperty(propertyStr, valueStr, forceLogging);

                    // add each value individually
                    for (int i = 0; i < maxStringListElements; i++) {
                        // note, the "extra" in the middle is needed due to a bug in skin parser
                        propertyStr = "#MovingPictures." + prefix + ".extra." + currField.FieldName + "." + (i + 1);
                        if (i < max) {
                            valueStr = valueStrList[i];
                        } else {
                            valueStr = null;
                        }
                        SetProperty(propertyStr, valueStr, forceLogging);
                    }
                }
                // for the movie score we add some special properties to give skinners more options
                else if (currField.FieldName == "score" && tableType == typeof(DBMovieInfo)) {
                    propertyStr = "#MovingPictures." + prefix + "." + currField.FieldName;

                    float score = (float)currField.GetValue(obj);
                    int percentage = (int)Math.Floor((score * 10));
                    int major = (int)Math.Floor(score);
                    int minor = (int)Math.Floor(((score - major) * 10));
                    int rounded = (int)(score + 0.5f);

                    NumberFormatInfo localizedScoreFormat = (NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();
                    localizedScoreFormat.NumberDecimalDigits = 1;

                    NumberFormatInfo invariantScoreFormat = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
                    invariantScoreFormat.NumberDecimalDigits = 1;

                    SetProperty(propertyStr + ".localized", score.ToString("N", localizedScoreFormat), forceLogging);
                    SetProperty(propertyStr + ".invariant", score.ToString("N", invariantScoreFormat), forceLogging);
                    SetProperty(propertyStr + ".rounded", rounded.ToString(), forceLogging);
                    SetProperty(propertyStr + ".percentage", percentage.ToString(), forceLogging);
                    SetProperty(propertyStr + ".major", major.ToString(), forceLogging);
                    SetProperty(propertyStr + ".minor", minor.ToString(), forceLogging);

                }
                // for the movie runtime we also add some special properties
                else if (currField.FieldName == "runtime" && tableType == typeof(DBMovieInfo)) {
                    propertyStr = "#MovingPictures." + prefix + "." + currField.FieldName;
                    DBMovieInfo movie = (DBMovieInfo)obj;

                    int seconds = 0;
                    bool actualRuntime = false;

                    // Check the user preference and display the runtime requested
                    // If the user choose actual runtime and it is not available default
                    // to the imported runtime
                    if (MovingPicturesCore.Settings.DisplayActualRuntime && movie.ActualRuntime > 0) {
                        // Actual runtime (as calculated by mediainfo)
                        // convert duration from milliseconds to seconds
                        seconds = (movie.ActualRuntime / 1000);
                        actualRuntime = true;
                    }
                    else {
                        // Runtime (as provided by the dataprovider)
                        // convert from minutes to seconds
                        seconds = (movie.Runtime * 60);
                    }

                    // Publish the runtime
                    PublishRuntime(seconds, actualRuntime, "#MovingPictures." + prefix + ".runtime.", forceLogging);

                }
                // for the popularity we add a localized property to make it easier to read in skins
                else if (currField.FieldName == "popularity" && tableType == typeof(DBMovieInfo)) {
                    propertyStr = "#MovingPictures." + prefix + "." + currField.FieldName;

                    int popularity = (int)currField.GetValue(obj);

                    NumberFormatInfo localizedScoreFormat = (NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();
                    localizedScoreFormat.NumberDecimalDigits = 0;

                    // Publish Popularity
                    SetProperty(propertyStr + ".raw", popularity.ToString(), forceLogging);
                    SetProperty(propertyStr + ".localized", popularity.ToString("N", localizedScoreFormat), forceLogging);

                }
                // for floats we need to make sure we use english style printing or imagelist controls
                // will break.
                else if (value.GetType() == typeof(float)) {
                    propertyStr = "#MovingPictures." + prefix + "." + currField.FieldName;
                    valueStr = ((float)currField.GetValue(obj)).ToString(CultureInfo.CreateSpecificCulture("en-US"));
                    SetProperty(propertyStr, valueStr, forceLogging);

                    // vanilla publication
                }
                else {
                    propertyStr = "#MovingPictures." + prefix + "." + currField.FieldName;
                    valueStr = currField.GetValue(obj).ToString().Trim();

                    // Category names have an extra translation check
                    if (currField.FieldName == "name" && tableType == typeof(DBNode<DBMovieInfo>))
                        valueStr = Translation.ParseString(valueStr);

                    SetProperty(propertyStr, valueStr, forceLogging);
                }
            }
        }
        // Updates the current object with all fields in the newData object that are
        // not set to default.
        public void CopyUpdatableValues(DatabaseTable newData)
        {
            if (newData == null) return;
            ReadOnlyCollection<DBField> fieldList = DBField.GetFieldList(newData.GetType());

            foreach (DBField currField in fieldList) {
                object newValue = currField.GetValue(newData);
                object oldValue = currField.GetValue(this);
                if (currField.AutoUpdate) {

                    if (newValue == null) {
                        currField.SetValue(this, newValue);
                        continue;
                    }

                    // if the updated value is just the default, don't update.
                    // something is better than nothing
                    if (newValue.Equals(currField.Default))
                        continue;

                    // if we have a string try to compare trimmed strings
                    if (newValue.GetType() == typeof(string) && ((string)newValue).Trim() == ((string)oldValue).Trim())
                        continue;

                    // if the value just hasn't changed, dont update
                    if (newValue.Equals(oldValue))
                        continue;

                    // check if the old value is the default value
                    bool oldValueIsDefault = false;
                    if (oldValue is string && currField.Default is string) {
                        if (((string)oldValue).Trim().Equals(((string)currField.Default).Trim()))
                            oldValueIsDefault = true;
                    }
                    else if (oldValue.Equals(currField.Default))
                        oldValueIsDefault = true;

                    // if we are protecting non-default values continue
                    if (protectExistingValuesFromCopy && !oldValueIsDefault)
                        continue;

                    currField.SetValue(this, newValue);
                }
            }
            // reset the value protection to true again
            protectExistingValuesFromCopy = true;
        }
        private void DatabaseManager_ObjectUpdated(DatabaseTable obj, TableUpdateInfo updateInfo)
        {
            if (!MovingPicturesCore.Settings.FollwitEnabled) {
                logger.Warn("Attempt to call follw.it made when service is disabled.");
                return;
            }

            try {
                // we're looking for user rating changes
                if (obj.GetType() != typeof(DBUserMovieSettings))
                    return;

                DBUserMovieSettings settings = (DBUserMovieSettings)obj;
                if (updateInfo.RatingChanged()) {
                    if (!IsOnline) {
                        logger.Warn("Can not send rating info to follw.it because service is offline");
                        return;
                    }

                    DBMovieInfo movie = settings.AttachedMovies[0];

                    if (currentlySyncingMovies.Contains(movie))
                        return;

                    FollwitBackgroundProcess bgProc = new FollwitBackgroundProcess();
                    bgProc.Action = FitActions.UpdateUserRating;
                    bgProc.Movies.Add(movie);
                    MovingPicturesCore.ProcessManager.StartProcess(bgProc);
                }

            }
            catch (Exception ex) {
                logger.ErrorException("Unexpected error sending rating information to follw.it!", ex);
                _follwitAPI = null;
                MovingPicturesCore.Follwit.Status = FollwitConnector.StatusEnum.INTERNAL_ERROR;
            }
        }
        // if a dblocalmedia object is updated and it happens to belong to the currently
        // selected movie, and we are on the file details tab, we need to update.
        private void localMediaUpdatedListener(DatabaseTable obj)
        {
            if (!fileDetailsSubPane.Visible)
                return;

            DBLocalMedia file = obj as DBLocalMedia;
            if (file == null) return;

            // This ensures we are thread safe. Makes sure this method is run by
            // the thread that created this panel.
            if (InvokeRequired) {
                Delegate method = new DatabaseManager.ObjectAffectedDelegate(localMediaUpdatedListener);
                object[] parameters = new object[] { obj };
                this.Invoke(method, parameters);
                return;
            }

            if (file.AttachedMovies.Count > 0) {
                foreach (DBMovieInfo currMovie in file.AttachedMovies) {
                    if (CurrentMovie == currMovie) {
                        updateFilePanel();
                        return;
                    }
                }
            }
        }
 private void OnFieldChanged(DatabaseTable obj, DBField field, object value)
 {
     if (FieldChanged != null) FieldChanged(obj, field, value);
 }
        internal static void MovingPictureOnObjectInserted(DatabaseTable obj)
        {
            try
              {
            if (obj.GetType() != typeof (DBMovieInfo))
              return;

            FanartHandlerSetup.Fh.AddToDirectoryTimerQueue("MovingPictures");
              }
              catch (Exception ex)
              {
            logger.Error("MovingPictureOnObjectInserted: " + ex);
              }
        }
        protected void DBManager_ObjectUpdated(DatabaseTable obj)
        {
            if (InvokeRequired) {
                Invoke(new MethodInvoker(delegate() { DBManager_ObjectUpdated(obj); }));
                return;
            }

            if (obj == Menu)
                BuildTreePanel();
        }
Example #16
0
        // Sets the value of this field for the given object.
        public void SetValue(DatabaseTable owner, object value)
        {
            try {

                // if we were passed a null value, try to set that.
                if (value == null) {
                    propertyInfo.GetSetMethod().Invoke(owner, new object[] { null });
                    return;
                }

                // if we were passed a matching object, just set it
                if (value.GetType() == propertyInfo.PropertyType) {
                    propertyInfo.GetSetMethod().Invoke(owner, new object[] { value });
                    return;
                }

                if (value is string)
                    propertyInfo.GetSetMethod().Invoke(owner, new object[] { ConvertString(owner.DBManager, (string)value) });

            }
            catch (Exception e) {
                if (e.GetType() == typeof(ThreadAbortException))
                    throw e;

                logger.Error("Error writing to " + owner.GetType().Name + "." + this.Name +
                                " Property: " + e.Message);
            }
        }
Example #17
0
 // sets the default value based on the datatype.
 public void InitializeValue(DatabaseTable owner)
 {
     SetValue(owner, Default);
 }
Example #18
0
 // Returns the value of this field for the given object.
 public object GetValue(DatabaseTable owner)
 {
     try {
         return propertyInfo.GetGetMethod().Invoke(owner, null);
     }
     catch (Exception) {
         throw new Exception("DBField does not belong to the Type of the supplied Owner.");
     }
 }
        /// <summary>
        /// Fired when an object is updated in the Moving Pictures Database
        /// </summary>
        /// <param name="obj"></param>
        private void DatabaseManager_ObjectUpdatedEx(DatabaseTable dbObject, TableUpdateInfo ui)
        {
            if (TraktSettings.AccountStatus != ConnectionState.Connected) return;

            //If it is user settings for a movie
            if (dbObject.GetType() == typeof(DBUserMovieSettings))
            {
                DBUserMovieSettings userMovieSettings = (DBUserMovieSettings)dbObject;
                DBMovieInfo movie = userMovieSettings.AttachedMovies[0];

                // don't do anything if movie is blocked
                if (TraktSettings.BlockedFilenames.Contains(movie.LocalMedia[0].FullPath) || TraktSettings.BlockedFolders.Any(f => movie.LocalMedia[0].FullPath.ToLowerInvariant().Contains(f.ToLowerInvariant())))
                {
                    TraktLogger.Info("Movie {0} is on the blocked list so we didn't update Trakt", movie.Title);
                    return;
                }

                // if we are syncing, we maybe manually setting state from trakt
                // in this case we dont want to resend to trakt
                if (SyncInProgress) return;

                // we check the watched flag and update Trakt respectfully
                // ignore if movie is the current movie being scrobbled, this will be set to watched automatically
                if (ui.WatchedCountChanged() && movie != currentMovie)
                {
                    if (userMovieSettings.WatchedCount == 0)
                    {
                        TraktLogger.Info("Received Un-Watched event in MovingPictures for movie '{0}'", movie.Title);
                        SyncMovie(CreateSyncData(movie), TraktSyncModes.unseen);
                    }
                    else
                    {
                        TraktLogger.Info("Received Watched event in MovingPictures for movie '{0}'", movie.Title);
                        if (!g_Player.IsVideo)
                        {
                            SyncMovie(CreateSyncData(movie), TraktSyncModes.seen);
                            RemoveMovieFromFiltersAndCategories(movie);
                        }
                    }
                }

                // we will update the Trakt rating of the Movie
                // ignore if we rated using trakt rate dialog
                if (ui.RatingChanged() && userMovieSettings.UserRating > 0 && !TraktRateSent)
                {
                    TraktLogger.Info("Received Rate event in MovingPictures for movie '{0}' with rating '{1}/5'", movie.Title, userMovieSettings.UserRating);
                    RateMovie(CreateRateData(movie, (userMovieSettings.UserRating * 2).ToString()));
                }
            }
        }
        private void movieDeletedListener(DatabaseTable obj)
        {
            // This ensures we are thread safe. Makes sure this method is run by
            // the thread that created this panel.
            if (InvokeRequired) {
                Delegate method = new DatabaseManager.ObjectAffectedDelegate(movieDeletedListener);
                object[] parameters = new object[] { obj };
                this.Invoke(method, parameters);
                return;
            }

            // if this is not a movie object, break
            if (obj.GetType() != typeof(DBMovieInfo))
                return;

            // remove movie from list
            DBMovieInfo movie = (DBMovieInfo)obj;
            lock (lockList) {
                if (listItems.ContainsKey(movie)) {
                    listItems[movie].Selected = false;
                    updateMoviePanel();
                    updateFilePanel();

                    movieListBox.Items.Remove(listItems[movie]);
                    listItems.Remove(movie);
                }
            }
        }
 public IRelationList GetRelationList(DatabaseTable dbObject)
 {
     return (IRelationList)getRelationListMethod.Invoke(dbObject, null);
 }
        private void movieInsertedListener(DatabaseTable obj)
        {
            // if this is not a movie object, break
            if (obj.GetType() != typeof(DBMovieInfo))
                return;

            // This ensures we are thread safe. Makes sure this method is run by
            // the thread that created this panel.
            if (InvokeRequired) {
                if (!FindForm().Visible) return;
                Delegate method = new DatabaseManager.ObjectAffectedDelegate(movieInsertedListener);
                object[] parameters = new object[] { obj };
                this.Invoke(method, parameters);
                return;
            }

            // add movie to the list
            addMovie((DBMovieInfo)obj);

            bool reassigning = false;
            foreach (DBLocalMedia currFile in processingFiles) {
                if (((DBMovieInfo)obj).LocalMedia.Contains(currFile))
                    reassigning = true;
                else {
                    reassigning = false;
                    break;
                }
            }
            lock (lockList) {
                if (reassigning)
                    listItems[(DBMovieInfo)obj].Selected = true;
            }
        }
        // Updates the current object with all fields in the newData object
        public void Copy(DatabaseTable newData)
        {
            if (newData == null) return;
            ReadOnlyCollection<DBField> fieldList = DBField.GetFieldList(newData.GetType());

            foreach (DBField currField in fieldList)
                currField.SetValue(this, currField.GetValue(newData));
        }
        /// <summary>
        /// Listens for newly added movies from the database manager. Used for triggering delayed 
        /// actions when a disk is inserted.
        /// </summary>
        /// <param name="obj"></param>
        private void OnMovieAdded(DatabaseTable obj)
        {
            // if not a movie, not a recently inserted disk, or if we aren't in Moving Pics, quit
            if (obj.GetType() != typeof(DBMovieInfo) || recentInsertedDiskSerials.Count == 0 || GUIWindowManager.ActiveWindow != GetID)
                return;

            DBMovieInfo movie = (DBMovieInfo)obj;

            if (movie.LocalMedia.Count == 0)
                return;

            string path = movie.LocalMedia[0].FullPath.ToLower();
            logger.Debug("OnMovieAdded: " + movie.Title);

            // Check if this path was recently inserted
            if (recentInsertedDiskSerials.ContainsKey(path))
                // Double check the serial (just in case)
                if (movie.LocalMedia[0].VolumeSerial == recentInsertedDiskSerials[path]) {
                    recentInsertedDiskSerials.Clear();
                    HandleInsertedDisk(movie, 1);
                    return;
                }
        }
        private void DatabaseManager_ObjectInserted(DatabaseTable obj)
        {
            if (!MovingPicturesCore.Settings.FollwitEnabled) {
                logger.Warn("Attempt to call follw.it made when service is disabled.");
                return;
            }

            try {
                if (obj.GetType() == typeof(DBWatchedHistory)) {
                    DBWatchedHistory wh = (DBWatchedHistory)obj;
                    DBMovieInfo movie = wh.Movie;

                    WatchMovie(movie, true);
                }
                else if (obj.GetType() == typeof(DBMovieInfo)) {
                    DBMovieInfo movie = (DBMovieInfo)obj;
                    FollwitBackgroundProcess bgProc = new FollwitBackgroundProcess();
                    bgProc.Action = FitActions.AddMoviesToCollection;
                    bgProc.Movies.Add(movie);
                    MovingPicturesCore.ProcessManager.StartProcess(bgProc);
                }
            }
            catch (Exception ex) {
                logger.ErrorException("Unexpected error connecting to follw.it!", ex);
                _follwitAPI = null;
                MovingPicturesCore.Follwit.Status = FollwitConnector.StatusEnum.INTERNAL_ERROR;
            }
        }
        private void OnObjectInserted(DatabaseTable obj)
        {
            // Update Recent Added/Watched lists
              if ((obj.GetType() == typeof(DBMovieInfo)) && movPicRecentAddedEnabled)
              {
            smcLog.WriteLog(string.Format("New movie added: {0}", ((DBMovieInfo)obj).Title), LogLevel.Info);
            getLastThreeAddedMovies();
              }
              else if ((obj.GetType() == typeof(DBWatchedHistory)) && movPicRecentWatchedEnabled)
              {
            smcLog.WriteLog(string.Format("movie watched: {0}", ((DBWatchedHistory)obj).Movie.Title), LogLevel.Info);
            getLastThreeWatchedMovies();

            // Filter Recently Added
            if (MiscConfigGUI.FilterWatchedInRecentlyAdded)
            {
              getLastThreeAddedMovies();
            }
              }
        }
        private void movieDeletedListener(DatabaseTable obj)
        {
            if (!MovingPicturesCore.Settings.FollwitEnabled) {
                logger.Warn("Attempt to call follw.it made when service is disabled.");
                return;
            }

            try {
                // if this is not a movie object, break
                if (obj.GetType() != typeof(DBMovieInfo))
                    return;

                if (!IsOnline) {
                    logger.Warn("Can not remove movie from follw.it collection because service is offline");
                    return;
                }

                DBMovieInfo movie = (DBMovieInfo)obj;

                List<DBMovieInfo> allMovies = DBMovieInfo.GetAll();

                int fitIdMovieCount = (from m in allMovies
                                       where m.FitId == movie.FitId
                                       select m).Count();

                if (fitIdMovieCount == 0)
                {
                    FollwitBackgroundProcess bgProc = new FollwitBackgroundProcess();
                    bgProc.Action = FitActions.RemoveMovieFromCollection;
                    bgProc.Movies.Add(movie);
                    MovingPicturesCore.ProcessManager.StartProcess(bgProc);
                }

            }
            catch (Exception ex) {
                logger.ErrorException("Unexpected error removing an object from your follw.it collection!", ex);
                _follwitAPI = null;
                MovingPicturesCore.Follwit.Status = FollwitConnector.StatusEnum.INTERNAL_ERROR;
            }
        }
        /// <summary>
        /// Fired when an object is removed from the MovingPictures Database
        /// </summary>
        private void DatabaseManager_ObjectDeleted(DatabaseTable obj)
        {
            // only remove from collection if the user wants us to
            if (!TraktSettings.KeepTraktLibraryClean || !TraktSettings.SyncLibrary)
                return;

            // check connection state
            if (TraktSettings.AccountStatus != ConnectionState.Connected)
                return;

            // if we have removed a movie from MovingPictures we want to update Trakt library
            if (obj.GetType() != typeof(DBMovieInfo))
                return;

            var syncThread = new Thread((objMovie) =>
            {
                var movie = objMovie as DBMovieInfo;

                var traktMovie = new TraktMovie
                {
                    Ids = new TraktMovieId { Imdb = movie.ImdbID, Tmdb = GetTmdbID(movie).ToNullableInt32() },
                    Title = movie.Title,
                    Year = movie.Year
                };

                TraktLogger.Info("Removing movie from trakt.tv collection, Title = '{0}', Year = '{1}', IMDB ID = '{2}', TMDb ID = '{3}'", movie.Title, movie.Year, movie.ImdbID ?? "<empty>", GetTmdbID(movie) ?? "<empty>");

                if (TraktSettings.SkipMoviesWithNoIdsOnSync)
                {
                    traktMovie.Title = null;
                    traktMovie.Year = null;
                    if (!BasicHandler.IsValidImdb(traktMovie.Ids.Imdb) && traktMovie.Ids.Tmdb == null)
                    {
                        TraktLogger.Info("Skipping movie removal from trakt.tv collection, movie has no valid online ID's.");
                        return;
                    }
                }

                // update local cache
                TraktCache.RemoveMovieFromCollection(traktMovie);

                var response = TraktAPI.TraktAPI.RemoveMovieFromCollection(traktMovie);
                TraktLogger.LogTraktResponse(response);
            })
            {
                IsBackground = true,
                Name = "Sync"
            };

            syncThread.Start(obj);
        }
        // Listens for new import paths and adds them to the DiskWatcher
        private static void onPathAdded(DatabaseTable obj)
        {
            // If this is not an import path object break
            if (obj.GetType() != typeof(DBImportPath))
                return;

            // Add the new import path to the watched drives
            AddWatchDrive(((DBImportPath)obj).FullPath);
        }
 /// <summary>
 /// Publishes standard object details to the skin
 /// </summary>
 /// <param name="obj">any object derived from databasetable</param>
 /// <param name="prefix">prefix for the generated skin properties</param>
 private void PublishDetails(DatabaseTable obj, string prefix)
 {
     PublishDetails(obj, prefix, false);
 }