/// <summary> /// Used to get a list of TvDB Series ID's that require updating /// </summary> /// <param name="tvDBIDs">The list Of Series ID's that need to be updated. Pass in an empty list</param> /// <returns>The current server time before the update started</returns> public string IncrementalTvDBUpdate(ref List<int> tvDBIDs, ref bool tvDBOnline) { // check if we have record of doing an automated update for the TvDB previously // if we have then we have kept a record of the server time and can do a delta update // otherwise we need to do a full update and keep a record of the time List<int> allTvDBIDs = new List<int>(); tvDBIDs = new List<int>(); tvDBOnline = true; try { CrossRef_AniDB_TvDBRepository repCrossRef = new CrossRef_AniDB_TvDBRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); // record the tvdb server time when we started // we record the time now instead of after we finish, to include any possible misses string currentTvDBServerTime = CurrentServerTime; if (currentTvDBServerTime.Length == 0) { tvDBOnline = false; return currentTvDBServerTime; } foreach (AnimeSeries ser in repSeries.GetAll()) { List<CrossRef_AniDB_TvDBV2> xrefs = ser.GetCrossRefTvDBV2(); if (xrefs == null) continue; foreach (CrossRef_AniDB_TvDBV2 xref in xrefs) { if (!allTvDBIDs.Contains(xref.TvDBID)) allTvDBIDs.Add(xref.TvDBID); } } // get the time we last did a TvDB update // if this is the first time it will be null // update the anidb info ever 24 hours ScheduledUpdateRepository repSched = new ScheduledUpdateRepository(); ScheduledUpdate sched = repSched.GetByUpdateType((int)ScheduledUpdateType.TvDBInfo); string lastServerTime = ""; if (sched != null) { TimeSpan ts = DateTime.Now - sched.LastUpdate; logger.Trace("Last tvdb info update was {0} hours ago", ts.TotalHours.ToString()); if (!string.IsNullOrEmpty(sched.UpdateDetails)) lastServerTime = sched.UpdateDetails; // the UpdateDetails field for this type will actually contain the last server time from // TheTvDB that a full update was performed } // get a list of updates from TvDB since that time if (lastServerTime.Length > 0) { List<int> seriesList = GetUpdatedSeriesList(lastServerTime); logger.Trace("{0} series have been updated since last download", seriesList.Count.ToString()); logger.Trace("{0} TvDB series locally", allTvDBIDs.Count.ToString()); foreach (int id in seriesList) { if (allTvDBIDs.Contains(id)) tvDBIDs.Add(id); } logger.Trace("{0} TvDB local series have been updated since last download", tvDBIDs.Count.ToString()); } else { // use the full list tvDBIDs = allTvDBIDs; } return currentTvDBServerTime; } catch (Exception ex) { logger.ErrorException("IncrementalTvDBUpdate: "+ ex.ToString(), ex); return ""; } }
public static void ScanForMatches() { AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); List<AnimeSeries> allSeries = repSeries.GetAll(); CrossRef_AniDB_OtherRepository repCrossRef = new CrossRef_AniDB_OtherRepository(); foreach (AnimeSeries ser in allSeries) { AniDB_Anime anime = ser.GetAnime(); if (anime == null) continue; if (anime.IsMovieDBLinkDisabled) continue; // don't scan if it is associated on the TvDB if (anime.GetCrossRefTvDBV2().Count > 0) continue; // don't scan if it is associated on the MovieDB if (anime.GetCrossRefMovieDB() != null) continue; // don't scan if it is not a movie if (!anime.SearchOnMovieDB) continue; logger.Trace("Found anime movie without MovieDB association: " + anime.MainTitle); CommandRequest_MovieDBSearchAnime cmd = new CommandRequest_MovieDBSearchAnime(ser.AniDB_ID, false); cmd.Save(); } }
public static void ScanForMatches() { AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); List<AnimeSeries> allSeries = repSeries.GetAll(); CrossRef_AniDB_TvDBV2Repository repCrossRef = new CrossRef_AniDB_TvDBV2Repository(); List<CrossRef_AniDB_TvDBV2> allCrossRefs = repCrossRef.GetAll(); List<int> alreadyLinked = new List<int>(); foreach (CrossRef_AniDB_TvDBV2 xref in allCrossRefs) { alreadyLinked.Add(xref.AnimeID); } foreach (AnimeSeries ser in allSeries) { if (alreadyLinked.Contains(ser.AniDB_ID)) continue; AniDB_Anime anime = ser.GetAnime(); if (anime!= null) { logger.Trace("Found anime without tvDB association: " + anime.MainTitle); if (!anime.SearchOnTvDB) continue; if (anime.IsTvDBLinkDisabled) { logger.Trace("Skipping scan tvDB link because it is disabled: " + anime.MainTitle); continue; } } CommandRequest_TvDBSearchAnime cmd = new CommandRequest_TvDBSearchAnime(ser.AniDB_ID, false); cmd.Save(); } }
public void RecreateAllGroups() { try { // pause queues JMMService.CmdProcessorGeneral.Paused = true; JMMService.CmdProcessorHasher.Paused = true; JMMService.CmdProcessorImages.Paused = true; AnimeGroupRepository repGroups = new AnimeGroupRepository(); AnimeGroup_UserRepository repGroupUser = new AnimeGroup_UserRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); // get all the old groups List<AnimeGroup> oldGroups = repGroups.GetAll(); List<AnimeGroup_User> oldGroupUsers = repGroupUser.GetAll(); // create a new group, where we will place all the series temporarily AnimeGroup tempGroup = new AnimeGroup(); tempGroup.GroupName = "AAA Migrating Groups AAA"; tempGroup.Description = "AAA Migrating Groups AAA"; tempGroup.SortName = "AAA Migrating Groups AAA"; tempGroup.DateTimeUpdated = DateTime.Now; tempGroup.DateTimeCreated = DateTime.Now; repGroups.Save(tempGroup); // move all series to the new group foreach (AnimeSeries ser in repSeries.GetAll()) { ser.AnimeGroupID = tempGroup.AnimeGroupID; repSeries.Save(ser, false); } // delete all the old groups foreach (AnimeGroup grp in oldGroups) repGroups.Delete(grp.AnimeGroupID); // delete all the old group user records foreach (AnimeGroup_User grpUser in oldGroupUsers) repGroupUser.Delete(grpUser.AnimeGroupID); // recreate groups foreach (AnimeSeries ser in repSeries.GetAll()) { bool createNewGroup = true; if (ServerSettings.AutoGroupSeries) { List<AnimeGroup> grps = AnimeGroup.GetRelatedGroupsFromAnimeID(ser.AniDB_ID); // only use if there is just one result if (grps != null && grps.Count > 0 && !grps[0].GroupName.Equals("AAA Migrating Groups AAA")) { ser.AnimeGroupID = grps[0].AnimeGroupID; createNewGroup = false; } } if (createNewGroup) { AnimeGroup anGroup = new AnimeGroup(); anGroup.Populate(ser); repGroups.Save(anGroup); ser.AnimeGroupID = anGroup.AnimeGroupID; } repSeries.Save(ser, false); } // delete the temp group if (tempGroup.GetAllSeries().Count == 0) repGroups.Delete(tempGroup.AnimeGroupID); // create group user records and update group stats foreach (AnimeGroup grp in repGroups.GetAll()) grp.UpdateStatsFromTopLevel(true, true); // un-pause queues JMMService.CmdProcessorGeneral.Paused = false; JMMService.CmdProcessorHasher.Paused = false; JMMService.CmdProcessorImages.Paused = false; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } }
public string SaveUser(Contract_JMMUser user) { JMMUserRepository repUsers = new JMMUserRepository(); try { bool existingUser = false; bool updateStats = false; JMMUser jmmUser = null; if (user.JMMUserID.HasValue) { jmmUser = repUsers.GetByID(user.JMMUserID.Value); if (jmmUser == null) return "User not found"; existingUser = true; } else { jmmUser = new JMMUser(); updateStats = true; } if (existingUser && jmmUser.IsAniDBUser != user.IsAniDBUser) updateStats = true; jmmUser.HideCategories = user.HideCategories; jmmUser.IsAniDBUser = user.IsAniDBUser; jmmUser.IsTraktUser = user.IsTraktUser; jmmUser.IsAdmin = user.IsAdmin; jmmUser.Username = user.Username; jmmUser.CanEditServerSettings = user.CanEditServerSettings; jmmUser.PlexUsers = user.PlexUsers; if (string.IsNullOrEmpty(user.Password)) jmmUser.Password = ""; // make sure that at least one user is an admin if (jmmUser.IsAdmin == 0) { bool adminExists = false; List<JMMUser> users = repUsers.GetAll(); foreach (JMMUser userOld in users) { if (userOld.IsAdmin == 1) { if (existingUser) { if (userOld.JMMUserID != jmmUser.JMMUserID) adminExists = true; } else adminExists = true; } } if (!adminExists) return "At least one user must be an administrator"; } repUsers.Save(jmmUser); // update stats if (updateStats) { AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); foreach (AnimeSeries ser in repSeries.GetAll()) ser.QueueUpdateStats(); } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); return ex.Message; } return ""; }
public static void ScanForMatches() { if (string.IsNullOrEmpty(ServerSettings.MAL_Username) || string.IsNullOrEmpty(ServerSettings.MAL_Password)) { logger.Warn("Won't SCAN MAL, MAL credentials not provided"); return; } AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); List<AnimeSeries> allSeries = repSeries.GetAll(); CrossRef_AniDB_MALRepository repCrossRef = new CrossRef_AniDB_MALRepository(); foreach (AnimeSeries ser in allSeries) { AniDB_Anime anime = ser.GetAnime(); if (anime == null) continue; if (anime.IsMALLinkDisabled) continue; // don't scan if it is associated on the TvDB List<CrossRef_AniDB_MAL> xrefs = anime.GetCrossRefMAL(); if (xrefs == null || xrefs.Count == 0) { logger.Trace(string.Format("Found anime without MAL association: {0} ({1})", anime.AnimeID, anime.MainTitle)); CommandRequest_MALSearchAnime cmd = new CommandRequest_MALSearchAnime(ser.AniDB_ID, false); cmd.Save(); } } }
public List<Contract_AnimeSeries> GetSeriesWithoutAnyFiles(int userID) { List<Contract_AnimeSeries> contracts = new List<Contract_AnimeSeries>(); VideoLocalRepository repVids = new VideoLocalRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); try { foreach (AnimeSeries ser in repSeries.GetAll()) { if (repVids.GetByAniDBAnimeID(ser.AniDB_ID).Count == 0) { contracts.Add(ser.ToContract(ser.GetUserRecord(userID))); } } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return contracts; }
public List<Contract_AnimeGroup> GetAnimeGroupsForFilter(int groupFilterID, int userID, bool getSingleSeriesGroups) { List<Contract_AnimeGroup> retGroups = new List<Contract_AnimeGroup>(); try { using (var session = JMMService.SessionFactory.OpenSession()) { DateTime start = DateTime.Now; GroupFilterRepository repGF = new GroupFilterRepository(); JMMUserRepository repUsers = new JMMUserRepository(); JMMUser user = repUsers.GetByID(session, userID); if (user == null) return retGroups; GroupFilter gf = null; if (groupFilterID == -999) { // all groups gf = new GroupFilter(); gf.GroupFilterName = "All"; } else { gf = repGF.GetByID(session, groupFilterID); if (gf == null) return retGroups; } //Contract_GroupFilterExtended contract = gf.ToContractExtended(user); AnimeGroupRepository repGroups = new AnimeGroupRepository(); List<AnimeGroup> allGrps = repGroups.GetAll(session); AnimeGroup_UserRepository repUserRecords = new AnimeGroup_UserRepository(); List<AnimeGroup_User> userRecords = repUserRecords.GetByUserID(session, userID); Dictionary<int, AnimeGroup_User> dictUserRecords = new Dictionary<int, AnimeGroup_User>(); foreach (AnimeGroup_User userRec in userRecords) dictUserRecords[userRec.AnimeGroupID] = userRec; TimeSpan ts = DateTime.Now - start; string msg = string.Format("Got groups for filter DB: {0} - {1} in {2} ms", gf.GroupFilterName, allGrps.Count, ts.TotalMilliseconds); logger.Info(msg); start = DateTime.Now; AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); List<AnimeSeries> allSeries = new List<AnimeSeries>(); if (getSingleSeriesGroups) allSeries = repSeries.GetAll(session); if ((StatsCache.Instance.StatUserGroupFilter.ContainsKey(user.JMMUserID)) && (StatsCache.Instance.StatUserGroupFilter[user.JMMUserID].ContainsKey(gf.GroupFilterID))) { HashSet<int> groups = StatsCache.Instance.StatUserGroupFilter[user.JMMUserID][gf.GroupFilterID]; foreach (AnimeGroup grp in allGrps) { AnimeGroup_User userRec = null; if (dictUserRecords.ContainsKey(grp.AnimeGroupID)) userRec = dictUserRecords[grp.AnimeGroupID]; if (groups.Contains(grp.AnimeGroupID)) { Contract_AnimeGroup contractGrp = grp.ToContract(userRec); if (getSingleSeriesGroups) { if (contractGrp.Stat_SeriesCount == 1) { AnimeSeries ser = GetSeriesForGroup(grp.AnimeGroupID, allSeries); if (ser != null) contractGrp.SeriesForNameOverride = ser.ToContract(ser.GetUserRecord(session, userID)); } } retGroups.Add(contractGrp); } } } ts = DateTime.Now - start; msg = string.Format("Got groups for filter EVAL: {0} - {1} in {2} ms", gf.GroupFilterName, retGroups.Count, ts.TotalMilliseconds); logger.Info(msg); return retGroups; } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return retGroups; }
public List<Contract_AnimeRating> GetAnimeRatings(int collectionState, int watchedState, int ratingVotedState, int userID) { List<Contract_AnimeRating> contracts = new List<Contract_AnimeRating>(); try { AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); List<AnimeSeries> series = repSeries.GetAll(); Dictionary<int, AnimeSeries> dictSeries = new Dictionary<int, AnimeSeries>(); foreach (AnimeSeries ser in series) dictSeries[ser.AniDB_ID] = ser; RatingCollectionState _collectionState = (RatingCollectionState)collectionState; RatingWatchedState _watchedState = (RatingWatchedState)watchedState; RatingVotedState _ratingVotedState = (RatingVotedState)ratingVotedState; DateTime start = DateTime.Now; AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); /* // build a dictionary of categories AniDB_CategoryRepository repCats = new AniDB_CategoryRepository(); AniDB_Anime_CategoryRepository repAnimeCat = new AniDB_Anime_CategoryRepository(); List<AniDB_Category> allCatgeories = repCats.GetAll(); Dictionary<int, AniDB_Category> allCatgeoriesDict = new Dictionary<int, AniDB_Category>(); foreach (AniDB_Category cat in allCatgeories) allCatgeoriesDict[cat.CategoryID] = cat; List<AniDB_Anime_Category> allAnimeCatgeories = repAnimeCat.GetAll(); Dictionary<int, List<AniDB_Anime_Category>> allAnimeCatgeoriesDict = new Dictionary<int, List<AniDB_Anime_Category>>(); // foreach (AniDB_Anime_Category aniCat in allAnimeCatgeories) { if (!allAnimeCatgeoriesDict.ContainsKey(aniCat.AnimeID)) allAnimeCatgeoriesDict[aniCat.AnimeID] = new List<AniDB_Anime_Category>(); allAnimeCatgeoriesDict[aniCat.AnimeID].Add(aniCat); } // build a dictionary of titles AniDB_Anime_TitleRepository repTitles = new AniDB_Anime_TitleRepository(); List<AniDB_Anime_Title> allTitles = repTitles.GetAll(); Dictionary<int, List<AniDB_Anime_Title>> allTitlesDict = new Dictionary<int, List<AniDB_Anime_Title>>(); foreach (AniDB_Anime_Title title in allTitles) { if (!allTitlesDict.ContainsKey(title.AnimeID)) allTitlesDict[title.AnimeID] = new List<AniDB_Anime_Title>(); allTitlesDict[title.AnimeID].Add(title); } // build a dictionary of tags AniDB_TagRepository repTags = new AniDB_TagRepository(); AniDB_Anime_TagRepository repAnimeTag = new AniDB_Anime_TagRepository(); List<AniDB_Tag> allTags = repTags.GetAll(); Dictionary<int, AniDB_Tag> allTagsDict = new Dictionary<int, AniDB_Tag>(); foreach (AniDB_Tag tag in allTags) allTagsDict[tag.TagID] = tag; List<AniDB_Anime_Tag> allAnimeTags = repAnimeTag.GetAll(); Dictionary<int, List<AniDB_Anime_Tag>> allAnimeTagsDict = new Dictionary<int, List<AniDB_Anime_Tag>>(); // foreach (AniDB_Anime_Tag aniTag in allAnimeTags) { if (!allAnimeTagsDict.ContainsKey(aniTag.AnimeID)) allAnimeTagsDict[aniTag.AnimeID] = new List<AniDB_Anime_Tag>(); allAnimeTagsDict[aniTag.AnimeID].Add(aniTag); } // build a dictionary of languages AdhocRepository rep = new AdhocRepository(); Dictionary<int, LanguageStat> dictAudioStats = rep.GetAudioLanguageStatsForAnime(); Dictionary<int, LanguageStat> dictSubtitleStats = rep.GetSubtitleLanguageStatsForAnime(); Dictionary<int, string> dictAnimeVideoQualStats = rep.GetAllVideoQualityByAnime(); Dictionary<int, AnimeVideoQualityStat> dictAnimeEpisodeVideoQualStats = rep.GetEpisodeVideoQualityStatsByAnime(); * */ List<AniDB_Anime> animes = repAnime.GetAll(); // user votes AniDB_VoteRepository repVotes = new AniDB_VoteRepository(); List<AniDB_Vote> allVotes = repVotes.GetAll(); JMMUserRepository repUsers = new JMMUserRepository(); JMMUser user = repUsers.GetByID(userID); if (user == null) return contracts; int i = 0; foreach (AniDB_Anime anime in animes) { i++; // evaluate collection states if (_collectionState == RatingCollectionState.AllEpisodesInMyCollection) { if (!anime.FinishedAiring) continue; if (!dictSeries.ContainsKey(anime.AnimeID)) continue; if (dictSeries[anime.AnimeID].MissingEpisodeCount > 0) continue; } if (_collectionState == RatingCollectionState.InMyCollection) if (!dictSeries.ContainsKey(anime.AnimeID)) continue; if (_collectionState == RatingCollectionState.NotInMyCollection) if (dictSeries.ContainsKey(anime.AnimeID)) continue; if (!user.AllowedAnime(anime)) continue; // evaluate watched states if (_watchedState == RatingWatchedState.AllEpisodesWatched) { if (!dictSeries.ContainsKey(anime.AnimeID)) continue; AnimeSeries_User userRec = dictSeries[anime.AnimeID].GetUserRecord(userID); if (userRec == null) continue; if (userRec.UnwatchedEpisodeCount > 0) continue; } if (_watchedState == RatingWatchedState.NotWatched) { if (dictSeries.ContainsKey(anime.AnimeID)) { AnimeSeries_User userRec = dictSeries[anime.AnimeID].GetUserRecord(userID); if (userRec != null) { if (userRec.UnwatchedEpisodeCount == 0) continue; } } } // evaluate voted states if (_ratingVotedState == RatingVotedState.Voted) { bool voted = false; foreach (AniDB_Vote vote in allVotes) { if (vote.EntityID == anime.AnimeID && (vote.VoteType == (int)AniDBVoteType.Anime || vote.VoteType == (int)AniDBVoteType.AnimeTemp)) { voted = true; break; } } if (!voted) continue; } if (_ratingVotedState == RatingVotedState.NotVoted) { bool voted = false; foreach (AniDB_Vote vote in allVotes) { if (vote.EntityID == anime.AnimeID && (vote.VoteType == (int)AniDBVoteType.Anime || vote.VoteType == (int)AniDBVoteType.AnimeTemp)) { voted = true; break; } } if (voted) continue; } Contract_AnimeRating contract = new Contract_AnimeRating(); contract.AnimeID = anime.AnimeID; Contract_AniDB_AnimeDetailed contractAnimeDetailed = new Contract_AniDB_AnimeDetailed(); contractAnimeDetailed.AnimeTitles = new List<Contract_AnimeTitle>(); contractAnimeDetailed.Tags = new List<Contract_AnimeTag>(); contractAnimeDetailed.CustomTags = new List<Contract_CustomTag>(); contractAnimeDetailed.UserVote = null; contractAnimeDetailed.AniDBAnime = anime.ToContract(); // get user vote foreach (AniDB_Vote vote in allVotes) { if (vote.EntityID == anime.AnimeID && (vote.VoteType == (int)AniDBVoteType.Anime || vote.VoteType == (int)AniDBVoteType.AnimeTemp)) { contractAnimeDetailed.UserVote = vote.ToContract(); break; } } contract.AnimeDetailed = contractAnimeDetailed; if (dictSeries.ContainsKey(anime.AnimeID)) { contract.AnimeSeries = dictSeries[anime.AnimeID].ToContract(dictSeries[anime.AnimeID].GetUserRecord(userID)); } contracts.Add(contract); } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return contracts; }
public List<Contract_AnimeEpisode> GetAllEpisodesWithMultipleFiles(int userID, bool onlyFinishedSeries, bool ignoreVariations) { List<Contract_AnimeEpisode> eps = new List<Contract_AnimeEpisode>(); try { AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); Dictionary<int, int> dictSeriesAnime = new Dictionary<int, int>(); Dictionary<int, bool> dictAnimeFinishedAiring = new Dictionary<int, bool>(); Dictionary<int, bool> dictSeriesFinishedAiring = new Dictionary<int, bool>(); if (onlyFinishedSeries) { List<AnimeSeries> allSeries = repSeries.GetAll(); foreach (AnimeSeries ser in allSeries) dictSeriesAnime[ser.AnimeSeriesID] = ser.AniDB_ID; List<AniDB_Anime> allAnime = repAnime.GetAll(); foreach (AniDB_Anime anime in allAnime) dictAnimeFinishedAiring[anime.AnimeID] = anime.FinishedAiring; foreach (KeyValuePair<int, int> kvp in dictSeriesAnime) { if (dictAnimeFinishedAiring.ContainsKey(kvp.Value)) dictSeriesFinishedAiring[kvp.Key] = dictAnimeFinishedAiring[kvp.Value]; } } foreach (AnimeEpisode ep in repEps.GetEpisodesWithMultipleFiles(ignoreVariations)) { if (onlyFinishedSeries) { bool finishedAiring = false; if (dictSeriesFinishedAiring.ContainsKey(ep.AnimeSeriesID)) finishedAiring = dictSeriesFinishedAiring[ep.AnimeSeriesID]; if (!finishedAiring) continue; } eps.Add(ep.ToContract(true, userID, null)); } return eps; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); return eps; } }
public List<Contract_AnimeSeries> GetAllSeries(int userID) { AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); AniDB_Anime_TitleRepository repTitles = new AniDB_Anime_TitleRepository(); //TODO: Custom Tags: Do I need to add custom tags for searches // get all the series List<Contract_AnimeSeries> seriesContractList = new List<Contract_AnimeSeries>(); try { DateTime start = DateTime.Now; DateTime start2 = DateTime.Now; List<AnimeSeries> series = repSeries.GetAll(); List<AniDB_Anime> animes = repAnime.GetAll(); Dictionary<int, AniDB_Anime> dictAnimes = new Dictionary<int, AniDB_Anime>(); foreach (AniDB_Anime anime in animes) dictAnimes[anime.AnimeID] = anime; TimeSpan ts2 = DateTime.Now - start2; logger.Info("GetAllSeries:Anime:RawData in {0} ms", ts2.TotalMilliseconds); start2 = DateTime.Now; // tvdb - cross refs CrossRef_AniDB_TvDBV2Repository repCrossRef = new CrossRef_AniDB_TvDBV2Repository(); List<CrossRef_AniDB_TvDBV2> allCrossRefs = repCrossRef.GetAll(); Dictionary<int, List<CrossRef_AniDB_TvDBV2>> dictCrossRefsV2 = new Dictionary<int, List<CrossRef_AniDB_TvDBV2>>(); foreach (CrossRef_AniDB_TvDBV2 xref in allCrossRefs) { if (!dictCrossRefsV2.ContainsKey(xref.AnimeID)) dictCrossRefsV2[xref.AnimeID] = new List<CrossRef_AniDB_TvDBV2>(); dictCrossRefsV2[xref.AnimeID].Add(xref); } ts2 = DateTime.Now - start2; logger.Info("GetAllSeries:TvDB CrossRefs:RawData in {0} ms", ts2.TotalMilliseconds); start2 = DateTime.Now; // tvdb - series info TvDB_SeriesRepository repTvSeries = new TvDB_SeriesRepository(); List<TvDB_Series> allTvSeries = repTvSeries.GetAll(); Dictionary<int, TvDB_Series> dictTvSeries = new Dictionary<int, TvDB_Series>(); foreach (TvDB_Series tvs in allTvSeries) dictTvSeries[tvs.SeriesID] = tvs; ts2 = DateTime.Now - start2; logger.Info("GetAllSeries:TvDB:RawData in {0} ms", ts2.TotalMilliseconds); start2 = DateTime.Now; // moviedb CrossRef_AniDB_OtherRepository repOtherCrossRef = new CrossRef_AniDB_OtherRepository(); List<CrossRef_AniDB_Other> allOtherCrossRefs = repOtherCrossRef.GetAll(); Dictionary<int, CrossRef_AniDB_Other> dictMovieCrossRefs = new Dictionary<int, CrossRef_AniDB_Other>(); foreach (CrossRef_AniDB_Other xref in allOtherCrossRefs) { if (xref.CrossRefType == (int)CrossRefType.MovieDB) dictMovieCrossRefs[xref.AnimeID] = xref; } ts2 = DateTime.Now - start2; logger.Info("GetAllSeries:MovieDB:RawData in {0} ms", ts2.TotalMilliseconds); start2 = DateTime.Now; // MAL CrossRef_AniDB_MALRepository repMALCrossRef = new CrossRef_AniDB_MALRepository(); List<CrossRef_AniDB_MAL> allMALCrossRefs = repMALCrossRef.GetAll(); Dictionary<int, List<CrossRef_AniDB_MAL>> dictMALCrossRefs = new Dictionary<int, List<CrossRef_AniDB_MAL>>(); foreach (CrossRef_AniDB_MAL xref in allMALCrossRefs) { if (!dictMALCrossRefs.ContainsKey(xref.AnimeID)) dictMALCrossRefs[xref.AnimeID] = new List<CrossRef_AniDB_MAL>(); dictMALCrossRefs[xref.AnimeID].Add(xref); } ts2 = DateTime.Now - start2; logger.Info("GetAllSeries:MAL:RawData in {0} ms", ts2.TotalMilliseconds); start2 = DateTime.Now; // user records AnimeSeries_UserRepository repSeriesUser = new AnimeSeries_UserRepository(); List<AnimeSeries_User> userRecordList = repSeriesUser.GetByUserID(userID); Dictionary<int, AnimeSeries_User> dictUserRecords = new Dictionary<int, AnimeSeries_User>(); foreach (AnimeSeries_User serUser in userRecordList) dictUserRecords[serUser.AnimeSeriesID] = serUser; ts2 = DateTime.Now - start2; logger.Info("GetAllSeries:UserRecs:RawData in {0} ms", ts2.TotalMilliseconds); start2 = DateTime.Now; // default images AniDB_Anime_DefaultImageRepository repDefImages = new AniDB_Anime_DefaultImageRepository(); List<AniDB_Anime_DefaultImage> allDefaultImages = repDefImages.GetAll(); ts2 = DateTime.Now - start2; logger.Info("GetAllSeries:DefaultImages:RawData in {0} ms", ts2.TotalMilliseconds); start2 = DateTime.Now; // titles List<AniDB_Anime_Title> allTitles = repTitles.GetAllForLocalSeries(); Dictionary<int, List<AniDB_Anime_Title>> dictTitles = new Dictionary<int, List<AniDB_Anime_Title>>(); foreach (AniDB_Anime_Title atit in allTitles) { if (!dictTitles.ContainsKey(atit.AnimeID)) dictTitles[atit.AnimeID] = new List<AniDB_Anime_Title>(); dictTitles[atit.AnimeID].Add(atit); } ts2 = DateTime.Now - start2; logger.Info("GetAllSeries:Titles:RawData in {0} ms", ts2.TotalMilliseconds); start2 = DateTime.Now; TimeSpan ts = DateTime.Now - start; logger.Info("GetAllSeries:RawData in {0} ms", ts.TotalMilliseconds); Dictionary<int, AniDB_Anime_DefaultImage> dictDefaultsPosters = new Dictionary<int, AniDB_Anime_DefaultImage>(); Dictionary<int, AniDB_Anime_DefaultImage> dictDefaultsFanart = new Dictionary<int, AniDB_Anime_DefaultImage>(); Dictionary<int, AniDB_Anime_DefaultImage> dictDefaultsWideBanner = new Dictionary<int, AniDB_Anime_DefaultImage>(); start = DateTime.Now; foreach (AniDB_Anime_DefaultImage defaultImage in allDefaultImages) { ImageSizeType sizeType = (ImageSizeType)defaultImage.ImageType; if (sizeType == ImageSizeType.Fanart) dictDefaultsFanart[defaultImage.AnimeID] = defaultImage; if (sizeType == ImageSizeType.Poster) dictDefaultsPosters[defaultImage.AnimeID] = defaultImage; if (sizeType == ImageSizeType.WideBanner) dictDefaultsWideBanner[defaultImage.AnimeID] = defaultImage; } foreach (AnimeSeries aser in series) { if (!dictAnimes.ContainsKey(aser.AniDB_ID)) continue; List<CrossRef_AniDB_TvDBV2> xrefs = new List<CrossRef_AniDB_TvDBV2>(); if (dictCrossRefsV2.ContainsKey(aser.AniDB_ID)) xrefs = dictCrossRefsV2[aser.AniDB_ID]; List<TvDB_Series> tvseriesV2 = new List<TvDB_Series>(); if (xrefs != null) { foreach (CrossRef_AniDB_TvDBV2 xref in xrefs) { if (dictTvSeries.ContainsKey(xref.TvDBID)) tvseriesV2.Add(dictTvSeries[xref.TvDBID]); } } CrossRef_AniDB_Other xrefMovie = null; if (dictMovieCrossRefs.ContainsKey(aser.AniDB_ID)) xrefMovie = dictMovieCrossRefs[aser.AniDB_ID]; List<CrossRef_AniDB_MAL> xrefMAL = null; if (dictMALCrossRefs.ContainsKey(aser.AniDB_ID)) xrefMAL = dictMALCrossRefs[aser.AniDB_ID]; MovieDB_Movie movie = null; if (xrefMovie != null) movie = xrefMovie.GetMovieDB_Movie(); AnimeSeries_User userRec = null; if (dictUserRecords.ContainsKey(aser.AnimeSeriesID)) userRec = dictUserRecords[aser.AnimeSeriesID]; List<AniDB_Anime_Title> titles = null; if (dictTitles.ContainsKey(aser.AniDB_ID)) titles = dictTitles[aser.AniDB_ID]; AniDB_Anime_DefaultImage defPoster = null; AniDB_Anime_DefaultImage defFanart = null; AniDB_Anime_DefaultImage defWideBanner = null; if (dictDefaultsPosters.ContainsKey(aser.AniDB_ID)) defPoster = dictDefaultsPosters[aser.AniDB_ID]; if (dictDefaultsFanart.ContainsKey(aser.AniDB_ID)) defFanart = dictDefaultsFanart[aser.AniDB_ID]; if (dictDefaultsWideBanner.ContainsKey(aser.AniDB_ID)) defWideBanner = dictDefaultsWideBanner[aser.AniDB_ID]; seriesContractList.Add(aser.ToContract(dictAnimes[aser.AniDB_ID], xrefs, xrefMovie, userRec, tvseriesV2, xrefMAL, true, defPoster, defFanart, defWideBanner, titles, movie)); } ts = DateTime.Now - start; logger.Info("GetAllSeries:ProcessedData in {0} ms", ts.TotalMilliseconds); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return seriesContractList; }
public void InitStats() { try { DateTime start = DateTime.Now; ClearAllData(); #region Get the data AnimeGroupRepository repGroups = new AnimeGroupRepository(); AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AniDB_CategoryRepository repCats = new AniDB_CategoryRepository(); AniDB_Anime_CategoryRepository repAnimeCat = new AniDB_Anime_CategoryRepository(); AniDB_Anime_TitleRepository repTitles = new AniDB_Anime_TitleRepository(); List<AnimeGroup> allGrps = repGroups.GetAll(); Dictionary<int, AnimeGroup> allGroupsDict = new Dictionary<int, AnimeGroup>(); foreach (AnimeGroup agrp in allGrps) allGroupsDict[agrp.AnimeGroupID] = agrp; TimeSpan ts = DateTime.Now - start; logger.Info("Get All GROUPS (Database) in {0} ms", ts.TotalMilliseconds); // anime start = DateTime.Now; List<AniDB_Anime> allAnime = repAnime.GetAll(); Dictionary<int, AniDB_Anime> allAnimeDict = new Dictionary<int, AniDB_Anime>(); foreach (AniDB_Anime anime in allAnime) allAnimeDict[anime.AnimeID] = anime; ts = DateTime.Now - start; logger.Info("Get All ANIME (Database) in {0} ms", ts.TotalMilliseconds); // categories start = DateTime.Now; List<AniDB_Category> allCatgeories = repCats.GetAll(); Dictionary<int, AniDB_Category> allCatgeoriesDict = new Dictionary<int, AniDB_Category>(); foreach (AniDB_Category cat in allCatgeories) allCatgeoriesDict[cat.CategoryID] = cat; List<AniDB_Anime_Category> allAnimeCatgeories = repAnimeCat.GetAll(); Dictionary<int, List<int>> allAnimeCatgeoriesDict = new Dictionary<int, List<int>>(); // animeid / list of category id's foreach (AniDB_Anime_Category aniCat in allAnimeCatgeories) { if (!allAnimeCatgeoriesDict.ContainsKey(aniCat.AnimeID)) allAnimeCatgeoriesDict[aniCat.AnimeID] = new List<int>(); allAnimeCatgeoriesDict[aniCat.AnimeID].Add(aniCat.CategoryID); } ts = DateTime.Now - start; logger.Info("Get All CATEGORIES (Database) in {0} ms", ts.TotalMilliseconds); // titles start = DateTime.Now; List<AniDB_Anime_Title> allTitles = repTitles.GetAll(); Dictionary<int, List<AniDB_Anime_Title>> allTitlesDict = new Dictionary<int, List<AniDB_Anime_Title>>(); // animeid / list of titles foreach (AniDB_Anime_Title aniTitle in allTitles) { if (!allTitlesDict.ContainsKey(aniTitle.AnimeID)) allTitlesDict[aniTitle.AnimeID] = new List<AniDB_Anime_Title>(); allTitlesDict[aniTitle.AnimeID].Add(aniTitle); } ts = DateTime.Now - start; logger.Info("Get All TITLES (Database) in {0} ms", ts.TotalMilliseconds); // user votes start = DateTime.Now; AniDB_VoteRepository repVotes = new AniDB_VoteRepository(); List<AniDB_Vote> allVotes = repVotes.GetAll(); ts = DateTime.Now - start; logger.Info("Get All VOTES (Database) in {0} ms", ts.TotalMilliseconds); // video quality start = DateTime.Now; AdhocRepository rep = new AdhocRepository(); Dictionary<int, string> allVidQuality = rep.GetAllVideoQualityByGroup(); ts = DateTime.Now - start; logger.Info("Get VIDEO QUALITY STATS (Database) in {0} ms", ts.TotalMilliseconds); // video quality episode stats start = DateTime.Now; Dictionary<int, AnimeVideoQualityStat> dictStats = rep.GetEpisodeVideoQualityStatsByAnime(); ts = DateTime.Now - start; logger.Info("Get VIDEO QUALITY EPISODE STATS (Database) in {0} ms", ts.TotalMilliseconds); // audio and subtitle language stats start = DateTime.Now; Dictionary<int, LanguageStat> dictAudioStats = rep.GetAudioLanguageStatsForAnime(); Dictionary<int, LanguageStat> dictSubtitleStats = rep.GetSubtitleLanguageStatsForAnime(); ts = DateTime.Now - start; logger.Info("Get LANGUAGE STATS (Database) in {0} ms", ts.TotalMilliseconds); start = DateTime.Now; List<AnimeSeries> allSeries = repSeries.GetAll(); ts = DateTime.Now - start; logger.Info("Get All Series (Database) in {0} ms", ts.TotalMilliseconds); // TvDB start = DateTime.Now; CrossRef_AniDB_TvDBV2Repository repCrossRef = new CrossRef_AniDB_TvDBV2Repository(); List<CrossRef_AniDB_TvDBV2> allCrossRefs = repCrossRef.GetAll(); List<int> animeWithTvDBCrossRef = new List<int>(); foreach (CrossRef_AniDB_TvDBV2 xref in allCrossRefs) { if (!animeWithTvDBCrossRef.Contains(xref.AnimeID)) animeWithTvDBCrossRef.Add(xref.AnimeID); } ts = DateTime.Now - start; logger.Info("Get All AniDB->TvDB Cross Refs (Database) in {0} ms", ts.TotalMilliseconds); // MovieDB start = DateTime.Now; CrossRef_AniDB_OtherRepository repOtherCrossRef = new CrossRef_AniDB_OtherRepository(); List<CrossRef_AniDB_Other> allOtherCrossRefs = repOtherCrossRef.GetAll(); List<int> animeWithMovieCrossRef = new List<int>(); foreach (CrossRef_AniDB_Other xref in allOtherCrossRefs) { if (!animeWithMovieCrossRef.Contains(xref.AnimeID) && xref.CrossRefType == (int)CrossRefType.MovieDB) animeWithMovieCrossRef.Add(xref.AnimeID); } ts = DateTime.Now - start; logger.Info("Get All AniDB->MovieDB Cross Refs (Database) in {0} ms", ts.TotalMilliseconds); // MAL start = DateTime.Now; CrossRef_AniDB_MALRepository repMALCrossRef = new CrossRef_AniDB_MALRepository(); List<CrossRef_AniDB_MAL> allMALCrossRefs = repMALCrossRef.GetAll(); List<int> animeWithMALCrossRef = new List<int>(); foreach (CrossRef_AniDB_MAL xref in allMALCrossRefs) { if (!animeWithMALCrossRef.Contains(xref.AnimeID)) animeWithMALCrossRef.Add(xref.AnimeID); } ts = DateTime.Now - start; logger.Info("Get All AniDB->MAL Cross Refs (Database) in {0} ms", ts.TotalMilliseconds); #endregion start = DateTime.Now; var session = JMMService.SessionFactory.OpenSession(); foreach (AnimeGroup ag in allGrps) { // get all the series for this group List<AnimeSeries> seriesForGroup = new List<AnimeSeries>(); GetAnimeSeriesRecursive(ag, ref seriesForGroup, allSeries, allGroupsDict); /* if (ag.AnimeGroupID == 915) { Console.Write(""); } */ DateTime? Stat_AirDate_Min = null; DateTime? Stat_AirDate_Max = null; DateTime? Stat_EndDate = new DateTime(1980, 1, 1); DateTime? Stat_SeriesCreatedDate = null; bool isComplete = false; bool hasFinishedAiring = false; bool isCurrentlyAiring = false; List<int> categoryIDList = new List<int>(); List<string> audioLanguageList = new List<string>(); List<string> subtitleLanguageList = new List<string>(); string Stat_AllTitles = ""; string Stat_AllCategories = ""; string Stat_AllVideoQualityEpisodes = ""; decimal totalVotesPerm = 0, totalVotesTemp = 0, totalVotes = 0; int countVotesPerm = 0, countVotesTemp = 0, countVotes = 0; bool hasTvDB = true; bool hasMAL = true; bool hasMovieDB = true; bool hasMovieDBOrTvDB = true; int seriesCount = 0; int epCount = 0; foreach (AnimeSeries series in seriesForGroup) { seriesCount++; if (allAnimeDict.ContainsKey(series.AniDB_ID)) { AniDB_Anime thisAnime = allAnimeDict[series.AniDB_ID]; epCount = epCount + thisAnime.EpisodeCountNormal; // All Video Quality Episodes // Try to determine if this anime has all the episodes available at a certain video quality // e.g. the series has all episodes in blu-ray if (dictStats.ContainsKey(series.AniDB_ID)) { if (series.AniDB_ID == 7656) { Debug.Print(""); } AnimeVideoQualityStat stat = dictStats[series.AniDB_ID]; foreach (KeyValuePair<string, int> kvp in stat.VideoQualityEpisodeCount) { if (kvp.Value >= thisAnime.EpisodeCountNormal) { if (Stat_AllVideoQualityEpisodes.Length > 0) Stat_AllVideoQualityEpisodes += ","; Stat_AllVideoQualityEpisodes += kvp.Key; } } } // Calculate Air Date DateTime? thisDate = thisAnime.AirDate; if (thisDate.HasValue) { if (Stat_AirDate_Min.HasValue) { if (thisDate.Value < Stat_AirDate_Min.Value) Stat_AirDate_Min = thisDate; } else Stat_AirDate_Min = thisDate; if (Stat_AirDate_Max.HasValue) { if (thisDate.Value > Stat_AirDate_Max.Value) Stat_AirDate_Max = thisDate; } else Stat_AirDate_Max = thisDate; } // calculate end date // if the end date is NULL it actually means it is ongoing, so this is the max possible value thisDate = thisAnime.EndDate; if (thisDate.HasValue && Stat_EndDate.HasValue) { if (thisDate.Value > Stat_EndDate.Value) Stat_EndDate = thisDate; } else Stat_EndDate = null; // Calculate Series Created Date thisDate = series.DateTimeCreated; if (thisDate.HasValue) { if (Stat_SeriesCreatedDate.HasValue) { if (thisDate.Value < Stat_SeriesCreatedDate.Value) Stat_SeriesCreatedDate = thisDate; } else Stat_SeriesCreatedDate = thisDate; } /* if (series.AniDB_ID == 2369) Debug.Write("Test"); */ // Note - only one series has to be finished airing to qualify if (thisAnime.EndDate.HasValue && thisAnime.EndDate.Value < DateTime.Now) hasFinishedAiring = true; // Note - only one series has to be currently airing to qualify if (!thisAnime.EndDate.HasValue || thisAnime.EndDate.Value > DateTime.Now) isCurrentlyAiring = true; // We evaluate IsComplete as true if // 1. series has finished airing // 2. user has all episodes locally // Note - only one series has to be complete for the group to be considered complete if (thisAnime.EndDate.HasValue) { if (thisAnime.EndDate.Value < DateTime.Now && series.MissingEpisodeCount == 0 && series.MissingEpisodeCountGroups == 0) { isComplete = true; } } // get categories if (allAnimeCatgeoriesDict.ContainsKey(series.AniDB_ID)) { foreach (int catID in allAnimeCatgeoriesDict[series.AniDB_ID]) { if (!categoryIDList.Contains(catID)) categoryIDList.Add(catID); } } // get audio languages if (dictAudioStats.ContainsKey(series.AniDB_ID)) { foreach (string lanName in dictAudioStats[series.AniDB_ID].LanguageNames) { if (!audioLanguageList.Contains(lanName)) audioLanguageList.Add(lanName); } } // get subtitle languages if (dictSubtitleStats.ContainsKey(series.AniDB_ID)) { foreach (string lanName in dictSubtitleStats[series.AniDB_ID].LanguageNames) { if (!subtitleLanguageList.Contains(lanName)) subtitleLanguageList.Add(lanName); } } // get titles if (allTitlesDict.ContainsKey(series.AniDB_ID)) { foreach (AniDB_Anime_Title title in allTitlesDict[series.AniDB_ID]) { if (Stat_AllTitles.Length > 0) Stat_AllTitles += ","; Stat_AllTitles += title.Title; } } // get votes foreach (AniDB_Vote vote in allVotes) { if (vote.EntityID == series.AniDB_ID && (vote.VoteType == (int)AniDBVoteType.Anime || vote.VoteType == (int)AniDBVoteType.AnimeTemp)) { countVotes++; totalVotes += (decimal)vote.VoteValue; if (vote.VoteType == (int)AniDBVoteType.Anime) { countVotesPerm++; totalVotesPerm += (decimal)vote.VoteValue; } if (vote.VoteType == (int)AniDBVoteType.AnimeTemp) { countVotesTemp++; totalVotesTemp += (decimal)vote.VoteValue; } break; } } } // for the group, if any of the series don't have a tvdb link // we will consider the group as not having a tvdb link if (!animeWithTvDBCrossRef.Contains(series.AniDB_ID)) hasTvDB = false; if (!animeWithMovieCrossRef.Contains(series.AniDB_ID)) hasMovieDB = false; if (!animeWithMALCrossRef.Contains(series.AniDB_ID)) hasMAL = false; if (!animeWithTvDBCrossRef.Contains(series.AniDB_ID) && !animeWithMovieCrossRef.Contains(series.AniDB_ID)) hasMovieDBOrTvDB = false; } if (allVidQuality.ContainsKey(ag.AnimeGroupID)) StatGroupVideoQuality[ag.AnimeGroupID] = allVidQuality[ag.AnimeGroupID]; else StatGroupVideoQuality[ag.AnimeGroupID] = ""; StatGroupVideoQualityEpisodes[ag.AnimeGroupID] = Stat_AllVideoQualityEpisodes; StatGroupIsComplete[ag.AnimeGroupID] = isComplete; StatGroupIsFinishedAiring[ag.AnimeGroupID] = hasFinishedAiring; StatGroupIsCurrentlyAiring[ag.AnimeGroupID] = isCurrentlyAiring; StatGroupSeriesCount[ag.AnimeGroupID] = seriesCount; StatGroupEpisodeCount[ag.AnimeGroupID] = epCount; StatGroupTitles[ag.AnimeGroupID] = Stat_AllTitles; StatGroupAirDate_Max[ag.AnimeGroupID] = Stat_AirDate_Max; StatGroupAirDate_Min[ag.AnimeGroupID] = Stat_AirDate_Min; StatGroupEndDate[ag.AnimeGroupID] = Stat_EndDate; StatGroupSeriesCreatedDate[ag.AnimeGroupID] = Stat_SeriesCreatedDate; StatGroupHasTvDB[ag.AnimeGroupID] = hasTvDB; StatGroupHasMAL[ag.AnimeGroupID] = hasMAL; StatGroupHasMovieDB[ag.AnimeGroupID] = hasMovieDB; StatGroupHasMovieDBOrTvDB[ag.AnimeGroupID] = hasMovieDBOrTvDB; decimal? Stat_UserVoteOverall = null; if (countVotes > 0) Stat_UserVoteOverall = totalVotes / (decimal)countVotes / (decimal)100; StatGroupUserVoteOverall[ag.AnimeGroupID] = Stat_UserVoteOverall; decimal? Stat_UserVotePermanent = null; if (countVotesPerm > 0) Stat_UserVotePermanent = totalVotesPerm / (decimal)countVotesPerm / (decimal)100; StatGroupUserVotePermanent[ag.AnimeGroupID] = Stat_UserVotePermanent; decimal? Stat_UserVoteTemporary = null; if (countVotesTemp > 0) Stat_UserVoteTemporary = totalVotesTemp / (decimal)countVotesTemp / (decimal)100; StatGroupUserVoteTemporary[ag.AnimeGroupID] = Stat_UserVoteTemporary; StatGroupAniDBRating[ag.AnimeGroupID] = ag.AniDBRating; Stat_AllCategories = ""; foreach (int catID in categoryIDList) { if (!allCatgeoriesDict.ContainsKey(catID)) continue; string catName = allCatgeoriesDict[catID].CategoryName; if (Stat_AllCategories.Length > 0) Stat_AllCategories += "|"; Stat_AllCategories += catName; } this.StatGroupCategories[ag.AnimeGroupID] = Stat_AllCategories; string Stat_AudioLanguages = ""; foreach (string audioLan in audioLanguageList) { if (Stat_AudioLanguages.Length > 0) Stat_AudioLanguages += ","; Stat_AudioLanguages += audioLan; } this.StatGroupAudioLanguages[ag.AnimeGroupID] = Stat_AudioLanguages; string Stat_SubtitleLanguages = ""; foreach (string subLan in subtitleLanguageList) { if (Stat_SubtitleLanguages.Length > 0) Stat_SubtitleLanguages += ","; Stat_SubtitleLanguages += subLan; } this.StatGroupSubtitleLanguages[ag.AnimeGroupID] = Stat_SubtitleLanguages; UpdateGroupFilterUsingGroup(ag.AnimeGroupID); UpdatePlexAnimeGroup(session, ag, allSeries); } ts = DateTime.Now - start; logger.Info("GetAllGroups (Contracts) in {0} ms", ts.TotalMilliseconds); //UpdateAllAnimeContracts(); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } }
public List<Contract_AnimeRating> GetAnimeRatings(int collectionState, int watchedState, int ratingVotedState, int userID) { List<Contract_AnimeRating> contracts = new List<Contract_AnimeRating>(); try { AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); List<AnimeSeries> series = repSeries.GetAll(); Dictionary<int, AnimeSeries> dictSeries = new Dictionary<int, AnimeSeries>(); foreach (AnimeSeries ser in series) dictSeries[ser.AniDB_ID] = ser; RatingCollectionState _collectionState = (RatingCollectionState)collectionState; RatingWatchedState _watchedState = (RatingWatchedState)watchedState; RatingVotedState _ratingVotedState = (RatingVotedState)ratingVotedState; DateTime start = DateTime.Now; AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); /* // build a dictionary of categories AniDB_CategoryRepository repCats = new AniDB_CategoryRepository(); AniDB_Anime_CategoryRepository repAnimeCat = new AniDB_Anime_CategoryRepository(); List<AniDB_Category> allCatgeories = repCats.GetAll(); Dictionary<int, AniDB_Category> allCatgeoriesDict = new Dictionary<int, AniDB_Category>(); foreach (AniDB_Category cat in allCatgeories) allCatgeoriesDict[cat.CategoryID] = cat; List<AniDB_Anime_Category> allAnimeCatgeories = repAnimeCat.GetAll(); Dictionary<int, List<AniDB_Anime_Category>> allAnimeCatgeoriesDict = new Dictionary<int, List<AniDB_Anime_Category>>(); // foreach (AniDB_Anime_Category aniCat in allAnimeCatgeories) { if (!allAnimeCatgeoriesDict.ContainsKey(aniCat.AnimeID)) allAnimeCatgeoriesDict[aniCat.AnimeID] = new List<AniDB_Anime_Category>(); allAnimeCatgeoriesDict[aniCat.AnimeID].Add(aniCat); } // build a dictionary of titles AniDB_Anime_TitleRepository repTitles = new AniDB_Anime_TitleRepository(); List<AniDB_Anime_Title> allTitles = repTitles.GetAll(); Dictionary<int, List<AniDB_Anime_Title>> allTitlesDict = new Dictionary<int, List<AniDB_Anime_Title>>(); foreach (AniDB_Anime_Title title in allTitles) { if (!allTitlesDict.ContainsKey(title.AnimeID)) allTitlesDict[title.AnimeID] = new List<AniDB_Anime_Title>(); allTitlesDict[title.AnimeID].Add(title); } // build a dictionary of tags AniDB_TagRepository repTags = new AniDB_TagRepository(); AniDB_Anime_TagRepository repAnimeTag = new AniDB_Anime_TagRepository(); List<AniDB_Tag> allTags = repTags.GetAll(); Dictionary<int, AniDB_Tag> allTagsDict = new Dictionary<int, AniDB_Tag>(); foreach (AniDB_Tag tag in allTags) allTagsDict[tag.TagID] = tag; List<AniDB_Anime_Tag> allAnimeTags = repAnimeTag.GetAll(); Dictionary<int, List<AniDB_Anime_Tag>> allAnimeTagsDict = new Dictionary<int, List<AniDB_Anime_Tag>>(); // foreach (AniDB_Anime_Tag aniTag in allAnimeTags) { if (!allAnimeTagsDict.ContainsKey(aniTag.AnimeID)) allAnimeTagsDict[aniTag.AnimeID] = new List<AniDB_Anime_Tag>(); allAnimeTagsDict[aniTag.AnimeID].Add(aniTag); } // build a dictionary of languages AdhocRepository rep = new AdhocRepository(); Dictionary<int, LanguageStat> dictAudioStats = rep.GetAudioLanguageStatsForAnime(); Dictionary<int, LanguageStat> dictSubtitleStats = rep.GetSubtitleLanguageStatsForAnime(); Dictionary<int, string> dictAnimeVideoQualStats = rep.GetAllVideoQualityByAnime(); Dictionary<int, AnimeVideoQualityStat> dictAnimeEpisodeVideoQualStats = rep.GetEpisodeVideoQualityStatsByAnime(); * */ List<AniDB_Anime> animes = repAnime.GetAll(); // user votes AniDB_VoteRepository repVotes = new AniDB_VoteRepository(); List<AniDB_Vote> allVotes = repVotes.GetAll(); JMMUserRepository repUsers = new JMMUserRepository(); JMMUser user = repUsers.GetByID(userID); if (user == null) return contracts; int i = 0; foreach (AniDB_Anime anime in animes) { i++; // evaluate collection states if (_collectionState == RatingCollectionState.AllEpisodesInMyCollection) { if (!anime.FinishedAiring) continue; if (!dictSeries.ContainsKey(anime.AnimeID)) continue; if (dictSeries[anime.AnimeID].MissingEpisodeCount > 0) continue; } if (_collectionState == RatingCollectionState.InMyCollection) if (!dictSeries.ContainsKey(anime.AnimeID)) continue; if (_collectionState == RatingCollectionState.NotInMyCollection) if (dictSeries.ContainsKey(anime.AnimeID)) continue; if (!user.AllowedAnime(anime)) continue; // evaluate watched states if (_watchedState == RatingWatchedState.AllEpisodesWatched) { if (!dictSeries.ContainsKey(anime.AnimeID)) continue; AnimeSeries_User userRec = dictSeries[anime.AnimeID].GetUserRecord(userID); if (userRec == null) continue; if (userRec.UnwatchedEpisodeCount > 0) continue; } if (_watchedState == RatingWatchedState.NotWatched) { if (dictSeries.ContainsKey(anime.AnimeID)) { AnimeSeries_User userRec = dictSeries[anime.AnimeID].GetUserRecord(userID); if (userRec != null) { if (userRec.UnwatchedEpisodeCount == 0) continue; } } } // evaluate voted states if (_ratingVotedState == RatingVotedState.Voted) { bool voted = false; foreach (AniDB_Vote vote in allVotes) { if (vote.EntityID == anime.AnimeID && (vote.VoteType == (int)AniDBVoteType.Anime || vote.VoteType == (int)AniDBVoteType.AnimeTemp)) { voted = true; break; } } if (!voted) continue; } if (_ratingVotedState == RatingVotedState.NotVoted) { bool voted = false; foreach (AniDB_Vote vote in allVotes) { if (vote.EntityID == anime.AnimeID && (vote.VoteType == (int)AniDBVoteType.Anime || vote.VoteType == (int)AniDBVoteType.AnimeTemp)) { voted = true; break; } } if (voted) continue; } Contract_AnimeRating contract = new Contract_AnimeRating(); contract.AnimeID = anime.AnimeID; Contract_AniDB_AnimeDetailed contractAnimeDetailed = new Contract_AniDB_AnimeDetailed(); contractAnimeDetailed.AnimeTitles = new List<Contract_AnimeTitle>(); contractAnimeDetailed.Categories = new List<Contract_AnimeCategory>(); contractAnimeDetailed.Tags = new List<Contract_AnimeTag>(); contractAnimeDetailed.UserVote = null; contractAnimeDetailed.AniDBAnime = anime.ToContract(); /* if (dictAnimeVideoQualStats.ContainsKey(anime.AnimeID)) contractAnimeDetailed.Stat_AllVideoQuality = dictAnimeVideoQualStats[anime.AnimeID]; else contractAnimeDetailed.Stat_AllVideoQuality = ""; contractAnimeDetailed.Stat_AllVideoQuality_Episodes = ""; // All Video Quality Episodes // Try to determine if this anime has all the episodes available at a certain video quality // e.g. the series has all episodes in blu-ray if (dictAnimeEpisodeVideoQualStats.ContainsKey(anime.AnimeID)) { AnimeVideoQualityStat stat = dictAnimeEpisodeVideoQualStats[anime.AnimeID]; foreach (KeyValuePair<string, int> kvp in stat.VideoQualityEpisodeCount) { if (kvp.Value >= anime.EpisodeCountNormal) { if (contractAnimeDetailed.Stat_AllVideoQuality_Episodes.Length > 0) contractAnimeDetailed.Stat_AllVideoQuality_Episodes += ","; contractAnimeDetailed.Stat_AllVideoQuality_Episodes += kvp.Key; } } } List<string> audioLanguageList = new List<string>(); List<string> subtitleLanguageList = new List<string>(); // get audio languages if (dictAudioStats.ContainsKey(anime.AnimeID)) { foreach (string lanName in dictAudioStats[anime.AnimeID].LanguageNames) { if (!audioLanguageList.Contains(lanName)) audioLanguageList.Add(lanName); } } // get subtitle languages if (dictSubtitleStats.ContainsKey(anime.AnimeID)) { foreach (string lanName in dictSubtitleStats[anime.AnimeID].LanguageNames) { if (!subtitleLanguageList.Contains(lanName)) subtitleLanguageList.Add(lanName); } } contractAnimeDetailed.Stat_AudioLanguages = ""; foreach (string audioLan in audioLanguageList) { if (contractAnimeDetailed.Stat_AudioLanguages.Length > 0) contractAnimeDetailed.Stat_AudioLanguages += ","; contractAnimeDetailed.Stat_AudioLanguages += audioLan; } contractAnimeDetailed.Stat_SubtitleLanguages = ""; foreach (string subLan in subtitleLanguageList) { if (contractAnimeDetailed.Stat_SubtitleLanguages.Length > 0) contractAnimeDetailed.Stat_SubtitleLanguages += ","; contractAnimeDetailed.Stat_SubtitleLanguages += subLan; } if (allTitlesDict.ContainsKey(anime.AnimeID)) { foreach (AniDB_Anime_Title title in allTitlesDict[anime.AnimeID]) { Contract_AnimeTitle ctitle = new Contract_AnimeTitle(); ctitle.AnimeID = title.AnimeID; ctitle.Language = title.Language; ctitle.Title = title.Title; ctitle.TitleType = title.TitleType; contractAnimeDetailed.AnimeTitles.Add(ctitle); } } if (allAnimeCatgeoriesDict.ContainsKey(anime.AnimeID)) { List<AniDB_Anime_Category> aniCats = allAnimeCatgeoriesDict[anime.AnimeID]; foreach (AniDB_Anime_Category aniCat in aniCats) { if (allCatgeoriesDict.ContainsKey(aniCat.CategoryID)) { AniDB_Category cat = allCatgeoriesDict[aniCat.CategoryID]; Contract_AnimeCategory ccat = new Contract_AnimeCategory(); ccat.CategoryDescription = cat.CategoryDescription; ccat.CategoryID = cat.CategoryID; ccat.CategoryName = cat.CategoryName; ccat.IsHentai = cat.IsHentai; ccat.ParentID = cat.ParentID; ccat.Weighting = aniCat.Weighting; contractAnimeDetailed.Categories.Add(ccat); } } } if (allAnimeTagsDict.ContainsKey(anime.AnimeID)) { List<AniDB_Anime_Tag> aniTags = allAnimeTagsDict[anime.AnimeID]; foreach (AniDB_Anime_Tag aniTag in aniTags) { if (allTagsDict.ContainsKey(aniTag.TagID)) { AniDB_Tag tag = allTagsDict[aniTag.TagID]; Contract_AnimeTag ctag = new Contract_AnimeTag(); ctag.Approval = aniTag.Approval; ctag.GlobalSpoiler = tag.GlobalSpoiler; ctag.LocalSpoiler = tag.LocalSpoiler; ctag.Spoiler = tag.Spoiler; ctag.TagCount = tag.TagCount; ctag.TagDescription = tag.TagDescription; ctag.TagID = tag.TagID; ctag.TagName = tag.TagName; contractAnimeDetailed.Tags.Add(ctag); } } }*/ // get user vote foreach (AniDB_Vote vote in allVotes) { if (vote.EntityID == anime.AnimeID && (vote.VoteType == (int)AniDBVoteType.Anime || vote.VoteType == (int)AniDBVoteType.AnimeTemp)) { contractAnimeDetailed.UserVote = vote.ToContract(); break; } } contract.AnimeDetailed = contractAnimeDetailed; if (dictSeries.ContainsKey(anime.AnimeID)) { contract.AnimeSeries = dictSeries[anime.AnimeID].ToContract(dictSeries[anime.AnimeID].GetUserRecord(userID)); } contracts.Add(contract); } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return contracts; }
public static void UpdateAllStats() { AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); foreach (AnimeSeries ser in repSeries.GetAll()) { ser.QueueUpdateStats(); } }
public static void SyncCollectionToTrakt() { try { if (!ServerSettings.Trakt_IsEnabled || string.IsNullOrEmpty(ServerSettings.Trakt_AuthToken)) return; // check that we have at least one user nominated for Trakt JMMUserRepository repUsers = new JMMUserRepository(); List<JMMUser> traktUsers = repUsers.GetTraktUsers(); if (traktUsers.Count == 0) return; AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); List<AnimeSeries> allSeries = repSeries.GetAll(); // now get the full users collection from Trakt List<TraktV2ShowCollectedResult> collected = new List<TraktV2ShowCollectedResult>(); List<TraktV2ShowWatchedResult> watched = new List<TraktV2ShowWatchedResult>(); if (!GetTraktCollectionInfo(ref collected, ref watched)) return; TraktV2SyncCollectionEpisodesByNumber syncCollectionAdd = new TraktV2SyncCollectionEpisodesByNumber(); TraktV2SyncCollectionEpisodesByNumber syncCollectionRemove = new TraktV2SyncCollectionEpisodesByNumber(); TraktV2SyncWatchedEpisodesByNumber syncHistoryAdd = new TraktV2SyncWatchedEpisodesByNumber(); TraktV2SyncWatchedEpisodesByNumber syncHistoryRemove = new TraktV2SyncWatchedEpisodesByNumber(); #region Local Collection Sync /////////////////////////////////////////////////////////////////////////////////////// // First take a look at our local collection and update on Trakt /////////////////////////////////////////////////////////////////////////////////////// AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); int counter = 0; foreach (AnimeSeries series in allSeries) { counter++; logger.Trace("Syncing check - local collection: {0} / {1} - {2}", counter, allSeries.Count, series.GetSeriesName()); AniDB_Anime anime = repAnime.GetByAnimeID(series.AniDB_ID); if (anime == null) continue; //if (anime.AnimeID != 3427) continue; TraktSummaryContainer traktSummary = new TraktSummaryContainer(); traktSummary.Populate(series.AniDB_ID); if (traktSummary.CrossRefTraktV2 == null || traktSummary.CrossRefTraktV2.Count == 0) continue; // get the current watched records for this series on Trakt foreach (AnimeEpisode ep in series.GetAnimeEpisodes()) { if (ep.EpisodeTypeEnum == enEpisodeType.Episode || ep.EpisodeTypeEnum == enEpisodeType.Special) { EpisodeSyncDetails epsync = ReconSyncTraktEpisode(series, ep, traktSummary, traktUsers, collected, watched, false); if (epsync != null) { switch (epsync.SyncType) { case TraktSyncType.CollectionAdd: syncCollectionAdd.AddEpisode(epsync.Slug, epsync.Season, epsync.EpNumber, epsync.EpDate); break; case TraktSyncType.CollectionRemove: syncCollectionRemove.AddEpisode(epsync.Slug, epsync.Season, epsync.EpNumber, epsync.EpDate); break; case TraktSyncType.HistoryAdd: syncHistoryAdd.AddEpisode(epsync.Slug, epsync.Season, epsync.EpNumber, epsync.EpDate); break; case TraktSyncType.HistoryRemove: syncHistoryRemove.AddEpisode(epsync.Slug, epsync.Season, epsync.EpNumber, epsync.EpDate); break; } } } } } #endregion // refresh online info, just in case it was chnaged by the last operations if (!GetTraktCollectionInfo(ref collected, ref watched)) return; #region Online Collection Sync /////////////////////////////////////////////////////////////////////////////////////// // Now look at the collection according to Trakt, and remove it if we don't have it locally /////////////////////////////////////////////////////////////////////////////////////// CrossRef_AniDB_TraktV2Repository repCrossRef = new CrossRef_AniDB_TraktV2Repository(); counter = 0; foreach (TraktV2ShowCollectedResult col in collected) { counter++; logger.Trace("Syncing check - Online collection: {0} / {1} - {2}", counter, collected.Count, col.show.Title); //continue; // check if we have this series locally List<CrossRef_AniDB_TraktV2> xrefs = repCrossRef.GetByTraktID(col.show.ids.slug); if (xrefs.Count > 0) { foreach (CrossRef_AniDB_TraktV2 xref in xrefs) { AnimeSeries locSeries = repSeries.GetByAnimeID(xref.AnimeID); if (locSeries == null) continue; TraktSummaryContainer traktSummary = new TraktSummaryContainer(); traktSummary.Populate(locSeries.AniDB_ID); if (traktSummary.CrossRefTraktV2 == null || traktSummary.CrossRefTraktV2.Count == 0) continue; // if we have this series locSeries, let's sync the whole series foreach (AnimeEpisode ep in locSeries.GetAnimeEpisodes()) { if (ep.EpisodeTypeEnum == enEpisodeType.Episode || ep.EpisodeTypeEnum == enEpisodeType.Special) { EpisodeSyncDetails epsync = ReconSyncTraktEpisode(locSeries, ep, traktSummary, traktUsers, collected, watched, false); if (epsync != null) { switch (epsync.SyncType) { case TraktSyncType.CollectionAdd: syncCollectionAdd.AddEpisode(epsync.Slug, epsync.Season, epsync.EpNumber, epsync.EpDate); break; case TraktSyncType.CollectionRemove: syncCollectionRemove.AddEpisode(epsync.Slug, epsync.Season, epsync.EpNumber, epsync.EpDate); break; case TraktSyncType.HistoryAdd: syncHistoryAdd.AddEpisode(epsync.Slug, epsync.Season, epsync.EpNumber, epsync.EpDate); break; case TraktSyncType.HistoryRemove: syncHistoryRemove.AddEpisode(epsync.Slug, epsync.Season, epsync.EpNumber, epsync.EpDate); break; } } } } } } else { // Actually we can't do this, because the user may have other non Anime series and Movies /* // series doesn't exist locally at all, so let's completely remove it from Trakt foreach (TraktV2CollectedSeason colSeason in col.seasons) { foreach (TraktV2CollectedEpisode colEp in colSeason.episodes) { string msg = string.Format("SYNC ONLINE: Removing from Trakt Collection: Slug: {0} - S:{1} - EP:{2}", col.show.ids.slug, colSeason.number, colEp.number); logger.Trace(msg); SyncEpisodeToTrakt(TraktSyncType.CollectionRemove, col.show.ids.slug, colSeason.number, colEp.number, DateTime.Now, false); } }*/ } } #endregion // refresh online info, just in case it was chnaged by the last operations if (!GetTraktCollectionInfo(ref collected, ref watched)) return; #region Online History (Watched/Unwatched) Sync /////////////////////////////////////////////////////////////////////////////////////// // Now look at the history according to Trakt, and remove it if we don't have it locally /////////////////////////////////////////////////////////////////////////////////////// counter = 0; foreach (TraktV2ShowWatchedResult wtch in watched) { counter++; logger.Trace("Syncing check - Online History: {0} / {1} - {2}", counter, watched.Count, wtch.show.Title); //continue; // check if we have this series locally List<CrossRef_AniDB_TraktV2> xrefs = repCrossRef.GetByTraktID(wtch.show.ids.slug); if (xrefs.Count > 0) { foreach (CrossRef_AniDB_TraktV2 xref in xrefs) { AnimeSeries locSeries = repSeries.GetByAnimeID(xref.AnimeID); if (locSeries == null) continue; TraktSummaryContainer traktSummary = new TraktSummaryContainer(); traktSummary.Populate(locSeries.AniDB_ID); if (traktSummary.CrossRefTraktV2 == null || traktSummary.CrossRefTraktV2.Count == 0) continue; // if we have this series locSeries, let's sync the whole series foreach (AnimeEpisode ep in locSeries.GetAnimeEpisodes()) { if (ep.EpisodeTypeEnum == enEpisodeType.Episode || ep.EpisodeTypeEnum == enEpisodeType.Special) { EpisodeSyncDetails epsync = ReconSyncTraktEpisode(locSeries, ep, traktSummary, traktUsers, collected, watched, false); if (epsync != null) { switch (epsync.SyncType) { case TraktSyncType.CollectionAdd: syncCollectionAdd.AddEpisode(epsync.Slug, epsync.Season, epsync.EpNumber, epsync.EpDate); break; case TraktSyncType.CollectionRemove: syncCollectionRemove.AddEpisode(epsync.Slug, epsync.Season, epsync.EpNumber, epsync.EpDate); break; case TraktSyncType.HistoryAdd: syncHistoryAdd.AddEpisode(epsync.Slug, epsync.Season, epsync.EpNumber, epsync.EpDate); break; case TraktSyncType.HistoryRemove: syncHistoryRemove.AddEpisode(epsync.Slug, epsync.Season, epsync.EpNumber, epsync.EpDate); break; } } } } } } else { // Actually we can't do this, because the user may have other non Anime series and Movies /* // series doesn't exist locally at all, so let's completely remove it from Trakt foreach (TraktV2WatchedSeason wtchSeason in wtch.seasons) { foreach (TraktV2WatchedEpisode wtchEp in wtchSeason.episodes) { string msg = string.Format("SYNC ONLINE: Removing from Trakt History: Slug: {0} - S:{1} - EP:{2}", wtch.show.ids.slug, wtchSeason.number, wtchEp.number); logger.Trace(msg); SyncEpisodeToTrakt(TraktSyncType.HistoryRemove, wtch.show.ids.slug, wtchSeason.number, wtchEp.number, DateTime.Now, false); } }*/ } } #endregion // send the data to Trakt string json = string.Empty; string url = TraktURIs.SyncCollectionAdd; string retData = string.Empty; if (syncCollectionAdd.shows != null && syncCollectionAdd.shows.Count > 0) { json = JSONHelper.Serialize<TraktV2SyncCollectionEpisodesByNumber>(syncCollectionAdd); url = TraktURIs.SyncCollectionAdd; retData = string.Empty; SendData(url, json, "POST", BuildRequestHeaders(), ref retData); } if (syncCollectionRemove.shows != null && syncCollectionRemove.shows.Count > 0) { json = JSONHelper.Serialize<TraktV2SyncCollectionEpisodesByNumber>(syncCollectionRemove); url = TraktURIs.SyncCollectionRemove; retData = string.Empty; SendData(url, json, "POST", BuildRequestHeaders(), ref retData); } if (syncHistoryAdd.shows != null && syncHistoryAdd.shows.Count > 0) { json = JSONHelper.Serialize<TraktV2SyncWatchedEpisodesByNumber>(syncHistoryAdd); url = TraktURIs.SyncHistoryAdd; retData = string.Empty; SendData(url, json, "POST", BuildRequestHeaders(), ref retData); } if (syncHistoryRemove.shows != null && syncHistoryRemove.shows.Count > 0) { json = JSONHelper.Serialize<TraktV2SyncWatchedEpisodesByNumber>(syncHistoryRemove); url = TraktURIs.SyncHistoryRemove; retData = string.Empty; SendData(url, json, "POST", BuildRequestHeaders(), ref retData); } logger.Trace("Test"); } catch (Exception ex) { logger.ErrorException("Error in TraktTVHelper.SyncCollectionToTrakt: " + ex.ToString(), ex); } }
public List<Contract_MissingEpisode> GetMissingEpisodes(int userID, bool onlyMyGroups, bool regularEpisodesOnly, int airingState) { List<Contract_MissingEpisode> contracts = new List<Contract_MissingEpisode>(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AiringState airState = (AiringState)airingState; Dictionary<int, AniDB_Anime> animeCache = new Dictionary<int, AniDB_Anime>(); Dictionary<int, List<Contract_GroupVideoQuality>> gvqCache = new Dictionary<int, List<Contract_GroupVideoQuality>>(); Dictionary<int, List<Contract_GroupFileSummary>> gfqCache = new Dictionary<int, List<Contract_GroupFileSummary>>(); try { int i = 0; List<AnimeSeries> allSeries = repSeries.GetAll(); foreach (AnimeSeries ser in allSeries) { i++; //string msg = string.Format("Updating series {0} of {1} ({2}) - {3}", i, allSeries.Count, ser.Anime.MainTitle, DateTime.Now); //logger.Debug(msg); //if (ser.Anime.AnimeID != 69) continue; int missingEps = ser.MissingEpisodeCount; if (onlyMyGroups) missingEps = ser.MissingEpisodeCountGroups; bool finishedAiring = ser.GetAnime().FinishedAiring; if (!finishedAiring && airState == AiringState.FinishedAiring) continue; if (finishedAiring && airState == AiringState.StillAiring) continue; DateTime start = DateTime.Now; TimeSpan ts = DateTime.Now - start; double totalTiming = 0; double timingVids = 0; double timingSeries = 0; double timingAnime = 0; double timingQuality = 0; double timingEps = 0; double timingAniEps = 0; int epCount = 0; DateTime oStart = DateTime.Now; if (missingEps > 0) { // find the missing episodes start = DateTime.Now; List<AnimeEpisode> eps = ser.GetAnimeEpisodes(); ts = DateTime.Now - start; timingEps += ts.TotalMilliseconds; epCount = eps.Count; foreach (AnimeEpisode aep in ser.GetAnimeEpisodes()) { if (regularEpisodesOnly && aep.EpisodeTypeEnum != enEpisodeType.Episode) continue; AniDB_Episode aniep = aep.AniDB_Episode; if (aniep.FutureDated) continue; start = DateTime.Now; List<VideoLocal> vids = aep.GetVideoLocals(); ts = DateTime.Now - start; timingVids += ts.TotalMilliseconds; if (vids.Count == 0) { Contract_MissingEpisode contract = new Contract_MissingEpisode(); contract.AnimeID = ser.AniDB_ID; start = DateTime.Now; contract.AnimeSeries = ser.ToContract(ser.GetUserRecord(userID)); ts = DateTime.Now - start; timingSeries += ts.TotalMilliseconds; AniDB_Anime anime = null; if (animeCache.ContainsKey(ser.AniDB_ID)) anime = animeCache[ser.AniDB_ID]; else { start = DateTime.Now; anime = ser.GetAnime(); ts = DateTime.Now - start; timingAnime += ts.TotalMilliseconds; animeCache[ser.AniDB_ID] = anime; } contract.AnimeTitle = anime.MainTitle; start = DateTime.Now; contract.GroupFileSummary = ""; List<Contract_GroupVideoQuality> summ = null; if (gvqCache.ContainsKey(ser.AniDB_ID)) summ = gvqCache[ser.AniDB_ID]; else { summ = GetGroupVideoQualitySummary(anime.AnimeID); gvqCache[ser.AniDB_ID] = summ; } foreach (Contract_GroupVideoQuality gvq in summ) { if (contract.GroupFileSummary.Length > 0) contract.GroupFileSummary += " --- "; contract.GroupFileSummary += string.Format("{0} - {1}/{2}/{3}bit ({4})", gvq.GroupNameShort, gvq.Resolution, gvq.VideoSource, gvq.VideoBitDepth, gvq.NormalEpisodeNumberSummary); } contract.GroupFileSummarySimple = ""; List<Contract_GroupFileSummary> summFiles = null; if (gfqCache.ContainsKey(ser.AniDB_ID)) summFiles = gfqCache[ser.AniDB_ID]; else { summFiles = GetGroupFileSummary(anime.AnimeID); gfqCache[ser.AniDB_ID] = summFiles; } foreach (Contract_GroupFileSummary gfq in summFiles) { if (contract.GroupFileSummarySimple.Length > 0) contract.GroupFileSummarySimple += ", "; contract.GroupFileSummarySimple += string.Format("{0} ({1})", gfq.GroupNameShort, gfq.NormalEpisodeNumberSummary); } ts = DateTime.Now - start; timingQuality += ts.TotalMilliseconds; animeCache[ser.AniDB_ID] = anime; start = DateTime.Now; contract.EpisodeID = aniep.EpisodeID; contract.EpisodeNumber = aniep.EpisodeNumber; contract.EpisodeType = aniep.EpisodeType; contracts.Add(contract); ts = DateTime.Now - start; timingAniEps += ts.TotalMilliseconds; } } ts = DateTime.Now - oStart; totalTiming = ts.TotalMilliseconds; string msg2 = string.Format("Timing for series {0} ({1}) : {2}/{3}/{4}/{5}/{6}/{7} - {8} eps (AID: {9})", ser.GetAnime().MainTitle, totalTiming, timingVids, timingSeries, timingAnime, timingQuality, timingEps, timingAniEps, epCount, ser.GetAnime().AnimeID); //logger.Debug(msg2); } } List<SortPropOrFieldAndDirection> sortCriteria = new List<SortPropOrFieldAndDirection>(); sortCriteria.Add(new SortPropOrFieldAndDirection("AnimeTitle", false, SortType.eString)); sortCriteria.Add(new SortPropOrFieldAndDirection("EpisodeType", false, SortType.eInteger)); sortCriteria.Add(new SortPropOrFieldAndDirection("EpisodeNumber", false, SortType.eInteger)); contracts = Sorting.MultiSort<Contract_MissingEpisode>(contracts, sortCriteria); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return contracts; }
public static void ScanForMatches() { AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); List<AnimeSeries> allSeries = repSeries.GetAll(); CrossRef_AniDB_TraktV2Repository repCrossRef = new CrossRef_AniDB_TraktV2Repository(); List<CrossRef_AniDB_TraktV2> allCrossRefs = repCrossRef.GetAll(); List<int> alreadyLinked = new List<int>(); foreach (CrossRef_AniDB_TraktV2 xref in allCrossRefs) { alreadyLinked.Add(xref.AnimeID); } foreach (AnimeSeries ser in allSeries) { if (alreadyLinked.Contains(ser.AniDB_ID)) continue; AniDB_Anime anime = ser.GetAnime(); if (anime != null) logger.Trace("Found anime without Trakt association: " + anime.MainTitle); if (anime.IsTraktLinkDisabled) continue; CommandRequest_TraktSearchAnime cmd = new CommandRequest_TraktSearchAnime(ser.AniDB_ID, false); cmd.Save(); } }
public static void SyncCollectionToTrakt() { try { if (string.IsNullOrEmpty(ServerSettings.Trakt_Username) || string.IsNullOrEmpty(ServerSettings.Trakt_Password)) return; AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); List<AnimeSeries> allSeries = repSeries.GetAll(); foreach (AnimeSeries series in allSeries) { //SyncCollectionToTrakt_Series(series); CommandRequest_TraktSyncCollectionSeries cmd = new CommandRequest_TraktSyncCollectionSeries(series.AnimeSeriesID, series.GetAnime().MainTitle); cmd.Save(); } } catch (Exception ex) { logger.ErrorException("Error in TraktTVHelper.SyncCollectionToTrakt: " + ex.ToString(), ex); } }