/// <summary>
        /// syncs the watched state locally from trakt.tv
        /// </summary>
        public static void SyncTraktWatchedState()
        {
            if (string.IsNullOrEmpty(TraktAPI.Username) || string.IsNullOrEmpty(TraktAPI.Password))
            {
                return;
            }

            // Get all local unwatched episodes
            SQLCondition     conditions = new SQLCondition(new DBOnlineEpisode(), DBOnlineEpisode.cWatched, false, SQLConditionType.Equal);
            List <DBEpisode> episodes   = DBEpisode.Get(conditions, false);

            var watchedItems = TraktAPI.GetUserWatched(TraktAPI.Username);

            MPTVSeriesLog.Write("Trakt: Syncronizing Watched/Seen from trakt.tv");

            // go through all unwatched episodes and check if watched online
            foreach (DBEpisode episode in episodes)
            {
                // if the episode exists on server response
                // then we mark as watched locally
                if (HasEpisode(watchedItems, episode))
                {
                    MPTVSeriesLog.Write("Trakt: Marking '{0}' as watched", episode.ToString());
                    episode[DBOnlineEpisode.cWatched]   = true;
                    episode[DBOnlineEpisode.cTraktSeen] = true;
                    episode.Commit();
                }
            }

            MPTVSeriesLog.Write("Finished Syncronizing Watched/Seen state from trakt.tv");
        }
        /// <summary>
        /// Play episode async
        /// </summary>
        /// <param name="episode">Episode to play</param>
        /// <param name="startPosition">Postion from where playback should be started (only valid if resum=false)</param>
        /// <param name="resume">Resume from last stop?</param>
        private static void DoPlayEpisode(DBEpisode episode, bool resume, int startPosition)
        {
            if (GUIGraphicsContext.form.InvokeRequired)
            {
                PlayEpisodeAsyncDelegate d = new PlayEpisodeAsyncDelegate(DoPlayEpisode);
                GUIGraphicsContext.form.Invoke(d, new object[] { episode, resume, startPosition });
                return;
            }

            WifiRemote.LogMessage("Play episode (resume: " + resume + ", pos: " + startPosition, WifiRemote.LogType.Debug);

            if (player == null)
            {
                player = new VideoHandler();
            }

            // Reset stopTime if resume is false
            if (!resume)
            {
                episode[DBEpisode.cStopTime] = 0;
            }

            player.ResumeOrPlay((DBEpisode)episode);

            if (!resume && startPosition > 0)
            {
                g_Player.SeekAbsolute(startPosition);
            }
        }
Exemple #3
0
        public List <DBEpisode> getEpisodeItems(int stepIndex, string[] currentStepSelection)
        {
            MPTVSeriesLog.Write("View: Get Episodes", MPTVSeriesLog.LogLevel.Debug);
            SQLCondition conditions = null;

            if (stepIndex >= m_steps.Count)
            {
                return(null);                            // wrong index specified!!
            }
            addHierarchyConditions(ref stepIndex, ref currentStepSelection, ref conditions);

            MPTVSeriesLog.Write("View: Get Episodes: Executing SQL", MPTVSeriesLog.LogLevel.Debug);
            List <DBEpisode> eps = DBEpisode.Get(conditions);

            // WARNING: this naturally only works if the ordering is by season/episodeOrder
            // inline the special episodes to there relevant positions (Season == 0 by airsbefore_episode)
            MPTVSeriesLog.Write("View: Sorting Episodes", MPTVSeriesLog.LogLevel.Debug);
            if (m_steps[stepIndex].inLineSpecials && currentStepSelection[currentStepSelection.Length - 1] != "0")
            {
                if (m_steps[stepIndex].inLineSpecialsAsc)
                {
                    eps = Helper.inverseList <DBEpisode>(eps);
                }
                eps.Sort();
            }
            return(eps);
        }
        /// <summary>
        /// Playback the first unwatched episode for a series using TVSeries internal Video Handler
        /// If no Unwatched episodes exists, play the Most Recently Aired
        ///
        /// Taken from Trakt-for-MediaPortal:
        /// https://github.com/Technicolour/Trakt-for-Mediaportal/blob/master/TraktPlugin/TraktHandlers/TVSeries.cs
        /// </summary>
        /// <param name="seriesid">series id of episode</param>
        /// <param name="resume">Resume from last stop?</param>
        public static void PlayFirstUnwatchedEpisode(int seriesid, bool resume)
        {
            var episodes = DBEpisode.Get(seriesid);

            if (episodes == null || episodes.Count == 0)
            {
                return;
            }

            // filter out anything we can't play
            episodes.RemoveAll(e => string.IsNullOrEmpty(e[DBEpisode.cFilename]));
            if (episodes.Count == 0)
            {
                return;
            }

            // sort episodes using DBEpisode sort comparer
            // this takes into consideration Aired/DVD order and Specials in-line sorting
            episodes.Sort();

            // get first episode unwatched, otherwise get most recently aired
            var episode = episodes.Where(e => e[DBOnlineEpisode.cWatched] == 0).FirstOrDefault();

            if (episode == null)
            {
                WifiRemote.LogMessage("No Unwatched episodes found, Playing most recent episode", WifiRemote.LogType.Info);
                episode = episodes.LastOrDefault();
            }

            if (episode != null)
            {
                PlayEpisode(episode, resume);
            }
        }
        void MarkEpisodeAsWatched(DBEpisode episode)
        {
            // Could be a double episode, so mark both as watched
            SQLCondition condition = new SQLCondition();

            condition.Add(new DBEpisode(), DBEpisode.cFilename, episode[DBEpisode.cFilename], SQLConditionType.Equal);
            List <DBEpisode> episodes = DBEpisode.Get(condition, false);

            foreach (DBEpisode ep in episodes)
            {
                string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                ep[DBOnlineEpisode.cWatched]         = 1;
                ep[DBOnlineEpisode.cPlayCount]       = ep[DBOnlineEpisode.cPlayCount] + 1;
                ep[DBEpisode.cDateWatched]           = date;
                ep[DBOnlineEpisode.cLastWatchedDate] = date;
                if (string.IsNullOrEmpty(ep[DBOnlineEpisode.cFirstWatchedDate]))
                {
                    ep[DBOnlineEpisode.cFirstWatchedDate] = date;
                }
                ep.Commit();
            }
            // Update Episode Counts
            DBSeries series = Helper.getCorrespondingSeries(m_currentEpisode[DBEpisode.cSeriesID]);
            DBSeason season = Helper.getCorrespondingSeason(episode[DBEpisode.cSeriesID], episode[DBEpisode.cSeasonIndex]);

            DBSeason.UpdateEpisodeCounts(series, season);
        }
Exemple #6
0
        public static string getLogos(ref DBEpisode ep, int imgHeight, int imgWidth, bool firstOnly)
        {
            if (ep == null)
            {
                return(null);
            }

            try
            {
                lastWasCached = false;
                DBEpisode inCache = !Settings.isConfig ? cache.getEpisode(ep[DBEpisode.cSeriesID], ep[DBEpisode.cSeasonIndex], ep[DBOnlineEpisode.cEpisodeIndex]) : null;
                tmpEp = inCache == null || inCache[DBEpisode.cFilename] != ep[DBEpisode.cFilename] ? ep : inCache;
                // zeflash: since we use an image allocator we can't use a cache for the episode image anymore - so always call getLogos
                tmpEp.cachedLogoResults = null; // have to redo caching here
                lastResult = getLogos(Level.Episode, imgHeight, imgWidth, firstOnly, ref tmpEp.cachedLogoResults);

                if (!lastWasCached)
                {
                    cache.addChangeEpisode(tmpEp);
                }
                return(lastResult);
            }
            catch
            {
                return(null);
            }
        }
Exemple #7
0
        public static void UpdateEpisodeCounts(DBSeries series, DBSeason season)
        {
            if (series == null || season == null)
            {
                return;
            }

            int epsTotal     = 0;
            int epsUnWatched = 0;

            // Updated Season count
            DBEpisode.GetSeasonEpisodeCounts(series, season, out epsTotal, out epsUnWatched);

            season[DBSeason.cEpisodeCount]      = epsTotal;
            season[DBSeason.cEpisodesUnWatched] = epsUnWatched;
            season[DBSeason.cUnwatchedItems]    = epsUnWatched > 0;
            season.Commit();

            // Now Update the series count
            epsTotal     = 0;
            epsUnWatched = 0;

            DBEpisode.GetSeriesEpisodeCounts(series[DBSeries.cID], out epsTotal, out epsUnWatched);

            series[DBOnlineSeries.cEpisodeCount]      = epsTotal;
            series[DBOnlineSeries.cEpisodesUnWatched] = epsUnWatched;
            series[DBOnlineSeries.cUnwatchedItems]    = epsUnWatched > 0;
            series.Commit();
        }
        public static void RateEpisode(DBEpisode episode)
        {
            if (string.IsNullOrEmpty(TraktAPI.Username) || string.IsNullOrEmpty(TraktAPI.Password))
            {
                return;
            }

            new Thread(delegate()
            {
                DBSeries series = Helper.getCorrespondingSeries(episode[DBOnlineEpisode.cSeriesID]);

                TraktRateValue loveorhate = episode[DBOnlineEpisode.cMyRating] >= 7.0 ? TraktRateValue.love : TraktRateValue.hate;

                TraktRateEpisode episodeData = new TraktRateEpisode()
                {
                    Episode  = episode[DBOnlineEpisode.cEpisodeIndex],
                    Rating   = loveorhate.ToString(),
                    Season   = episode[DBOnlineEpisode.cSeasonIndex],
                    SeriesID = episode[DBOnlineEpisode.cSeriesID],
                    Year     = series.Year,
                    Title    = series[DBOnlineSeries.cOriginalName],
                    UserName = TraktAPI.Username,
                    Password = TraktAPI.Password
                };

                TraktRateResponse response = TraktAPI.RateEpisode(episodeData);

                // check for any error and notify
                CheckTraktErrorAndNotify(response, false);
            })
            {
                IsBackground = true,
                Name         = "Trakt Rate Episode"
            }.Start();
        }
        /// <summary>
        /// Create PlayListItem from TvSeries episode id
        /// </summary>
        /// <param name="compositeId">Composite id of episode</param>
        /// <returns>PlayListItem item</returns>
        internal static MediaPortal.Playlists.PlayListItem CreatePlaylistItemFromEpisode(String compositeId)
        {
            var episodes = DBEpisode.Get(new SQLCondition(new DBTable("online_episodes"), "CompositeID", new DBValue(compositeId), SQLConditionType.Equal));
            var episode  = episodes.FirstOrDefault(e => !string.IsNullOrEmpty(e[DBEpisode.cFilename]));

            return(CreatePlaylistItemFromEpisode(episode));
        }
Exemple #10
0
 static string replaceEpisodeTags(DBEpisode s, string what)
 {
     if (s == null || what.Length < epIdentifier.Length)
     {
         return(what);
     }
     return(getValuesOfType(s, what, epParse, epIdentifier));
 }
        /// <summary>
        /// Play an episode
        ///
        /// Thanks to Trakt-for-MediaPortal:
        /// https://github.com/Technicolour/Trakt-for-Mediaportal/blob/master/TraktPlugin/TraktHandlers/TVSeries.cs
        /// </summary>
        /// <param name="episode">A valid tvseries episode</param>
        /// <param name="resume">Resume from last stop?</param>
        /// <param name="startPosition">Postion from where playback should be started (only valid if resum=false)</param>
        /// <returns></returns>
        private static void PlayEpisode(DBEpisode episode, bool resume, int startPosition = 0)
        {
            // Play on a new thread
            ThreadStart ts = delegate() { DoPlayEpisode(episode, resume, startPosition); };
            Thread      playEpisodeAsync = new Thread(ts);

            playEpisodeAsync.Start();
        }
Exemple #12
0
        static bool HasEpisode(IEnumerable <TraktWatchedShows> watchedItems, DBEpisode episode)
        {
            IEnumerable <TraktWatchedShows> items = watchedItems.Where(s => s.SeriesId == episode[DBOnlineEpisode.cSeriesID] &&
                                                                       s.Seasons.Where(e => e.Season == episode[DBOnlineEpisode.cSeasonIndex] &&
                                                                                       e.Episodes.Contains(episode[DBOnlineEpisode.cEpisodeIndex])).Count() == 1);

            return(items.Count() == 1);
        }
Exemple #13
0
 static void DBEpisode_dbEpisodeUpdateOccured(DBEpisode updated)
 {
     //MPTVSeriesLog.Write("Cache: Episode Commit occured: ", updated.ToString(), MPTVSeriesLog.LogLevel.Debug);
     if (getEpisode(updated[DBEpisode.cSeriesID], updated[DBEpisode.cSeasonIndex], updated[DBEpisode.cEpisodeIndex]) != null)
     {
         addChangeEpisode(updated);
     }
 }
        protected override bool GrabFileDetails()
        {
            try {
                episode = WindowPlugins.GUITVSeries.TVSeriesPlugin.m_SelectedEpisode;
                if (episode == null) return false;

                series = Helper.getCorrespondingSeries(episode[DBEpisode.cSeriesID]);
                if (series == null) return false;

                string seriesTitle = series[DBOnlineSeries.cOriginalName];

                string seasonIdx = episode[DBEpisode.cSeasonIndex];
                string episodeIdx = episode[DBEpisode.cEpisodeIndex];
                string episodeIdxAbs = episode[DBOnlineEpisode.cAbsoluteNumber];

                bool absolute = false;

                if (series[DBOnlineSeries.cChosenEpisodeOrder] == "Absolute" && !string.IsNullOrEmpty(episodeIdxAbs)) {
                    absolute = true;
                }

                int seasonIdxInt = -1;
                int.TryParse(seasonIdx, out seasonIdxInt);
                int episodeIdxInt = -1;
                int.TryParse(episodeIdx, out episodeIdxInt);
                int episodeIdxAbsInt = -1;
                int.TryParse(episodeIdxAbs, out episodeIdxAbsInt);

                string thumb = ImageAllocator.GetSeriesPosterAsFilename(series);
                string fanart = Fanart.getFanart(episode[DBEpisode.cSeriesID]).FanartFilename;
                string episodeFileName = episode[DBEpisode.cFilename];

                _mediaDetail = new BasicMediaDetail();

                _mediaDetail.Title = seriesTitle;

                _mediaDetail.AbsoluteNumbering = absolute;

                _mediaDetail.Season = seasonIdxInt;
                _mediaDetail.Episode = episodeIdxInt;
                _mediaDetail.EpisodeAbs = episodeIdxAbsInt;

                _mediaDetail.Thumb = thumb;
                _mediaDetail.FanArt = fanart;

                _mediaDetail.Files = new List<FileInfo>();
                if (!string.IsNullOrEmpty(episodeFileName))
                    _mediaDetail.Files.Add(new FileInfo(episodeFileName));

                _mediaDetail.TvdbId = series[DBSeries.cID];

                return true;
            }
            catch (Exception e) {
                logger.ErrorException(string.Format("Unexpected error when pulling data from TVSeries{0}", Environment.NewLine), e);
                return false;
            }
        }
        /// <summary>
        /// Play an episode of a specific series and season
        ///
        /// Thanks to Trakt-for-MediaPortal:
        /// https://github.com/Technicolour/Trakt-for-Mediaportal/blob/master/TraktPlugin/TraktHandlers/TVSeries.cs
        /// </summary>
        /// <param name="seriesId">ID of the series</param>
        /// <param name="seasonNumber">Number of the season</param>
        /// <param name="episodeNumber">Number of the episode</param>
        /// <paraparam name="resume">Resume from last stop?</paraparam>
        /// <param name="startPosition">Position from which the video should start in seconds (e.g. StartPosition=180 will start the episode 3 minutes into the video). Will be ignored if AskToResume is true.</param>
        public static void Play(int seriesId, int seasonNumer, int episodeNumber, bool resume, int startPosition = 0)
        {
            var episodes = DBEpisode.Get(seriesId, seasonNumer);
            var episode  = episodes.FirstOrDefault(e => (e[DBEpisode.cEpisodeIndex] == episodeNumber || e[DBEpisode.cEpisodeIndex2] == episodeNumber) && !string.IsNullOrEmpty(e[DBEpisode.cFilename]));

            if (episode == null)
            {
                return;
            }

            PlayEpisode(episode, resume, startPosition);
        }
        /// <summary>
        /// Play an episode of a specific series and season
        ///
        /// Thanks to Trakt-for-MediaPortal:
        /// https://github.com/Technicolour/Trakt-for-Mediaportal/blob/master/TraktPlugin/TraktHandlers/TVSeries.cs
        /// </summary>
        /// <param name="compositeId">Composite id of the episode</param>
        /// <paraparam name="resume">Resume from last stop?</paraparam>
        /// <param name="startPosition">Position from which the video should start in seconds (e.g. StartPosition=180 will start the episode 3 minutes into the video). Will be ignored if AskToResume is true.</param>
        public static void PlayEpisode(String compositeId, bool resume, int startPosition)
        {
            var episodes = DBEpisode.Get(new SQLCondition(new DBTable("online_episodes"), "CompositeID", new DBValue(compositeId), SQLConditionType.Equal));
            var episode  = episodes.FirstOrDefault(e => !string.IsNullOrEmpty(e[DBEpisode.cFilename]));

            if (episode == null)
            {
                return;
            }

            PlayEpisode(episode, resume, startPosition);;
        }
        /// <summary>
        /// Create PlayListItem from TvSeries show
        /// </summary>
        /// <param name="seriesId">Id of show</param>
        /// <returns>PlayListItem item</returns>
        internal static List <MediaPortal.Playlists.PlayListItem> CreatePlaylistItemsFromShow(int seriesId)
        {
            List <MediaPortal.Playlists.PlayListItem> returnList = new List <MediaPortal.Playlists.PlayListItem>();
            var episodes = DBEpisode.Get(seriesId);

            foreach (DBEpisode e in episodes)
            {
                returnList.Add(CreatePlaylistItemFromEpisode(e));
            }

            return(returnList);
        }
Exemple #18
0
        public static DBEpisode getEpisode(int SeriesID, int SeasonIndex, int EpisodeIndex)
        {
            singleSeriesRef = _cache.getSubItem(SeriesID);
            DBEpisode e = null;

            if (singleSeriesRef != null)
            {
                singleSeasonRef = singleSeriesRef.getSubItem(SeasonIndex);
                e = singleSeasonRef == null ? null : singleSeasonRef.getItemOfSubItem(EpisodeIndex);
            }
            //MPTVSeriesLog.Write("Cache: Requested Episode: " + SeriesID.ToString() + " S" + SeasonIndex.ToString() + " E" + EpisodeIndex.ToString() + (e == null ? " - Failed" : " - Sucess"), MPTVSeriesLog.LogLevel.Debug);
            return(e);
        }
Exemple #19
0
        public static void UpdateEpisodeCounts(DBSeries series)
        {
            if (series == null)
            {
                return;
            }

            int seriesEpsTotal     = 0;
            int seriesEpsUnWatched = 0;
            int epsTotal           = 0;
            int epsUnWatched       = 0;

            // Update for each season in series and add each to total series count
            SQLCondition condition = new SQLCondition();

            if (!DBOption.GetOptions(DBOption.cShowHiddenItems))
            {
                //don't include hidden seasons unless the ShowHiddenItems option is set
                condition.Add(new DBSeason(), DBSeason.cHidden, 0, SQLConditionType.Equal);
            }

            List <DBSeason> Seasons = DBSeason.Get(series[DBSeries.cID], condition);

            foreach (DBSeason season in Seasons)
            {
                epsTotal     = 0;
                epsUnWatched = 0;

                DBEpisode.GetSeasonEpisodeCounts(series, season, out epsTotal, out epsUnWatched);
                season[DBSeason.cEpisodeCount]      = epsTotal;
                season[DBSeason.cEpisodesUnWatched] = epsUnWatched;
                season[DBSeason.cUnwatchedItems]    = epsUnWatched > 0;
                season.Commit();

                seriesEpsTotal += epsTotal;
                // Count the Special (Season 0 (zero)) episodes as watched!
                if ((season[DBSeason.cIndex] != 0) || (season[DBSeason.cIndex] == 0 && !DBOption.GetOptions(DBOption.cCountSpecialEpisodesAsWatched)))
                {
                    seriesEpsUnWatched += epsUnWatched;
                }

                MPTVSeriesLog.Write(string.Format("Series \"{0} Season {1}\" has {2}/{3} unwatched episodes", series.ToString(), season[DBSeason.cIndex], epsUnWatched, epsTotal), MPTVSeriesLog.LogLevel.Debug);
            }

            MPTVSeriesLog.Write(string.Format("Series \"{0}\" has {1}/{2} unwatched episodes", series.ToString(), seriesEpsUnWatched, seriesEpsTotal), MPTVSeriesLog.LogLevel.Debug);

            series[DBOnlineSeries.cEpisodeCount]      = seriesEpsTotal;
            series[DBOnlineSeries.cEpisodesUnWatched] = seriesEpsUnWatched;
            series[DBOnlineSeries.cUnwatchedItems]    = seriesEpsUnWatched > 0;
            series.Commit();
        }
Exemple #20
0
        private bool AddItem(string episodeID)
        {
            SQLCondition condition = new SQLCondition();

            condition.Add(new DBOnlineEpisode(), DBOnlineEpisode.cID, episodeID, SQLConditionType.Equal);

            List <DBEpisode> ep = DBEpisode.Get(condition, false);

            if (ep.Count > 0)
            {
                PlayListItem newItem = new PlayListItem(ep[0]);
                playlist.Add(newItem);
            }
            return(true);
        }
Exemple #21
0
        public static void UpdateUnWatched(DBEpisode episode)
        {
            DBOnlineSeries series = new DBOnlineSeries(episode[DBEpisode.cSeriesID]);
            DBEpisode      FirstUnwatchedEpisode = DBEpisode.GetFirstUnwatched(series[DBSeries.cID]);

            if (FirstUnwatchedEpisode != null)
            {
                series[DBOnlineSeries.cUnwatchedItems] = true;
            }
            else
            {
                series[DBOnlineSeries.cUnwatchedItems] = false;
            }
            series.Commit();
        }
Exemple #22
0
        public static void UpdateUnWatched(DBEpisode episode)
        {
            DBSeason  season = new DBSeason(episode[DBEpisode.cSeriesID], episode[DBEpisode.cSeasonIndex]);
            DBEpisode FirstUnwatchedEpisode = DBEpisode.GetFirstUnwatched(season[DBSeason.cSeriesID], season[DBSeason.cIndex]);

            if (FirstUnwatchedEpisode != null)
            {
                season[DBSeason.cUnwatchedItems] = true;
            }
            else
            {
                season[DBSeason.cUnwatchedItems] = false;
            }
            season.Commit();
        }
Exemple #23
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="filename">Filename of the currently played episode</param>
        public NowPlayingSeries(string filename)
        {
            try
            {
                SQLCondition     query    = new SQLCondition(new DBEpisode(), DBEpisode.cFilename, filename, SQLConditionType.Equal);
                List <DBEpisode> episodes = DBEpisode.Get(query);

                if (episodes.Count > 0)
                {
                    episodeFound = true;

                    SeriesId    = episodes[0].onlineEpisode[DBOnlineEpisode.cSeriesID];
                    SeasonId    = episodes[0].onlineEpisode[DBOnlineEpisode.cSeasonID];
                    EpisodeId   = episodes[0].onlineEpisode[DBOnlineEpisode.cID];
                    CompositeId = episodes[0].fullItem[DBEpisode.cCompositeID];

                    Episode     = episodes[0].onlineEpisode[DBOnlineEpisode.cEpisodeIndex];
                    Season      = episodes[0].onlineEpisode[DBOnlineEpisode.cSeasonIndex];
                    Plot        = episodes[0].onlineEpisode[DBOnlineEpisode.cEpisodeSummary];
                    Title       = episodes[0].onlineEpisode[DBOnlineEpisode.cEpisodeName];
                    Director    = episodes[0].onlineEpisode[DBOnlineEpisode.cDirector];
                    Writer      = episodes[0].onlineEpisode[DBOnlineEpisode.cWriter];
                    Rating      = episodes[0].onlineEpisode[DBOnlineEpisode.cRating];
                    MyRating    = episodes[0].onlineEpisode[DBOnlineEpisode.cMyRating];
                    RatingCount = episodes[0].onlineEpisode[DBOnlineEpisode.cRatingCount];
                    AirDate     = episodes[0].onlineEpisode[DBOnlineEpisode.cFirstAired];

                    DBSeries s = Helper.getCorrespondingSeries(episodes[0].onlineEpisode[DBOnlineEpisode.cSeriesID]);
                    Series = s[DBOnlineSeries.cPrettyName];
                    Status = s[DBOnlineSeries.cStatus];
                    Genre  = s[DBOnlineSeries.cGenre];

                    // Get season poster path
                    DBSeason season = DBSeason.getRaw(SeriesId, episodes[0].onlineEpisode[DBOnlineEpisode.cSeasonIndex]);
                    ImageName = ImageAllocator.GetSeasonBannerAsFilename(season);

                    // Fall back to series poster if no season poster is available
                    if (String.IsNullOrEmpty(ImageName))
                    {
                        ImageName = ImageAllocator.GetSeriesPosterAsFilename(s);
                    }
                }
            }
            catch (Exception e)
            {
                WifiRemote.LogMessage("Error getting now playing tvseries: " + e.Message, WifiRemote.LogType.Error);
            }
        }
        public static LatestMediaHandler.MQTTItem CheckDB(string SearchFile)
        {
            LatestMediaHandler.MQTTItem item = new LatestMediaHandler.MQTTItem();
            if (MQTTPlugin.DebugMode)
            {
                Logger.Debug("Check to see if video is in MP-TVSeries database.");
            }

            if (Utils.IsAssemblyAvailable("MP-TVSeries", new Version(2, 6, 3, 1242)))
            {
                if (MQTTPlugin.DebugMode)
                {
                    Logger.Debug("MP-TVSeries found, searching Database for: " + SearchFile);
                }
                try
                {
                    SQLCondition     query    = new SQLCondition(new DBEpisode(), DBEpisode.cFilename, SearchFile, SQLConditionType.Equal);
                    List <DBEpisode> episodes = DBEpisode.Get(query);
                    if (MQTTPlugin.DebugMode)
                    {
                        Logger.Debug("Found: " + episodes.Count.ToString() + " episodes.");
                    }
                    if (episodes.Count > 0)
                    {
                        DBSeries s = Helper.getCorrespondingSeries(episodes[0].onlineEpisode[DBOnlineEpisode.cSeriesID]);
                        if (MQTTPlugin.DebugMode)
                        {
                            Logger.Debug("Video is in MP-TVSeries database.");
                        }

                        item.Id       = episodes[0][DBEpisode.cSeriesID];
                        item.Title    = s.ToString() + " - " + episodes[0][DBEpisode.cEpisodeName];
                        item.Filename = SearchFile;
                        item.Genres   = s[DBOnlineSeries.cGenre];
                        item.GetArtwork("tv");
                    }
                }
                catch (Exception e)
                {
                    Logger.Error("Error getting info from TVSeries Database: " + e.Message);
                }
            }
            return(item);
        }
Exemple #25
0
        static void getTableFieldname(string what, out DBTable table, out string fieldname)
        {
            string sTable = string.Empty;

            fieldname = string.Empty;
            table     = null;
            what      = what.Replace("<", "").Replace(">", "").Trim();
            sTable    = what.Split('.')[0];
            switch (sTable)
            {
            case "Series":
                if (new DBOnlineSeries().FieldNames.Contains(what.Split('.')[1]))
                {
                    table     = new DBOnlineSeries();
                    fieldname = what.Split('.')[1];
                }
                else
                {
                    table     = new DBSeries();
                    fieldname = what.Split('.')[1];
                }
                break;

            case "Season":
                table     = new DBSeason();
                fieldname = what.Split('.')[1];
                break;

            case "Episode":
                if (new DBOnlineEpisode().FieldNames.Contains(what.Split('.')[1]))
                {
                    table     = new DBOnlineEpisode();
                    fieldname = what.Split('.')[1];
                }
                else
                {
                    table     = new DBEpisode();
                    fieldname = what.Split('.')[1];
                }
                break;
            }
        }
Exemple #26
0
        public static List <DBEpisode> GetEpisodesToSync(DBSeries series, TraktSyncModes mode)
        {
            List <DBEpisode> episodes = new List <DBEpisode>();

            SQLCondition conditions = new SQLCondition();

            if (series == null)
            {
                // Get episodes for every series
                conditions.Add(new DBOnlineEpisode(), DBOnlineEpisode.cSeriesID, 0, SQLConditionType.GreaterThan);
            }
            else
            {
                // Get episodes for a single series
                conditions.Add(new DBOnlineEpisode(), DBOnlineEpisode.cSeriesID, series[DBSeries.cID], SQLConditionType.Equal);
            }

            switch (mode)
            {
            case TraktSyncModes.library:
                conditions.Add(new DBOnlineEpisode(), DBOnlineEpisode.cTraktLibrary, 0, SQLConditionType.Equal);
                conditions.Add(new DBOnlineEpisode(), DBOnlineEpisode.cHidden, 0, SQLConditionType.Equal);
                conditions.Add(new DBEpisode(), DBEpisode.cFilename, string.Empty, SQLConditionType.NotEqual);
                episodes = DBEpisode.Get(conditions, false);
                break;

            case TraktSyncModes.seen:
                conditions.Add(new DBOnlineEpisode(), DBOnlineEpisode.cHidden, 0, SQLConditionType.Equal);
                conditions.Add(new DBOnlineEpisode(), DBOnlineEpisode.cWatched, 1, SQLConditionType.Equal);
                conditions.Add(new DBOnlineEpisode(), DBOnlineEpisode.cTraktSeen, 0, SQLConditionType.Equal);
                episodes = DBEpisode.Get(conditions, false);
                break;

            case TraktSyncModes.unseen:
                conditions.Add(new DBOnlineEpisode(), DBOnlineEpisode.cHidden, 0, SQLConditionType.Equal);
                conditions.Add(new DBOnlineEpisode(), DBOnlineEpisode.cTraktSeen, 2, SQLConditionType.Equal);
                episodes = DBEpisode.Get(conditions, false);
                break;
            }

            return(episodes);
        }
Exemple #27
0
        public void HideSeason(bool hide)
        {
            MPTVSeriesLog.Write(string.Format("{0} series {1}, season {2} from view", (hide ? "Hiding" : "UnHiding"), Helper.getCorrespondingSeries(this[DBSeason.cSeriesID]), this[DBSeason.cIndex]));

            // respect 'Show Local Files Only' setting
            List <DBEpisode> episodes = DBEpisode.Get(int.Parse(this[DBSeason.cSeriesID]), int.Parse((this[DBSeason.cIndex])));

            if (episodes != null)
            {
                foreach (DBEpisode episode in episodes)
                {
                    // Hide Episodes
                    episode.HideEpisode(hide);
                }
            }

            // Hide Season
            this[DBSeason.cHidden] = hide;
            this.Commit();
        }
        private void onFacadeItemSelected(GUIListItem item, GUIControl parent)
        {
            // if this is not a message from the facade, exit
            if (parent != m_Facade && parent != m_Facade.FilmstripLayout &&
                parent != m_Facade.ThumbnailLayout && parent != m_Facade.ListLayout &&
                parent != m_Facade.PlayListLayout)
            {
                return;
            }

            if (item == null || item.TVTag == null)
            {
                return;
            }

            DBEpisode episode = item.TVTag as DBEpisode;

            if (episode == null || prevSelectedEpisode == episode)
            {
                return;
            }

            if (item.IsPlayed)
            {
                episode[DBOnlineEpisode.cWatched] = true;
            }

            // Push properties to skin
            TVSeriesPlugin.setGUIProperty(guiProperty.Title.ToString(), FieldGetter.resolveDynString(m_sFormatEpisodeTitle, episode));
            TVSeriesPlugin.setGUIProperty(guiProperty.Subtitle.ToString(), FieldGetter.resolveDynString(m_sFormatEpisodeSubtitle, episode));
            TVSeriesPlugin.setGUIProperty(guiProperty.Description.ToString(), FieldGetter.resolveDynString(m_sFormatEpisodeMain, episode));
            TVSeriesPlugin.setGUIProperty(guiProperty.Logos.ToString(), localLogos.getLogos(ref episode, TVSeriesPlugin.logosHeight, TVSeriesPlugin.logosWidth));
            TVSeriesPlugin.setGUIProperty(guiProperty.EpisodeImage.ToString(), ImageAllocator.GetEpisodeImage(episode));
            GUIPropertyManager.SetProperty("#selectedthumb", ImageAllocator.GetEpisodeImage(episode));

            TVSeriesPlugin.pushFieldsToSkin(episode, "Episode");

            // Some strange issues with logos when using mouse and hovering over current item
            // Dont push properties next time if the same episode is selected
            prevSelectedEpisode = episode;
        }
Exemple #29
0
        public static String GetEpisodeImage(DBEpisode episode)
        {
            bool HideEpisodeImage = true;

            if (!localLogos.appendEpImage && (episode[DBOnlineEpisode.cWatched] || !DBOption.GetOptions(DBOption.cHideUnwatchedThumbnail)))
            {
                HideEpisodeImage = false;
            }

            // show episode image
            if (!HideEpisodeImage && !String.IsNullOrEmpty(episode.Image) && System.IO.File.Exists(episode.Image))
            {
                return(episode.Image);
            }
            else
            {
                // show a fanart thumb instead
                Fanart fanart = Fanart.getFanart(episode[DBOnlineEpisode.cSeriesID]);
                return(fanart.FanartThumbFilename);
            }
        }
        void OnPlaybackChanged(g_Player.MediaType type, int timeMovieStopped, string filename)
        {
            if (PlayBackOpWasOfConcern(g_Player.IsVideo? g_Player.MediaType.Video : g_Player.MediaType.Unknown, g_Player.CurrentFile))
            {
                if (PlayPropertyUpdater.IsBusy)
                {
                    PlayPropertyUpdater.CancelAsync();
                }
                LogPlayBackOp("changed", g_Player.CurrentFile);
                try
                {
                    #region Set Resume Point or Watched
                    double watchedAfter = DBOption.GetOptions(DBOption.cWatchedAfter);
                    if (!m_previousEpisode[DBOnlineEpisode.cWatched] &&
                        (timeMovieStopped / playlistPlayer.g_Player.Duration) > watchedAfter / 100)
                    {
                        m_previousEpisode[DBEpisode.cStopTime] = 0;
                        m_previousEpisode.Commit();
                        MPTVSeriesLog.Write("This episode counts as watched");
                        MarkEpisodeAsWatched(m_previousEpisode);
                        SetGUIProperties(true);
                    }
                    else
                    {
                        m_previousEpisode[DBEpisode.cStopTime] = timeMovieStopped;
                        m_previousEpisode.Commit();
                        SetGUIProperties(true);
                    }
                    #endregion

                    m_previousEpisode = null;
                }
                catch (Exception e)
                {
                    MPTVSeriesLog.Write("TVSeriesPlugin.VideoHandler.OnPlaybackChanged()\r\n" + e.ToString());
                }
            }
        }
Exemple #31
0
        public static void addChangeEpisode(DBEpisode episode)
        {
            if (episode == null)
            {
                return;
            }

            _cache.AddDummy(episode[DBSeason.cSeriesID]);
            singleSeriesRef = _cache.getSubItem(episode[DBSeason.cSeriesID]);

            if (singleSeriesRef == null)
            {
                return;
            }
            singleSeriesRef.AddDummy(episode[DBSeason.cIndex]);

            var hc = singleSeriesRef.getSubItem(episode[DBSeason.cIndex]);

            if (hc != null)
            {
                hc.AddRaw(episode[DBEpisode.cEpisodeIndex], episode);
            }
        }
        /// <summary>
        /// Updates the DB episode.
        /// </summary>
        /// <param name="episode">The episode.</param>
        /// <param name="e">The db episode.</param>
        /// <exception cref="Uncas.PodCastPlayer.Repository.RepositoryException"></exception>
        private void UpdateDBEpisode(
            Episode episode,
            DBEpisode e)
        {
            e.Date = episode.Date;
            e.Description = episode.Description;
            e.DownloadedBytes =
                episode.DownloadedBytes;
            e.FileName = episode.FileName;
            e.FileSizeInBytes =
                episode.FileSizeInBytes;
            e.MediaUrl = episode.MediaUrl.ToString();
            e.PendingDownload =
                episode.PendingDownload;
            e.Title = episode.Title;

            try
            {
                this.DB.Update<DBEpisode>(e);
            }
            catch (Exception ex)
            {
                // TODO: EXCEPTION: Unknown SubSonic exception
                throw new RepositoryException(
                    "Error updating episode",
                    ex);
            }
        }
Exemple #33
0
        /// <summary>
        /// Play episode async
        /// </summary>
        /// <param name="episode">Episode to play</param>
        /// <param name="startPosition">Postion from where playback should be started (only valid if resum=false)</param>
        /// <param name="resume">Resume from last stop?</param>
        private static void DoPlayEpisode(DBEpisode episode, bool resume, int startPosition)
        {
            if (GUIGraphicsContext.form.InvokeRequired)
            {
                PlayEpisodeAsyncDelegate d = new PlayEpisodeAsyncDelegate(DoPlayEpisode);
                GUIGraphicsContext.form.Invoke(d, new object[] { episode, resume, startPosition });
                return;
            }

            WifiRemote.LogMessage("Play episode (resume: " + resume + ", pos: " + startPosition, WifiRemote.LogType.Debug);

            if (player == null) player = new VideoHandler();

            // Reset stopTime if resume is false
            if (!resume)
            {
                episode[DBEpisode.cStopTime] = 0;
            }

            player.ResumeOrPlay((DBEpisode)episode);

            if (!resume && startPosition > 0)
            {
                g_Player.SeekAbsolute(startPosition);
            }
        }
        private void OnEpisodeStopped(DBEpisode episode)
        {
            if (TraktSettings.AccountStatus != ConnectionState.Connected) return;

            // Episode does not count as watched, we dont need to do anything.
            TraktLogger.Info("Stopped TVSeries episode playback '{0}'", episode.ToString());
            EpisodeWatching = false;
            StopScrobble();

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

            cancelWatching.Start();
        }
        private void RateEpisode(DBEpisode episode)
        {
            Thread rateThread = new Thread(delegate()
            {
                TraktLogger.Info("Recieved rate episode event from tvseries");

                TraktRateEpisode episodeRateData = CreateEpisodeRateData(episode);
                if (episodeRateData == null) return;
                TraktRateResponse response = TraktAPI.TraktAPI.RateEpisode(episodeRateData);

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

            rateThread.Start();
        }
 public static bool PlayEpisode(DBEpisode episode)
 {
     if (player == null) player = new VideoHandler();
     return player.ResumeOrPlay(episode);
 }
        private TraktEpisodeScrobble CreateScrobbleData(DBEpisode episode)
        {
            DBSeries series = Helper.getCorrespondingSeries(episode[DBEpisode.cSeriesID]);
            if (series == null || series[DBOnlineSeries.cTraktIgnore]) return null;

            // create scrobble data
            TraktEpisodeScrobble scrobbleData = new TraktEpisodeScrobble
            {
                Title = series[DBOnlineSeries.cOriginalName],
                Year = series.Year,
                Season = episode[DBOnlineEpisode.cSeasonIndex],
                Episode = episode[DBOnlineEpisode.cEpisodeIndex],
                EpisodeID = episode[DBOnlineEpisode.cID],
                SeriesID = series[DBSeries.cID],
                PluginVersion = TraktSettings.Version,
                MediaCenter = "Mediaportal",
                MediaCenterVersion = Assembly.GetEntryAssembly().GetName().Version.ToString(),
                MediaCenterBuildDate = String.Empty,
                UserName = TraktSettings.Username,
                Password = TraktSettings.Password
            };

            return scrobbleData;
        }
        protected static DBEpisode WaitForSyncedEpisode(DBEpisode episode)
        {
            if (episode == null) return null;
            if (episode[DBOnlineEpisode.cFollwitId] != 0) return episode;

            TimeSpan retryDelay = new TimeSpan(0, 0, 30);
            int limit = 8;
            int epId = episode[DBOnlineEpisode.cID];

            int tries = 0;
            while (tries < limit) {
                // reload the episode from the db to check for changes
                SQLCondition condition = new SQLCondition();
                condition.Add(new DBOnlineEpisode(), DBOnlineEpisode.cID, epId, SQLConditionType.Equal);
                condition.Add(new DBOnlineEpisode(), DBOnlineEpisode.cFollwitId, 0, SQLConditionType.NotEqual);
                List<DBEpisode> episodes = DBEpisode.Get(condition, false);

                if (episodes.Count > 0) return episodes[0];

                Thread.Sleep(retryDelay);
                tries++;
            }

            return null;
        }
 /// <summary>
 /// Confirm that tvseries dbepisode exists in our trakt collection
 /// </summary>
 /// <param name="traktEpisodes">trakt episode collection</param>
 /// <param name="episode">tvseries episode object</param>
 /// <returns>true if episode exists</returns>
 private bool TraktEpisodeExists(IEnumerable<TraktLibraryShow> traktEpisodes, DBEpisode episode)
 {
     var items = traktEpisodes.Where(s => s.SeriesId == episode[DBOnlineEpisode.cSeriesID] &&
                                                        s.Seasons.Where(e => e.Season == episode[DBOnlineEpisode.cSeasonIndex] &&
                                                                             e.Episodes.Contains(episode[DBOnlineEpisode.cEpisodeIndex])).Count() == 1);
     return items.Count() == 1;
 }
        public static void Rate(DBEpisode episode, int rating)
        {
            if (!Enabled || episode == null || !episode.IsAvailableLocally) return;
            DBSeries series = DBSeries.Get(episode[DBEpisode.cSeriesID]);

            Thread thread = new Thread(new ThreadStart(delegate {
                try {
                    episode = WaitForSyncedEpisode(episode);
                    if (episode == null) return;

                    // start timer and send request
                    DateTime start = DateTime.Now;
                    int fivePointRating = (int)Math.Round(rating / 2.0, MidpointRounding.AwayFromZero);
                    FollwitApi.RateTVEpisode("follwit", episode[DBOnlineEpisode.cFollwitId], fivePointRating);

                    // log our success
                    MPTVSeriesLog.Write("[follw.it] Rated '{0} S{1}E{2}' a {3}/5. ({4})",
                                        series[DBOnlineSeries.cPrettyName],
                                        episode[DBOnlineEpisode.cCombinedSeason],
                                        episode[DBOnlineEpisode.cEpisodeIndex],
                                        fivePointRating,
                                        DateTime.Now - start);
                }
                catch (Exception e) {
                    // ah crap.
                    MPTVSeriesLog.Write("[follw.it] Failed rating '{0} S{1}E{2}': {3}",
                                        series[DBOnlineSeries.cPrettyName],
                                        episode[DBOnlineEpisode.cCombinedSeason],
                                        episode[DBOnlineEpisode.cEpisodeIndex],
                                        e.Message);
                }
            }));

            thread.IsBackground = true;
            thread.Name = "follw.it rating updater";
            thread.Start();
        }
        public static void Watch(DBEpisode episode, bool watched, bool showInStream)
        {
            if (!Enabled || episode == null || !episode.IsAvailableLocally) return;

            DBSeries series = DBSeries.Get(episode[DBEpisode.cSeriesID]);

            Thread thread = new Thread(new ThreadStart(delegate {
                try {
                    episode = WaitForSyncedEpisode(episode);
                    if (episode == null) return;

                    // start timer and send request
                    DateTime start = DateTime.Now;
                    FollwitApi.WatchedTVEpisode("follwit", episode[DBOnlineEpisode.cFollwitId], watched, showInStream);

                    // log our success
                    MPTVSeriesLog.Write("[follw.it] Set '{0} S{1}E{2}' watched status to {3}. ({4})",
                                        series[DBOnlineSeries.cPrettyName],
                                        episode[DBOnlineEpisode.cCombinedSeason],
                                        episode[DBOnlineEpisode.cEpisodeIndex],
                                        watched.ToString().ToLower(),
                                        DateTime.Now - start);
                }
                catch (Exception e) {
                    // ah crap.
                    MPTVSeriesLog.Write("[follw.it] Failed setting watched status for '{0} S{1}E{2}': {3}",
                                        series[DBOnlineSeries.cPrettyName],
                                        episode[DBOnlineEpisode.cCombinedSeason],
                                        episode[DBOnlineEpisode.cEpisodeIndex],
                                        e.Message);
                }
            }));

            thread.IsBackground = true;
            thread.Name = "follw.it watched updater";
            thread.Start();
        }
        public static void NowWatching(DBEpisode episode, bool watching)
        {
            if (!Enabled || episode == null || !episode.IsAvailableLocally) return;
            DBSeries series = DBSeries.Get(episode[DBEpisode.cSeriesID]);

            Thread thread = new Thread(new ThreadStart(delegate {
                try {
                    episode = WaitForSyncedEpisode(episode);
                    if (episode == null) return;

                    // start timer and send request
                    DateTime start = DateTime.Now;
                    if (watching) FollwitApi.WatchingTVEpisode("follwit", episode[DBOnlineEpisode.cFollwitId]);
                    else FollwitApi.StopWatchingTVEpisode("follwit", episode[DBOnlineEpisode.cFollwitId]);

                    // log our success
                    MPTVSeriesLog.Write("[follw.it] Sent {0} watching status for '{1} S{2}E{3}'. ({4})",
                                        watching ? "now" : "stopped",
                                        series[DBOnlineSeries.cPrettyName],
                                        episode[DBOnlineEpisode.cCombinedSeason],
                                        episode[DBOnlineEpisode.cEpisodeIndex],
                                        DateTime.Now - start);
                }
                catch (Exception e) {
                    // ah crap.
                    MPTVSeriesLog.Write("[follw.it] Failed sending now watching status for '{0} S{1}E{2}': {3}",
                                        series[DBOnlineSeries.cPrettyName],
                                        episode[DBOnlineEpisode.cCombinedSeason],
                                        episode[DBOnlineEpisode.cEpisodeIndex],
                                        e.Message);
                }
            }));

            thread.IsBackground = true;
            thread.Name = "follw.it now watching updater";
            thread.Start();
        }
        public static FitEpisode GetFitEpisode(DBEpisode mptvEpisode)
        {
            if (mptvEpisode == null)
                return null;

            FitEpisode fitEp = new FitEpisode();
            fitEp.SourceName = "tvdb";
            fitEp.SourceId = mptvEpisode.onlineEpisode[DBOnlineEpisode.cID];
            fitEp.InCollection = true;

            if (!String.IsNullOrEmpty(mptvEpisode[DBOnlineEpisode.cMyRating])) {
                int value;
                int.TryParse(mptvEpisode[DBOnlineEpisode.cMyRating], out value);
                fitEp.Rating = (int)Math.Round(value / 2.0, MidpointRounding.AwayFromZero);
            }

            fitEp.Watched = mptvEpisode[DBOnlineEpisode.cWatched] == 1;

            return fitEp;
        }
Exemple #44
0
 void m_VideoHandler_RateRequestOccured(DBEpisode episode)
 {
     ask2Rate = episode;
 }
Exemple #45
0
 /// <summary>
 /// Play an episode
 /// 
 /// Thanks to Trakt-for-MediaPortal:
 /// https://github.com/Technicolour/Trakt-for-Mediaportal/blob/master/TraktPlugin/TraktHandlers/TVSeries.cs
 /// </summary>
 /// <param name="episode">A valid tvseries episode</param>
 /// <param name="resume">Resume from last stop?</param>
 /// <param name="startPosition">Postion from where playback should be started (only valid if resum=false)</param>
 /// <returns></returns>
 private static void PlayEpisode(DBEpisode episode, bool resume, int startPosition = 0)
 {
     // Play on a new thread
     ThreadStart ts = delegate() { DoPlayEpisode(episode, resume, startPosition); };
     Thread playEpisodeAsync = new Thread(ts);
     playEpisodeAsync.Start();
 }
Exemple #46
0
        private void Season_OnItemSelected(GUIListItem item)
        {
            if (m_bQuickSelect) return;

            m_SelectedEpisode = null;
            if (item == null || item.TVTag == null)
                return;

            setNewListLevelOfCurrView(m_CurrViewStep);

            DBSeason season = item.TVTag as DBSeason;
            if (season == null) return;

            m_SelectedSeason = season;

            // set watched/unavailable flag
            if (dummyIsWatched != null) dummyIsWatched.Visible = (int.Parse(season[DBOnlineSeries.cEpisodesUnWatched]) == 0);
            if (dummyIsAvailable != null) dummyIsAvailable.Visible = season[DBSeason.cHasLocalFiles];

            setGUIProperty(guiProperty.Title, FieldGetter.resolveDynString(m_sFormatSeasonTitle, season));
            setGUIProperty(guiProperty.Subtitle, FieldGetter.resolveDynString(m_sFormatSeasonSubtitle, season));
            setGUIProperty(guiProperty.Description, FieldGetter.resolveDynString(m_sFormatSeasonMain, season));

            // Delayed Image Loading of Season Banners
            string filename = ImageAllocator.GetSeasonBannerAsFilename(season);
            if (filename.Length == 0)
            {
                // Load Series Poster instead
                if (DBOption.GetOptions(DBOption.cSubstituteMissingArtwork) && m_SelectedSeries != null)
                {
                    filename = ImageAllocator.GetSeriesPosterAsFilename(m_SelectedSeries);
                }
            }
            seasonbanner.Filename = filename;

            setGUIProperty(guiProperty.Logos, localLogos.getLogos(ref season, logosHeight, logosWidth));

            clearGUIProperty(guiProperty.EpisodeImage);

            if (!m_CurrLView.stepHasSeriesBeforeIt(m_CurrViewStep))
            {
                // it is the case
                m_SelectedSeries = Helper.getCorrespondingSeries(season[DBSeason.cSeriesID]);
                if (m_SelectedSeries != null)
                {
                    seriesbanner.Filename = ImageAllocator.GetSeriesBannerAsFilename(m_SelectedSeries);
                    seriesposter.Filename = ImageAllocator.GetSeriesPosterAsFilename(m_SelectedSeries);
                }
                else
                {
                    clearGUIProperty(guiProperty.SeriesBanner);
                    clearGUIProperty(guiProperty.SeriesPoster);
                }
            }

            pushFieldsToSkin(m_SelectedSeason, "Season");

            // Load Fanart
            m_FanartItem = m_SelectedSeason;
            if (DBOption.GetOptions(DBOption.cFanartRandom))
            {
                // We should update fanart as soon as new series is selected or
                // if timer was disabled (e.g. fullscreen playback)
                if (m_SelectedSeries[DBSeries.cID].ToString() != m_prevSeriesID || m_bFanartTimerDisabled)
                    m_FanartTimer.Change(0, DBOption.GetOptions(DBOption.cRandomFanartInterval));
            }
            else
                loadFanart(m_FanartItem);

            // Remember last series, so we dont re-initialize random fanart timer
            m_prevSeriesID = m_SelectedSeries[DBSeries.cID];
        }
        /// <summary>
        /// Shows the Rate Episode Dialog after playback has ended
        /// </summary>
        /// <param name="episode">The episode being rated</param>
        private void ShowRateDialog(DBEpisode episode)
        {
            if (DBOption.GetOptions(DBOption.cAskToRate)) return;   // tvseries dialog is enabled
            if (!TraktSettings.ShowRateDialogOnWatched) return;     // not enabled
            if (episode[DBOnlineEpisode.cMyRating] > 0) return;     // already rated

            TraktLogger.Debug("Showing rate dialog for '{0}'", episode.ToString());

            new Thread((o) =>
            {
                DBEpisode epToRate = o as DBEpisode;
                if (epToRate == null) return;

                DBSeries series = Helper.getCorrespondingSeries(epToRate[DBOnlineEpisode.cSeriesID]);

                TraktRateEpisode rateObject = new TraktRateEpisode
                {
                    SeriesID = epToRate[DBOnlineEpisode.cSeriesID],
                    Title = series == null ? string.Empty : series.ToString(),
                    Episode = epToRate[DBOnlineEpisode.cEpisodeIndex],
                    Season = epToRate[DBOnlineEpisode.cSeasonIndex],
                    UserName = TraktSettings.Username,
                    Password = TraktSettings.Password
                };

                // get the rating submitted to trakt
                int rating = int.Parse(GUIUtils.ShowRateDialog<TraktRateEpisode>(rateObject));

                if (rating > 0)
                {
                    TraktLogger.Debug("Rating {0} as {1}/10", epToRate.ToString(), rating.ToString());
                    epToRate[DBOnlineEpisode.cMyRating] = rating;
                    epToRate.Commit();

                    // update the facade holding the episode objects
                    var listItem = FindEpisodeInFacade(episode);
                    if (listItem != null)
                    {
                        listItem.TVTag = epToRate;
                    }
                }
            })
            {
                Name = "Rate",
                IsBackground = true
            }.Start(episode);
        }
Exemple #48
0
        public override void OnAction(Action action)
        {
            DBEpisode selectedEpisode = null;
            DBSeason selectedSeason = null;
            DBSeries selectedSeries = null;

            switch (action.wID)
            {
                case Action.ActionType.ACTION_PARENT_DIR:
                    m_CurrViewStep = 0;
                    m_stepSelections.Clear();
                    m_stepSelectionPretty.Clear();
                    m_stepSelections.Add(new string[] { null });
                    ImageAllocator.FlushAll();
                    GUIWindowManager.ShowPreviousWindow();
                    break;

                case Action.ActionType.ACTION_PREVIOUS_MENU:
                    // back one level
                    MPTVSeriesLog.Write("ACTION_PREVIOUS_MENU", MPTVSeriesLog.LogLevel.Debug);
                    if (m_CurrViewStep == 0 || m_stepSelectionPretty.Count == 0 || m_JumpToViewLevel)
                    {
                        goto case Action.ActionType.ACTION_PARENT_DIR;
                    }
                    else
                    {
                        m_stepSelections.RemoveAt(m_CurrViewStep);
                        m_stepSelectionPretty.RemoveAt(m_stepSelectionPretty.Count - 1);
                        m_CurrViewStep--;
                        setNewListLevelOfCurrView(m_CurrViewStep);
                        m_back_up_select_this = m_stepSelection;
                        m_stepSelection = m_stepSelections[m_CurrViewStep];
                        skipSeasonIfOne_DirectionDown = false; // otherwise the user cant get back out
                        LoadFacade();
                    }
                    break;

                case Action.ActionType.ACTION_SHOW_PLAYLIST:
                    ShowPlaylistWindow();
                    break;

                case Action.ActionType.ACTION_QUEUE_ITEM:
                    // Add selected item(s) to playlist
                    AddItemToPlayList();
                    break;

                case Action.ActionType.REMOTE_0:
                    if (DBOption.GetOptions(DBOption.cShowDeleteMenu))
                    {
                        // MediaPortal Delete Shortcut on Remote/Keyboard
                        if (this.m_Facade.SelectedListItem == null || this.m_Facade.SelectedListItem.TVTag == null)
                            return;

                        if (this.listLevel == Listlevel.Group)
                            return;

                        selectedSeries = null;
                        selectedSeason = null;
                        selectedEpisode = null;

                        switch (this.listLevel)
                        {
                            case Listlevel.Series:
                                selectedSeries = this.m_Facade.SelectedListItem.TVTag as DBSeries;
                                break;
                            case Listlevel.Season:
                                selectedSeason = this.m_Facade.SelectedListItem.TVTag as DBSeason;
                                selectedSeries = Helper.getCorrespondingSeries(selectedSeason[DBSeason.cSeriesID]);
                                break;
                            case Listlevel.Episode:
                                selectedEpisode = this.m_Facade.SelectedListItem.TVTag as DBEpisode;
                                selectedSeason = Helper.getCorrespondingSeason(selectedEpisode[DBEpisode.cSeriesID], selectedEpisode[DBEpisode.cSeasonIndex]);
                                selectedSeries = Helper.getCorrespondingSeries(selectedEpisode[DBEpisode.cSeriesID]);
                                break;
                        }
                        // Invoke Delete Menu
                        ShowDeleteMenu(selectedSeries, selectedSeason, selectedEpisode);
                        m_bOnActionProcessed = true;
                        return;
                    }
                    break;

                case Action.ActionType.ACTION_KEY_PRESSED:
                    // For some reason this action gets processed twice after deleting an item
                    // using the shortcut above (ZERO on Remote action). This is a workaround
                    // so MediaPortal doesnt throw an exception.
                    if (m_bOnActionProcessed && this.m_Facade.SelectedListItemIndex == -1)
                    {
                        m_bOnActionProcessed = false;
                        return;
                    }
                    base.OnAction(action);
                    break;

                case Action.ActionType.ACTION_PLAY:
                case Action.ActionType.ACTION_MUSIC_PLAY:
                    selectedSeries = null;
                    selectedSeason = null;
                    selectedEpisode = null;
                    string selectedGroup = null;

                    switch (this.listLevel)
                    {
                        case Listlevel.Group:
                            selectedGroup = this.m_Facade.SelectedListItem.TVTag as string;
                            break;
                        case Listlevel.Series:
                            selectedSeries = this.m_Facade.SelectedListItem.TVTag as DBSeries;
                            break;
                        case Listlevel.Season:
                            selectedSeason = this.m_Facade.SelectedListItem.TVTag as DBSeason;
                            break;
                        case Listlevel.Episode:
                            selectedEpisode = this.m_Facade.SelectedListItem.TVTag as DBEpisode;
                            break;
                    }

                    OnPlaySeriesOrSeasonAction onPlayAction = (OnPlaySeriesOrSeasonAction)(int)DBOption.GetOptions(DBOption.cOnPlaySeriesOrSeasonAction);

                    m_SelectedEpisode = null;
                    if (selectedEpisode != null)
                    {
                        if (selectedEpisode[DBEpisode.cIsAvailable])
                            m_SelectedEpisode = selectedEpisode;
                        else
                            m_SelectedEpisode = null;
                    }
                    else if (selectedGroup != null || selectedSeason != null || selectedSeries != null)
                    {
                        if (onPlayAction == OnPlaySeriesOrSeasonAction.AlwaysAsk)
                        {
                            List<GUIListItem> items = new List<GUIListItem>();
                            items.Add(new GUIListItem(Helper.UppercaseFirst(Translation.RandomEpisode)));
                            items.Add(new GUIListItem(Helper.UppercaseFirst(Translation.FirstUnwatchedEpisode)));
                            items.Add(new GUIListItem(Helper.UppercaseFirst(Translation.RandomUnwatchedEpisode)));
                            items.Add(new GUIListItem(Helper.UppercaseFirst(Translation.LatestEpisode)));

                            onPlayAction = (OnPlaySeriesOrSeasonAction)(ShowMenuDialog(Translation.PlaySomething, items) + 1);
                        }

                        if (onPlayAction != OnPlaySeriesOrSeasonAction.DoNothing)
                        {
                            List<DBEpisode> episodeList = null;
                            if (selectedSeason != null)
                            {
                                episodeList = m_CurrLView.getAllEpisodesForStep(m_CurrViewStep + 1, new string[] { selectedSeason[DBSeason.cSeriesID].ToString(), selectedSeason[DBSeason.cIndex].ToString() });
                            }
                            else if (selectedSeries != null)
                            {
                                episodeList = m_CurrLView.getAllEpisodesForStep(m_CurrViewStep + 1, new string[] { selectedSeries[DBSeries.cID].ToString() });
                            }
                            else if (selectedGroup != null)
                            {
                                episodeList = m_CurrLView.getAllEpisodesForStep(m_CurrViewStep + 1, new string[] { selectedGroup });
                            }

                            switch (onPlayAction)
                            {
                                case OnPlaySeriesOrSeasonAction.Random:
                                    episodeList = FilterEpisodeList(episodeList, true, false);
                                    m_SelectedEpisode = GetRandomEpisode(episodeList);
                                    break;
                                case OnPlaySeriesOrSeasonAction.FirstUnwatched:
                                    episodeList = FilterEpisodeList(episodeList, true, true);
                                    m_SelectedEpisode = GetFirstOrLastEpisode(episodeList, true);
                                    break;
                                case OnPlaySeriesOrSeasonAction.RandomUnwatched:
                                    episodeList = FilterEpisodeList(episodeList, true, true);
                                    m_SelectedEpisode = GetRandomEpisode(episodeList);
                                    break;
                                case OnPlaySeriesOrSeasonAction.Latest:
                                    episodeList = FilterEpisodeList(episodeList, true, false);
                                    m_SelectedEpisode = GetFirstOrLastEpisode(episodeList, false);
                                    break;
                            }
                        }
                    }

                    if (m_SelectedEpisode == null)
                    {
                        switch (onPlayAction)
                        {
                            case OnPlaySeriesOrSeasonAction.Random:
                                ShowNotifyDialog(Translation.PlayError, string.Format(Translation.UnableToFindAny, Translation.RandomEpisode));
                                break;
                            case OnPlaySeriesOrSeasonAction.FirstUnwatched:
                                ShowNotifyDialog(Translation.PlayError, string.Format(Translation.UnableToFindAny, Translation.FirstUnwatchedEpisode));
                                break;
                            case OnPlaySeriesOrSeasonAction.RandomUnwatched:
                                ShowNotifyDialog(Translation.PlayError, string.Format(Translation.UnableToFindAny, Translation.RandomUnwatchedEpisode));
                                break;
                            case OnPlaySeriesOrSeasonAction.Latest:
                                ShowNotifyDialog(Translation.PlayError, string.Format(Translation.UnableToFindAny, Translation.LatestEpisode));
                                break;
                        }
                        goto default;
                    }
                    MPTVSeriesLog.Write("Selected Episode OnAction Play: ", m_SelectedEpisode[DBEpisode.cCompositeID].ToString(), MPTVSeriesLog.LogLevel.Debug);
                    CommonPlayEpisodeAction();

                    break;

                case Action.ActionType.ACTION_PREV_PICTURE:
                case Action.ActionType.ACTION_NEXT_PICTURE:
                    // Cycle Artwork
                    if (this.m_Facade.SelectedListItem == null || this.m_Facade.SelectedListItem.TVTag == null)
                        return;

                    // can only cycle artwork on series and seasons
                    if (this.listLevel == Listlevel.Group || this.listLevel == Listlevel.Episode)
                        return;

                    selectedSeries = null;
                    selectedSeason = null;
                    selectedEpisode = null;

                    bool nextImage = action.wID == Action.ActionType.ACTION_NEXT_PICTURE ? true : false;

                    switch (this.listLevel)
                    {
                        case Listlevel.Series:
                            selectedSeries = this.m_Facade.SelectedListItem.TVTag as DBSeries;
                            string layout = DBOption.GetOptions(DBOption.cView_Series_ListFormat);
                            switch (this.m_Facade.CurrentLayout)
                            {
                                case GUIFacadeControl.Layout.LargeIcons:
                                    CycleSeriesBanner(selectedSeries, nextImage);
                                    break;
                                case GUIFacadeControl.Layout.Filmstrip:
                                case GUIFacadeControl.Layout.CoverFlow:
                                    CycleSeriesPoster(selectedSeries, nextImage);
                                    break;
                                case GUIFacadeControl.Layout.List:
                                    if (layout == "ListPosters")
                                    {
                                        CycleSeriesPoster(selectedSeries, nextImage);
                                    }
                                    else
                                    {
                                        CycleSeriesBanner(selectedSeries, nextImage);
                                    }
                                    break;
                            }
                            break;
                        case Listlevel.Season:
                            selectedSeason = this.m_Facade.SelectedListItem.TVTag as DBSeason;
                            CycleSeasonPoster(selectedSeason, nextImage);
                            break;
                    }
                    break;

                default:
                    base.OnAction(action);
                    break;
            }
        }
        /// <summary>
        /// Finds an episode in the current TVSeries Episode List
        /// </summary>
        /// <param name="episode"></param>
        /// <returns></returns>
        public static GUIListItem FindEpisodeInFacade(DBEpisode episode)
        {
            if (Facade == null) return null;

            for (int i = 0; i < Facade.Count; i++)
            {
                var control = Facade[i];
                GUIListItem listItem = control as GUIListItem;
                if (listItem == null) return null;

                // not in the episode level anymore
                DBEpisode ep = listItem.TVTag as DBEpisode;
                if (ep == null) return null;

                if (ep.Equals(episode))
                    return listItem;
            }

            return null;
        }
Exemple #50
0
        private void UpdateEpisodes(DBSeries series, DBSeason season, DBEpisode episode)
        {
            List<DBValue> epIDsUpdates = new List<DBValue>();
            List<DBValue> seriesIDsUpdates = new List<DBValue>();

            SQLCondition conditions = null;
            string searchPattern = string.Empty;

            // Get selected Series and/or list of Episode(s) to update
            switch (this.listLevel)
            {
                case Listlevel.Series:
                    seriesIDsUpdates.Add(series[DBSeries.cID]);
                    conditions = new SQLCondition(new DBOnlineEpisode(), DBOnlineEpisode.cSeriesID, series[DBSeries.cID], SQLConditionType.Equal);
                    epIDsUpdates.AddRange(DBEpisode.GetSingleField(DBOnlineEpisode.cID, conditions, new DBOnlineEpisode()));
                    searchPattern = "*.jpg";
                    break;

                case Listlevel.Season:
                    conditions = new SQLCondition(new DBOnlineEpisode(), DBOnlineEpisode.cSeriesID, season[DBSeason.cSeriesID], SQLConditionType.Equal);
                    conditions.Add(new DBOnlineEpisode(), DBOnlineEpisode.cSeasonIndex, season[DBSeason.cIndex], SQLConditionType.Equal);
                    epIDsUpdates.AddRange(DBEpisode.GetSingleField(DBOnlineEpisode.cID, conditions, new DBOnlineEpisode()));
                    searchPattern = season[DBSeason.cIndex] + "x*.jpg";
                    break;

                case Listlevel.Episode:
                    epIDsUpdates.Add(episode[DBOnlineEpisode.cID]);
                    conditions = new SQLCondition(new DBOnlineEpisode(), DBOnlineEpisode.cID, episode[DBOnlineEpisode.cID], SQLConditionType.Equal);
                    searchPattern = episode[DBOnlineEpisode.cSeasonIndex] + "x" + episode[DBOnlineEpisode.cEpisodeIndex] + ".jpg";
                    break;
            }

            // Delete Physical Thumbnails
            // Dont prompt if just doing a single episode update
            bool deleteThumbs = true;
            if (this.listLevel != Listlevel.Episode)
            {
                GUIDialogYesNo dlgYesNo = (GUIDialogYesNo)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_YES_NO);
                if (dlgYesNo != null)
                {
                    dlgYesNo.Reset();
                    dlgYesNo.SetHeading(Translation.DeleteThumbnailsHeading);
                    dlgYesNo.SetLine(1, Translation.DeleteThumbnailsLine1);
                    dlgYesNo.SetLine(2, Translation.DeleteThumbnailsLine2);
                    dlgYesNo.SetDefaultToYes(false);
                    dlgYesNo.DoModal(GUIWindowManager.ActiveWindow);
                    if (!dlgYesNo.IsConfirmed) deleteThumbs = false;
                }
            }

            if (deleteThumbs)
            {
                string thumbnailPath = Helper.PathCombine(Settings.GetPath(Settings.Path.banners), Helper.cleanLocalPath(series.ToString()) + @"\Episodes");

                // Search and delete matching files that actually exist
                string[] fileList = Directory.GetFiles(thumbnailPath, searchPattern);

                foreach (string file in fileList)
                {
                    MPTVSeriesLog.Write("Deleting Episode Thumbnail: " + file);
                    FileInfo fileInfo = new FileInfo(file);
                    try
                    {
                        fileInfo.Delete();
                    }
                    catch (Exception ex)
                    {
                        MPTVSeriesLog.Write("Failed to Delete Episode Thumbnail: " + file + ": " + ex.Message);
                    }
                }

                // Remove local thumbnail reference from db so that it thumbnails will be downloaded
                DBEpisode.GlobalSet(new DBOnlineEpisode(), DBOnlineEpisode.cEpisodeThumbnailFilename, (DBValue)"", conditions);
            }

            // Execute Online Parsing Actions
            if (epIDsUpdates.Count > 0)
            {

                lock (m_parserUpdaterQueue)
                {
                    List<ParsingAction> parsingActions = new List<ParsingAction>();
                    // Conditional parsing actions
                    if (this.listLevel == Listlevel.Series) parsingActions.Add(ParsingAction.UpdateSeries);
                    parsingActions.Add(ParsingAction.UpdateEpisodes);
                    if (deleteThumbs) parsingActions.Add(ParsingAction.UpdateEpisodeThumbNails);
                    parsingActions.Add(ParsingAction.UpdateEpisodeCounts);

                    m_parserUpdaterQueue.Add(new CParsingParameters(parsingActions, seriesIDsUpdates, epIDsUpdates));
                }

            }
        }
        private TraktRateEpisode CreateEpisodeRateData(DBEpisode episode)
        {
            DBSeries series = Helper.getCorrespondingSeries(episode[DBOnlineEpisode.cSeriesID]);

            if (series == null || series[DBOnlineSeries.cTraktIgnore]) return null;

            string rating = episode[DBOnlineEpisode.cMyRating];

            TraktRateEpisode episodeData = new TraktRateEpisode()
            {
                Episode = episode[DBOnlineEpisode.cEpisodeIndex],
                Rating = rating,
                Season = episode[DBOnlineEpisode.cSeasonIndex],
                SeriesID = episode[DBOnlineEpisode.cSeriesID],
                Year = series.Year,
                Title = series[DBOnlineSeries.cOriginalName],
                UserName = TraktSettings.Username,
                Password = TraktSettings.Password
            };

            TraktLogger.Info("Rating '{0}' as '{1}/10'", episode.ToString(), rating.ToString());
            return episodeData;
        }
Exemple #52
0
        private void ShowDeleteMenu(DBSeries series, DBSeason season, DBEpisode episode)
        {
            String sDialogHeading = String.Empty;

            switch (this.listLevel)
            {
                case Listlevel.Series:
                    sDialogHeading = Translation.Delete_that_series;
                    break;

                case Listlevel.Season:
                    sDialogHeading = Translation.Delete_that_season;
                    break;

                case Listlevel.Episode:
                    sDialogHeading = Translation.Delete_that_episode;
                    break;
            }

            IDialogbox dlg = (IDialogbox)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
            if (dlg == null)
                return;

            dlg.Reset();
            dlg.SetHeading(sDialogHeading);

            // Add Menu items
            GUIListItem pItem = null;

            pItem = new GUIListItem(Translation.DeleteFromDisk);
            dlg.Add(pItem);
            pItem.ItemId = (int)DeleteMenuItems.disk;

            pItem = new GUIListItem(Translation.DeleteFromDatabase);
            dlg.Add(pItem);
            pItem.ItemId = (int)DeleteMenuItems.database;

            pItem = new GUIListItem(Translation.DeleteFromFileDatabase);
            dlg.Add(pItem);
            pItem.ItemId = (int)DeleteMenuItems.diskdatabase;

            if (this.listLevel == Listlevel.Episode && episode != null && episode.checkHasLocalSubtitles())
            {
                pItem = new GUIListItem(Translation.DeleteSubtitles);
                dlg.Add(pItem);
                pItem.ItemId = (int)DeleteMenuItems.subtitles;
            }

            pItem = new GUIListItem(Translation.Cancel);
            dlg.Add(pItem);
            pItem.ItemId = (int)DeleteMenuItems.cancel;

            // Show Menu
            dlg.DoModal(GUIWindowManager.ActiveWindow);
            if (dlg.SelectedId < 0 || dlg.SelectedId == (int)DeleteMenuItems.cancel)
                return;

            List<string> resultMsg = null;
            string msgDlgCaption = string.Empty;

            #region Delete Subtitles
            if (dlg.SelectedId == (int)DeleteMenuItems.subtitles)
            {
                msgDlgCaption = Translation.UnableToDeleteSubtitles;
                switch (this.listLevel)
                {
                    case Listlevel.Episode:
                        if (episode == null) return;
                        resultMsg = episode.deleteLocalSubTitles();
                        break;
                }
            }
            #endregion

            #region Delete From Disk, Database or Both
            if (dlg.SelectedId != (int)DeleteMenuItems.subtitles)
            {
                msgDlgCaption = Translation.UnableToDelete;
                switch (this.listLevel)
                {
                    #region Delete Series
                    case Listlevel.Series:
                        resultMsg = series.deleteSeries((DeleteMenuItems)dlg.SelectedId);
                        break;
                    #endregion

                    #region Delete Season
                    case Listlevel.Season:
                        resultMsg = season.deleteSeason((DeleteMenuItems)dlg.SelectedId);
                        break;
                    #endregion

                    #region Delete Episode
                    case Listlevel.Episode:
                        resultMsg = episode.deleteEpisode((DeleteMenuItems)dlg.SelectedId);
                        break;
                    #endregion
                }
                // only update the counts if the database entry for the series still exists
                if (!DBSeries.IsSeriesRemoved) DBSeries.UpdateEpisodeCounts(series);
            }
            #endregion

            // Re-load the facade to accurately reflect actions taked above
            LoadFacade();

            // Show errors, if any
            if (resultMsg != null && resultMsg.Count > 0)
            {
                GUIDialogText errorDialog = (GUIDialogText)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_TEXT);
                errorDialog.SetHeading(msgDlgCaption);
                errorDialog.SetText(string.Join("\n", resultMsg.ToArray()));
                errorDialog.DoModal(GUIWindowManager.ActiveWindow);
            }
        }
        private void OnEpisodeStarted(DBEpisode episode)
        {
            if (TraktSettings.AccountStatus != ConnectionState.Connected) return;

            TraktLogger.Info("Starting TVSeries episode playback '{0}'", episode.ToString());
            EpisodeWatching = true;
            CurrentEpisode = episode;
        }
Exemple #54
0
        private void Series_OnItemSelected(GUIListItem item)
        {
            if (m_bQuickSelect) return;

            m_SelectedSeason = null;
            m_SelectedEpisode = null;
            if (item == null || item.TVTag == null || !(item.TVTag is DBSeries))
                return;

            setNewListLevelOfCurrView(m_CurrViewStep);

            DBSeries series = item.TVTag as DBSeries;
            if (series == null) return;

            m_SelectedSeries = series;

            // set watched/unavailable flag
            if (dummyIsWatched != null) dummyIsWatched.Visible = (int.Parse(series[DBOnlineSeries.cEpisodesUnWatched]) == 0);
            if (dummyIsAvailable != null) dummyIsAvailable.Visible = series[DBSeason.cHasLocalFiles];

            clearGUIProperty(guiProperty.EpisodeImage);
            seasonbanner.Filename = "";

            setGUIProperty(guiProperty.Title, FieldGetter.resolveDynString(m_sFormatSeriesTitle, series));
            setGUIProperty(guiProperty.Subtitle, FieldGetter.resolveDynString(m_sFormatSeriesSubtitle, series));
            setGUIProperty(guiProperty.Description, FieldGetter.resolveDynString(m_sFormatSeriesMain, series));

            // Delayed Image Loading of Series Banners/Posters
            seriesbanner.Filename = ImageAllocator.GetSeriesBannerAsFilename(series);
            seriesposter.Filename = ImageAllocator.GetSeriesPosterAsFilename(series);

            setGUIProperty(guiProperty.Logos, localLogos.getLogos(ref series, logosHeight, logosWidth));

            pushFieldsToSkin(m_SelectedSeries, "Series");

            // Load Fanart
            // Re-initialize timer for random fanart
            m_FanartItem = m_SelectedSeries;
            if (DBOption.GetOptions(DBOption.cFanartRandom))
            {
                // We should update fanart as soon as new series is selected or
                // if timer was disabled (e.g. fullscreen playback)
                if (m_SelectedSeries[DBSeries.cID].ToString() != m_prevSeriesID || m_bFanartTimerDisabled)
                    m_FanartTimer.Change(0, DBOption.GetOptions(DBOption.cRandomFanartInterval));
            }
            else
                loadFanart(m_FanartItem);

            // Remember last series, so we dont re-initialize random fanart timer
            m_prevSeriesID = m_SelectedSeries[DBSeries.cID];
        }
        private void OnEpisodeWatched(DBEpisode episode)
        {
            if (TraktSettings.AccountStatus != ConnectionState.Connected) return;

            DBEpisode currentEpisode = null;
            EpisodeWatching = false;

            Thread scrobbleEpisode = new Thread(delegate(object o)
            {
                DBEpisode ep = o as DBEpisode;
                if (o == null) return;

                // submit watched state to trakt API
                // could be a double episode so mark last one as watched
                // 1st episode is set to watched during playback timer
                if (ep[DBEpisode.cEpisodeIndex2] > 0 && MarkedFirstAsWatched)
                {
                    // only set 2nd episode as watched here
                    SQLCondition condition = new SQLCondition();
                    condition.Add(new DBEpisode(), DBEpisode.cFilename, ep[DBEpisode.cFilename], SQLConditionType.Equal);
                    List<DBEpisode> episodes = DBEpisode.Get(condition, false);
                    currentEpisode = episodes[1];
                }
                else
                {
                    // single episode
                    currentEpisode = ep;
                }

                // show trakt rating dialog
                ShowRateDialog(currentEpisode);

                TraktLogger.Info("TVSeries episode considered watched '{0}'", currentEpisode.ToString());

                // get scrobble data to send to api
                TraktEpisodeScrobble scrobbleData = CreateScrobbleData(currentEpisode);
                if (scrobbleData == null) return;

                // set duration/progress in scrobble data
                double duration = currentEpisode[DBEpisode.cLocalPlaytime] / 60000;
                scrobbleData.Duration = Convert.ToInt32(duration).ToString();
                scrobbleData.Progress = "100";

                TraktResponse response = TraktAPI.TraktAPI.ScrobbleEpisodeState(scrobbleData, TraktScrobbleStates.scrobble);
                TraktAPI.TraktAPI.LogTraktResponse(response);
            })
            {
                IsBackground = true,
                Name = "Scrobble Episode"
            };

            scrobbleEpisode.Start(episode);
        }
Exemple #56
0
 /// <summary>
 /// Create PlayListItem from TvSeries DBEpisode
 /// </summary>
 /// <param name="episode">DBEpisode</param>
 /// <returns>PlayListItem item</returns>
 private static MediaPortal.Playlists.PlayListItem CreatePlaylistItemFromEpisode(DBEpisode episode)
 {
     if (episode != null)
     {
         MediaPortal.Playlists.PlayListItem item = new MediaPortal.Playlists.PlayListItem();
         item.FileName = episode[DBEpisode.cFilename];
         item.Duration = episode[DBEpisode.cLocalPlaytime] / 1000;
         item.Description = episode[DBOnlineEpisode.cEpisodeName];
         return item;
     }
     return null;
 }
Exemple #57
0
        private void playRandomEp()
        {
            List<DBEpisode> episodeList = m_CurrLView.getAllEpisodesForStep(m_CurrViewStep, m_stepSelection);

            episodeList = FilterEpisodeList(episodeList, true, false);

            m_SelectedEpisode = GetRandomEpisode(episodeList);

            if (m_SelectedEpisode == null)
            {
                ShowNotifyDialog(Translation.PlayError, string.Format(Translation.UnableToFindAny, Translation.RandomEpisode));
            }
            else
            {
                MPTVSeriesLog.Write("Selected Random Episode: ", m_SelectedEpisode[DBEpisode.cCompositeID].ToString(), MPTVSeriesLog.LogLevel.Debug);

                CommonPlayEpisodeAction();
            }
        }
Exemple #58
0
        private void Group_OnItemSelected(GUIListItem item)
        {
            m_SelectedSeries = null;
            m_SelectedSeason = null;
            m_SelectedEpisode = null;
            if (item == null) return;

            setNewListLevelOfCurrView(m_CurrViewStep);

            // let's try to give the user a bit more information
            string groupedBy = m_CurrLView.groupedInfo(m_CurrViewStep);
            if (groupedBy.Contains("<Ser"))
            {
                int count = 0;
                string seriesNames = string.Empty;
                SQLCondition cond = new SQLCondition();
                cond.AddOrderItem(DBOnlineSeries.Q(DBOnlineSeries.cPrettyName), SQLCondition.orderType.Ascending);
                cond.SetLimit(20);

                bool requiresSplit = false; // use sql 'like' for split fields

                // selected group label
                string selectedItem = this.m_Facade.SelectedListItem.Label.ToString();

                // unknown really is "" so get all with null values here
                if (selectedItem == Translation.Unknown)
                {
                    selectedItem = string.Empty;
                }
                else
                    if (m_CurrLView.m_steps[m_CurrViewStep].groupedBy.attempSplit) requiresSplit = true;

                string field = groupedBy.Substring(groupedBy.IndexOf('.') + 1).Replace(">", "");
                string tableName = "online_series";
                string tableField = tableName + "." + field;
                string userEditField = tableField + DBTable.cUserEditPostFix;
                string value = requiresSplit ? "like " + "'%" + selectedItem + "%'" : "= " + "'" + selectedItem + "'";
                string sql = string.Empty;

                // check if the useredit column exists
                if (DBTable.ColumnExists(tableName, field + DBTable.cUserEditPostFix))
                {
                    sql = "(case when (" + userEditField + " is null or " + userEditField + " = " + "'" + "'" + ") " +
                             "then " + tableField + " else " + userEditField + " " +
                             "end) " + value;
                }
                else
                {
                    sql = tableField + " " + value;
                }

                cond.AddCustom(sql);

                if (DBOption.GetOptions(DBOption.cView_Episode_OnlyShowLocalFiles))
                {
                    // not generic
                    SQLCondition fullSubCond = new SQLCondition();
                    fullSubCond.AddCustom(DBOnlineEpisode.Q(DBOnlineEpisode.cSeriesID), DBOnlineSeries.Q(DBOnlineSeries.cID), SQLConditionType.Equal);
                    cond.AddCustom(" exists( " + DBEpisode.stdGetSQL(fullSubCond, false) + " )");
                }
                if (!DBOption.GetOptions(DBOption.cShowHiddenItems))
                    cond.AddCustom("exists ( select id from local_series where id = online_series.id and hidden = 0)");

                foreach (string series in DBOnlineSeries.GetSingleField(DBOnlineSeries.cPrettyName, cond, new DBOnlineSeries()))
                {
                    seriesNames += series + Environment.NewLine;
                    count++;
                }

                setGUIProperty(guiProperty.SeriesCount, count.ToString());
                setGUIProperty(guiProperty.Subtitle, count.ToString() + " " + (count == 1 ? Translation.Series : Translation.Series_Plural));
                setGUIProperty(guiProperty.Description, seriesNames);
            }
            else
            {
                clearGUIProperty(guiProperty.Description);
                clearGUIProperty(guiProperty.Subtitle);
            }

            setGUIProperty(guiProperty.Title, item.Label.ToString());

            setGUIProperty(guiProperty.Logos, localLogos.getLogos(m_CurrLView.groupedInfo(m_CurrViewStep), this.m_Facade.SelectedListItem.Label, logosHeight, logosWidth));

            clearGUIProperty(guiProperty.EpisodeImage);

            DisableFanart();
        }
Exemple #59
0
 public PlayListItem(DBEpisode episode)
 {
     Episode = episode;
 }
Exemple #60
0
 static void getTableFieldname(string what, out DBTable table, out string fieldname)
 {
     string sTable = string.Empty;
     fieldname = string.Empty;
     table = null;
     what = what.Replace("<", "").Replace(">", "").Trim();
     sTable = what.Split('.')[0];
     switch (sTable)
     {
         case "Series":
             if(new DBOnlineSeries().FieldNames.Contains(what.Split('.')[1]))
             {
                 table = new DBOnlineSeries();
                 fieldname = what.Split('.')[1];
             }
             else
             {
                 table = new DBSeries();
                 fieldname = what.Split('.')[1];
             }
             break;
         case "Season":
             table = new DBSeason();
             fieldname = what.Split('.')[1];
             break;
         case "Episode":
             if (new DBOnlineEpisode().FieldNames.Contains(what.Split('.')[1]))
             {
                 table = new DBOnlineEpisode();
                 fieldname = what.Split('.')[1];
             }
             else
             {
                 table = new DBEpisode();
                 fieldname = what.Split('.')[1];
             }
             break;
     }
 }