Beispiel #1
0
        /// <summary>
        /// Saves any movies that return as 'already_exists' from library sync calls
        /// </summary>
        /// <param name="response">Trakt Sync Movie Response</param>
        public static void InsertAlreadyExistMovies(TraktSyncResponse response)
        {
            if (response == null || response.AlreadyExistMovies == null)
            {
                return;
            }

            foreach (var movie in response.AlreadyExistMovies)
            {
                if (TraktSettings.AlreadyExistMovies == null)
                {
                    TraktSettings.AlreadyExistMovies = new SyncMovieCheck();
                }

                TraktLogger.Info("Inserting movie into already-exist list: Title: {0}, Year: {1}, IMDb: {2}", movie.Title, movie.Year, movie.IMDBID);

                if (TraktSettings.AlreadyExistMovies.Movies != null)
                {
                    if (!TraktSettings.AlreadyExistMovies.Movies.Contains(movie))
                    {
                        TraktSettings.AlreadyExistMovies.Movies.Add(movie);
                    }
                }
                else
                {
                    TraktSettings.AlreadyExistMovies.Movies = new List <TraktMovieSync.Movie>();
                    TraktSettings.AlreadyExistMovies.Movies.Add(movie);
                }
            }
        }
Beispiel #2
0
        static void PlayTrailer(string url, PlayerFactory factory, bool?preparedPlayerResult)
        {
            if (preparedPlayerResult != null)
            {
                (factory.PreparedPlayer as OVSPLayer).GoFullscreen = true;

                var savedFactory = g_Player.Factory;
                g_Player.Factory = factory;

                try
                {
                    g_Player.Play(factory.PreparedUrl, g_Player.MediaType.Video);
                }
                catch (Exception e)
                {
                    TraktLogger.Warning("Exception while playing trailer: {0}", e.Message);
                }
                g_Player.Factory = savedFactory;
            }
            else
            {
                factory.PreparedPlayer.Dispose();
                GUIUtils.ShowNotifyDialog(GUI.Translation.Error, GUI.Translation.UnableToPlayTrailer);
            }
        }
Beispiel #3
0
        private void InitProperties()
        {
            // Fanart
            backdrop.GUIImageOne  = FanartBackground;
            backdrop.GUIImageTwo  = FanartBackground2;
            backdrop.LoadingImage = loadingImage;

            // set search term from loading parameter
            if (!string.IsNullOrEmpty(_loadParameter))
            {
                TraktLogger.Debug("Episode Search Loading Parameter: {0}", _loadParameter);
                SearchTerm = _loadParameter;
            }

            // remember previous search term
            SearchTermChanged = false;
            if (PreviousSearchTerm != SearchTerm)
            {
                SearchTermChanged = true;
            }
            PreviousSearchTerm = SearchTerm;

            // set context property
            GUIUtils.SetProperty("#Trakt.Search.SearchTerm", SearchTerm);

            // load last layout
            CurrentLayout = (Layout)TraktSettings.SearchShowsDefaultLayout;

            // update button label
            GUIControl.SetControlLabel(GetID, layoutButton.GetID, GUICommon.GetLayoutTranslation(CurrentLayout));
        }
        public void StopScrobble()
        {
            if (CurrentRecording == null)
            {
                return;
            }

            // get current progress of player
            bool   watched  = false;
            double progress = 0.0;

            if (g_Player.Duration > 0.0)
            {
                progress = Math.Round((g_Player.CurrentPosition / g_Player.Duration) * 100.0, 2);
            }

            TraktLogger.Info("Video recording has stopped, checking progress. Title = '{0}', Current Position = '{1}', Duration = '{2}', Progress = '{3}%'",
                             CurrentRecording.Title, g_Player.CurrentPosition.ToString(), g_Player.Duration.ToString(), progress > 100.0 ? "100" : progress.ToString());

            // if recording is at least 80% complete, consider watched
            // consider watched with invalid progress as well, we should never be exactly 0.0
            if (progress == 0.0 || progress >= 80.0)
            {
                watched = true;

                // Show rate dialog
                BasicHandler.ShowRateDialog(CurrentRecording);
            }

            BasicHandler.StopScrobble(CurrentRecording, watched);

            CurrentRecording = null;
        }
Beispiel #5
0
        static void GetTrailerUrl(string htmlPage)
        {
            // get playback url from stream
            TraktLogger.Debug("Getting playback url from page '{0}'", htmlPage);

            GUIBackgroundTask.Instance.ExecuteInBackgroundAndCallback(() =>
            {
                var ovHosterProxy = OnlineVideosAppDomain.Domain.CreateInstanceAndUnwrap(typeof(OnlineVideosHosterProxy).Assembly.FullName, typeof(OnlineVideosHosterProxy).FullName) as OnlineVideosHosterProxy;
                var url           = ovHosterProxy.GetVideoUrls(htmlPage);
                return(url);
            },
                                                                      delegate(bool success, object result)
            {
                string url = result as string;

                if (success)
                {
                    if (!string.IsNullOrEmpty(url))
                    {
                        BufferTrailer(url);
                    }
                    else
                    {
                        TraktLogger.Info("Unable to get url for trailer playback.", url);
                        GUIUtils.ShowNotifyDialog(GUI.Translation.Error, GUI.Translation.UnableToPlayTrailer);
                    }
                }
            },
                                                                      GUI.Translation.GettingTrailerUrls, false);
        }
Beispiel #6
0
        /// <summary>
        /// Reads all Skin Settings
        /// </summary>
        /// <param name="filename"></param>
        public static void Load(string filename)
        {
            // Check if File Exist
            if (!System.IO.File.Exists(filename))
            {
                TraktLogger.Warning("Trakt Skin Settings does not exist!");
                return;
            }

            XmlDocument doc = new XmlDocument();

            try
            {
                doc.Load(filename);
            }
            catch (XmlException e)
            {
                TraktLogger.Error("Cannot Load skin settings xml file!: {0}", e.Message);
                return;
            }

            // Read and Import Skin Settings
            GetOverlayPositions(doc);

            // Read Dashboard Skin Setings
            GetDashboardSkinSettings(doc);
        }
Beispiel #7
0
 public void DisposeEvents()
 {
     TraktLogger.Debug("Removing Hooks from My Anime");
     animeWindow.OnToggleWatched -= new MainWindow.OnToggleWatchedHandler(OnToggleWatched);
     animeWindow.OnRateSeries    -= new MainWindow.OnRateSeriesHandler(OnRateSeries);
     animeWindow = null;
 }
Beispiel #8
0
        private void InitProperties()
        {
            // set search term from loading parameter
            if (!string.IsNullOrEmpty(_loadParameter))
            {
                TraktLogger.Debug("User Search Loading Parameter: {0}", _loadParameter);
                SearchTerm = _loadParameter;
            }

            // remember previous search term
            SearchTermChanged = false;
            if (PreviousSearchTerm != SearchTerm)
            {
                SearchTermChanged = true;
            }
            PreviousSearchTerm = SearchTerm;

            // set context property
            GUIUtils.SetProperty("#Trakt.Search.SearchTerm", SearchTerm);

            // load last layout
            CurrentLayout = (GUIFacadeControl.Layout)TraktSettings.SearchUsersDefaultLayout;

            // update button label
            if (layoutButton != null)
            {
                GUIControl.SetControlLabel(GetID, layoutButton.GetID, GUICommon.GetLayoutTranslation(CurrentLayout));
            }
        }
        /// <summary>
        /// Gets the current program
        /// </summary>
        /// <returns></returns>
        private VideoInfo GetCurrentProgram()
        {
            VideoInfo videoInfo = new VideoInfo();

            // get current program details
            Program program = TVHome.Navigator.Channel.CurrentProgram;

            if (program == null || string.IsNullOrEmpty(program.Title))
            {
                TraktLogger.Info("Unable to get current program from database.");
                return(null);
            }
            else
            {
                string title = null;
                string year  = null;
                GetTitleAndYear(program, out title, out year);

                videoInfo = new VideoInfo
                {
                    Type       = !string.IsNullOrEmpty(program.EpisodeNum) || !string.IsNullOrEmpty(program.SeriesNum) ? VideoType.Series : VideoType.Movie,
                    Title      = title,
                    Year       = year,
                    SeasonIdx  = program.SeriesNum,
                    EpisodeIdx = program.EpisodeNum,
                    StartTime  = program.StartTime,
                    Runtime    = GetRuntime(program)
                };
            }

            return(videoInfo);
        }
        private void OnToggleWatched(MFMovie movie, bool watched, int count)
        {
            TraktLogger.Info("Received togglewatched event from My Films");

            if (TraktSettings.AccountStatus != ConnectionState.Connected)
            {
                return;
            }

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

            Thread toggleWatchedThread = new Thread((o) =>
            {
                MFMovie tMovie         = o as MFMovie;
                TraktResponse response = TraktAPI.TraktAPI.SyncMovieLibrary(CreateSyncData(tMovie), watched ? TraktSyncModes.seen : TraktSyncModes.unseen);
                TraktAPI.TraktAPI.LogTraktResponse(response);
            })
            {
                IsBackground = true,
                Name         = "ToggleWatched"
            };

            toggleWatchedThread.Start(movie);
        }
        private void OnImportComplete()
        {
            if (TraktSettings.AccountStatus != ConnectionState.Connected)
            {
                return;
            }

            TraktLogger.Debug("My Films import complete, initiating online sync");

            // sync again
            Thread syncThread = new Thread(delegate()
            {
                while (SyncInProgress)
                {
                    // only do one sync at a time
                    TraktLogger.Debug("My Films sync still in progress, waiting to complete. Trying again in 60secs.");
                    Thread.Sleep(60000);
                }
                SyncLibrary();
            })
            {
                IsBackground = true,
                Name         = "LibrarySync"
            };

            syncThread.Start();
        }
        private void OnRateItem(MFMovie movie, string value)
        {
            TraktLogger.Info("Received rating event from MyFilms");

            if (TraktSettings.AccountStatus != ConnectionState.Connected)
            {
                return;
            }

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

            // My Films is a 100 point scale out of 10. Treat as decimal and then round off
            string            rating   = Math.Round(Convert.ToDecimal(value), MidpointRounding.AwayFromZero).ToString();
            TraktRateResponse response = null;

            Thread rateThread = new Thread((o) =>
            {
                MFMovie tMovie = o as MFMovie;

                response = TraktAPI.TraktAPI.RateMovie(CreateRateData(tMovie, rating));

                TraktAPI.TraktAPI.LogTraktResponse(response);
            })
            {
                IsBackground = true,
                Name         = "Rate"
            };

            rateThread.Start(movie);
        }
        private void OnStoppedMovie(MFMovie movie)
        {
            if (TraktSettings.AccountStatus != ConnectionState.Connected)
            {
                return;
            }

            if (!TraktSettings.BlockedFilenames.Contains(movie.File) && !TraktSettings.BlockedFolders.Any(f => movie.File.ToLowerInvariant().Contains(f.ToLowerInvariant())))
            {
                TraktLogger.Info("Stopped My Films movie playback: '{0}'", movie.Title);

                CurrentMovie = null;
                StopScrobble();

                // send cancelled watching state
                Thread cancelWatching = new Thread(delegate()
                {
                    TraktMovieScrobble scrobbleData = new TraktMovieScrobble {
                        UserName = TraktSettings.Username, Password = TraktSettings.Password
                    };
                    TraktResponse response = TraktAPI.TraktAPI.ScrobbleMovieState(scrobbleData, TraktScrobbleStates.cancelwatching);
                    TraktAPI.TraktAPI.LogTraktResponse(response);
                })
                {
                    IsBackground = true,
                    Name         = "CancelWatching"
                };

                cancelWatching.Start();
            }
        }
        public MyFilmsHandler(int priority)
        {
            // check if plugin exists otherwise plugin could accidently get added to list
            string pluginFilename = Path.Combine(Config.GetSubFolder(Config.Dir.Plugins, "Windows"), "MyFilms.dll");

            if (!File.Exists(pluginFilename))
            {
                throw new FileNotFoundException("Plugin not found!");
            }
            else
            {
                FileVersionInfo fvi     = FileVersionInfo.GetVersionInfo(pluginFilename);
                string          version = fvi.ProductVersion;
                if (new Version(version) < new Version(6, 0, 0, 2616))
                {
                    throw new FileLoadException("Plugin does not meet minimum requirements!");
                }
            }

            // Subscribe to Events
            TraktLogger.Debug("Adding Hooks to My Films");
            MyFilmsDetail.RateItem     += new MyFilmsDetail.RatingEventDelegate(OnRateItem);
            MyFilmsDetail.WatchedItem  += new MyFilmsDetail.WatchedEventDelegate(OnToggleWatched);
            MyFilmsDetail.MovieStarted += new MyFilmsDetail.MovieStartedEventDelegate(OnStartedMovie);
            MyFilmsDetail.MovieStopped += new MyFilmsDetail.MovieStoppedEventDelegate(OnStoppedMovie);
            MyFilmsDetail.MovieWatched += new MyFilmsDetail.MovieWatchedEventDelegate(OnWatchedMovie);
            MyFilms.ImportComplete     += new MyFilms.ImportCompleteEventDelegate(OnImportComplete);

            Priority = priority;
        }
Beispiel #15
0
        public static TmdbSeasonImages GetSeasonImages(int?id, int season, bool forceUpdate = false)
        {
            if (id == null)
            {
                return(null);
            }

            // if its in our cache return it
            TmdbSeasonImages seasonImages;

            if (Seasons.TryGetValue(Tuple.Create(id, season), out seasonImages))
            {
                if (forceUpdate)
                {
                    return(seasonImages);
                }

                // but only if the request is not very old
                if (DateTime.Now.Subtract(new TimeSpan(TraktSettings.TmdbSeasonImageMaxCacheAge, 0, 0, 0, 0)) < seasonImages.RequestAge.ToDateTime())
                {
                    return(seasonImages);
                }

                TraktLogger.Info("Season image cache expired. TMDb ID = '{0}', Season = '{1}', Request Age = '{2}'", id, seasonImages.Season, seasonImages.RequestAge);
                RemoveSeasonImagesFromCache(seasonImages);
            }

            // get movie images from tmdb and add to the cache
            seasonImages = TmdbAPI.TmdbAPI.GetSeasonImages(id.ToString(), season);
            AddSeasonImagesToCache(seasonImages);

            return(seasonImages);
        }
        private void DeleteList(TraktUserList list)
        {
            if (!GUIUtils.ShowYesNoDialog(Translation.Lists, Translation.ConfirmDeleteList, false))
            {
                return;
            }

            GUIBackgroundTask.Instance.ExecuteInBackgroundAndCallback(() =>
            {
                TraktLogger.Info("Deleting list '{0}'", list.Name);
                TraktList deleteList = new TraktList {
                    UserName = TraktSettings.Username, Password = TraktSettings.Password, Slug = list.Slug
                };
                return(TraktAPI.TraktAPI.ListDelete(deleteList));
            },
                                                                      delegate(bool success, object result)
            {
                if (success)
                {
                    TraktResponse response = result as TraktResponse;
                    TraktLogger.LogTraktResponse <TraktResponse>(response);
                    if (response.Status == "success")
                    {
                        // reload with new list
                        TraktLists.ClearCache(TraktSettings.Username);
                        LoadLists();
                    }
                    else
                    {
                        GUIUtils.ShowNotifyDialog(Translation.Lists, response.Error);
                    }
                }
            }, Translation.DeletingList, true);
        }
Beispiel #17
0
        public static TmdbPeopleImages GetPersonImages(int?id, bool forceUpdate = false)
        {
            if (id == null)
            {
                return(null);
            }

            // if its in our cache return it
            TmdbPeopleImages personImages;

            if (People.TryGetValue(id, out personImages))
            {
                if (forceUpdate)
                {
                    return(personImages);
                }

                // but only if the request is not very old
                if (DateTime.Now.Subtract(new TimeSpan(TraktSettings.TmdbPersonImageMaxCacheAge, 0, 0, 0, 0)) < personImages.RequestAge.ToDateTime())
                {
                    return(personImages);
                }

                TraktLogger.Info("People image cache expired. TMDb ID = '{0}', Request Age = '{1}'", id, personImages.RequestAge);
                RemovePeopleImagesFromCache(personImages);
            }

            // get movie images from tmdb and add to the cache
            personImages = TmdbAPI.TmdbAPI.GetPeopleImages(id.ToString());
            AddPeopleImagesToCache(personImages);

            return(personImages);
        }
 private void EditList(TraktList list)
 {
     GUIBackgroundTask.Instance.ExecuteInBackgroundAndCallback(() =>
     {
         return(TraktAPI.TraktAPI.ListUpdate(list));
     },
                                                               delegate(bool success, object result)
     {
         if (success)
         {
             TraktResponse response = result as TraktResponse;
             TraktLogger.LogTraktResponse <TraktResponse>(response);
             if (response.Status == "success")
             {
                 // reload with new list
                 TraktLists.ClearCache(TraktSettings.Username);
                 LoadLists();
             }
             else
             {
                 GUIUtils.ShowNotifyDialog(Translation.Lists, response.Error);
             }
         }
     }, Translation.EditingList, true);
 }
Beispiel #19
0
        private void OnToggleWatched(List <AnimeEpisode> episodes, bool state)
        {
            if (TraktSettings.AccountStatus != ConnectionState.Connected)
            {
                return;
            }

            TraktLogger.Info("Received togglewatched event from my anime");

            Thread toggleWatched = new Thread(delegate()
            {
                foreach (var series in episodes.Select(e => e.Series.TvDB_ID).Distinct().ToList())
                {
                    if (series == null)
                    {
                        continue;
                    }
                    TraktEpisodeSync episodeSyncData = CreateSyncData(AnimeSeries.GetSeriesWithSpecificTvDB((int)series).First(), episodes);
                    if (episodeSyncData == null)
                    {
                        return;
                    }
                    TraktResponse response = TraktAPI.TraktAPI.SyncEpisodeLibrary(episodeSyncData, state ? TraktSyncModes.seen : TraktSyncModes.unseen);
                    TraktAPI.TraktAPI.LogTraktResponse(response);
                }
            })
            {
                IsBackground = true,
                Name         = "ToggleWatched"
            };

            toggleWatched.Start();
        }
        // Loads an Image from a File by invoking GDI Plus instead of using build-in
        // .NET methods, or falls back to Image.FromFile. GDI Plus should be faster.
        public static Image LoadImageFastFromFile(string filename)
        {
            IntPtr imagePtr = IntPtr.Zero;
            Image  image    = null;

            try
            {
                if (GdipLoadImageFromFile(filename, out imagePtr) != 0)
                {
                    image = LoadImageSafe(filename);
                }

                else
                {
                    image = (Image)typeof(Bitmap).InvokeMember("FromGDIplus", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, new object[] { imagePtr });
                }
            }
            catch (Exception e)
            {
                TraktLogger.Warning("Failed to load image {0}: {1}", filename, e.Message);
                image = null;
            }

            return(image);
        }
Beispiel #21
0
        private void OnRateSeries(AnimeSeries series, string rateValue)
        {
            if (TraktSettings.AccountStatus != ConnectionState.Connected)
            {
                return;
            }

            TraktLogger.Info("Received rating event for series from my anime");

            Thread rateThread = new Thread(delegate()
            {
                TraktRateSeries seriesRateData = CreateSeriesRateData(series, rateValue);
                if (seriesRateData == null)
                {
                    return;
                }
                TraktRateResponse response = TraktAPI.TraktAPI.RateSeries(seriesRateData);

                // check for any error and notify
                TraktAPI.TraktAPI.LogTraktResponse(response);
            })
            {
                IsBackground = true,
                Name         = "Rate"
            };

            rateThread.Start();
        }
        private void ScrobbleProgram(VideoInfo program)
        {
            Thread scrobbleProgram = new Thread(delegate(object obj)
            {
                VideoInfo videoInfo = obj as VideoInfo;
                if (videoInfo == null)
                {
                    return;
                }

                TraktLogger.Info("Playback of '{0}' in 4TR tv-live is considered watched.", videoInfo.ToString());

                if (videoInfo.Type == VideoType.Series)
                {
                    BasicHandler.ScrobbleEpisode(videoInfo, TraktScrobbleStates.scrobble);
                }
                else
                {
                    BasicHandler.ScrobbleMovie(videoInfo, TraktScrobbleStates.scrobble);
                }
            })
            {
                IsBackground = true,
                Name         = "Scrobble"
            };

            scrobbleProgram.Start(program);
        }
Beispiel #23
0
        private TraktMovieScrobble CreateMovieScrobbleData(ITrackingInfo info)
        {
            try
            {
                // create scrobble data
                TraktMovieScrobble scrobbleData = new TraktMovieScrobble
                {
                    Title                = info.Title,
                    Year                 = info.Year > 1900 ? info.Year.ToString() : null,
                    IMDBID               = info.ID_IMDB,
                    TMDBID               = info.ID_TMDB,
                    PluginVersion        = TraktSettings.Version,
                    MediaCenter          = "Mediaportal",
                    MediaCenterVersion   = Assembly.GetEntryAssembly().GetName().Version.ToString(),
                    MediaCenterBuildDate = String.Empty,
                    UserName             = TraktSettings.Username,
                    Password             = TraktSettings.Password
                };

                return(scrobbleData);
            }
            catch (Exception e)
            {
                TraktLogger.Error("Error creating scrobble data: {0}", e.Message);
                return(null);
            }
        }
        /// <summary>
        /// Gets the current program
        /// </summary>
        /// <returns></returns>
        private VideoInfo GetCurrentProgram()
        {
            VideoInfo videoInfo = new VideoInfo();

            // get current program details
            GuideProgram program = ForTheRecordMain.GetProgramAt(DateTime.Now);

            if (program == null || string.IsNullOrEmpty(program.Title))
            {
                TraktLogger.Info("Unable to get current program from database.");
                return(null);
            }
            else
            {
                string title = null;
                string year  = null;
                GetTitleAndYear(program, out title, out year);

                videoInfo = new VideoInfo
                {
                    Type       = program.EpisodeNumber != null || program.SeriesNumber != null ? VideoType.Series : VideoType.Movie,
                    Title      = title,
                    Year       = year,
                    SeasonIdx  = program.SeriesNumber == null ? null : program.SeriesNumber.ToString(),
                    EpisodeIdx = program.EpisodeNumber == null ? null : program.EpisodeNumber.ToString(),
                    StartTime  = program.StartTime,
                    Runtime    = GetRuntime(program)
                };
            }

            return(videoInfo);
        }
Beispiel #25
0
        public OnlineVideos(int priority)
        {
            // check if plugin exists otherwise plugin could accidently get added to list
            string pluginFilename = Path.Combine(Config.GetSubFolder(Config.Dir.Plugins, "Windows"), "OnlineVideos.MediaPortal1.dll");

            if (!File.Exists(pluginFilename))
            {
                throw new FileNotFoundException("Plugin not found!");
            }
            else
            {
                FileVersionInfo fvi     = FileVersionInfo.GetVersionInfo(pluginFilename);
                string          version = fvi.ProductVersion;
                if (new Version(version) < new Version(0, 31, 0, 0))
                {
                    throw new FileLoadException("Plugin does not meet minimum requirements!");
                }
            }

            TraktLogger.Debug("Adding Hooks to OnlineVideos");

            // Subscribe to Player Events
            ovObject = (GUIOnlineVideos)GUIWindowManager.GetWindow((int)ExternalPluginWindows.OnlineVideos);
            ovObject.TrackVideoPlayback += new GUIOnlineVideos.TrackVideoPlaybackHandler(TrackVideoPlayback);

            Priority = priority;
        }
Beispiel #26
0
        static string LoadFileCache(string filename, string defaultValue)
        {
            string returnValue = defaultValue;

            try
            {
                if (File.Exists(filename))
                {
                    TraktLogger.Debug("Loading file from disk. Filename = '{0}'", filename);
                    returnValue = File.ReadAllText(filename, Encoding.UTF8);
                    if (string.IsNullOrEmpty(returnValue))
                    {
                        TraktLogger.Warning("Unexpected contents in file '{0}', restoring default value", filename);
                        returnValue = defaultValue;
                    }
                }
            }
            catch (Exception e)
            {
                TraktLogger.Error(string.Format("Error loading file from disk. Filename = '{0}', Error = '{1}'", filename, e.Message));
                return(defaultValue);
            }

            return(returnValue);
        }
        private void StartScrobble()
        {
            ISettingsManager settingsManager = ServiceRegistration.Get <ISettingsManager>();
            TraktSettings    settings        = settingsManager.Load <TraktSettings>();

            if (string.IsNullOrEmpty(settings.TraktOAuthToken))
            {
                TraktLogger.Info("0Auth Token not available");
                return;
            }

            if (!Login(settings.TraktOAuthToken))
            {
                return;
            }

            if (_dataMovie.Movie != null && IsMovie(currentPlayingMediaItem))
            {
                _dataMovie.Progress = 0;
                var response = TraktAPI.StartMovieScrobble(_dataMovie);
                TraktLogger.LogTraktResponse(response);
                return;
            }
            if (_dataEpisode != null && IsSeries(currentPlayingMediaItem))
            {
                _dataEpisode.Progress = 0;
                var response = TraktAPI.StartEpisodeScrobble(_dataEpisode);
                TraktLogger.LogTraktResponse(response);
                return;
            }
            TraktLogger.Info("Can't start scrobble, scrobbledata not available");
        }
Beispiel #28
0
        public static void Init()
        {
            TraktLogger.Info("Loading TMDb request cache");

            // load cached images from files and convert them to a thread-safe dictionary keyed by ID (and season/episode)
            var movies = LoadFileCache(MovieCacheFile, "[]").FromJSONArray <TmdbMovieImages>().ToList();

            Movies = new ConcurrentDictionary <int?, TmdbMovieImages>(movies.Distinct().ToDictionary(m => m.Id));

            var shows = LoadFileCache(ShowCacheFile, "[]").FromJSONArray <TmdbShowImages>().ToList();

            Shows = new ConcurrentDictionary <int?, TmdbShowImages>(shows.Distinct().ToDictionary(s => s.Id));

            var seasons = LoadFileCache(SeasonCacheFile, "[]").FromJSONArray <TmdbSeasonImages>().ToList();

            Seasons = new ConcurrentDictionary <Tuple <int?, int>, TmdbSeasonImages>(seasons.Distinct().ToDictionary(s => Tuple.Create(s.Id, s.Season)));

            var episodes = LoadFileCache(EpisodeCacheFile, "[]").FromJSONArray <TmdbEpisodeImages>().ToList();

            Episodes = new ConcurrentDictionary <Tuple <int?, int, int>, TmdbEpisodeImages>(episodes.Distinct().ToDictionary(e => Tuple.Create(e.Id, e.Season, e.Episode)));

            var people = LoadFileCache(PersonCacheFile, "[]").FromJSONArray <TmdbPeopleImages>().ToList();

            People = new ConcurrentDictionary <int?, TmdbPeopleImages>(people.Distinct().ToDictionary(p => p.Id));

            // get updated configuration from TMDb
            GetTmdbConfiguration();
        }
Beispiel #29
0
        /// <summary>
        /// Gets the current program
        /// </summary>
        /// <returns></returns>
        private VideoInfo GetCurrentProgram()
        {
            VideoInfo videoInfo = new VideoInfo();

            // get current program details
            Program program = TVHome.Navigator.Channel.CurrentProgram;

            if (program == null || string.IsNullOrEmpty(program.Title))
            {
                TraktLogger.Info("Unable to get current program from database");
                return(null);
            }
            else
            {
                string title = null;
                string year  = null;
                BasicHandler.GetTitleAndYear(program.Title, out title, out year);

                videoInfo = new VideoInfo
                {
                    Type       = !string.IsNullOrEmpty(program.EpisodeNum) || !string.IsNullOrEmpty(program.SeriesNum) ? VideoType.Series : VideoType.Movie,
                    Title      = title,
                    Year       = year,
                    SeasonIdx  = program.SeriesNum,
                    EpisodeIdx = program.EpisodeNum,
                    StartTime  = program.StartTime,
                    Runtime    = GetRuntime(program)
                };

                TraktLogger.Info("Current program details. Title='{0}', Year='{1}', Season='{2}', Episode='{3}', StartTime='{4}', Runtime='{5}'", videoInfo.Title, videoInfo.Year.ToLogString(), videoInfo.SeasonIdx.ToLogString(), videoInfo.EpisodeIdx.ToLogString(), videoInfo.StartTime == null ? "<empty>" : videoInfo.StartTime.ToString(), videoInfo.Runtime);
            }

            return(videoInfo);
        }
Beispiel #30
0
        /// <summary>
        /// Scrobbles a episode from a videoInfo object
        /// </summary>
        /// <returns>returns true if successfully scrobbled</returns>
        public static bool ScrobbleEpisode(VideoInfo videoInfo, TraktScrobbleStates state)
        {
            // get scrobble data to send to api
            TraktEpisodeScrobble scrobbleData = CreateEpisodeScrobbleData(videoInfo);

            if (scrobbleData == null)
            {
                return(false);
            }

            // get duration/position in minutes
            double duration = videoInfo.Runtime > 0.0 ? videoInfo.Runtime : g_Player.Duration / 60;
            double position = g_Player.CurrentPosition / 60;
            double progress = 0.0;

            if (duration > 0.0)
            {
                progress = (position / duration) * 100.0;
            }

            // sometimes with recordings/timeshifting we can get invalid player properties
            // adjust if duration is less than a typical episode
            scrobbleData.Duration = (duration < 10.0) ? "30" : Convert.ToInt32(duration).ToString();
            scrobbleData.Progress = (state == TraktScrobbleStates.scrobble) ? "100" : Convert.ToInt32(progress).ToString();

            TraktResponse response = TraktAPI.TraktAPI.ScrobbleEpisodeState(scrobbleData, state);

            return(TraktLogger.LogTraktResponse(response));
        }