public static void InitCache() { string t = "AnimeEpisodes"; ServerState.Instance.CurrentSetupStatus = string.Format(JMMServer.Properties.Resources.Database_Cache, t, string.Empty); AnimeEpisodeRepository repo = new AnimeEpisodeRepository(); Cache = new PocoCache <int, AnimeEpisode>(repo.InternalGetAll(), a => a.AnimeEpisodeID); Series = Cache.CreateIndex(a => a.AnimeSeriesID); EpisodeIDs = Cache.CreateIndex(a => a.AniDB_EpisodeID); int cnt = 0; List <AnimeEpisode> grps = Cache.Values.Where(a => a.PlexContractVersion < AnimeEpisode.PLEXCONTRACT_VERSION).ToList(); int max = grps.Count; foreach (AnimeEpisode g in grps) { repo.Save(g); cnt++; if (cnt % 10 == 0) { ServerState.Instance.CurrentSetupStatus = string.Format(JMMServer.Properties.Resources.Database_Cache, t, " DbRegen - " + cnt + "/" + max); } } ServerState.Instance.CurrentSetupStatus = string.Format(JMMServer.Properties.Resources.Database_Cache, t, " DbRegen - " + max + "/" + max); }
public override void ProcessCommand() { logger.Info("Processing CommandRequest_TraktCollectionEpisode: {0}-{1}", AnimeEpisodeID, Action); try { logger.Info("CommandRequest_TraktCollectionEpisode - DEBUG01"); if (!ServerSettings.Trakt_IsEnabled || string.IsNullOrEmpty(ServerSettings.Trakt_AuthToken)) return; logger.Info("CommandRequest_TraktCollectionEpisode - DEBUG02"); AnimeEpisodeRepository repEpisodes = new AnimeEpisodeRepository(); AnimeEpisode ep = repEpisodes.GetByID(AnimeEpisodeID); if (ep != null) { logger.Info("CommandRequest_TraktCollectionEpisode - DEBUG03"); TraktSyncType syncType = TraktSyncType.CollectionAdd; if (ActionEnum == TraktSyncAction.Remove) syncType = TraktSyncType.CollectionRemove; TraktTVHelper.SyncEpisodeToTrakt(ep, syncType); } } catch (Exception ex) { logger.Error("Error processing CommandRequest_TraktCollectionEpisode: {0} - {1} - {2}", AnimeEpisodeID, Action, ex.ToString()); return; } }
public override void ProcessCommand() { logger.Info("Processing CommandRequest_UpdateMyListFileStatus: {0}", Hash); try { VideoLocalRepository repVids = new VideoLocalRepository(); AnimeEpisodeRepository repEpisodes = new AnimeEpisodeRepository(); // NOTE - we might return more than one VideoLocal record here, if there are duplicates by hash VideoLocal vid = repVids.GetByHash(this.Hash); if (vid != null) { bool isManualLink = false; List<CrossRef_File_Episode> xrefs = vid.EpisodeCrossRefs; if (xrefs.Count > 0) isManualLink = xrefs[0].CrossRefSource != (int)CrossRefSource.AniDB; if (isManualLink) { JMMService.AnidbProcessor.UpdateMyListFileStatus(xrefs[0].AnimeID, xrefs[0].Episode.EpisodeNumber, this.Watched); logger.Info("Updating file list status (GENERIC): {0} - {1}", vid.ToString(), this.Watched); } else { if (WatchedDateAsSecs > 0) { DateTime? watchedDate = Utils.GetAniDBDateAsDate(WatchedDateAsSecs); JMMService.AnidbProcessor.UpdateMyListFileStatus(vid, this.Watched, watchedDate); } else JMMService.AnidbProcessor.UpdateMyListFileStatus(vid, this.Watched, null); logger.Info("Updating file list status: {0} - {1}", vid.ToString(), this.Watched); } if (UpdateSeriesStats) { // update watched stats List<AnimeEpisode> eps = repEpisodes.GetByHash(vid.ED2KHash); if (eps.Count > 0) { // all the eps should belong to the same anime eps[0].GetAnimeSeries().UpdateStats(true, false, true); //eps[0].AnimeSeries.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true, true, false); } } } } catch (Exception ex) { logger.Error("Error processing CommandRequest_UpdateMyListFileStatus: {0} - {1}", Hash, ex.ToString()); return; } }
public void UpdateContract(ISession session, AnimeEpisode_User aeu) { AnimeEpisodeRepository aerepo = new AnimeEpisodeRepository(); Contract_AnimeEpisode caep = aeu.Contract ?? new Contract_AnimeEpisode(); AnimeEpisode ep = aerepo.GetByID(aeu.AnimeEpisodeID); if (ep == null) { return; } AniDB_Episode aniEp = ep.AniDB_Episode; caep.AniDB_EpisodeID = ep.AniDB_EpisodeID; caep.AnimeEpisodeID = ep.AnimeEpisodeID; caep.AnimeSeriesID = ep.AnimeSeriesID; caep.DateTimeUpdated = ep.DateTimeUpdated; caep.IsWatched = aeu.WatchedCount > 0 ? 1 : 0; caep.PlayedCount = aeu.PlayedCount; caep.StoppedCount = aeu.StoppedCount; caep.WatchedCount = aeu.WatchedCount; caep.WatchedDate = aeu.WatchedDate; if (aniEp != null) { caep.AniDB_AirDate = aniEp.AirDateAsDate; caep.AniDB_EnglishName = aniEp.EnglishName; caep.AniDB_LengthSeconds = aniEp.LengthSeconds; caep.AniDB_Rating = aniEp.Rating; caep.AniDB_RomajiName = aniEp.RomajiName; caep.AniDB_Votes = aniEp.Votes; caep.EpisodeNumber = aniEp.EpisodeNumber; caep.EpisodeNameRomaji = aniEp.RomajiName; caep.EpisodeNameEnglish = aniEp.EnglishName; caep.EpisodeType = aniEp.EpisodeType; } //TODO if this is needed, calculating it in here will not affect performance caep.ReleaseGroups = new List <Contract_AniDBReleaseGroup>(); aeu.Contract = caep; }
public override void ProcessCommand() { logger.Info("Processing CommandRequest_TraktShowEpisodeUnseen: {0}", AnimeEpisodeID); try { AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeEpisode ep = repEps.GetByID(AnimeEpisodeID); if (ep == null) { logger.Error("Could not find anime epiosde: {0}", AnimeEpisodeID); return; } TraktTVHelper.SyncEpisodeToTrakt(ep, TraktSyncType.HistoryRemove); } catch (Exception ex) { logger.Error("Error processing CommandRequest_TraktShowEpisodeUnseen: {0} - {1}", AnimeEpisodeID, ex.ToString()); return; } }
public override void ProcessCommand() { logger.Info("Processing CommandRequest_TraktShowScrobble: {0}", AnimeEpisodeID); try { AnimeEpisodeRepository repEpisodes = new AnimeEpisodeRepository(); AnimeEpisode ep = repEpisodes.GetByID(AnimeEpisodeID); if (ep != null) { // before scrobbling try to ensure the episode is in the users collection by sync'ing the series //TraktTVHelper.SyncCollectionToTrakt_Series(ep.AnimeSeries); TraktTVHelper.MarkEpisodeWatched(ep); } } catch (Exception ex) { logger.Error("Error processing CommandRequest_TraktShowScrobble: {0} - {1}", AnimeEpisodeID, ex.ToString()); return; } }
public void Save(VideoLocal obj, bool updateEpisodes) { lock (obj) { if (obj.VideoLocalID == 0) { obj.Media = null; using (var session = JMMService.SessionFactory.OpenSession()) { // populate the database using (var transaction = session.BeginTransaction()) { session.SaveOrUpdate(obj); transaction.Commit(); } } } using (var session = JMMService.SessionFactory.OpenSession()) { UpdateMediaContracts(obj); using (var transaction = session.BeginTransaction()) { session.SaveOrUpdate(obj); transaction.Commit(); } Cache.Update(obj); } } if (updateEpisodes) { AnimeEpisodeRepository repo = new AnimeEpisodeRepository(); foreach (AnimeEpisode ep in obj.GetAnimeEpisodes()) { repo.Save(ep); } } }
public Contract_AnimeEpisode GetNextUnwatchedEpisodeForGroup(int animeGroupID, int userID) { try { AnimeGroupRepository repGroups = new AnimeGroupRepository(); AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeSeriesRepository repAnimeSer = new AnimeSeriesRepository(); AnimeGroup grp = repGroups.GetByID(animeGroupID); if (grp == null) return null; List<AnimeSeries> allSeries = grp.GetAllSeries(); List<SortPropOrFieldAndDirection> sortCriteria = new List<SortPropOrFieldAndDirection>(); sortCriteria.Add(new SortPropOrFieldAndDirection("AirDate", false, SortType.eDateTime)); allSeries = Sorting.MultiSort<AnimeSeries>(allSeries, sortCriteria); foreach (AnimeSeries ser in allSeries) { Contract_AnimeEpisode contract = GetNextUnwatchedEpisode(ser.AnimeSeriesID, userID); if (contract != null) return contract; } return null; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); return null; } }
public Contract_AnimeEpisode GetNextUnwatchedEpisode(ISession session, int animeSeriesID, int userID) { try { AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeSeriesRepository repAnimeSer = new AnimeSeriesRepository(); AnimeEpisode_UserRepository repEpUser = new AnimeEpisode_UserRepository(); // get all the data first // we do this to reduce the amount of database calls, which makes it a lot faster AnimeSeries series = repAnimeSer.GetByID(session, animeSeriesID); if (series == null) return null; //List<AnimeEpisode> epList = repEps.GetUnwatchedEpisodes(animeSeriesID, userID); List<AnimeEpisode> epList = new List<AnimeEpisode>(); Dictionary<int, AnimeEpisode_User> dictEpUsers = new Dictionary<int, AnimeEpisode_User>(); foreach (AnimeEpisode_User userRecord in repEpUser.GetByUserIDAndSeriesID(session, userID, animeSeriesID)) dictEpUsers[userRecord.AnimeEpisodeID] = userRecord; foreach (AnimeEpisode animeep in repEps.GetBySeriesID(session, animeSeriesID)) { if (!dictEpUsers.ContainsKey(animeep.AnimeEpisodeID)) { epList.Add(animeep); continue; } AnimeEpisode_User usrRec = dictEpUsers[animeep.AnimeEpisodeID]; if (usrRec.WatchedCount == 0 || !usrRec.WatchedDate.HasValue) epList.Add(animeep); } AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository(); List<AniDB_Episode> aniEpList = repAniEps.GetByAnimeID(session, series.AniDB_ID); Dictionary<int, AniDB_Episode> dictAniEps = new Dictionary<int, AniDB_Episode>(); foreach (AniDB_Episode aniep in aniEpList) dictAniEps[aniep.EpisodeID] = aniep; List<Contract_AnimeEpisode> candidateEps = new List<Contract_AnimeEpisode>(); foreach (AnimeEpisode ep in epList) { if (dictAniEps.ContainsKey(ep.AniDB_EpisodeID)) { AniDB_Episode anidbep = dictAniEps[ep.AniDB_EpisodeID]; if (anidbep.EpisodeType == (int)enEpisodeType.Episode || anidbep.EpisodeType == (int)enEpisodeType.Special) { AnimeEpisode_User userRecord = null; if (dictEpUsers.ContainsKey(ep.AnimeEpisodeID)) userRecord = dictEpUsers[ep.AnimeEpisodeID]; Contract_AnimeEpisode epContract = ep.ToContract(anidbep, new List<VideoLocal>(), userRecord, series.GetUserRecord(session, userID)); candidateEps.Add(epContract); } } } if (candidateEps.Count == 0) return null; // sort by episode type and number to find the next episode List<SortPropOrFieldAndDirection> sortCriteria = new List<SortPropOrFieldAndDirection>(); sortCriteria.Add(new SortPropOrFieldAndDirection("EpisodeType", false, SortType.eInteger)); sortCriteria.Add(new SortPropOrFieldAndDirection("EpisodeNumber", false, SortType.eInteger)); candidateEps = Sorting.MultiSort<Contract_AnimeEpisode>(candidateEps, sortCriteria); // this will generate a lot of queries when the user doesn have files // for these episodes foreach (Contract_AnimeEpisode canEp in candidateEps) { // now refresh from the database to get file count AnimeEpisode epFresh = repEps.GetByID(canEp.AnimeEpisodeID); if (epFresh.GetVideoLocals().Count > 0) return epFresh.ToContract(true, userID, series.GetUserRecord(session, userID)); } return null; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); return null; } }
public Contract_AnimeEpisode GetLastWatchedEpisodeForSeries(int animeSeriesID, int jmmuserID) { try { using (var session = JMMService.SessionFactory.OpenSession()) { AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeEpisode_UserRepository repEpUser = new AnimeEpisode_UserRepository(); JMMUserRepository repUsers = new JMMUserRepository(); JMMUser user = repUsers.GetByID(session, jmmuserID); if (user == null) return null; List<AnimeEpisode_User> userRecords = repEpUser.GetLastWatchedEpisodeForSeries(session, animeSeriesID, jmmuserID); if (userRecords == null || userRecords.Count == 0) return null; AnimeEpisode ep = repEps.GetByID(session, userRecords[0].AnimeEpisodeID); if (ep == null) return null; return ep.ToContract(session, jmmuserID); } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return null; }
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 MetroContract_Anime_Summary GetAnimeSummary(int animeID) { try { using (var session = JMMService.SessionFactory.OpenSession()) { AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); AniDB_Anime anime = repAnime.GetByAnimeID(session, animeID); if (anime == null) return null; AnimeSeries ser = repSeries.GetByAnimeID(session, animeID); MetroContract_Anime_Summary summ = new MetroContract_Anime_Summary(); summ.AnimeID = anime.AnimeID; summ.AnimeName = anime.MainTitle; summ.AnimeSeriesID = 0; summ.BeginYear = anime.BeginYear; summ.EndYear = anime.EndYear; summ.PosterName = anime.GetDefaultPosterPathNoBlanks(session); ImageDetails imgDet = anime.GetDefaultPosterDetailsNoBlanks(session); summ.ImageType = (int)imgDet.ImageType; summ.ImageID = imgDet.ImageID; if (ser != null) { summ.AnimeName = ser.GetSeriesName(session); summ.AnimeSeriesID = ser.AnimeSeriesID; } return summ; } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return null; }
/// <summary> /// Set watched status on all normal episodes /// </summary> /// <param name="animeSeriesID"></param> /// <param name="watchedStatus"></param> /// <param name="maxEpisodeNumber">Use this to specify a max episode number to apply to</param> /// <returns></returns> public string SetWatchedStatusOnSeries(int animeSeriesID, bool watchedStatus, int maxEpisodeNumber, int episodeType, int userID) { try { AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); List<AnimeEpisode> eps = repEps.GetBySeriesID(animeSeriesID); AnimeSeries ser = null; foreach (AnimeEpisode ep in eps) { if (ep.EpisodeTypeEnum == (enEpisodeType)episodeType && ep.AniDB_Episode.EpisodeNumber <= maxEpisodeNumber) { // check if this episode is already watched bool currentStatus = false; AnimeEpisode_User epUser = ep.GetUserRecord(userID); if (epUser != null) currentStatus = epUser.WatchedCount > 0 ? true : false; if (currentStatus != watchedStatus) { logger.Info("Updating episode: {0} to {1}", ep.AniDB_Episode.EpisodeNumber, watchedStatus); ep.ToggleWatchedStatus(watchedStatus, true, DateTime.Now, false, false, userID, false); } } ser = ep.GetAnimeSeries(); } // now update the stats if (ser != null) { ser.UpdateStats(true, true, true); //StatsCache.Instance.UpdateUsingSeries(ser.AnimeSeriesID); } return ""; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); return ex.Message; } }
public void IncrementEpisodeStats(int animeEpisodeID, int userID, int statCountType) { try { AnimeEpisodeRepository repEpisodes = new AnimeEpisodeRepository(); AnimeEpisode ep = repEpisodes.GetByID(animeEpisodeID); if (ep == null) return; AnimeEpisode_UserRepository repEpisodeUsers = new AnimeEpisode_UserRepository(); AnimeEpisode_User epUserRecord = ep.GetUserRecord(userID); if (epUserRecord == null) { epUserRecord = new AnimeEpisode_User(); epUserRecord.PlayedCount = 0; epUserRecord.StoppedCount = 0; epUserRecord.WatchedCount = 0; } epUserRecord.AnimeEpisodeID = ep.AnimeEpisodeID; epUserRecord.AnimeSeriesID = ep.AnimeSeriesID; epUserRecord.JMMUserID = userID; //epUserRecord.WatchedDate = DateTime.Now; switch ((StatCountType)statCountType) { case StatCountType.Played: epUserRecord.PlayedCount++; break; case StatCountType.Stopped: epUserRecord.StoppedCount++; break; case StatCountType.Watched: epUserRecord.WatchedCount++; break; } repEpisodeUsers.Save(epUserRecord); AnimeSeries ser = ep.GetAnimeSeries(); if (ser == null) return; AnimeSeries_UserRepository repSeriesUser = new AnimeSeries_UserRepository(); AnimeSeries_User userRecord = ser.GetUserRecord(userID); if (userRecord == null) userRecord = new AnimeSeries_User(userID, ser.AnimeSeriesID); switch ((StatCountType)statCountType) { case StatCountType.Played: userRecord.PlayedCount++; break; case StatCountType.Stopped: userRecord.StoppedCount++; break; case StatCountType.Watched: userRecord.WatchedCount++; break; } repSeriesUser.Save(userRecord); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } }
public List<Contract_AnimeEpisode> GetEpisodesRecentlyAdded(int maxRecords, int jmmuserID) { List<Contract_AnimeEpisode> retEps = new List<Contract_AnimeEpisode>(); try { using (var session = JMMService.SessionFactory.OpenSession()) { AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeEpisode_UserRepository repEpUser = new AnimeEpisode_UserRepository(); JMMUserRepository repUsers = new JMMUserRepository(); VideoLocalRepository repVids = new VideoLocalRepository(); JMMUser user = repUsers.GetByID(session, jmmuserID); if (user == null) return retEps; List<VideoLocal> vids = repVids.GetMostRecentlyAdded(session, maxRecords); int numEps = 0; foreach (VideoLocal vid in vids) { foreach (AnimeEpisode ep in vid.GetAnimeEpisodes(session)) { if (user.AllowedSeries(ep.GetAnimeSeries(session))) { Contract_AnimeEpisode epContract = ep.ToContract(session, jmmuserID); if (epContract != null) { retEps.Add(epContract); numEps++; // Lets only return the specified amount if (retEps.Count == maxRecords) return retEps; } } } } } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return retEps; }
public List<Contract_AnimeEpisode> GetEpisodesForSeriesOld(int animeSeriesID) { List<Contract_AnimeEpisode> eps = new List<Contract_AnimeEpisode>(); try { DateTime start = DateTime.Now; AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeSeriesRepository repAnimeSer = new AnimeSeriesRepository(); CrossRef_File_EpisodeRepository repCrossRefs = new CrossRef_File_EpisodeRepository(); // get all the data first // we do this to reduce the amount of database calls, which makes it a lot faster AnimeSeries series = repAnimeSer.GetByID(animeSeriesID); if (series == null) return eps; List<AnimeEpisode> epList = repEps.GetBySeriesID(animeSeriesID); AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository(); List<AniDB_Episode> aniEpList = repAniEps.GetByAnimeID(series.AniDB_ID); Dictionary<int, AniDB_Episode> dictAniEps = new Dictionary<int, AniDB_Episode>(); foreach (AniDB_Episode aniep in aniEpList) dictAniEps[aniep.EpisodeID] = aniep; List<CrossRef_File_Episode> crossRefList = repCrossRefs.GetByAnimeID(series.AniDB_ID); TimeSpan ts = DateTime.Now - start; logger.Info("GetEpisodesForSeries: {0} (Database) in {1} ms", series.GetAnime().MainTitle, ts.TotalMilliseconds); start = DateTime.Now; foreach (AnimeEpisode ep in epList) { List<CrossRef_File_Episode> xrefs = new List<CrossRef_File_Episode>(); foreach (CrossRef_File_Episode xref in crossRefList) { if (ep.AniDB_EpisodeID == xref.EpisodeID) xrefs.Add(xref); } if (dictAniEps.ContainsKey(ep.AniDB_EpisodeID)) eps.Add(ep.ToContractOld(dictAniEps[ep.AniDB_EpisodeID])); } ts = DateTime.Now - start; logger.Info("GetEpisodesForSeries: {0} (Contracts) in {1} ms", series.GetAnime().MainTitle, ts.TotalMilliseconds); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return eps; }
public List<Contract_AnimeEpisode> GetEpisodesForSeries(int animeSeriesID, int userID) { List<Contract_AnimeEpisode> eps = new List<Contract_AnimeEpisode>(); try { DateTime start = DateTime.Now; AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeEpisode_UserRepository repEpUsers = new AnimeEpisode_UserRepository(); AnimeSeriesRepository repAnimeSer = new AnimeSeriesRepository(); VideoLocalRepository repVids = new VideoLocalRepository(); CrossRef_File_EpisodeRepository repCrossRefs = new CrossRef_File_EpisodeRepository(); // get all the data first // we do this to reduce the amount of database calls, which makes it a lot faster AnimeSeries series = repAnimeSer.GetByID(animeSeriesID); if (series == null) return eps; List<AnimeEpisode> epList = repEps.GetBySeriesID(animeSeriesID); List<AnimeEpisode_User> userRecordList = repEpUsers.GetByUserIDAndSeriesID(userID, animeSeriesID); Dictionary<int, AnimeEpisode_User> dictUserRecords = new Dictionary<int, AnimeEpisode_User>(); foreach (AnimeEpisode_User epuser in userRecordList) dictUserRecords[epuser.AnimeEpisodeID] = epuser; AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository(); List<AniDB_Episode> aniEpList = repAniEps.GetByAnimeID(series.AniDB_ID); Dictionary<int, AniDB_Episode> dictAniEps = new Dictionary<int, AniDB_Episode>(); foreach (AniDB_Episode aniep in aniEpList) dictAniEps[aniep.EpisodeID] = aniep; // get all the video local records and cross refs List<VideoLocal> vids = repVids.GetByAniDBAnimeID(series.AniDB_ID); List<CrossRef_File_Episode> crossRefs = repCrossRefs.GetByAnimeID(series.AniDB_ID); TimeSpan ts = DateTime.Now - start; logger.Info("GetEpisodesForSeries: {0} (Database) in {1} ms", series.GetAnime().MainTitle, ts.TotalMilliseconds); start = DateTime.Now; foreach (AnimeEpisode ep in epList) { if (dictAniEps.ContainsKey(ep.AniDB_EpisodeID)) { List<VideoLocal> epVids = new List<VideoLocal>(); foreach (CrossRef_File_Episode xref in crossRefs) { if (xref.EpisodeID == dictAniEps[ep.AniDB_EpisodeID].EpisodeID) { // don't add the same file twice, this will occur when // one file appears over more than one episodes Dictionary<string, string> addedFiles = new Dictionary<string, string>(); foreach (VideoLocal vl in vids) { if (string.Equals(xref.Hash, vl.Hash, StringComparison.InvariantCultureIgnoreCase)) { if (!addedFiles.ContainsKey(xref.Hash.Trim().ToUpper())) { addedFiles[xref.Hash.Trim().ToUpper()] = xref.Hash.Trim().ToUpper(); epVids.Add(vl); } } } } } AnimeEpisode_User epuser = null; if (dictUserRecords.ContainsKey(ep.AnimeEpisodeID)) epuser = dictUserRecords[ep.AnimeEpisodeID]; eps.Add(ep.ToContract(dictAniEps[ep.AniDB_EpisodeID], epVids, epuser, null)); } } ts = DateTime.Now - start; logger.Info("GetEpisodesForSeries: {0} (Contracts) in {1} ms", series.GetAnime().MainTitle, ts.TotalMilliseconds); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return eps; }
public Contract_AnimeEpisode GetEpisodeByAniDBEpisodeID(int episodeID, int userID) { try { AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeEpisode ep = repEps.GetByAniDBEpisodeID(episodeID); if (ep == null) return null; return ep.ToContract(userID); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); return null; } }
public string AssociateSingleFileWithMultipleEpisodes(int videoLocalID, int animeSeriesID, int startEpNum, int endEpNum) { try { VideoLocalRepository repVids = new VideoLocalRepository(); VideoLocal vid = repVids.GetByID(videoLocalID); if (vid == null) return "Could not find video record"; AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository(); CrossRef_File_EpisodeRepository repXRefs = new CrossRef_File_EpisodeRepository(); AnimeSeries ser = repSeries.GetByID(animeSeriesID); if (ser == null) return "Could not find anime series record"; for (int i = startEpNum; i <= endEpNum; i++) { List<AniDB_Episode> anieps = repAniEps.GetByAnimeIDAndEpisodeNumber(ser.AniDB_ID, i); if (anieps.Count == 0) return "Could not find the AniDB episode record"; AniDB_Episode aniep = anieps[0]; List<AnimeEpisode> eps = repEps.GetByAniEpisodeIDAndSeriesID(aniep.EpisodeID, ser.AnimeSeriesID); if (eps.Count == 0) return "Could not find episode record"; AnimeEpisode ep = eps[0]; CrossRef_File_Episode xref = new CrossRef_File_Episode(); xref.PopulateManually(vid, ep); repXRefs.Save(xref); CommandRequest_WebCacheSendXRefFileEpisode cr = new CommandRequest_WebCacheSendXRefFileEpisode(xref.CrossRef_File_EpisodeID); cr.Save(); } vid.RenameIfRequired(); vid.MoveFileIfRequired(); ser.QueueUpdateStats(); // update epidsode added stats ser.EpisodeAddedDate = DateTime.Now; repSeries.Save(ser); AnimeGroupRepository repGroups = new AnimeGroupRepository(); foreach (AnimeGroup grp in ser.AllGroupsAbove) { grp.EpisodeAddedDate = DateTime.Now; repGroups.Save(grp); } return ""; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return ""; }
public string AssociateSingleFile(int videoLocalID, int animeEpisodeID) { try { VideoLocalRepository repVids = new VideoLocalRepository(); VideoLocal vid = repVids.GetByID(videoLocalID); if (vid == null) return "Could not find video record"; AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeEpisode ep = repEps.GetByID(animeEpisodeID); if (ep == null) return "Could not find episode record"; CrossRef_File_EpisodeRepository repXRefs = new CrossRef_File_EpisodeRepository(); CrossRef_File_Episode xref = new CrossRef_File_Episode(); try { xref.PopulateManually(vid, ep); } catch (Exception ex) { string msg = string.Format("Error populating XREF: {0}", vid.ToStringDetailed()); throw; } repXRefs.Save(xref); vid.RenameIfRequired(); vid.MoveFileIfRequired(); CommandRequest_WebCacheSendXRefFileEpisode cr = new CommandRequest_WebCacheSendXRefFileEpisode(xref.CrossRef_File_EpisodeID); cr.Save(); AnimeSeries ser = ep.GetAnimeSeries(); ser.QueueUpdateStats(); // update epidsode added stats AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); ser.EpisodeAddedDate = DateTime.Now; repSeries.Save(ser); AnimeGroupRepository repGroups = new AnimeGroupRepository(); foreach (AnimeGroup grp in ser.AllGroupsAbove) { grp.EpisodeAddedDate = DateTime.Now; repGroups.Save(grp); } CommandRequest_AddFileToMyList cmdAddFile = new CommandRequest_AddFileToMyList(vid.Hash); cmdAddFile.Save(); return ""; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return ""; }
/// <summary> /// Finds the previous episode for use int the next unwatched episode /// </summary> /// <param name="animeSeriesID"></param> /// <param name="userID"></param> /// <returns></returns> public Contract_AnimeEpisode GetPreviousEpisodeForUnwatched(int animeSeriesID, int userID) { try { Contract_AnimeEpisode nextEp = GetNextUnwatchedEpisode(animeSeriesID, userID); if (nextEp == null) return null; int epType = nextEp.EpisodeType; int epNum = nextEp.EpisodeNumber - 1; if (epNum <= 0) return null; AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository(); AnimeSeriesRepository repAnimeSer = new AnimeSeriesRepository(); AnimeSeries series = repAnimeSer.GetByID(animeSeriesID); if (series == null) return null; List<AniDB_Episode> anieps = repAniEps.GetByAnimeIDAndEpisodeTypeNumber(series.AniDB_ID, (enEpisodeType)epType, epNum); if (anieps.Count == 0) return null; AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeEpisode ep = repEps.GetByAniDBEpisodeID(anieps[0].EpisodeID); if (ep == null) return null; return ep.ToContract(true, userID, null); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); return null; } }
public List<Contract_VideoLocal> GetVideoLocalsForEpisode(int episodeID, int userID) { List<Contract_VideoLocal> contracts = new List<Contract_VideoLocal>(); try { AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeEpisode ep = repEps.GetByID(episodeID); if (ep != null) { foreach (VideoLocal vid in ep.GetVideoLocals()) { contracts.Add(vid.ToContract(userID)); } } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return contracts; }
void workerMyAnime2_DoWork(object sender, DoWorkEventArgs e) { MA2Progress ma2Progress = new MA2Progress(); ma2Progress.CurrentFile = 0; ma2Progress.ErrorMessage = ""; ma2Progress.MigratedFiles = 0; ma2Progress.TotalFiles = 0; try { string databasePath = e.Argument as string; string connString = string.Format(@"data source={0};useutf16encoding=True", databasePath); SQLiteConnection myConn = new SQLiteConnection(connString); myConn.Open(); // get a list of unlinked files VideoLocalRepository repVids = new VideoLocalRepository(); AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository(); AniDB_AnimeRepository repAniAnime = new AniDB_AnimeRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); List<VideoLocal> vids = repVids.GetVideosWithoutEpisode(); ma2Progress.TotalFiles = vids.Count; foreach (VideoLocal vid in vids) { ma2Progress.CurrentFile = ma2Progress.CurrentFile + 1; workerMyAnime2.ReportProgress(0, ma2Progress); // search for this file in the XrossRef table in MA2 string sql = string.Format("SELECT AniDB_EpisodeID from CrossRef_Episode_FileHash WHERE Hash = '{0}' AND FileSize = {1}", vid.ED2KHash, vid.FileSize); SQLiteCommand sqCommand = new SQLiteCommand(sql); sqCommand.Connection = myConn; SQLiteDataReader myReader = sqCommand.ExecuteReader(); while (myReader.Read()) { int episodeID = 0; if (!int.TryParse(myReader.GetValue(0).ToString(), out episodeID)) continue; if (episodeID <= 0) continue; sql = string.Format("SELECT AnimeID from AniDB_Episode WHERE EpisodeID = {0}", episodeID); sqCommand = new SQLiteCommand(sql); sqCommand.Connection = myConn; SQLiteDataReader myReader2 = sqCommand.ExecuteReader(); while (myReader2.Read()) { int animeID = myReader2.GetInt32(0); // so now we have all the needed details we can link the file to the episode // as long as wehave the details in JMM AniDB_Anime anime = null; AniDB_Episode ep = repAniEps.GetByEpisodeID(episodeID); if (ep == null) { logger.Debug("Getting Anime record from AniDB...."); anime = JMMService.AnidbProcessor.GetAnimeInfoHTTP(animeID, true, ServerSettings.AutoGroupSeries); } else anime = repAniAnime.GetByAnimeID(animeID); // create the group/series/episode records if needed AnimeSeries ser = null; if (anime == null) continue; logger.Debug("Creating groups, series and episodes...."); // check if there is an AnimeSeries Record associated with this AnimeID ser = repSeries.GetByAnimeID(animeID); if (ser == null) { // create a new AnimeSeries record ser = anime.CreateAnimeSeriesAndGroup(); } ser.CreateAnimeEpisodes(); // check if we have any group status data for this associated anime // if not we will download it now AniDB_GroupStatusRepository repStatus = new AniDB_GroupStatusRepository(); if (repStatus.GetByAnimeID(anime.AnimeID).Count == 0) { CommandRequest_GetReleaseGroupStatus cmdStatus = new CommandRequest_GetReleaseGroupStatus(anime.AnimeID, false); cmdStatus.Save(); } // update stats ser.EpisodeAddedDate = DateTime.Now; repSeries.Save(ser); AnimeGroupRepository repGroups = new AnimeGroupRepository(); foreach (AnimeGroup grp in ser.AllGroupsAbove) { grp.EpisodeAddedDate = DateTime.Now; repGroups.Save(grp); } AnimeEpisode epAnime = repEps.GetByAniDBEpisodeID(episodeID); if (epAnime == null) continue; CrossRef_File_EpisodeRepository repXRefs = new CrossRef_File_EpisodeRepository(); CrossRef_File_Episode xref = new CrossRef_File_Episode(); try { xref.PopulateManually(vid, epAnime); } catch (Exception ex) { string msg = string.Format("Error populating XREF: {0} - {1}", vid.ToStringDetailed(), ex.ToString()); throw; } repXRefs.Save(xref); vid.RenameIfRequired(); vid.MoveFileIfRequired(); // update stats for groups and series if (ser != null) { // update all the groups above this series in the heirarchy ser.UpdateStats(true, true, true); StatsCache.Instance.UpdateUsingSeries(ser.AnimeSeriesID); } // Add this file to the users list if (ServerSettings.AniDB_MyList_AddFiles) { CommandRequest_AddFileToMyList cmd = new CommandRequest_AddFileToMyList(vid.ED2KHash); cmd.Save(); } ma2Progress.MigratedFiles = ma2Progress.MigratedFiles + 1; workerMyAnime2.ReportProgress(0, ma2Progress); } myReader2.Close(); //Console.WriteLine(myReader.GetString(0)); } myReader.Close(); } myConn.Close(); ma2Progress.CurrentFile = ma2Progress.CurrentFile + 1; workerMyAnime2.ReportProgress(0, ma2Progress); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); ma2Progress.ErrorMessage = ex.Message; workerMyAnime2.ReportProgress(0, ma2Progress); } }
/// <summary> /// Delete a series, and everything underneath it (episodes, files) /// </summary> /// <param name="animeSeriesID"></param> /// <param name="deleteFiles">also delete the physical files</param> /// <returns></returns> public string DeleteAnimeSeries(int animeSeriesID, bool deleteFiles, bool deleteParentGroup) { try { AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeSeriesRepository repAnimeSer = new AnimeSeriesRepository(); VideoLocalRepository repVids = new VideoLocalRepository(); AnimeGroupRepository repGroups = new AnimeGroupRepository(); AnimeSeries ser = repAnimeSer.GetByID(animeSeriesID); if (ser == null) return "Series does not exist"; int animeGroupID = ser.AnimeGroupID; foreach (AnimeEpisode ep in ser.GetAnimeEpisodes()) { foreach (VideoLocal vid in ep.GetVideoLocals()) { if (deleteFiles) { logger.Info("Deleting video local record and file: {0}", vid.FullServerPath); if (!File.Exists(vid.FullServerPath)) return "File could not be found"; File.Delete(vid.FullServerPath); } CommandRequest_DeleteFileFromMyList cmdDel = new CommandRequest_DeleteFileFromMyList(vid.Hash, vid.FileSize); cmdDel.Save(); repVids.Delete(vid.VideoLocalID); } repEps.Delete(ep.AnimeEpisodeID); } repAnimeSer.Delete(ser.AnimeSeriesID); // finally update stats AnimeGroup grp = repGroups.GetByID(animeGroupID); if (grp != null) { if (grp.GetAllSeries().Count == 0) { DeleteAnimeGroup(grp.AnimeGroupID, false); } else { grp.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true, true, true); StatsCache.Instance.UpdateUsingGroup(grp.TopLevelAnimeGroup.AnimeGroupID); } } return ""; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); return ex.Message; } }
public static int Scrobble(ScrobblePlayingType scrobbleType, string AnimeEpisodeID, ScrobblePlayingStatus scrobbleStatus, float progress) { try { if (!ServerSettings.Trakt_IsEnabled || string.IsNullOrEmpty(ServerSettings.Trakt_AuthToken)) return 401; string json = ""; string url = ""; switch (scrobbleStatus) { case ScrobblePlayingStatus.Start: url = TraktURIs.SetScrobbleStart; break; case ScrobblePlayingStatus.Pause: url = TraktURIs.SetScrobblePause; break; case ScrobblePlayingStatus.Stop: url = TraktURIs.SetScrobbleStop; break; } //1.get traktid and slugid from episode id int aep = 0; int.TryParse(AnimeEpisodeID, out aep); AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeEpisode ep = repEps.GetByID(aep); string slugID = ""; int season = 0; int epNumber = 0; int? traktID = GetTraktEpisodeIdV2(ep, ref slugID, ref season, ref epNumber); //2.generate json if (traktID == null && traktID > 0) { switch (scrobbleType) { case ScrobblePlayingType.episode: TraktV2ScrobbleEpisode showE = new TraktV2ScrobbleEpisode(); showE.Init(progress, traktID, slugID, season, epNumber); json = JSONHelper.Serialize<TraktV2ScrobbleEpisode>(showE); break; //do we have any movies that work? case ScrobblePlayingType.movie: TraktV2ScrobbleMovie showM = new TraktV2ScrobbleMovie(); json = JSONHelper.Serialize<TraktV2ScrobbleMovie>(showM); showM.Init(progress, slugID, traktID.ToString()); break; } //3. send Json string retData = string.Empty; int response = SendData(url, json, "POST", BuildRequestHeaders(), ref retData); } else { //3. nothing to send log error logger.Warn("TraktTVHelper.Scrobble: No TraktID found for: " + "AnimeEpisodeID: " + aep.ToString() + " AnimeRomajiName: " + ep.AniDB_Episode.RomajiName); return 404; } return 200; } catch (Exception ex) { logger.ErrorException("Error in TraktTVHelper.Scrobble: " + ex.ToString(), ex); return 500; } }
public Contract_ToggleWatchedStatusOnEpisode_Response ToggleWatchedStatusOnEpisode(int animeEpisodeID, bool watchedStatus, int userID) { Contract_ToggleWatchedStatusOnEpisode_Response response = new Contract_ToggleWatchedStatusOnEpisode_Response(); response.ErrorMessage = ""; response.AnimeEpisode = null; try { AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeEpisode ep = repEps.GetByID(animeEpisodeID); if (ep == null) { response.ErrorMessage = "Could not find anime episode record"; return response; } ep.ToggleWatchedStatus(watchedStatus, true, DateTime.Now, false, false, userID, true); ep.GetAnimeSeries().UpdateStats(true, false, true); //StatsCache.Instance.UpdateUsingSeries(ep.GetAnimeSeries().AnimeSeriesID); // refresh from db ep = repEps.GetByID(animeEpisodeID); response.AnimeEpisode = ep.ToContract(userID); return response; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); response.ErrorMessage = ex.Message; return response; } }
public List<Contract_VideoDetailed> GetFilesForEpisode(int episodeID, int userID) { try { AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeEpisode ep = repEps.GetByID(episodeID); if (ep != null) return ep.GetVideoDetailedContracts(userID); else return new List<Contract_VideoDetailed>(); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return new List<Contract_VideoDetailed>(); }
public List<Contract_AnimeEpisode> GetEpisodesRecentlyAddedSummary(int maxRecords, int jmmuserID) { List<Contract_AnimeEpisode> retEps = new List<Contract_AnimeEpisode>(); try { AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeEpisode_UserRepository repEpUser = new AnimeEpisode_UserRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); JMMUserRepository repUsers = new JMMUserRepository(); VideoLocalRepository repVids = new VideoLocalRepository(); using (var session = JMMService.SessionFactory.OpenSession()) { JMMUser user = repUsers.GetByID(session, jmmuserID); if (user == null) return retEps; DateTime start = DateTime.Now; string sql = "Select ae.AnimeSeriesID, max(vl.DateTimeCreated) as MaxDate " + "From VideoLocal vl " + "INNER JOIN CrossRef_File_Episode xref ON vl.Hash = xref.Hash " + "INNER JOIN AnimeEpisode ae ON ae.AniDB_EpisodeID = xref.EpisodeID " + "GROUP BY ae.AnimeSeriesID " + "ORDER BY MaxDate desc "; ArrayList results = DatabaseHelper.GetData(sql); TimeSpan ts2 = DateTime.Now - start; logger.Info("GetEpisodesRecentlyAddedSummary:RawData in {0} ms", ts2.TotalMilliseconds); start = DateTime.Now; int numEps = 0; foreach (object[] res in results) { int animeSeriesID = int.Parse(res[0].ToString()); AnimeSeries ser = repSeries.GetByID(session, animeSeriesID); if (ser == null) continue; if (!user.AllowedSeries(ser)) continue; List<VideoLocal> vids = repVids.GetMostRecentlyAddedForAnime(session, 1, ser.AniDB_ID); if (vids.Count == 0) continue; List<AnimeEpisode> eps = vids[0].GetAnimeEpisodes(session); if (eps.Count == 0) continue; Contract_AnimeEpisode epContract = eps[0].ToContract(session, jmmuserID); if (epContract != null) { retEps.Add(epContract); numEps++; // Lets only return the specified amount if (retEps.Count == maxRecords) { ts2 = DateTime.Now - start; logger.Info("GetEpisodesRecentlyAddedSummary:Episodes in {0} ms", ts2.TotalMilliseconds); start = DateTime.Now; return retEps; } } } ts2 = DateTime.Now - start; logger.Info("GetEpisodesRecentlyAddedSummary:Episodes in {0} ms", ts2.TotalMilliseconds); start = DateTime.Now; } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return retEps; }
public string AssociateMultipleFiles(List<int> videoLocalIDs, int animeSeriesID, int startingEpisodeNumber, bool singleEpisode) { try { CrossRef_File_EpisodeRepository repXRefs = new CrossRef_File_EpisodeRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); VideoLocalRepository repVids = new VideoLocalRepository(); AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository(); AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeSeries ser = repSeries.GetByID(animeSeriesID); if (ser == null) return "Could not find anime series record"; int epNumber = startingEpisodeNumber; int count = 1; foreach (int videoLocalID in videoLocalIDs) { VideoLocal vid = repVids.GetByID(videoLocalID); if (vid == null) return "Could not find video local record"; List<AniDB_Episode> anieps = repAniEps.GetByAnimeIDAndEpisodeNumber(ser.AniDB_ID, epNumber); if (anieps.Count == 0) return "Could not find the AniDB episode record"; AniDB_Episode aniep = anieps[0]; List<AnimeEpisode> eps = repEps.GetByAniEpisodeIDAndSeriesID(aniep.EpisodeID, ser.AnimeSeriesID); if (eps.Count == 0) return "Could not find episode record"; AnimeEpisode ep = eps[0]; CrossRef_File_Episode xref = new CrossRef_File_Episode(); xref.PopulateManually(vid, ep); // TODO do this properly if (singleEpisode) { xref.EpisodeOrder = count; if (videoLocalIDs.Count > 5) xref.Percentage = 100; else xref.Percentage = GetEpisodePercentages(videoLocalIDs.Count)[count - 1]; } repXRefs.Save(xref); vid.RenameIfRequired(); vid.MoveFileIfRequired(); CommandRequest_WebCacheSendXRefFileEpisode cr = new CommandRequest_WebCacheSendXRefFileEpisode(xref.CrossRef_File_EpisodeID); cr.Save(); count++; if (!singleEpisode) epNumber++; } ser.QueueUpdateStats(); // update epidsode added stats ser.EpisodeAddedDate = DateTime.Now; repSeries.Save(ser); AnimeGroupRepository repGroups = new AnimeGroupRepository(); foreach (AnimeGroup grp in ser.AllGroupsAbove) { grp.EpisodeAddedDate = DateTime.Now; repGroups.Save(grp); } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return ""; }
private void ProcessFile_AniDB(VideoLocal vidLocal) { logger.Trace("Checking for AniDB_File record for: {0} --- {1}", vidLocal.Hash, vidLocal.FilePath); // check if we already have this AniDB_File info in the database AniDB_FileRepository repAniFile = new AniDB_FileRepository(); AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository(); AniDB_AnimeRepository repAniAnime = new AniDB_AnimeRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); VideoLocalRepository repVidLocals = new VideoLocalRepository(); AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); CrossRef_File_EpisodeRepository repXrefFE = new CrossRef_File_EpisodeRepository(); AniDB_File aniFile = null; if (!ForceAniDB) { aniFile = repAniFile.GetByHashAndFileSize(vidLocal.Hash, vlocal.FileSize); if (aniFile == null) logger.Trace("AniDB_File record not found"); } int animeID = 0; if (aniFile == null) { // get info from AniDB logger.Debug("Getting AniDB_File record from AniDB...."); Raw_AniDB_File fileInfo = JMMService.AnidbProcessor.GetFileInfo(vidLocal); if (fileInfo != null) { // check if we already have a record aniFile = repAniFile.GetByHashAndFileSize(vidLocal.Hash, vlocal.FileSize); if (aniFile == null) aniFile = new AniDB_File(); aniFile.Populate(fileInfo); //overwrite with local file name string localFileName = Path.GetFileName(vidLocal.FilePath); aniFile.FileName = localFileName; repAniFile.Save(aniFile, false); aniFile.CreateLanguages(); aniFile.CreateCrossEpisodes(localFileName); if (!string.IsNullOrEmpty(fileInfo.OtherEpisodesRAW)) { string[] epIDs = fileInfo.OtherEpisodesRAW.Split(','); foreach (string epid in epIDs) { int id = 0; if (int.TryParse(epid, out id)) { CommandRequest_GetEpisode cmdEp = new CommandRequest_GetEpisode(id); cmdEp.Save(); } } } animeID = aniFile.AnimeID; } } bool missingEpisodes = false; // if we still haven't got the AniDB_File Info we try the web cache or local records if (aniFile == null) { // check if we have any records from previous imports List<CrossRef_File_Episode> crossRefs = repXrefFE.GetByHash(vidLocal.Hash); if (crossRefs == null || crossRefs.Count == 0) { // lets see if we can find the episode/anime info from the web cache if (ServerSettings.WebCache_XRefFileEpisode_Get) { crossRefs = XMLService.Get_CrossRef_File_Episode(vidLocal); if (crossRefs == null || crossRefs.Count == 0) { logger.Debug("Cannot find AniDB_File record or get cross ref from web cache record so exiting: {0}", vidLocal.ED2KHash); return; } else { foreach (CrossRef_File_Episode xref in crossRefs) { // in this case we need to save the cross refs manually as AniDB did not provide them repXrefFE.Save(xref); } } } else { logger.Debug("Cannot get AniDB_File record so exiting: {0}", vidLocal.ED2KHash); return; } } // we assume that all episodes belong to the same anime foreach (CrossRef_File_Episode xref in crossRefs) { animeID = xref.AnimeID; AniDB_Episode ep = repAniEps.GetByEpisodeID(xref.EpisodeID); if (ep == null) missingEpisodes = true; } } else { // check if we have the episode info // if we don't, we will need to re-download the anime info (which also has episode info) if (aniFile.EpisodeCrossRefs.Count == 0) { animeID = aniFile.AnimeID; // if we have the anidb file, but no cross refs it means something has been broken logger.Debug("Could not find any cross ref records for: {0}", vidLocal.ED2KHash); missingEpisodes = true; } else { foreach (CrossRef_File_Episode xref in aniFile.EpisodeCrossRefs) { AniDB_Episode ep = repAniEps.GetByEpisodeID(xref.EpisodeID); if (ep == null) missingEpisodes = true; animeID = xref.AnimeID; } } } // get from DB AniDB_Anime anime = repAniAnime.GetByAnimeID(animeID); bool animeRecentlyUpdated = false; if (anime != null) { TimeSpan ts = DateTime.Now - anime.DateTimeUpdated; if (ts.TotalHours < 4) animeRecentlyUpdated = true; } // even if we are missing episode info, don't get data more than once every 4 hours // this is to prevent banning if (missingEpisodes && !animeRecentlyUpdated) { logger.Debug("Getting Anime record from AniDB...."); // try using the cache first using (var session = JMMService.SessionFactory.OpenSession()) { anime = JMMService.AnidbProcessor.GetAnimeInfoHTTPFromCache(session, animeID, ServerSettings.AutoGroupSeries); } // if not in cache try from AniDB if (anime == null) anime = JMMService.AnidbProcessor.GetAnimeInfoHTTP(animeID, true, ServerSettings.AutoGroupSeries); } // create the group/series/episode records if needed AnimeSeries ser = null; if (anime != null) { logger.Debug("Creating groups, series and episodes...."); // check if there is an AnimeSeries Record associated with this AnimeID ser = repSeries.GetByAnimeID(animeID); if (ser == null) { // create a new AnimeSeries record ser = anime.CreateAnimeSeriesAndGroup(); } ser.CreateAnimeEpisodes(); // check if we have any group status data for this associated anime // if not we will download it now AniDB_GroupStatusRepository repStatus = new AniDB_GroupStatusRepository(); if (repStatus.GetByAnimeID(anime.AnimeID).Count == 0) { CommandRequest_GetReleaseGroupStatus cmdStatus = new CommandRequest_GetReleaseGroupStatus(anime.AnimeID, false); cmdStatus.Save(); } // update stats ser.EpisodeAddedDate = DateTime.Now; repSeries.Save(ser); AnimeGroupRepository repGroups = new AnimeGroupRepository(); foreach (AnimeGroup grp in ser.AllGroupsAbove) { grp.EpisodeAddedDate = DateTime.Now; repGroups.Save(grp); } } vidLocal.RenameIfRequired(); vidLocal.MoveFileIfRequired(); // update stats for groups and series if (ser != null) { // update all the groups above this series in the heirarchy ser.UpdateStats(true, true, true); StatsCache.Instance.UpdateUsingSeries(ser.AnimeSeriesID); } // Add this file to the users list if (ServerSettings.AniDB_MyList_AddFiles) { CommandRequest_AddFileToMyList cmd = new CommandRequest_AddFileToMyList(vidLocal.ED2KHash); cmd.Save(); } // lets also try adding to the users trakt collecion by sync'ing the series if (ser != null) { CommandRequest_TraktSyncCollectionSeries cmdTrakt = new CommandRequest_TraktSyncCollectionSeries(ser.AnimeSeriesID, ser.GetAnime().MainTitle); cmdTrakt.Save(); } // sync the series on MAL if (ser != null) { CommandRequest_MALUpdatedWatchedStatus cmdMAL = new CommandRequest_MALUpdatedWatchedStatus(ser.AniDB_ID); cmdMAL.Save(); } }
public List<Contract_AnimeEpisode> GetEpisodesRecentlyWatched(int maxRecords, int jmmuserID) { List<Contract_AnimeEpisode> retEps = new List<Contract_AnimeEpisode>(); try { using (var session = JMMService.SessionFactory.OpenSession()) { AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeEpisode_UserRepository repEpUser = new AnimeEpisode_UserRepository(); JMMUserRepository repUsers = new JMMUserRepository(); JMMUser user = repUsers.GetByID(session, jmmuserID); if (user == null) return retEps; // get a list of series that is applicable List<AnimeEpisode_User> allEpUserRecs = repEpUser.GetMostRecentlyWatched(session, jmmuserID); foreach (AnimeEpisode_User userRecord in allEpUserRecs) { AnimeEpisode ep = repEps.GetByID(session, userRecord.AnimeEpisodeID); if (ep == null) continue; Contract_AnimeEpisode epContract = ep.ToContract(session, jmmuserID); if (epContract != null) { retEps.Add(epContract); // Lets only return the specified amount if (retEps.Count == maxRecords) return retEps; } } } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return retEps; }
public override void ProcessCommand() { logger.Info("Processing CommandRequest_MALDownloadStatusFromMAL"); try { if (string.IsNullOrEmpty(ServerSettings.MAL_Username) || string.IsNullOrEmpty(ServerSettings.MAL_Password)) return; // find the latest eps to update AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); myanimelist mal = MALHelper.GetMALAnimeList(); if (mal == null) return; if (mal.anime == null) return; CrossRef_AniDB_MALRepository repCrossRef = new CrossRef_AniDB_MALRepository(); AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository(); AnimeEpisodeRepository repEp = new AnimeEpisodeRepository(); // find the anidb user JMMUserRepository repUsers = new JMMUserRepository(); List<JMMUser> aniDBUsers = repUsers.GetAniDBUsers(); if (aniDBUsers.Count == 0) return; JMMUser user = aniDBUsers[0]; foreach (myanimelistAnime malAnime in mal.anime) { // look up the anime CrossRef_AniDB_MAL xref = repCrossRef.GetByMALID(malAnime.series_animedb_id); if (xref == null) continue; if (malAnime.series_animedb_id == 8107 || malAnime.series_animedb_id == 10737) { Console.Write(""); } // check if this anime has any other links List<CrossRef_AniDB_MAL> allXrefs = repCrossRef.GetByAnimeID(xref.AnimeID); if (allXrefs.Count == 0) continue; // find the range of watched episodes that this applies to int startEpNumber = xref.StartEpisodeNumber; int endEpNumber = GetUpperEpisodeLimit(allXrefs, xref); List<AniDB_Episode> aniEps = repAniEps.GetByAnimeID(xref.AnimeID); foreach (AniDB_Episode aniep in aniEps) { if (aniep.EpisodeType != xref.StartEpisodeType) continue; AnimeEpisode ep = repEp.GetByAniDBEpisodeID(aniep.EpisodeID); if (ep == null) continue; int adjustedWatchedEps = malAnime.my_watched_episodes + xref.StartEpisodeNumber - 1; int epNum = aniep.EpisodeNumber; if (epNum < startEpNumber || epNum > endEpNumber) continue; AnimeEpisode_User usrRec = ep.GetUserRecord(user.JMMUserID); if (epNum <= adjustedWatchedEps) { // update if the user doesn't have a record (means not watched) // or it is currently un-watched bool update = false; if (usrRec == null) update = true; else { if (!usrRec.WatchedDate.HasValue) update = true; } if (update) ep.ToggleWatchedStatus(true, true, DateTime.Now, user.JMMUserID, false); } else { bool update = false; if (usrRec != null) { if (usrRec.WatchedDate.HasValue) update = true; } if (update) ep.ToggleWatchedStatus(false, true, DateTime.Now, user.JMMUserID, false); } } } } catch (Exception ex) { logger.Error("Error processing CommandRequest_MALDownloadStatusFromMAL: {0}", ex.ToString()); return; } }
/// <summary> /// Gets a list of episodes watched based on the most recently watched series /// It will return the next episode to watch in the most recent 10 series /// </summary> /// <returns></returns> public List<Contract_AnimeEpisode> GetEpisodesToWatch_RecentlyWatched(int maxRecords, int jmmuserID) { List<Contract_AnimeEpisode> retEps = new List<Contract_AnimeEpisode>(); try { using (var session = JMMService.SessionFactory.OpenSession()) { AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeSeriesRepository repAnimeSer = new AnimeSeriesRepository(); AnimeSeries_UserRepository repSeriesUser = new AnimeSeries_UserRepository(); JMMUserRepository repUsers = new JMMUserRepository(); DateTime start = DateTime.Now; JMMUser user = repUsers.GetByID(session, jmmuserID); if (user == null) return retEps; // get a list of series that is applicable List<AnimeSeries_User> allSeriesUser = repSeriesUser.GetMostRecentlyWatched(session, jmmuserID); TimeSpan ts = DateTime.Now - start; logger.Info(string.Format("GetEpisodesToWatch_RecentlyWatched:Series: {0}", ts.TotalMilliseconds)); start = DateTime.Now; foreach (AnimeSeries_User userRecord in allSeriesUser) { AnimeSeries series = repAnimeSer.GetByID(session, userRecord.AnimeSeriesID); if (series == null) continue; if (!user.AllowedSeries(series)) continue; Contract_AnimeEpisode ep = GetNextUnwatchedEpisode(session, userRecord.AnimeSeriesID, jmmuserID); if (ep != null) { retEps.Add(ep); // Lets only return the specified amount if (retEps.Count == maxRecords) { ts = DateTime.Now - start; logger.Info(string.Format("GetEpisodesToWatch_RecentlyWatched:Episodes: {0}", ts.TotalMilliseconds)); return retEps; } } } ts = DateTime.Now - start; logger.Info(string.Format("GetEpisodesToWatch_RecentlyWatched:Episodes: {0}", ts.TotalMilliseconds)); } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return retEps; }