Ejemplo n.º 1
0
 public static DBSeries getCorrespondingSeries(int id)
 {
     try
     {
         DBSeries cached = cache.getSeries(id);
         if (cached != null)
         {
             return(cached);
         }
         SQLCondition cond = new SQLCondition();
         cond.Add(new DBSeries(), DBSeries.cID, id, SQLConditionType.Equal);
         List <DBSeries> tmpSeries = DBSeries.Get(cond);
         foreach (DBSeries series in tmpSeries) // should only be one!
         {
             if (series[DBSeries.cID] == id)
             {
                 cache.addChangeSeries(series);
                 return(series);
             }
         }
         return(null);
     }
     catch (Exception)
     {
         return(null);
     }
 }
Ejemplo n.º 2
0
        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);
        }
Ejemplo n.º 3
0
        public static DBSeries getSeries(int SeriesID)
        {
            DBSeries s = _cache.getItemOfSubItem(SeriesID);

            //MPTVSeriesLog.Write("Cache: Requested Series: " + SeriesID.ToString() + (s == null ? " - Failed" : " - Sucess"), MPTVSeriesLog.LogLevel.Debug);
            return(s);
        }
Ejemplo n.º 4
0
        private static TraktSync GetTraktSyncObject(DBSeries series, List <DBEpisode> episodes)
        {
            // set series properties for episodes
            TraktSync traktSync = new TraktSync
            {
                Password = TraktAPI.Password,
                UserName = TraktAPI.Username,
                SeriesID = series[DBSeries.cID],
                IMDBID   = series[DBOnlineSeries.cIMDBID],
                Year     = series.Year,
                Title    = series[DBOnlineSeries.cOriginalName]
            };

            // get list of episodes for series
            List <TraktSync.Episode> epList = new List <TraktSync.Episode>();

            foreach (DBEpisode ep in episodes.Where(e => e[DBEpisode.cSeriesID] == series[DBSeries.cID]))
            {
                TraktSync.Episode episode = new TraktSync.Episode();
                episode.SeasonIndex  = ep[DBOnlineEpisode.cSeasonIndex];
                episode.EpisodeIndex = ep[DBOnlineEpisode.cEpisodeIndex];
                epList.Add(episode);
            }

            traktSync.EpisodeList = epList;
            return(traktSync);
        }
Ejemplo n.º 5
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();
        }
Ejemplo n.º 6
0
        public static void RateSeries(DBSeries series)
        {
            if (string.IsNullOrEmpty(TraktAPI.Username) || string.IsNullOrEmpty(TraktAPI.Password))
            {
                return;
            }

            new Thread(delegate()
            {
                TraktRateValue loveorhate = series[DBOnlineSeries.cMyRating] >= 7.0 ? TraktRateValue.love : TraktRateValue.hate;

                TraktRateSeries seriesData = new TraktRateSeries()
                {
                    Rating   = loveorhate.ToString(),
                    SeriesID = series[DBOnlineSeries.cID],
                    Year     = series.Year,
                    Title    = series[DBOnlineSeries.cOriginalName],
                    UserName = TraktAPI.Username,
                    Password = TraktAPI.Password,
                };

                TraktRateResponse response = TraktAPI.RateSeries(seriesData);

                // check for any error and notify
                CheckTraktErrorAndNotify(response, false);
            })
            {
                IsBackground = true,
                Name         = "Trakt Rate Series"
            }.Start();
        }
Ejemplo n.º 7
0
        public static string stdGetSQL(SQLCondition conditions, bool selectFull, bool includeStdCond)
        {
            string field;

            if (selectFull)
            {
                SQLWhat what = new SQLWhat(new DBOnlineSeries());
                what.AddWhat(new DBSeries());
                field = what;
            }
            else
            {
                field = DBOnlineSeries.Q(DBOnlineSeries.cID) + " from " + DBOnlineSeries.cTableName;
            }

            if (includeStdCond)
            {
                conditions.AddCustom(stdConditions.ConditionsSQLString);
            }

            string conds   = conditions;
            string orderBy = string.Empty;

            if (selectFull)
            {
                bool bUseSortName = DBOption.GetOptions(DBOption.cUseSortName);
                orderBy = conditions.customOrderStringIsSet
                      ? conditions.orderString
                      : " order by " + (bUseSortName?"upper(" + DBOnlineSeries.Q(DBOnlineSeries.cSortName) + "),":"") + "upper(" + DBOnlineSeries.Q(DBOnlineSeries.cPrettyName) + ")";
            }
            return("select " + field + " left join " + cTableName + " on " + DBSeries.Q(cID) + "==" + DBOnlineSeries.Q(cID)
                   + conds
                   + orderBy
                   + conditions.limitString);
        }
Ejemplo n.º 8
0
        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();
        }
Ejemplo n.º 9
0
 static void DBSeries_dbSeriesUpdateOccured(DBSeries updated)
 {
     //MPTVSeriesLog.Write("Cache: Series Commit occured: ",  updated.ToString(), MPTVSeriesLog.LogLevel.Debug);
     if (_cache.getItemOfSubItem(updated[DBSeries.cID]) != null)
     {
         addChangeSeries(updated);
     }
 }
Ejemplo n.º 10
0
 static string replaceSeriesTags(DBSeries s, string what)
 {
     if (s == null || what.Length < seriesIdentifier.Length)
     {
         return(what);
     }
     return(getValuesOfType(s, what, seriesParse, seriesIdentifier));
 }
Ejemplo n.º 11
0
        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;
            }
        }
Ejemplo n.º 12
0
        public List <string> deleteSeries(TVSeriesPlugin.DeleteMenuItems type)
        {
            List <string> resultMsg = new List <string>();

            // Always delete from Local episode table if deleting from disk or database
            SQLCondition condition = new SQLCondition();

            condition.Add(new DBSeason(), DBSeason.cSeriesID, this[DBSeries.cID], SQLConditionType.Equal);

            /* TODO dunno if to include or exclude hidden items.
             * if they are excluded then the if (resultMsg.Count is wrong and should do another select to get proper count
             * 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(condition, false);

            if (seasons != null)
            {
                foreach (DBSeason season in seasons)
                {
                    resultMsg.AddRange(season.deleteSeason(type));
                }
            }

            #region Facade Remote Color
            // if we were successful at deleting all episodes of series from disk, set HasLocalFiles to false
            // note: we only do this if the database entries still exist
            if (resultMsg.Count == 0 && type == TVSeriesPlugin.DeleteMenuItems.disk)
            {
                this[DBOnlineSeries.cHasLocalFiles] = false;
                this.Commit();
            }
            #endregion

            #region Cleanup
            // if there are no error messages and if we need to delete from db
            // Delete from online tables and season/series tables
            IsSeriesRemoved = false;
            if (resultMsg.Count == 0 && type != TVSeriesPlugin.DeleteMenuItems.disk)
            {
                condition = new SQLCondition();
                condition.Add(new DBSeries(), DBSeries.cID, this[DBSeries.cID], SQLConditionType.Equal);
                DBSeries.Clear(condition);

                condition = new SQLCondition();
                condition.Add(new DBOnlineSeries(), DBOnlineSeries.cID, this[DBSeries.cID], SQLConditionType.Equal);
                DBOnlineSeries.Clear(condition);

                IsSeriesRemoved = true;
            }
            #endregion

            return(resultMsg);
        }
Ejemplo n.º 13
0
 public static void addChangeSeries(DBSeries series)
 {
     if (series == null)
     {
         return;
     }
     //MPTVSeriesLog.Write("Cache: Adding/Changing Series: " + series[DBSeries.cID], MPTVSeriesLog.LogLevel.Debug);
     _cache.Add(series[DBSeries.cID], series);
 }
Ejemplo n.º 14
0
        public static void UpdateEpisodeCounts(DBSeries series, Dictionary <string, List <EpisodeCounter> > episodes)
        {
            if (series == null)
            {
                return;
            }

            string seriesId           = series[DBSeries.cID];
            int    seriesEpsTotal     = 0;
            int    seriesEpsUnWatched = 0;
            bool   airedOrder         = series.IsAiredOrder;

            // dont worry about filtering season list, we already have a filtered episode list
            // query without std conditions for faster response.
            var conditions = new SQLCondition(new DBSeason(), DBSeason.cSeriesID, seriesId, SQLConditionType.Equal);
            var seasons    = DBSeason.Get(conditions, false);

            // update season counts
            List <EpisodeCounter> eps = new List <EpisodeCounter>();

            if (episodes.TryGetValue(seriesId, out eps))
            {
                foreach (var season in seasons)
                {
                    var seasonEps = eps.Where(e => airedOrder ? e.SeasonAirIdx == season[DBSeason.cIndex] : e.SeasonDvdIdx == season[DBSeason.cIndex]).ToList();

                    // dont commit seasons if are not viewing them
                    // episodes for count is already filtered so can return 0 results
                    if (seasonEps.Count == 0)
                    {
                        continue;
                    }

                    int count          = seasonEps.Count();
                    int unWatchedCount = seasonEps.Where(e => e.EpisodeWatched != "1").Count();

                    season[DBSeason.cEpisodeCount]      = count;
                    season[DBSeason.cEpisodesUnWatched] = unWatchedCount;
                    season[DBSeason.cUnwatchedItems]    = unWatchedCount > 0;
                    season.Commit();

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

                // update series counts
                series[DBOnlineSeries.cEpisodeCount]      = seriesEpsTotal;
                series[DBOnlineSeries.cEpisodesUnWatched] = seriesEpsUnWatched;
                series[DBOnlineSeries.cUnwatchedItems]    = seriesEpsUnWatched > 0;
                series.Commit();
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Builds a string of pipe seperated tagged views for a series
        /// </summary>
        /// <param name="series">Series object</param>
        /// <param name="addView">Set to true if adding a view to series</param>
        /// <param name="viewName">Name of view</param>
        /// <returns></returns>
        public static string GetSeriesViewTags(DBSeries series, bool addView, string viewName)
        {
            // Get Current tags in series
            string newTags  = string.Empty;
            string currTags = series[DBOnlineSeries.cViewTags].ToString().Trim();

            string[] splitTags = currTags.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

            if (addView)
            {
                // If no view tags exists, add it
                if (currTags.Length == 0)
                {
                    newTags = "|" + viewName + "|";
                }
                else
                {
                    // Check if view tag already exists, ignoring case. If not add it
                    bool tagExists = false;
                    foreach (string tag in splitTags)
                    {
                        if (tag.Equals(viewName, StringComparison.CurrentCultureIgnoreCase))
                        {
                            tagExists = true;
                            newTags   = currTags;
                            break;
                        }
                    }
                    // Add view tag to series if it doesnt exist
                    if (!tagExists)
                    {
                        newTags = currTags + viewName + "|";
                    }
                }
            }
            else
            {
                // Remove tag if its exists
                foreach (string tag in splitTags)
                {
                    if (!tag.Equals(viewName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        newTags += "|" + tag;
                    }
                }
                if (newTags.Length > 0)
                {
                    newTags += "|";
                }
            }
            return(newTags);
        }
Ejemplo n.º 16
0
        public List <DBSeries> getSeriesItems(int stepIndex, string[] currentStepSelection)
        {
            MPTVSeriesLog.Write("View: Get Series Items", 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 Series Items: Executing SQL", MPTVSeriesLog.LogLevel.Debug);
            return(DBSeries.Get(conditions));
        }
Ejemplo n.º 17
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();
        }
Ejemplo n.º 18
0
        public static string getLogos(ref DBSeries series, int imgHeight, int imgWidth)
        {
            if (series == null)
            {
                return(null);
            }
            DBSeries inCache = !Settings.isConfig ? cache.getSeries(series[DBSeries.cID]) : null;

            tmpSeries  = inCache == null ? series : inCache;
            lastResult = getLogos(Level.Series, imgHeight, imgWidth, ref tmpSeries.cachedLogoResults);
            if (!lastWasCached)
            {
                cache.addChangeSeries(tmpSeries);
            }
            return(lastResult);
        }
Ejemplo n.º 19
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;
            }
        }
Ejemplo n.º 20
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);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Returns a pretty String representation of this DBOnlineEpisode (Series - 1x01 - Pilot)
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            DBSeries lSeries = Helper.getCorrespondingSeries(this[DBOnlineEpisode.cSeriesID]);

            if (lSeries != null)
            {
                bool lDvdSortOrder = lSeries[DBOnlineSeries.cEpisodeSortOrder] == "DVD";
                if (lDvdSortOrder && this[cDVDEpisodeNumber] == 0)
                {
                    lDvdSortOrder = false;
                }

                string lSeasonField  = lDvdSortOrder ? cDVDSeasonNumber : cSeasonIndex;
                string lEpisodeField = lDvdSortOrder ? cDVDEpisodeNumber : cEpisodeIndex;

                return(string.Format("{0} - {1}x{2} - {3}", lSeries[DBOnlineSeries.cPrettyName].ToString(), this[lSeasonField], this[lEpisodeField], this[cEpisodeName]));
            }
            else
            {
                return(string.Format("{0} - {1}x{2} - {3}", Translation.Unknown, this[cSeasonIndex], this[cEpisodeIndex], this[cEpisodeName]));
            }
        }
Ejemplo n.º 22
0
        private static List <DBSeries> Get(String sqlQuery)
        {
            SQLiteResultSet results = DBTVSeries.Execute(sqlQuery);
            List <DBSeries> outList = new List <DBSeries>();

            if (results.Rows.Count > 0)
            {
                for (int index = 0; index < results.Rows.Count; index++)
                {
                    DBSeries series = new DBSeries();
                    series.Read(ref results, index);
                    series.m_onlineSeries = new DBOnlineSeries();
                    series.m_onlineSeries.Read(ref results, index);
                    outList.Add(series);
                    if (series[cID] < 0 && series.m_onlineSeries[DBOnlineSeries.cPrettyName].ToString().Length == 0)
                    {
                        series.m_onlineSeries[DBOnlineSeries.cPrettyName] = series[cParsedName];
                        series.m_onlineSeries.Commit();
                    }
                }
            }
            return(outList);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Create scrobble data that can be used to send to Trakt API
        /// </summary>
        public static TraktEpisodeScrobble CreateScrobbleData(DBEpisode episode)
        {
            string username = TraktAPI.Username;
            string password = TraktAPI.Password;

            // check if trakt is enabled
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return(null);
            }

            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],
                SeriesID             = series[DBSeries.cID],
                PluginVersion        = Settings.Version.ToString(),
                MediaCenter          = "mp-tvseries",
                MediaCenterVersion   = Settings.MPVersion.ToString(),
                MediaCenterBuildDate = Settings.MPBuildDate.ToString("yyyy-MM-dd HH:mm:ss"),
                UserName             = username,
                Password             = password
            };

            return(scrobbleData);
        }
Ejemplo n.º 24
0
        private TraktRateSeries CreateSeriesRateData(DBSeries series)
        {
            if (series == null || series[DBOnlineSeries.cTraktIgnore]) return null;

            string rating = series[DBOnlineSeries.cMyRating];

            TraktRateSeries seriesData = new TraktRateSeries()
            {
                Rating = rating,
                SeriesID = series[DBOnlineSeries.cID],
                Year = series.Year,
                Title = series[DBOnlineSeries.cOriginalName],
                UserName = TraktSettings.Username,
                Password = TraktSettings.Password,
            };

            TraktLogger.Info("Rating '{0}' as '{1}/10'", series.ToString(), rating.ToString());
            return seriesData;
        }
Ejemplo n.º 25
0
        private void OnToggleWatched(DBSeries series, List<DBEpisode> episodes, bool watched)
        {
            if (TraktSettings.AccountStatus != ConnectionState.Connected) return;

            Thread toggleWatched = new Thread(delegate()
            {
                TraktLogger.Info("Recieved togglewatched event from tvseries");

                TraktEpisodeSync episodeSyncData = CreateSyncData(series, episodes);
                if (episodeSyncData == null) return;
                TraktResponse response = TraktAPI.TraktAPI.SyncEpisodeLibrary(episodeSyncData, watched ? TraktSyncModes.seen : TraktSyncModes.unseen);
                TraktAPI.TraktAPI.LogTraktResponse(response);
            })
            {
                IsBackground = true,
                Name = "TVSeries Toggle Watched"
            };

            toggleWatched.Start();
        }
Ejemplo n.º 26
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();
        }
Ejemplo n.º 27
0
        public List <string> deleteSeason(TVSeriesPlugin.DeleteMenuItems type)
        {
            List <string> resultMsg = new List <string>();

            // Always delete from Local episode table if deleting from disk or database
            SQLCondition condition = new SQLCondition();

            condition.Add(new DBEpisode(), DBEpisode.cSeriesID, this[DBSeason.cSeriesID], SQLConditionType.Equal);
            condition.Add(new DBEpisode(), DBEpisode.cSeasonIndex, this[DBSeason.cIndex], SQLConditionType.Equal);

            /* TODO will include hidden episodes as hidden attribute is only in onlineepisodes. maybe we should include it in localepisodes also..
             * if hidden episodes are excluded then the if (resultMsg.Count is wrong and should do another select to get proper count
             * if (!DBOption.GetOptions(DBOption.cShowHiddenItems))
             * {
             *  //don't include hidden seasons unless the ShowHiddenItems option is set
             *  condition.Add(new DBEpisode(), idden, 0, SQLConditionType.Equal);
             * }
             */

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

            if (episodes != null)
            {
                bool hasLocalEpisodesToDelete = episodes.Exists(e => !string.IsNullOrEmpty(e[DBEpisode.cFilename]));
                hasLocalEpisodesToDelete &= (type == TVSeriesPlugin.DeleteMenuItems.disk || type == TVSeriesPlugin.DeleteMenuItems.diskdatabase);

                DBSeries series     = Helper.getCorrespondingSeries(this[DBSeason.cSeriesID]);
                string   seriesName = series == null ? this[DBSeason.cSeriesID].ToString() : series.ToString();

                // show progress dialog as this can be a long process esp for network drives
                // will show new progress for each season if deleting from the series level
                GUIDialogProgress progressDialog = null;
                if (!Settings.isConfig)
                {
                    progressDialog = (GUIDialogProgress)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_PROGRESS);
                    progressDialog.Reset();
                    progressDialog.DisplayProgressBar = true;
                    progressDialog.ShowWaitCursor     = false;
                    progressDialog.DisableCancel(true);
                    progressDialog.SetHeading(Translation.Delete);
                    progressDialog.Percentage = 0;
                    progressDialog.SetLine(1, string.Format("{0} {1} {2}", seriesName, Translation.Season, this[DBSeason.cIndex]));
                    progressDialog.SetLine(2, string.Empty);

                    // only show progress dialog if we have local files in season
                    if (hasLocalEpisodesToDelete)
                    {
                        progressDialog.StartModal(GUIWindowManager.ActiveWindow);
                    }
                }

                int counter = 0;

                foreach (DBEpisode episode in episodes)
                {
                    string episodeName = string.Format("{0}x{1} - {2}", episode[DBOnlineEpisode.cSeasonIndex], episode[DBOnlineEpisode.cEpisodeIndex], episode[DBOnlineEpisode.cEpisodeName]);
                    if (!Settings.isConfig)
                    {
                        progressDialog.SetLine(2, episodeName);
                    }
                    if (!Settings.isConfig)
                    {
                        GUIWindowManager.Process();
                    }

                    resultMsg.AddRange(episode.deleteEpisode(type, true));

                    if (!Settings.isConfig)
                    {
                        progressDialog.Percentage = Convert.ToInt32(((double)++counter / (double)episodes.Count) * 100.0);
                    }
                    if (!Settings.isConfig)
                    {
                        GUIWindowManager.Process();
                    }
                }

                // close progress dialog
                if (!Settings.isConfig)
                {
                    progressDialog.Close();
                }

                // if we have removed all episodes in season without error, cleanup the online table
                if (resultMsg.Count == 0 && type != TVSeriesPlugin.DeleteMenuItems.disk)
                {
                    condition = new SQLCondition();
                    condition.Add(new DBOnlineEpisode(), DBOnlineEpisode.cSeriesID, this[DBSeason.cSeriesID], SQLConditionType.Equal);
                    condition.Add(new DBOnlineEpisode(), DBOnlineEpisode.cSeasonIndex, this[DBSeason.cIndex], SQLConditionType.Equal);
                    DBOnlineEpisode.Clear(condition);
                }
            }

            #region Facade Remote Color
            // if we were successful at deleting all episodes of season from disk, set HasLocalFiles to false
            // note: we only do this if the database entries still exist
            if (resultMsg.Count == 0 && type == TVSeriesPlugin.DeleteMenuItems.disk)
            {
                this[cHasLocalFiles] = false;
                this.Commit();
            }

            // if we were successful at deleting all episodes of season from disk,
            // also check if any local episodes exist on disk for series and set HasLocalFiles to false
            if (resultMsg.Count == 0 && type != TVSeriesPlugin.DeleteMenuItems.database)
            {
                // Check Series for Local Files
                SQLCondition episodeConditions = new SQLCondition();
                episodeConditions.Add(new DBEpisode(), DBEpisode.cSeriesID, this[DBSeason.cSeriesID], SQLConditionType.Equal);
                List <DBEpisode> localEpisodes = DBEpisode.Get(episodeConditions);
                if (localEpisodes.Count == 0 && !DBSeries.IsSeriesRemoved)
                {
                    DBSeries series = DBSeries.Get(this[DBSeason.cSeriesID]);
                    if (series != null)
                    {
                        series[DBOnlineSeries.cHasLocalFiles] = false;
                        series.Commit();
                    }
                }
            }
            #endregion

            #region Cleanup

            // if there are no error messages and if we need to delete from db
            if (resultMsg.Count == 0 && type != TVSeriesPlugin.DeleteMenuItems.disk)
            {
                condition = new SQLCondition();
                condition.Add(new DBSeason(), DBSeason.cSeriesID, this[DBSeason.cSeriesID], SQLConditionType.Equal);
                condition.Add(new DBSeason(), DBSeason.cIndex, this[DBSeason.cIndex], SQLConditionType.Equal);
                DBSeason.Clear(condition);
            }

            DBSeries.IsSeriesRemoved = false;
            if (type != TVSeriesPlugin.DeleteMenuItems.disk)
            {
                // If local/online episode count is zero then delete the series and all seasons
                condition = new SQLCondition();
                condition.Add(new DBOnlineEpisode(), DBOnlineEpisode.cSeriesID, this[DBSeason.cSeriesID], SQLConditionType.Equal);
                episodes = DBEpisode.Get(condition, false);
                if (episodes.Count == 0)
                {
                    // Delete Seasons
                    condition = new SQLCondition();
                    condition.Add(new DBSeason(), DBSeason.cSeriesID, this[DBSeason.cSeriesID], SQLConditionType.Equal);
                    DBSeason.Clear(condition);

                    // Delete Local Series
                    condition = new SQLCondition();
                    condition.Add(new DBSeries(), DBSeries.cID, this[DBSeason.cSeriesID], SQLConditionType.Equal);
                    DBSeries.Clear(condition);

                    // Delete Online Series
                    condition = new SQLCondition();
                    condition.Add(new DBOnlineSeries(), DBOnlineSeries.cID, this[DBSeason.cSeriesID], SQLConditionType.Equal);
                    DBOnlineSeries.Clear(condition);

                    DBSeries.IsSeriesRemoved = true;
                }
            }
            #endregion

            return(resultMsg);
        }
Ejemplo n.º 28
0
        private void CreateSeriesNode(DBSeries series, List<DBSeason> seasons, int index)
        {
            if (series == null) return;

            string sName = (DBOption.GetOptions(DBOption.cUseSortName) ? series[DBOnlineSeries.cSortName] : series[DBOnlineSeries.cPrettyName]);
            TreeNode seriesNode = new TreeNode(sName);
            seriesNode.Name = DBSeries.cTableName;
            seriesNode.Tag = (DBSeries)series;
            this.treeView_Library.Nodes.Insert(index, seriesNode);
            Font fontDefault = treeView_Library.Font;

            // set color for non-local files
            if (series[DBOnlineSeries.cEpisodeCount] == 0)
            {
                seriesNode.ForeColor = System.Drawing.SystemColors.GrayText;
            }
            else
            {
                // set color for watched items
                if (series[DBOnlineSeries.cUnwatchedItems] == 0)
                    seriesNode.ForeColor = System.Drawing.Color.DarkBlue;
            }

            // set FontStyle
            if (series[DBSeries.cHidden])
                seriesNode.NodeFont = new Font(fontDefault.Name, fontDefault.Size, FontStyle.Italic);

            int seriesID = series[DBSeries.cID];

            if (seasons == null)
            {
                seasons = DBSeason.Get(new SQLCondition(new DBSeason(), DBSeason.cSeriesID, series[DBSeries.cID], SQLConditionType.Equal), false);
                if (seasons == null) return;
                
                seasons.Sort();
            }

            foreach (DBSeason season in seasons)
            {
                CreateSeasonTree(seriesNode, season);
            }
        }
Ejemplo n.º 29
0
        private void MarkEpisodesAsWatched(DBSeries show, List<DBEpisode> episodes)
        {
            var syncThread = new Thread((o) =>
            {
                // send show data as well in case tvdb ids are not available on trakt server
                // TraktSyncEpisodeRated object is good if we could trust trakt having the tvdb ids.
                // trakt is more likely to have a show tvdb id than a episode tvdb id
                var showEpisodes = new TraktSyncShowWatchedEx
                {
                    Title = show[DBOnlineSeries.cOriginalName],
                    Year = show.Year.ToNullableInt32(),
                    Ids = new TraktShowId
                    {
                        Tvdb = show[DBSeries.cID],
                        Imdb = BasicHandler.GetProperImdbId(show[DBOnlineSeries.cIMDBID])
                    }
                };

                var seasons = new List<TraktSyncShowWatchedEx.Season>();

                foreach (var episode in episodes)
                {
                    if (seasons.Exists(s => s.Number == episode[DBOnlineEpisode.cSeasonIndex]))
                    {
                        // add the episode to the season collection
                        seasons.First(s => s.Number == episode[DBOnlineEpisode.cSeasonIndex])
                               .Episodes.Add(new TraktSyncShowWatchedEx.Season.Episode
                               {
                                   Number = episode[DBOnlineEpisode.cEpisodeIndex],
                                   WatchedAt = DateTime.UtcNow.ToISO8601()
                               });

                    }
                    else
                    {
                        // create season and add episode to it's episode collection
                        seasons.Add(new TraktSyncShowWatchedEx.Season
                        {
                            Number = episode[DBOnlineEpisode.cSeasonIndex],
                            Episodes = new List<TraktSyncShowWatchedEx.Season.Episode>
                            {
                                new TraktSyncShowWatchedEx.Season.Episode
                                {
                                    Number = episode[DBOnlineEpisode.cEpisodeIndex],
                                    WatchedAt = DateTime.UtcNow.ToISO8601()
                                }
                            }
                        });
                    }
                }
                showEpisodes.Seasons = seasons;

                var showSync = new TraktSyncShowsWatchedEx
                {
                    Shows = new List<TraktSyncShowWatchedEx> { showEpisodes }
                };

                var response = TraktAPI.TraktAPI.AddShowsToWatchedHistoryEx(showSync);
                TraktLogger.LogTraktResponse(response);

                if (response != null && response.NotFound != null && response.NotFound.Episodes.Count == 0)
                {
                    // update local cache
                    TraktCache.AddEpisodesToWatchHistory(showEpisodes);
                }
            })
            {
                IsBackground = true,
                Name = "ToggleWatched"
            };

            syncThread.Start();
        }
Ejemplo n.º 30
0
        protected override void OnPageLoad()
        {
            MPTVSeriesLog.Write("OnPageLoad() started.", MPTVSeriesLog.LogLevel.Debug);
            if (m_Facade == null)
            {
                // Most likely the skin does not exist
                GUIDialogOK dlg = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK);
                dlg.Reset();
                dlg.SetHeading(Translation.wrongSkin);
                dlg.DoModal(GetID);
                GUIWindowManager.ShowPreviousWindow();
                return;
            }

            GUIPropertyManager.SetProperty("#currentmodule", pluginName);

            ImageAllocator.SetFontName(m_Facade.AlbumListLayout == null ? m_Facade.ListLayout.FontName : m_Facade.AlbumListLayout.FontName);

            #region Clear GUI Properties
            // Clear GUI Properties when first entering the plugin
            // This will avoid ugly property names being seen before
            // its corresponding value is assigned
            if (!m_bPluginLoaded)
            {
                clearGUIProperty(guiProperty.Subtitle);
                clearGUIProperty(guiProperty.Title);
                clearGUIProperty(guiProperty.Description);

                clearGUIProperty(guiProperty.CurrentView);
                clearGUIProperty(guiProperty.SimpleCurrentView);
                clearGUIProperty(guiProperty.NextView);
                clearGUIProperty(guiProperty.LastView);
                clearGUIProperty(guiProperty.SeriesCount);
                clearGUIProperty(guiProperty.GroupCount);
                clearGUIProperty(guiProperty.FilteredEpisodeCount);
                clearGUIProperty(guiProperty.WatchedCount);
                clearGUIProperty(guiProperty.UnWatchedCount);

                clearFieldsForskin("Series");
                clearFieldsForskin("Season");
                clearFieldsForskin("Episode");
            }
            #endregion

            localLogos.appendEpImage = m_Episode_Image == null ? true : false;

            #region View Setup and Loading Parameters
            bool viewSwitched = false;
            m_LoadingParameter = GetLoadingParameter();

            if (m_LoadingParameter.Type != LoadingParameterType.None && m_LoadingParameter.Type != LoadingParameterType.View)
            {
                m_JumpToViewLevel = true;

                if (m_allViews == null || m_allViews.Count == 0) m_allViews = logicalView.getAll(false);
                if (m_CurrLView == null) switchView((string)DBOption.GetOptions("lastView"));

                int viewLevels = m_CurrLView.m_steps.Count;

                m_SelectedSeries = Helper.getCorrespondingSeries(Convert.ToInt32(m_LoadingParameter.SeriesId));
                if (m_SelectedSeries == null)
                {
                    MPTVSeriesLog.Write("Failed to get series object from loading parameter!", MPTVSeriesLog.LogLevel.Debug);
                    m_LoadingParameter.Type = LoadingParameterType.None;
                }
                else
                {
                    MPTVSeriesLog.Write(string.Format("Loading into series: {0}", m_SelectedSeries.ToString(), MPTVSeriesLog.LogLevel.Debug));
                    m_stepSelection = new string[] { m_LoadingParameter.SeriesId };
                    m_stepSelections.Add(m_stepSelection);
                    pushFieldsToSkin(m_SelectedSeries, "Series");
                }

                switch (m_LoadingParameter.Type)
                {
                    #region Series
                    case LoadingParameterType.Series:
                        // load into Season view if multiple seasons exists
                        // will auto drill down to current available season if only one exists
                        if (viewLevels > 1) m_CurrViewStep = viewLevels - 2;
                        else m_CurrViewStep = 0;
                        this.listLevel = Listlevel.Season;
                        break;
                    #endregion

                    #region Season
                    case LoadingParameterType.Season:
                        m_SelectedSeason = Helper.getCorrespondingSeason(Convert.ToInt32(m_LoadingParameter.SeriesId), Convert.ToInt32(m_LoadingParameter.SeasonIdx));
                        if (m_SelectedSeason == null)
                        {
                            m_LoadingParameter.Type = LoadingParameterType.None;
                            break;
                        }
                        // load into episode view for series/season
                        if (viewLevels > 1) m_CurrViewStep = viewLevels - 1;
                        else m_CurrViewStep = 0;
                        this.listLevel = Listlevel.Episode;
                        m_stepSelection = new string[] { m_LoadingParameter.SeriesId, m_LoadingParameter.SeasonIdx };
                        m_stepSelections.Add(m_stepSelection);
                        break;
                    #endregion

                    #region Episode
                    case LoadingParameterType.Episode:
                        m_SelectedEpisode = DBEpisode.Get(Convert.ToInt32(m_LoadingParameter.SeriesId), Convert.ToInt32(m_LoadingParameter.SeasonIdx), Convert.ToInt32(m_LoadingParameter.EpisodeIdx));
                        if (m_SelectedEpisode == null)
                        {
                            m_LoadingParameter.Type = LoadingParameterType.None;
                            break;
                        }
                        // load into episode view for series/season
                        if (viewLevels > 1) m_CurrViewStep = viewLevels - 1;
                        else m_CurrViewStep = 0;
                        this.listLevel = Listlevel.Episode;
                        m_stepSelection = new string[] { m_LoadingParameter.SeriesId, m_LoadingParameter.SeasonIdx };
                        m_stepSelections.Add(m_stepSelection);
                        break;
                    #endregion
                }

                setViewLabels();
            }

            // Initialize View, also check if current view is locked after exiting and re-entering plugin
            if (m_LoadingParameter.Type == LoadingParameterType.None || m_LoadingParameter.Type == LoadingParameterType.View)
            {
                m_JumpToViewLevel = false;

                if (m_CurrLView == null || (m_CurrLView.ParentalControl && logicalView.IsLocked) || !string.IsNullOrEmpty(m_LoadingParameter.ViewName))
                {
                    // Get available Views
                    m_allViews = logicalView.getAll(false);
                    if (m_allViews.Count > 0)
                    {
                        try
                        {
                            if (m_LoadingParameter.Type == LoadingParameterType.View)
                            {
                                viewSwitched = switchView(m_LoadingParameter.ViewName);
                            }
                            else
                            {
                                viewSwitched = switchView((string)DBOption.GetOptions("lastView"));
                            }
                        }
                        catch
                        {
                            viewSwitched = false;
                            MPTVSeriesLog.Write("Error when switching view");
                        }
                    }
                    else
                    {
                        viewSwitched = false;
                        MPTVSeriesLog.Write("Error, cannot display items because no Views have been found!");
                    }
                }
                else
                {
                    viewSwitched = true;
                    setViewLabels();
                }

                // If unable to load view, exit
                if (!viewSwitched)
                {
                    GUIWindowManager.ShowPreviousWindow();
                    return;
                }
            }
            #endregion

            backdrop.GUIImageOne = FanartBackground;
            backdrop.GUIImageTwo = FanartBackground2;
            backdrop.LoadingImage = loadingImage;

            DBEpisode previouslySelectedEpisode = m_SelectedEpisode;

            LoadFacade();
            m_Facade.Focus = true;

            // Update Button Labels with translations
            if (viewMenuButton != null)
                viewMenuButton.Label = Translation.ButtonSwitchView;

            if (filterButton != null)
                filterButton.Label = Translation.Filters;

            if (ImportButton != null)
                ImportButton.Label = Translation.ButtonRunImport;

            if (LayoutMenuButton != null)
                LayoutMenuButton.Label = Translation.ButtonChangeLayout;

            if (OptionsMenuButton != null)
                OptionsMenuButton.Label = Translation.ButtonOptions;

            setProcessAnimationStatus(m_parserUpdaterWorking);

            if (m_Logos_Image != null)
            {
                logosHeight = m_Logos_Image.Height;
                logosWidth = m_Logos_Image.Width;
            }

            m_bPluginLoaded = true;

            Helper.disableNativeAutoplay();

            // Ask to Rate Episode, onPageLoad is triggered after returning from player
            if (ask2Rate != null)
            {
                showRatingsDialog(ask2Rate, true);
                ask2Rate = null;
                // Refresh the facade if we want to see the submitted rating
                if (this.listLevel == Listlevel.Episode)
                {
                    LoadFacade();
                }
            }

            // Play after subtitle download
            if (m_PlaySelectedEpisodeAfterSubtitles && previouslySelectedEpisode != null && previouslySelectedEpisode == m_SelectedEpisode)
            {
                CommonPlayEpisodeAction();
                m_PlaySelectedEpisodeAfterSubtitles = false;
            }

            // Push last update time to skin
            setGUIProperty(guiProperty.LastOnlineUpdate, DBOption.GetOptions(DBOption.cImport_OnlineUpdateScanLastTime));

            MPTVSeriesLog.Write("OnPageLoad() completed.", MPTVSeriesLog.LogLevel.Debug);
        }
Ejemplo n.º 31
0
        private void Episode_OnItemSelected(GUIListItem item)
        {
            if (item == null || item.TVTag == null)
                return;

            setNewListLevelOfCurrView(m_CurrViewStep);

            DBEpisode episode = item.TVTag as DBEpisode;
            if (episode == null) return;

            // set watched/unavailable flag
            if (dummyIsWatched != null) dummyIsWatched.Visible = episode[DBOnlineEpisode.cWatched];
            if (dummyIsAvailable != null) dummyIsAvailable.Visible = episode[DBEpisode.cFilename].ToString().Length > 0;

            m_SelectedEpisode = episode;
            setGUIProperty(guiProperty.Logos, localLogos.getLogos(ref episode, logosHeight, logosWidth));
            setGUIProperty(guiProperty.EpisodeImage, ImageAllocator.GetEpisodeImage(m_SelectedEpisode));
            setGUIProperty(guiProperty.Title, FieldGetter.resolveDynString(m_sFormatEpisodeTitle, episode));
            setGUIProperty(guiProperty.Subtitle, FieldGetter.resolveDynString(m_sFormatEpisodeSubtitle, episode));
            setGUIProperty(guiProperty.Description, FieldGetter.resolveDynString(m_sFormatEpisodeMain, episode));

            // with groups in episode view its possible the user never selected a series/season (flat view)
            // thus its desirable to display the series_banner and season banner on hover)
            if (!m_CurrLView.stepHasSeriesBeforeIt(m_CurrViewStep) || m_bUpdateBanner)
            {
                // it is the case
                m_SelectedSeason = Helper.getCorrespondingSeason(episode[DBEpisode.cSeriesID], episode[DBEpisode.cSeasonIndex]);
                m_SelectedSeries = Helper.getCorrespondingSeries(episode[DBEpisode.cSeriesID]);

                if (m_SelectedSeries != null)
                {
                    seriesbanner.Filename = ImageAllocator.GetSeriesBannerAsFilename(m_SelectedSeries);
                    seriesposter.Filename = ImageAllocator.GetSeriesPosterAsFilename(m_SelectedSeries);
                    pushFieldsToSkin(m_SelectedSeries, "Series");
                }
                else
                {
                    clearGUIProperty(guiProperty.SeriesBanner);
                    clearGUIProperty(guiProperty.SeriesPoster);
                }

                if (m_SelectedSeason != null)
                {
                    string filename = ImageAllocator.GetSeasonBannerAsFilename(m_SelectedSeason);
                    if (filename.Length == 0)
                    {
                        // Load Series Poster instead
                        if (DBOption.GetOptions(DBOption.cSubstituteMissingArtwork) && m_SelectedSeries != null)
                        {
                            filename = ImageAllocator.GetSeriesPosterAsFilename(m_SelectedSeries);
                        }
                    }
                    seasonbanner.Filename = filename;

                    pushFieldsToSkin(m_SelectedSeason, "Season");
                }
                else
                    clearGUIProperty(guiProperty.SeasonPoster);

                m_bUpdateBanner = false;
            }
            pushFieldsToSkin(m_SelectedEpisode, "Episode");

            // Load Fanart for Selected Series, might be in Episode Only View e.g. Recently Added, Latest
            if (m_SelectedSeries == null) return;

            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];
        }
Ejemplo n.º 32
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);
            }
        }
Ejemplo n.º 33
0
        private void ChangeEpisodeMatchingOrder(DBSeries series, string order)
        {
            MPTVSeriesLog.Write("Changing Episode Match Order for {0}, to {1}", series.ToString(), order);

            // get list of local episodes to re-match
            SQLCondition conditions = new SQLCondition();
            conditions.Add(new DBEpisode(), DBEpisode.cSeriesID, series[DBSeries.cID], SQLConditionType.Equal);
            List<DBEpisode> localEpisodes = DBEpisode.Get(conditions);
            OnlineParsing.matchOnlineToLocalEpisodes(series, localEpisodes, new GetEpisodes(series[DBSeries.cID]), order);
            return;
        }
Ejemplo n.º 34
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];
        }
Ejemplo n.º 35
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];
        }
Ejemplo n.º 36
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();
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Returns a pretty String representation of this DBOnlineEpisode (Series - 1x01 - Pilot)
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            DBSeries s = Helper.getCorrespondingSeries(this[DBOnlineEpisode.cSeriesID]);

            return(string.Format("{0} - {1}x{2} - {3}", (s == null ? string.Empty : s[DBOnlineSeries.cPrettyName].ToString()), this[DBOnlineEpisode.cSeasonIndex], this[DBOnlineEpisode.cEpisodeIndex], this[cEpisodeName]));
        }
Ejemplo n.º 38
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));
                }

            }
        }
Ejemplo n.º 39
0
        public void addSQLCondition(string what, string type, string condition)
        {
            if ((!what.Contains("<") || !what.Contains(".")) && !what.Contains("custom:"))
            {
                return;
            }

            SQLConditionType condtype;

            switch (type)
            {
            case "=":
                condtype = SQLConditionType.Equal;
                break;

            case ">":
                condtype = SQLConditionType.GreaterThan;
                break;

            case ">=":
                condtype = SQLConditionType.GreaterEqualThan;
                break;

            case "<":
                condtype = SQLConditionType.LessThan;
                break;

            case "<=":
                condtype = SQLConditionType.LessEqualThan;
                break;

            case "!=":
                condtype = SQLConditionType.NotEqual;
                break;

            case "like":
                condtype = SQLConditionType.Like;
                break;

            default:
                condtype = SQLConditionType.Equal;
                break;
            }

            DBTable table      = null;
            string  tableField = string.Empty;

            getTableFieldname(what, out table, out tableField);
            Type lType = table.GetType();

            SQLCondition fullSubCond = new SQLCondition();

            if (logicalViewStep.type.series == Type && (lType != typeof(DBSeries) && lType != typeof(DBOnlineSeries)))
            {
                if (lType == typeof(DBSeason))
                {
                    fullSubCond.AddCustom(DBSeason.Q(DBSeason.cSeriesID), DBOnlineSeries.Q(DBOnlineSeries.cID), SQLConditionType.Equal);
                    fullSubCond.AddCustom(DBSeason.Q(tableField), condition, condtype, true);

                    conds.AddCustom(" exists( " + DBSeason.stdGetSQL(fullSubCond, false) + " )");
                }
                else if (lType == typeof(DBOnlineEpisode))
                {
                    fullSubCond.AddCustom(DBOnlineEpisode.Q(tableField), condition, condtype, true);
                    conds.AddCustom(" online_series.id in ( " + DBEpisode.stdGetSQL(fullSubCond, false, true, DBOnlineEpisode.Q(DBOnlineEpisode.cSeriesID)) + " )");
                }
                else if (lType == typeof(DBEpisode))
                {
                    fullSubCond.AddCustom(DBEpisode.Q(tableField), condition, condtype, true);
                    conds.AddCustom(" online_series.id in ( " + DBEpisode.stdGetSQL(fullSubCond, false, true, DBOnlineEpisode.Q(DBOnlineEpisode.cSeriesID)) + " )");
                }
            }
            else if (logicalViewStep.type.season == Type && lType != typeof(DBSeason))
            {
                if (lType == typeof(DBOnlineSeries) || lType == typeof(DBSeries))
                {
                    fullSubCond.AddCustom(DBOnlineSeries.Q(DBOnlineSeries.cID), DBSeason.Q(DBSeason.cSeriesID), SQLConditionType.Equal);
                    fullSubCond.AddCustom(DBOnlineSeries.Q(tableField), condition, condtype, true);
                    conds.AddCustom(" exists( " + DBSeries.stdGetSQL(fullSubCond, false) + " )");
                }
                else if (lType == typeof(DBOnlineEpisode))
                {
                    // we rely on the join in dbseason for this (much, much faster)
                    conds.AddCustom(DBOnlineEpisode.Q(tableField), condition, condtype, true);
                }
                else if (lType == typeof(DBEpisode))
                {
                    fullSubCond.AddCustom(DBOnlineEpisode.Q(DBOnlineEpisode.cSeriesID), DBSeason.Q(DBSeason.cSeriesID), SQLConditionType.Equal);
                    fullSubCond.AddCustom(DBOnlineEpisode.Q(DBOnlineEpisode.cSeasonIndex), DBSeason.Q(DBSeason.cIndex), SQLConditionType.Equal);
                    fullSubCond.AddCustom(DBEpisode.Q(tableField), condition, condtype);
                    conds.AddCustom(" exists( " + DBEpisode.stdGetSQL(fullSubCond, false) + " )");
                }
            }
            else if (logicalViewStep.type.episode == Type && (lType != typeof(DBEpisode) && lType != typeof(DBOnlineEpisode)))
            {
                if (lType == typeof(DBOnlineSeries) || lType == typeof(DBSeries))
                {
                    fullSubCond.AddCustom(DBOnlineSeries.Q(DBOnlineSeries.cID), DBOnlineEpisode.Q(DBOnlineEpisode.cSeriesID), SQLConditionType.Equal);
                    fullSubCond.AddCustom(DBOnlineSeries.Q(tableField), condition, condtype, true);
                    conds.AddCustom(" exists( " + DBSeries.stdGetSQL(fullSubCond, false) + " )");
                }
                if (lType == typeof(DBSeason))
                {
                    fullSubCond.AddCustom(DBSeason.Q(DBSeason.cSeriesID), DBOnlineEpisode.Q(DBOnlineEpisode.cSeriesID), SQLConditionType.Equal);
                    fullSubCond.AddCustom(DBSeason.Q(DBSeason.cIndex), DBOnlineEpisode.Q(DBOnlineEpisode.cSeasonIndex), SQLConditionType.Equal);
                    fullSubCond.AddCustom(DBSeason.Q(tableField), condition, condtype, true);
                    conds.AddCustom(" exists( " + DBSeason.stdGetSQL(fullSubCond, false) + " )");
                }
            }
            else
            {
                // condition is on current table itself
                conds.Add(table, tableField, condition.Trim(), condtype);
            }
        }
Ejemplo n.º 40
0
        protected override void OnClicked(int controlId, GUIControl control, MediaPortal.GUI.Library.Action.ActionType actionType)
        {
            if (control == null) return; // may enter tvs from another window via click

            if (control == this.viewMenuButton)
            {
                showViewSwitchDialog();
                GUIControl.UnfocusControl(GetID, viewMenuButton.GetID);
                GUIControl.FocusControl(GetID, m_Facade.GetID);
                return;
            }

            if (control == this.filterButton)
            {
                ShowFiltersMenu();
                GUIControl.UnfocusControl(GetID, filterButton.GetID);
                GUIControl.FocusControl(GetID, m_Facade.GetID);
            }

            if (control == this.LayoutMenuButton)
            {
                ShowLayoutMenu();
                GUIControl.UnfocusControl(GetID, LayoutMenuButton.GetID);
                GUIControl.FocusControl(GetID, m_Facade.GetID);
                return;
            }

            if (control == this.OptionsMenuButton)
            {
                ShowOptionsMenu();
                GUIControl.UnfocusControl(GetID, OptionsMenuButton.GetID);
                GUIControl.FocusControl(GetID, m_Facade.GetID);
                return;
            }

            if (control == this.ImportButton)
            {
                lock (m_parserUpdaterQueue)
                {
                    m_parserUpdaterQueue.Add(new CParsingParameters(true, true));
                }
                // Start Import if delayed
                m_scanTimer.Change(1000, 1000);

                GUIControl.UnfocusControl(GetID, ImportButton.GetID);
                GUIControl.FocusControl(GetID, m_Facade.GetID);
                return;
            }

            if (control == this.LoadPlaylistButton)
            {
                OnShowSavedPlaylists(DBOption.GetOptions(DBOption.cPlaylistPath));
                GUIControl.UnfocusControl(GetID, LoadPlaylistButton.GetID);
                GUIControl.FocusControl(GetID, m_Facade.GetID);
                return;
            }

            if (actionType != Action.ActionType.ACTION_SELECT_ITEM) return; // some other events raised onClicked too for some reason?
            if (control == this.m_Facade)
            {
                if (this.m_Facade.SelectedListItem == null || this.m_Facade.SelectedListItem.TVTag == null)
                    return;

                #region Parental Control Check for Tagged Views
                if (this.listLevel == Listlevel.Group && logicalView.IsLocked)
                {
                    string viewName = this.m_Facade.SelectedListItem.Label;
                    DBView[] views = DBView.getTaggedViews();
                    foreach (DBView view in views)
                    {
                        if (view[DBView.cTransToken] == viewName || view[DBView.cPrettyName] == viewName)
                        {
                            // check if we are entering a protected view
                            if (view[DBView.cParentalControl])
                            {
                                GUIPinCode pinCodeDlg = (GUIPinCode)GUIWindowManager.GetWindow(GUIPinCode.ID);
                                pinCodeDlg.Reset();

                                pinCodeDlg.MasterCode = DBOption.GetOptions(DBOption.cParentalControlPinCode);
                                pinCodeDlg.EnteredPinCode = string.Empty;
                                pinCodeDlg.SetHeading(Translation.PinCode);
                                pinCodeDlg.SetLine(1, string.Format(Translation.PinCodeDlgLabel1, viewName));
                                pinCodeDlg.SetLine(2, Translation.PinCodeDlgLabel2);
                                pinCodeDlg.Message = Translation.PinCodeMessageIncorrect;
                                pinCodeDlg.DoModal(GUIWindowManager.ActiveWindow);
                                if (!pinCodeDlg.IsCorrect)
                                {
                                    MPTVSeriesLog.Write("PinCode entered was incorrect, showing Views Menu");
                                    return;
                                }
                                else
                                    logicalView.IsLocked = false;
                            }
                        }
                    }
                }
                #endregion

                m_back_up_select_this = null;
                switch (this.listLevel)
                {
                    case Listlevel.Group:
                        this.m_CurrViewStep++;
                        setNewListLevelOfCurrView(m_CurrViewStep);
                        m_stepSelection = new string[] { this.m_Facade.SelectedListItem.Label };
                        m_stepSelections.Add(m_stepSelection);
                        m_stepSelectionPretty.Add(this.m_Facade.SelectedListItem.Label);
                        MPTVSeriesLog.Write("Group Clicked: ", this.m_Facade.SelectedListItem.Label, MPTVSeriesLog.LogLevel.Debug);
                        LoadFacade();
                        this.m_Facade.Focus = true;
                        break;

                    case Listlevel.Series:
                        this.m_SelectedSeries = this.m_Facade.SelectedListItem.TVTag as DBSeries;
                        if (m_SelectedSeries == null) return;

                        this.m_CurrViewStep++;
                        setNewListLevelOfCurrView(m_CurrViewStep);
                        m_stepSelection = new string[] { m_SelectedSeries[DBSeries.cID].ToString() };
                        m_stepSelections.Add(m_stepSelection);
                        m_stepSelectionPretty.Add(this.m_SelectedSeries.ToString());
                        MPTVSeriesLog.Write("Series Clicked: ", m_stepSelection[0], MPTVSeriesLog.LogLevel.Debug);
                        this.LoadFacade();
                        this.m_Facade.Focus = true;
                        break;

                    case Listlevel.Season:
                        this.m_SelectedSeason = this.m_Facade.SelectedListItem.TVTag as DBSeason;
                        if (m_SelectedSeason == null) return;

                        this.m_CurrViewStep++;
                        setNewListLevelOfCurrView(m_CurrViewStep);
                        m_stepSelection = new string[] { m_SelectedSeason[DBSeason.cSeriesID].ToString(), m_SelectedSeason[DBSeason.cIndex].ToString() };
                        m_stepSelections.Add(m_stepSelection);
                        m_stepSelectionPretty.Add(m_SelectedSeason[DBSeason.cIndex] == 0 ? Translation.specials : Translation.Season + " " + m_SelectedSeason[DBSeason.cIndex]);
                        MPTVSeriesLog.Write("Season Clicked: ", m_stepSelection[0] + " - " + m_stepSelection[1], MPTVSeriesLog.LogLevel.Debug);
                        this.LoadFacade();
                        this.m_Facade.Focus = true;
                        break;

                    case Listlevel.Episode:
                        m_SelectedEpisode = this.m_Facade.SelectedListItem.TVTag as DBEpisode;
                        if (m_SelectedEpisode == null) return;
                        MPTVSeriesLog.Write("Episode Clicked: ", m_SelectedEpisode[DBEpisode.cCompositeID].ToString(), MPTVSeriesLog.LogLevel.Debug);

                        CommonPlayEpisodeAction();
                        break;
                }
            }
            base.OnClicked(controlId, control, actionType);
        }
Ejemplo n.º 41
0
 private void CreateSeriesNode(DBSeries series, int index)
 {
     CreateSeriesNode(series, null, index);
 }
Ejemplo n.º 42
0
 static string replaceSeriesTags(DBSeries s, string what)
 {
     if (s == null || what.Length < seriesIdentifier.Length) return what;
     return getValuesOfType(s, what, seriesParse, seriesIdentifier);
 }
Ejemplo n.º 43
0
        private void OnToggleWatched(DBSeries show, List<DBEpisode> episodes, bool watched)
        {
            if (TraktSettings.AccountStatus != ConnectionState.Connected) return;

            TraktLogger.Info("Received a Toggle Watched event from tvseries. Show Title = '{0}', Episodes = '{1}', Watched = '{2}'", show[DBOnlineSeries.cOriginalName], episodes.Count, watched.ToString());

            if (show[DBOnlineSeries.cTraktIgnore]) return;

            if (watched)
                MarkEpisodesAsWatched(show, episodes);
            else
                MarkEpisodesAsUnWatched(show, episodes);
        }
Ejemplo n.º 44
0
 public static String GetSeriesPosterAsFilename(DBSeries series)
 {
     return series.Poster;
 }
Ejemplo n.º 45
0
        /// <summary>
        /// Sets the following Properties:
        /// "#Play.Current.Title"
        /// "#Play.Current.Plot"
        /// "#Play.Current.Thumb"
        /// "#Play.Current.Year"
        /// </summary>
        /// <param name="clear">Clears the properties instead of filling them if True</param>
        void SetGUIProperties(bool clear)
        {
            if (m_currentEpisode == null)
            {
                return;
            }

            DBSeries series = null;

            if (!clear)
            {
                series = Helper.getCorrespondingSeries(m_currentEpisode[DBEpisode.cSeriesID]);
            }
            DBSeason season = null;

            if (!clear)
            {
                season = Helper.getCorrespondingSeason(m_currentEpisode[DBEpisode.cSeriesID], m_currentEpisode[DBEpisode.cSeasonIndex]);
            }

            // Show Plot in OSD or Hide Spoilers (note: FieldGetter takes care of that)
            GUIPropertyManager.SetProperty("#Play.Current.Plot", clear ? " " : FieldGetter.resolveDynString(TVSeriesPlugin.m_sFormatEpisodeMain, m_currentEpisode));

            // Show Episode Thumbnail or Series Poster if Hide Spoilers is enabled
            string osdImage = string.Empty;

            if (!clear)
            {
                foreach (KeyValuePair <string, string> kvp in SkinSettings.VideoOSDImages)
                {
                    switch (kvp.Key)
                    {
                    case "episode":
                        osdImage = ImageAllocator.GetEpisodeImage(m_currentEpisode);
                        break;

                    case "season":
                        osdImage = season.Banner;
                        break;

                    case "series":
                        osdImage = series.Poster;
                        break;

                    case "custom":
                        string value = replaceDynamicFields(kvp.Value);
                        string file  = Helper.getCleanAbsolutePath(value);
                        if (System.IO.File.Exists(file))
                        {
                            osdImage = file;
                        }
                        break;
                    }

                    osdImage = osdImage.Trim();
                    if (string.IsNullOrEmpty(osdImage))
                    {
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            GUIPropertyManager.SetProperty("#Play.Current.Thumb", clear ? " " : osdImage);

            // double check, i don't want play images to be cleared on ended or stopped...
            if (PlayPropertyUpdater.CancellationPending)
            {
                return;
            }

            foreach (KeyValuePair <string, string> kvp in SkinSettings.VideoPlayImages)
            {
                if (!clear)
                {
                    string value = replaceDynamicFields(kvp.Value);
                    string file  = Helper.getCleanAbsolutePath(value);
                    if (System.IO.File.Exists(file))
                    {
                        MPTVSeriesLog.Write(string.Format("Setting play image {0} for property {1}", file, kvp.Key), MPTVSeriesLog.LogLevel.Debug);
                        GUIPropertyManager.SetProperty(kvp.Key, clear ? " " : file);
                    }
                }
                else
                {
                    MPTVSeriesLog.Write(string.Format("Clearing play image for property {0}", kvp.Key), MPTVSeriesLog.LogLevel.Debug);
                    GUIPropertyManager.SetProperty(kvp.Key, " ");
                }
            }

            GUIPropertyManager.SetProperty("#Play.Current.Title", clear ? " " : m_currentEpisode.onlineEpisode.CompleteTitle);
            GUIPropertyManager.SetProperty("#Play.Current.Year", clear ? " " : FieldGetter.resolveDynString("<" + DBEpisode.cOutName + "." + DBOnlineEpisode.cFirstAired + ">", m_currentEpisode, false));
            GUIPropertyManager.SetProperty("#Play.Current.Genre", clear ? " " : FieldGetter.resolveDynString(TVSeriesPlugin.m_sFormatEpisodeSubtitle, m_currentEpisode));
        }
Ejemplo n.º 46
0
        static DBSeries()
        {
            // make sure the table is created on first run (and columns are added before we call SET)
            DBSeries dummy = new DBSeries();

            s_nLastLocalID = DBOption.GetOptions(DBOption.cDBSeriesLastLocalID);

            s_FieldToDisplayNameMap.Add(cParsedName, "Parsed Name");

            int nCurrentDBVersion = cDBVersion;
            int nUpgradeDBVersion = DBOption.GetOptions(DBOption.cDBSeriesVersion);

            while (nUpgradeDBVersion != nCurrentDBVersion)
            {
                SQLCondition    condEmpty = new SQLCondition();
                List <DBSeries> AllSeries = Get(condEmpty);

                // take care of the upgrade in the table
                switch (nUpgradeDBVersion)
                {
                case 1:
                case 2:
                    // upgrade to version 3; clear the series table (we use 2 other tables now)
                    try
                    {
                        String sqlQuery = "DROP TABLE series";
                        DBTVSeries.Execute(sqlQuery);
                        nUpgradeDBVersion++;
                    }
                    catch { }
                    break;

                case 3:
                    // set all new perseries timestamps to 0
                    DBOnlineSeries.GlobalSet(new DBOnlineSeries(), DBOnlineSeries.cGetEpisodesTimeStamp, 0, new SQLCondition());
                    DBOnlineSeries.GlobalSet(new DBOnlineSeries(), DBOnlineSeries.cUpdateBannersTimeStamp, 0, new SQLCondition());
                    nUpgradeDBVersion++;
                    break;

                case 4:
                    DBSeries.GlobalSet(new DBSeries(), DBSeries.cHidden, 0, new SQLCondition());
                    nUpgradeDBVersion++;
                    break;

                case 5:
                    // copy all local parsed name into the online series if seriesID = 0
                    SQLCondition conditions = new SQLCondition();
                    conditions.Add(new DBOnlineSeries(), DBOnlineSeries.cID, 0, SQLConditionType.LessThan);
                    // just getting the series should be enough
                    List <DBSeries> seriesList = DBSeries.Get(conditions);
                    nUpgradeDBVersion++;
                    break;

                case 6:
                    // set all watched flag timestamp to 0 (will be created)
                    DBOnlineSeries.GlobalSet(new DBOnlineSeries(), DBOnlineSeries.cWatchedFileTimeStamp, 0, new SQLCondition());
                    nUpgradeDBVersion++;
                    break;

                case 7:
                    // all series no tagged for auto download at first
                    DBOnlineSeries.GlobalSet(new DBOnlineSeries(), DBOnlineSeries.cTaggedToDownload, 0, new SQLCondition());
                    nUpgradeDBVersion++;
                    break;

                case 8:
                    // create the unwatcheditem value by parsin the episodes
                    foreach (DBSeries series in AllSeries)
                    {
                        DBEpisode episode = DBEpisode.GetFirstUnwatched(series[DBSeries.cID]);
                        if (episode != null)
                        {
                            series[DBOnlineSeries.cUnwatchedItems] = true;
                        }
                        else
                        {
                            series[DBOnlineSeries.cUnwatchedItems] = false;
                        }
                        series.Commit();
                    }
                    nUpgradeDBVersion++;
                    break;

                case 9:
                    // Set number of watched/unwatched episodes
                    foreach (DBSeries series in AllSeries)
                    {
                        int epsTotal     = 0;
                        int epsUnWatched = 0;
                        DBEpisode.GetSeriesEpisodeCounts(series[DBSeries.cID], out epsTotal, out epsUnWatched);
                        series[DBOnlineSeries.cEpisodeCount]      = epsTotal;
                        series[DBOnlineSeries.cEpisodesUnWatched] = epsUnWatched;
                        series.Commit();
                    }
                    nUpgradeDBVersion++;
                    break;

                case 10:
                    // Update Sort Name Column
                    foreach (DBSeries series in AllSeries)
                    {
                        series[DBOnlineSeries.cSortName] = Helper.GetSortByName(series[DBOnlineSeries.cPrettyName]);
                        series.Commit();
                    }
                    nUpgradeDBVersion++;
                    break;

                case 11:
                    // Migrate isFavourite to new Tagged View
                    conditions = new SQLCondition();
                    conditions.Add(new DBOnlineSeries(), DBOnlineSeries.cIsFavourite, "1", SQLConditionType.Equal);
                    seriesList = DBSeries.Get(conditions);

                    MPTVSeriesLog.Write("Migrating Favourite Series");
                    foreach (DBSeries series in seriesList)
                    {
                        // Tagged view are seperated with the pipe "|" character
                        string tagName = "|" + DBView.cTranslateTokenFavourite + "|";
                        series[DBOnlineSeries.cViewTags] = Helper.GetSeriesViewTags(series, true, tagName);
                        series.Commit();
                    }

                    // Migrate isOnlineFavourite to new TaggedView
                    conditions = new SQLCondition();
                    conditions.Add(new DBOnlineSeries(), DBOnlineSeries.cIsOnlineFavourite, "1", SQLConditionType.Equal);
                    seriesList = DBSeries.Get(conditions);

                    MPTVSeriesLog.Write("Migrating Online Favourite Series");
                    foreach (DBSeries series in seriesList)
                    {
                        // Tagged view are seperated with the pipe "|" character
                        string tagName = "|" + DBView.cTranslateTokenOnlineFavourite + "|";
                        series[DBOnlineSeries.cViewTags] = Helper.GetSeriesViewTags(series, true, tagName);
                        series.Commit();
                    }

                    nUpgradeDBVersion++;
                    break;

                case 12:
                    // we now have parsed_series names as titlecased
                    // to avoid users having to re-identify series for new episodes, and to avoid duplicate entries, we upgrade existing series names

                    foreach (var series in AllSeries)
                    {
                        string oldName = series[DBSeries.cParsedName];
                        string newName = oldName.ToTitleCase();
                        MPTVSeriesLog.Write(string.Format("Upgrading Parsed Series Name: {0} to {1}", oldName, newName));
                        series[DBSeries.cParsedName] = newName;
                        series.Commit();
                    }

                    nUpgradeDBVersion++;
                    break;

                case 13:
                    // original name not working in previous release
                    DBOnlineSeries.GlobalSet(new DBOnlineSeries(), DBOnlineSeries.cOriginalName, (DBValue)string.Empty, new SQLCondition());
                    nUpgradeDBVersion++;
                    break;

                case 14:
                    // original name not working in previous release
                    DBOnlineSeries.GlobalSet(new DBOnlineSeries(), DBOnlineSeries.cTraktIgnore, 0, new SQLCondition());
                    nUpgradeDBVersion++;
                    break;

                default:
                    // new DB, nothing special to do
                    nUpgradeDBVersion = nCurrentDBVersion;
                    break;
                }
            }
            DBOption.SetOptions(DBOption.cDBSeriesVersion, nCurrentDBVersion);
        }
Ejemplo n.º 47
0
        public static void UpdateEpisodeCounts(DBSeries series, Dictionary<string, List<EpisodeCounter>> episodes)
        {
            if (series == null) return;

            string seriesId = series[DBSeries.cID];
            int seriesEpsTotal = 0;
            int seriesEpsUnWatched = 0;
            bool airedOrder = series.IsAiredOrder;

            // dont worry about filtering season list, we already have a filtered episode list
            // query without std conditions for faster response.
            var conditions = new SQLCondition(new DBSeason(), DBSeason.cSeriesID, seriesId, SQLConditionType.Equal); 
            var seasons = DBSeason.Get(conditions, false);

            // update season counts
            List<EpisodeCounter> eps = new List<EpisodeCounter>();
            if (episodes.TryGetValue(seriesId, out eps))
            {
                foreach(var season in seasons)
                {
                    var seasonEps = eps.Where(e => airedOrder ? e.SeasonAirIdx == season[DBSeason.cIndex] : e.SeasonDvdIdx == season[DBSeason.cIndex]).ToList();
                    
                    // dont commit seasons if are not viewing them
                    // episodes for count is already filtered so can return 0 results
                    if (seasonEps.Count == 0) continue;

                    int count = seasonEps.Count();
                    int unWatchedCount = seasonEps.Where(e => e.EpisodeWatched != "1").Count();

                    season[DBSeason.cEpisodeCount] = count;
                    season[DBSeason.cEpisodesUnWatched] = unWatchedCount;
                    season[DBSeason.cUnwatchedItems] = unWatchedCount > 0;
                    season.Commit();

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

                // update series counts
                series[DBOnlineSeries.cEpisodeCount] = seriesEpsTotal;
                series[DBOnlineSeries.cEpisodesUnWatched] = seriesEpsUnWatched;
                series[DBOnlineSeries.cUnwatchedItems] = seriesEpsUnWatched > 0;
                series.Commit();
            }
        }
Ejemplo n.º 48
0
 public static String GetSeriesBannerAsFilename(DBSeries series)
 {            
     return series.Banner;
 }
Ejemplo n.º 49
0
        static DBSeason()
        {
            DBSeason dummy = new DBSeason();

            ////////////////////////////////////////////////////////////////////////////////
            #region Pretty Names displayed in Configuration Details Tab
            s_FieldToDisplayNameMap.Add(cID, "Composite Season ID");
            s_FieldToDisplayNameMap.Add(cSeriesID, "Series ID");
            s_FieldToDisplayNameMap.Add(cIndex, "Season Index");
            s_FieldToDisplayNameMap.Add(cEpisodeCount, "Episodes");
            s_FieldToDisplayNameMap.Add(cEpisodesUnWatched, "Episodes UnWatched");
            s_FieldToDisplayNameMap.Add(cMyRating, "My Rating");
            #endregion
            ////////////////////////////////////////////////////////////////////////////////

            int nCurrentDBVersion = cDBVersion;
            int nUpgradeDBVersion = DBOption.GetOptions(DBOption.cDBSeasonVersion);
            while (nUpgradeDBVersion != nCurrentDBVersion)
            {
                SQLCondition    condEmpty  = new SQLCondition();
                List <DBSeason> AllSeasons = Get(condEmpty, true);
                // take care of the upgrade in the table
                switch (nUpgradeDBVersion)
                {
                case 1:
                    // upgrade to version 2; clear the season table (series table format changed)
                    try
                    {
                        String sqlQuery = "DROP TABLE season";
                        DBTVSeries.Execute(sqlQuery);
                        nUpgradeDBVersion++;
                    }
                    catch { }
                    break;

                case 2:
                    DBSeason.GlobalSet(DBSeason.cHidden, 0, new SQLCondition());
                    DBSeries.GlobalSet(DBOnlineSeries.cGetEpisodesTimeStamp, 0, new SQLCondition());
                    nUpgradeDBVersion++;
                    break;

                case 3:
                    // create the unwatcheditem value by parsin the episodes
                    foreach (DBSeason season in AllSeasons)
                    {
                        DBEpisode episode = DBEpisode.GetFirstUnwatched(season[DBSeason.cSeriesID], season[DBSeason.cIndex]);
                        if (episode != null)
                        {
                            season[DBSeason.cUnwatchedItems] = true;
                        }
                        else
                        {
                            season[DBSeason.cUnwatchedItems] = false;
                        }
                        season.Commit();
                    }
                    nUpgradeDBVersion++;
                    break;

                case 4:
                    // Set number of watched/unwatched episodes
                    foreach (DBSeason season in AllSeasons)
                    {
                        int epsTotal     = 0;
                        int epsUnWatched = 0;
                        DBEpisode.GetSeasonEpisodeCounts(season, out epsTotal, out epsUnWatched);
                        season[DBSeason.cEpisodeCount]      = epsTotal;
                        season[DBSeason.cEpisodesUnWatched] = epsUnWatched;
                        season.Commit();
                    }
                    nUpgradeDBVersion++;
                    break;

                default:
                    nUpgradeDBVersion = nCurrentDBVersion;
                    break;
                }
            }
            DBOption.SetOptions(DBOption.cDBSeasonVersion, nCurrentDBVersion);
        }
Ejemplo n.º 50
0
        public static String GetSeriesPoster(DBSeries series, bool isCoverflow)
        {
            string sFileName = series.Poster;;
            string sTextureName = string.Empty;

            bool ShowNewImage = false;

            NewEpisodeIndicatorType newEpisodeThumbType = (NewEpisodeIndicatorType)(int)DBOption.GetOptions(DBOption.cNewEpisodeThumbType);

            if (newEpisodeThumbType == NewEpisodeIndicatorType.recentlyadded)
            {
                ShowNewImage = series[DBOnlineSeries.cHasNewEpisodes];
            }
            else if (newEpisodeThumbType == NewEpisodeIndicatorType.unwatched)
            {
                ShowNewImage = series[DBOnlineSeries.cUnwatchedItems];
            }
            else if (newEpisodeThumbType == NewEpisodeIndicatorType.recentlyaddedunwatched)
            {
                ShowNewImage = series[DBOnlineSeries.cHasNewEpisodes] && series[DBOnlineSeries.cUnwatchedItems];
            }

            Size size = isCoverflow ? reqSeriesPosterCFSize : reqSeriesPosterSize;

            if (sFileName.Length > 0 && System.IO.File.Exists(sFileName))
            {
                if (ShowNewImage)
                {
                    //make banner with new tag
                    string ident = sFileName + "_new";
                    sTextureName = buildMemoryImage(drawNewBanner(sFileName, ImageType.poster), ident, size, true);
                }
                else
                {
                    if (DBOption.GetOptions(DBOption.cAltImgLoading))
                    {
                        // bypass memoryimagebuilder
                        sTextureName = sFileName;
                    }
                    else
                        sTextureName = buildMemoryImageFromFile(sFileName, size);
                }
            }

            if (string.IsNullOrEmpty(sTextureName))
            {
                // no image, use text, create our own
                string ident = "series_" + series[DBSeries.cID];
                Bitmap b = drawSimpleBanner(DefPosterSize, series[DBOnlineSeries.cPrettyName]); // create "full" size poster so we can stamp new on it
                if (ShowNewImage)
                {
                    drawNewBanner(b, ImageType.poster);
                }
                sTextureName = buildMemoryImage(b, ident, size, true);
            }

            if (sTextureName.Length > 0 && !s_SeriesImageList.Contains(sTextureName)) 
                s_SeriesImageList.Add(sTextureName);

            return sTextureName;
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Creates Sync Data based on Series object and a List of Episode objects
        /// </summary>
        /// <param name="series">The series to base the object on</param>
        /// <param name="epsiodes">The list of episodes to base the object on</param>
        /// <returns>The Trakt Sync data to send</returns>
        private TraktEpisodeSync CreateSyncData(DBSeries series, List<DBEpisode> episodes)
        {
            if (series == null || series[DBOnlineSeries.cTraktIgnore]) return null;

            // set series properties for episodes
            TraktEpisodeSync traktSync = new TraktEpisodeSync
            {
                Password = TraktSettings.Password,
                UserName = TraktSettings.Username,
                SeriesID = series[DBSeries.cID],
                IMDBID = series[DBOnlineSeries.cIMDBID],
                Year = series.Year,
                Title = series[DBOnlineSeries.cOriginalName]
            };

            // get list of episodes for series
            List<TraktEpisodeSync.Episode> epList = new List<TraktEpisodeSync.Episode>();

            foreach (DBEpisode ep in episodes.Where(e => e[DBEpisode.cSeriesID] == series[DBSeries.cID]))
            {
                TraktEpisodeSync.Episode episode = new TraktEpisodeSync.Episode();
                episode.SeasonIndex = ep[DBOnlineEpisode.cSeasonIndex];
                episode.EpisodeIndex = ep[DBOnlineEpisode.cEpisodeIndex];
                epList.Add(episode);
            }

            traktSync.EpisodeList = epList;
            return traktSync;
        }
Ejemplo n.º 52
0
 private bool ShowMatch(DBSeries localShow, TraktShow onlineShow)
 {
     if (onlineShow.Ids.Tvdb != null && onlineShow.Ids.Tvdb > 0)
     {
         return localShow[DBSeries.cID] == onlineShow.Ids.Tvdb;
     }
     else if (BasicHandler.IsValidImdb(onlineShow.Ids.Imdb) && BasicHandler.IsValidImdb(localShow[DBOnlineSeries.cIMDBID]))
     {
         return localShow[DBOnlineSeries.cIMDBID] == onlineShow.Ids.Imdb;
     }
     else
     {
         return BasicHandler.IsTitleMatch(localShow[DBOnlineSeries.cOriginalName], onlineShow.Title, onlineShow.Year) &&
                localShow.Year.ToNullableInt32() == onlineShow.Year;
     }
 }
Ejemplo n.º 53
0
        private void RateSeries(DBSeries series)
        {
            Thread rateThread = new Thread(delegate()
            {
                TraktLogger.Info("Recieved rate series event from tvseries");

                TraktRateSeries seriesRateData = CreateSeriesRateData(series);
                if (seriesRateData == null) return;
                TraktRateResponse response = TraktAPI.TraktAPI.RateSeries(seriesRateData);

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

            rateThread.Start();
        }
Ejemplo n.º 54
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;
     }
 }
Ejemplo n.º 55
0
        public void addHierarchyConditions(ref int stepIndex, ref string[] currentStepSelection, ref SQLCondition conditions)
        {
            logicalViewStep step = m_steps[stepIndex];

            conditions = step.conds.Copy(); // important, don't change the steps themselves

            // we need to add one additional condition to reflect the selection one hierarchy up
            if (currentStepSelection != null && currentStepSelection.Length > 0 && stepIndex > 0)
            {
                switch (m_steps[stepIndex - 1].Type)
                {
                case logicalViewStep.type.group:
                    bool requiresSplit = false;     // use sql 'like' for split fields

                    // selected group label
                    string selectedItem = currentStepSelection[0];

                    // we expect to get the selected group's label
                    // unknown really is "" so get all with null values here
                    if (selectedItem == Translation.Unknown)
                    {
                        selectedItem = string.Empty;
                    }
                    else
                    if (m_steps[stepIndex - 1].groupedBy.attempSplit)
                    {
                        requiresSplit = true;
                    }

                    string fieldName     = m_steps[stepIndex - 1].groupedBy.rawFieldname;
                    string tableName     = m_steps[stepIndex - 1].groupedBy.table.m_tableName;
                    string tableField    = tableName + "." + fieldName;
                    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, fieldName + DBTable.cUserEditPostFix))
                    {
                        sql = "(case when (" + userEditField + " is null or " + userEditField + " = " + "'" + "'" + ") " +
                              "then " + tableField + " else " + userEditField + " " +
                              "end) " + value;
                    }
                    else
                    {
                        sql = tableField + " " + value;
                    }

                    conditions.AddCustom(sql);
                    break;

                case logicalViewStep.type.series:
                    // we expect to get the seriesID as stepSel
                    conditions.Add(new DBSeason(), DBSeason.cSeriesID, currentStepSelection[0], SQLConditionType.Equal);
                    if (DBOption.GetOptions(DBOption.cSortSpecialSeasonLast))
                    {
                        conditions.InsertOrderItem(DBSeason.cTableName + "." + DBSeason.cIndex + " = 0", SQLCondition.orderType.Ascending);
                    }
                    break;

                case logicalViewStep.type.season:
                    // we expect to get the seriesID/seasonIndex as stepSel

                    // we want to query episodes using the CombinedSeason if Sort Order is "DVD"
                    // CombinedSeason gives us the DVD Season and if empty will give us the Aired Season
                    DBSeries series      = Helper.getCorrespondingSeries(int.Parse(currentStepSelection[0]));
                    bool     SortByDVD   = series[DBOnlineSeries.cEpisodeSortOrder] == "DVD";
                    string   seasonIndex = SortByDVD ? DBOnlineEpisode.cCombinedSeason : DBOnlineEpisode.cSeasonIndex;

                    conditions.Add(new DBOnlineEpisode(), DBOnlineEpisode.cSeriesID, currentStepSelection[0], SQLConditionType.Equal);
                    conditions.beginGroup();
                    conditions.Add(new DBOnlineEpisode(), seasonIndex, currentStepSelection[1], SQLConditionType.Equal);
                    if (DBOption.GetOptions(DBOption.cSortSpecials) && !SortByDVD)
                    {
                        conditions.nextIsOr = true;
                        conditions.Add(new DBOnlineEpisode(), DBOnlineEpisode.cAirsBeforeSeason, currentStepSelection[1], SQLConditionType.Equal);
                        conditions.Add(new DBOnlineEpisode(), DBOnlineEpisode.cAirsAfterSeason, currentStepSelection[1], SQLConditionType.Equal);
                        conditions.nextIsOr = false;
                    }
                    conditions.endGroup();
                    break;
                }
            }
        }
Ejemplo n.º 56
0
        private void RateShow(DBSeries show)
        {
            var rateThread = new Thread((objShow) =>
            {
                if (show[DBOnlineSeries.cTraktIgnore]) return;

                var rateShow = objShow as DBSeries;
                if (rateShow == null) return;

                TraktLogger.Info("Received a Rate Show event from tvseries. Show Title = '{0}', Show Year = '{1}', Show TVDb ID = '{2}'", show[DBOnlineSeries.cOriginalName], show.Year, show[DBSeries.cID]);

                var showRateData = new TraktSyncShowRated
                {
                    Ids = new TraktShowId
                    {
                        Tvdb = show[DBSeries.cID],
                        Imdb = BasicHandler.GetProperImdbId(show[DBOnlineSeries.cIMDBID])
                    },
                    Title = show[DBOnlineSeries.cOriginalName],
                    Year = show.Year.ToNullableInt32(),
                    Rating = show[DBOnlineSeries.cMyRating],
                    RatedAt = DateTime.UtcNow.ToISO8601()
                };

                // update local cache
                TraktCache.AddShowToRatings(showRateData, showRateData.Rating);

                var response = TraktAPI.TraktAPI.AddShowToRatings(showRateData);
                TraktLogger.LogTraktResponse(response);

                if (response != null && response.NotFound != null && response.NotFound.Shows.Count > 0)
                {
                    TraktCache.RemoveShowFromRatings(showRateData);
                }
            })
            {
                IsBackground = true,
                Name = "Rate"
            };

            rateThread.Start(show);
        }
Ejemplo n.º 57
0
        private void ShowEpisodeSortByMenu(DBSeries series, bool ChangeMatchingOrder)
        {
            IDialogbox dlg = (IDialogbox)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
            if (dlg == null)
                return;

            dlg.Reset();
            if (ChangeMatchingOrder)
                dlg.SetHeading(Translation.ChangeOnlineMatchOrder);
            else
                dlg.SetHeading(Translation.SortBy);

            #region Add Menu items
            GUIListItem pItem = null;

            string currMatchOrder = series[DBOnlineSeries.cChosenEpisodeOrder].ToString();
            if (string.IsNullOrEmpty(currMatchOrder)) currMatchOrder = EpisodeSortByMenuItems.Aired.ToString();

            string currSortOrder = series[DBOnlineSeries.cEpisodeSortOrder].ToString();
            if (string.IsNullOrEmpty(currSortOrder)) currSortOrder = EpisodeSortByMenuItems.Aired.ToString();

            string selection = ChangeMatchingOrder ? currMatchOrder : currSortOrder;

            // For now we will just add sort options for the Aired and DVD Order
            pItem = new GUIListItem(Translation.AiredOrder);
            dlg.Add(pItem);
            pItem.ItemId = (int)EpisodeSortByMenuItems.Aired;
            if (selection == EpisodeSortByMenuItems.Aired.ToString()) pItem.Selected = true;

            if (series[DBOnlineSeries.cEpisodeOrders].ToString().Contains(EpisodeSortByMenuItems.DVD.ToString()))
            {
                pItem = new GUIListItem(Translation.DVDOrder);
                dlg.Add(pItem);
                pItem.ItemId = (int)EpisodeSortByMenuItems.DVD;
                if (selection == EpisodeSortByMenuItems.DVD.ToString()) pItem.Selected = true;
            }

            // TODO: sort by absolute order and just show a single season in GUI...later
            if (series[DBOnlineSeries.cEpisodeOrders].ToString().Contains(EpisodeSortByMenuItems.Absolute.ToString()) && ChangeMatchingOrder)
            {
                pItem = new GUIListItem(Translation.AbsoluteOrder);
                dlg.Add(pItem);
                pItem.ItemId = (int)EpisodeSortByMenuItems.Absolute;
                if (selection == EpisodeSortByMenuItems.Absolute.ToString()) pItem.Selected = true;
            }

            if (ChangeMatchingOrder)
            {
                pItem = new GUIListItem(Translation.Title);
                dlg.Add(pItem);
                pItem.ItemId = (int)EpisodeSortByMenuItems.Title;
                if (selection == EpisodeSortByMenuItems.Title.ToString()) pItem.Selected = true;
            }
            #endregion

            #region Show Menu
            dlg.DoModal(GUIWindowManager.ActiveWindow);
            if (dlg.SelectedId < 0)
                return;

            // if we change matching order then we should also change
            // corresponding sort order
            switch (dlg.SelectedId)
            {
                case (int)EpisodeSortByMenuItems.Aired:
                    if (ChangeMatchingOrder)
                    {
                        series[DBOnlineSeries.cChosenEpisodeOrder] = EpisodeSortByMenuItems.Aired.ToString();
                        ChangeEpisodeMatchingOrder(series, EpisodeSortByMenuItems.Aired.ToString());
                    }
                    series[DBOnlineSeries.cEpisodeSortOrder] = EpisodeSortByMenuItems.Aired.ToString();
                    break;
                case (int)EpisodeSortByMenuItems.DVD:
                    if (ChangeMatchingOrder)
                    {
                        series[DBOnlineSeries.cChosenEpisodeOrder] = EpisodeSortByMenuItems.DVD.ToString();
                        ChangeEpisodeMatchingOrder(series, EpisodeSortByMenuItems.DVD.ToString());
                    }
                    series[DBOnlineSeries.cEpisodeSortOrder] = EpisodeSortByMenuItems.DVD.ToString();
                    break;
                case (int)EpisodeSortByMenuItems.Absolute:
                    if (ChangeMatchingOrder)
                    {
                        series[DBOnlineSeries.cChosenEpisodeOrder] = EpisodeSortByMenuItems.Absolute.ToString();
                        ChangeEpisodeMatchingOrder(series, EpisodeSortByMenuItems.Absolute.ToString());
                    }
                    break;
                case (int)EpisodeSortByMenuItems.Title:
                    series[DBOnlineSeries.cChosenEpisodeOrder] = EpisodeSortByMenuItems.Title.ToString();
                    ChangeEpisodeMatchingOrder(series, EpisodeSortByMenuItems.Title.ToString());
                    break;
            }
            #endregion

            // commit selection
            series.Commit();

            // re-calculate episode counts for each season as they can differ
            // with different sort orders
            if (!ChangeMatchingOrder)
            {
                DBSeries.UpdateEpisodeCounts(series);
            }

            // Re-load the facade to re-sort episodes
            LoadFacade();
        }
Ejemplo n.º 58
0
        private void CycleSeriesPoster(DBSeries series, bool next)
        {
            if (series.PosterList.Count <= 1) return;

            int nCurrent = series.PosterList.IndexOf(series.Poster);

            if (next)
            {
                nCurrent++;
                if (nCurrent >= series.PosterList.Count)
                    nCurrent = 0;
            }
            else
            {
                nCurrent--;
                if (nCurrent < 0)
                    nCurrent = series.PosterList.Count - 1;
            }

            series.Poster = series.PosterList[nCurrent];
            series.Commit();

            // No need to re-load the facade for non-graphical layouts
            if (m_Facade.CurrentLayout == GUIFacadeControl.Layout.List)
                seriesposter.Filename = ImageAllocator.GetSeriesPosterAsFilename(series);
            else
                LoadFacade();
        }
Ejemplo n.º 59
0
        public static logicalViewStep parseFromDB(string viewStep, bool hasSeriesBeforeIt)
        {
            logicalViewStep thisView = new logicalViewStep();

            thisView.hasSeriesBeforeIt = hasSeriesBeforeIt;
            string[] viewSteps = System.Text.RegularExpressions.Regex.Split(viewStep, s_intSeperator);
            thisView.setType(viewSteps[0]);
            thisView.addConditionsFromString(viewSteps[1]);
            if (viewSteps[2].Length > 0)
            {
                string[] orderFields = System.Text.RegularExpressions.Regex.Split(viewSteps[2], ";");
                thisView.inLineSpecials    = orderFields[0] == "<Episode.EpisodeIndex>";
                thisView.inLineSpecialsAsc = orderFields[0] != "desc";
                for (int i = 0; i < orderFields.Length; i += 2)
                {
                    if (thisView.Type != type.group)
                    {
                        DBTable table      = null;
                        string  tableField = string.Empty;
                        getTableFieldname(orderFields[i], out table, out tableField);
                        tableField = getQTableNameFromUnknownType(table, tableField);

                        // example of how the user can order by a different table
                        // needs to be enabled once definable views are ready

                        /*
                         * if (thisView.Type == type.season && table.GetType() != typeof(DBSeason))
                         * {
                         *  Type lType = table.GetType();
                         *  if (lType == typeof(DBOnlineSeries))
                         *      tableField = "( select " + tableField + " from " + DBOnlineSeries.cTableName
                         + " where " + DBOnlineSeries.Q(DBOnlineSeries.cID) + " = " + DBSeason.Q(DBSeason.cSeriesID) + ")";
                         + }*/

                        //if (thisView.Type == type.episode && ( table.GetType() == typeof(DBEpisode) || table.GetType() == typeof(DBOnlineEpisode)))
                        //{
                        //    // for perf reason a subquery is build, otherwise custom orders and the nessesary join really slow down sqllite!
                        //    SQLCondition subQueryConditions = thisView.conds.Copy(); // have to have all conds too
                        //    subQueryConditions.AddOrderItem(tableField, (orderFields[i + 1] == "asc" ? SQLCondition.orderType.Ascending : SQLCondition.orderType.Descending));
                        //    if (viewSteps[3].Length > 0) // set the limit too
                        //    {
                        //        try
                        //        {
                        //            subQueryConditions.SetLimit(System.Convert.ToInt32(viewSteps[3]));
                        //        }
                        //        catch (Exception)
                        //        {
                        //        }
                        //    }
                        //    thisView.conds.AddSubQuery("compositeid", table, subQueryConditions, table.m_tableName + "." + DBEpisode.cCompositeID, SQLConditionType.In);

                        //}

                        thisView.conds.AddOrderItem(tableField, (orderFields[i + 1] == "asc" ? SQLCondition.orderType.Ascending : SQLCondition.orderType.Descending));
                    }
                }
            }
            if (thisView.Type == type.group && thisView.groupedBy != null) // for groups always by their values (ignore user setting!)
            {
                if (thisView.groupedBy.table.GetType() == typeof(DBSeries))
                {
                    if (!DBOption.GetOptions(DBOption.cShowHiddenItems))
                    {
                        thisView.conds.Add(new DBSeries(), DBSeries.cHidden, 1, SQLConditionType.NotEqual);
                    }
                }
                else if (thisView.groupedBy.table.GetType() == typeof(DBOnlineSeries))
                {
                    if (!DBOption.GetOptions(DBOption.cShowHiddenItems))
                    {
                        thisView.conds.AddCustom(" not exists ( select * from " + DBSeries.cTableName + " where id = " + DBOnlineSeries.Q(DBOnlineSeries.cID) + " and " + DBSeries.Q(DBSeries.cHidden) + " = 1)");
                    }
                }
                else if (thisView.groupedBy.table.GetType() == typeof(DBSeason))
                {
                    if (!DBOption.GetOptions(DBOption.cShowHiddenItems))
                    {
                        thisView.conds.Add(new DBSeason(), DBSeason.cHidden, 1, SQLConditionType.NotEqual);
                    }
                }
                thisView.conds.AddOrderItem(thisView.groupedBy.tableField, SQLCondition.orderType.Descending); // tablefield includes tablename itself!
            }
            try
            {
                if (viewSteps[3].Length > 0)
                {
                    thisView.limitItems = System.Convert.ToInt32(viewSteps[3]);
                    thisView.conds.SetLimit(thisView.limitItems);
                }
            }
            catch (Exception)
            {
                MPTVSeriesLog.Write("Cannot interpret limit in logicalview, limit was: " + viewSteps[3]);
            }
            return(thisView);
        }
Ejemplo n.º 60
0
        private void ShowViewTagsMenu(bool add, DBSeries series)
        {
            IDialogbox dlg = (IDialogbox)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
            if (dlg == null)
                return;

            dlg.Reset();
            string sDialogHeading = (add ? Translation.AddViewTag : Translation.RemoveViewTag);
            dlg.SetHeading(sDialogHeading);

            GUIListItem pItem = null;
            DBView[] views = DBView.getTaggedViews();

            string currTags = series[DBOnlineSeries.cViewTags];
            String[] splitTags = currTags.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

            // Add Menu items
            if (add)
            {
                // List available tag views
                foreach (DBView view in views)
                {
                    string viewname = view[DBView.cTransToken];
                    // We dont want to add it to the list if its already a member
                    if (!currTags.Contains("|" + viewname + "|"))
                    {
                        pItem = new GUIListItem(viewname);
                        dlg.Add(pItem);
                        pItem.ItemId = view[DBView.cIndex];
                    }
                }

                pItem = new GUIListItem(Translation.NewViewTag + " ...");
                dlg.Add(pItem);
                pItem.ItemId = (int)eContextItems.viewAddToNewView;
            }
            else
            {
                // we list all the tags that current series is a member of
                int iItemIdx = 1000;
                foreach (String tag in splitTags)
                {
                    pItem = new GUIListItem(tag);
                    dlg.Add(pItem);
                    pItem.ItemId = iItemIdx++;
                }
            }

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

            #region Add a New Tagged View
            string selectedItem = string.Empty;
            if (dlg.SelectedId == (int)eContextItems.viewAddToNewView)
            {
                GetStringFromUserDescriptor Keyboard = new GetStringFromUserDescriptor();
                Keyboard.Text = string.Empty;
                Keyboard.ShiftEnabled = true;
                bool viewExists = true;

                while (viewExists)
                {
                    if (this.GetStringFromUser(Keyboard, out selectedItem) == ReturnCode.OK)
                    {
                        // Create View if it doesnt exist
                        viewExists = false;
                        foreach (DBView view in views)
                        {
                            if (selectedItem.Equals(view[DBView.cTransToken], StringComparison.CurrentCultureIgnoreCase))
                            {
                                ShowViewExistsMessage(selectedItem);
                                viewExists = true;
                                break;
                            }
                        }
                    }
                    else
                        return;
                }
                if (selectedItem.Length == 0)
                    return;

                // Add New View to database
                // Ensure index is unique...assumes index is updated when deleting views
                int index = logicalView.getAll(true).Count;
                string config = DBView.GetTaggedViewConfigString(selectedItem);

                MPTVSeriesLog.Write(string.Format("Creating New Tagged View: {0}", selectedItem));
                DBView.AddView(index, selectedItem, selectedItem, config, true);
            }
            #endregion

            string newTags = string.Empty;

            // Get Selected Item if not a new Tag
            if (dlg.SelectedId != (int)eContextItems.viewAddToNewView)
                selectedItem = dlg.SelectedLabelText;

            // Add / Remove Tag from series
            if (add)
            {
                MPTVSeriesLog.Write(string.Format("Adding new Tag \"{0}\" to series: {1}", selectedItem, series.ToString()));
                newTags = Helper.GetSeriesViewTags(series, true, selectedItem);
            }
            else
            {
                MPTVSeriesLog.Write(string.Format("Removing Tag \"{0}\" from series: {1}", selectedItem, series.ToString()));
                newTags = Helper.GetSeriesViewTags(series, false, selectedItem);
            }

            // Update Main View List
            m_allViews = logicalView.getAll(false);

            // Commit changes to database
            series[DBOnlineSeries.cViewTags] = newTags;
            series.Commit();

            // Special case to handle online favourites
            // We need to add/remove from online database
            if (selectedItem == DBView.cTranslateTokenOnlineFavourite)
            {
                string account = DBOption.GetOptions(DBOption.cOnlineUserID);
                if (String.IsNullOrEmpty(account))
                {
                    GUIDialogOK dlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK);
                    dlgOK.SetHeading(Translation.OnlineFavourites);
                    dlgOK.SetLine(1, Translation.TVDB_INFO_ACCOUNTID_1);
                    dlgOK.SetLine(2, Translation.TVDB_INFO_ACCOUNTID_2);
                    dlgOK.DoModal(GUIWindowManager.ActiveWindow);
                    MPTVSeriesLog.Write("Cannot submit online favourite, make sure you have your Account identifier set!");
                }
                else
                {
                    Online_Parsing_Classes.OnlineAPI.ConfigureFavourites(add, account, series[DBOnlineSeries.cID]);
                }
            }

            // Load Facade to reflect changes
            // We only need to reload when removing from a View that is active
            if (!add)
            {
                if (m_CurrLView.Name.Equals(selectedItem, StringComparison.CurrentCultureIgnoreCase) ||
                    m_CurrLView.gettypeOfStep(0) == logicalViewStep.type.group)
                    LoadFacade();
            }
        }