public override void ProcessCommand() { logger.Info("Processing CommandRequest_MALUpdatedWatchedStatus: {0}", AnimeID); try { // find the latest eps to update AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); AniDB_Anime anime = repAnime.GetByAnimeID(AnimeID); if (anime == null) { return; } List <CrossRef_AniDB_MAL> crossRefs = anime.GetCrossRefMAL(); if (crossRefs == null || crossRefs.Count == 0) { return; } AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeSeries ser = repSeries.GetByAnimeID(AnimeID); if (ser == null) { return; } MALHelper.UpdateMALSeries(ser); } catch (Exception ex) { logger.Error("Error processing CommandRequest_MALUpdatedWatchedStatus: {0} - {1}", AnimeID, ex.ToString()); return; } }
public List <AnimeSeries> GetSeries(ISession session) { AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); List <AnimeSeries> seriesList = repSeries.GetByGroupID(this.AnimeGroupID); return(seriesList); }
public void UpdateGroupFilters() { AnimeGroupRepository repGroups = new AnimeGroupRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); GroupFilterRepository repGrpFilter = new GroupFilterRepository(); List <GroupFilter> gfs = repGrpFilter.GetAll(); List <AnimeGroup> allGrps = repGroups.GetAllTopLevelGroups(); // No Need of subgroups List <AnimeSeries> allSeries = repSeries.GetAll(); foreach (GroupFilter gf in gfs) { bool change = false; foreach (AnimeGroup grp in allGrps) { Contract_AnimeGroup cgrp = grp.GetUserContract(this.JMMUserID); change |= gf.CalculateGroupFilterGroups(cgrp, Contract, JMMUserID); } foreach (AnimeSeries ser in allSeries) { Contract_AnimeSeries cser = ser.GetUserContract(this.JMMUserID); change |= gf.CalculateGroupFilterSeries(cser, Contract, JMMUserID); } if (change) { repGrpFilter.Save(gf); } } }
public override void ProcessCommand() { logger.Info("Processing CommandRequest_TraktSyncCollectionSeries"); try { if (!ServerSettings.Trakt_IsEnabled || string.IsNullOrEmpty(ServerSettings.Trakt_AuthToken)) { return; } AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeSeries series = repSeries.GetByID(AnimeSeriesID); if (series == null) { logger.Error("Could not find anime series: {0}", AnimeSeriesID); return; } TraktTVHelper.SyncCollectionToTrakt_Series(series); } catch (Exception ex) { logger.Error("Error processing CommandRequest_TraktSyncCollectionSeries: {0}", ex.ToString()); return; } }
private List <string> GetPosterFilenames(ISession session) { List <string> allPosters = new List <string>(); // check if user has specied a fanart to always be used if (DefaultAnimeSeriesID.HasValue) { AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeSeries defaultSeries = repSeries.GetByID(session, DefaultAnimeSeriesID.Value); if (defaultSeries != null) { AniDB_Anime anime = defaultSeries.GetAnime(session); string defPosterPathNoBlanks = anime.GetDefaultPosterPathNoBlanks(session); if (!string.IsNullOrEmpty(defPosterPathNoBlanks) && File.Exists(defPosterPathNoBlanks)) { allPosters.Add(defPosterPathNoBlanks); return(allPosters); } } } foreach (AnimeSeries ser in GetAllSeries(session)) { AniDB_Anime anime = ser.GetAnime(session); string defPosterPathNoBlanks = anime.GetDefaultPosterPathNoBlanks(session); if (!string.IsNullOrEmpty(defPosterPathNoBlanks) && File.Exists(defPosterPathNoBlanks)) { allPosters.Add(defPosterPathNoBlanks); } } return(allPosters); }
public static void UpdateAllStats() { AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); foreach (AnimeSeries ser in repSeries.GetAll()) { ser.QueueUpdateStats(); } }
public override void ProcessCommand() { logger.Info("Get AniDB episode info: {0}", EpisodeID); try { // we don't use this command to update episode info // we actually use it to update the cross ref info instead // and we only use it for the "Other Episodes" section of the FILE command // because that field doesn't tell you what anime it belongs to CrossRef_File_EpisodeRepository repCrossRefs = new CrossRef_File_EpisodeRepository(); List <CrossRef_File_Episode> xrefs = repCrossRefs.GetByEpisodeID(EpisodeID); if (xrefs.Count == 0) { return; } Raw_AniDB_Episode epInfo = JMMService.AnidbProcessor.GetEpisodeInfo(EpisodeID); if (epInfo != null) { AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); //Change, AniDB_File do not create Series Episodes does. foreach (CrossRef_File_Episode xref in xrefs) { int oldAnimeID = xref.AnimeID; xref.AnimeID = epInfo.AnimeID; repCrossRefs.Save(xref); AnimeSeries ser = repSeries.GetByAnimeID(oldAnimeID); if (ser != null) { ser.QueueUpdateStats(); } //StatsCache.Instance.UpdateUsingAnime(oldAnimeID); ser = repSeries.GetByAnimeID(epInfo.AnimeID); if (ser != null) { ser.QueueUpdateStats(); } //StatsCache.Instance.UpdateUsingAnime(epInfo.AnimeID); } } } catch (Exception ex) { logger.Error("Error processing CommandRequest_GetEpisode: {0} - {1}", EpisodeID, ex.ToString()); return; } }
public override void ProcessCommand() { AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeSeries ser = repSeries.GetByAnimeID(AnimeID); if (ser != null) { ser.UpdateStats(true, true, true); } }
public void UpdateGroupFilter(HashSet <GroupFilterConditionType> types) { AnimeSeriesRepository repo = new AnimeSeriesRepository(); JMMUserRepository repouser = new JMMUserRepository(); AnimeSeries ser = repo.GetByID(AnimeSeriesID); JMMUser usr = repouser.GetByID(JMMUserID); if (ser != null && usr != null) { ser.UpdateGroupFilters(types, usr); } }
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(); } }
private static void InitCache(this IDatabase db) { JMMUserRepository.InitCache(); AniDB_AnimeRepository.InitCache(); VideoInfoRepository.InitCache(); VideoLocalRepository.InitCache(); VideoLocal_UserRepository.InitCache(); List <GroupFilter> recalc = GroupFilterRepository.InitCache(); AnimeEpisodeRepository.InitCache(); AnimeEpisode_UserRepository.InitCache(); AnimeSeriesRepository.InitCache(); AnimeSeries_UserRepository.InitCache(); AnimeGroupRepository.InitCache(); AnimeGroup_UserRepository.InitCache(); GroupFilterRepository.InitCacheSecondPart(recalc); DatabaseFixes.ExecuteDatabaseFixes(); db.CleanUpMemory(); }
/* * public static void DownloadAllEpisodes() * { * CrossRef_AniDB_TvDBV2Repository repCrossRef = new CrossRef_AniDB_TvDBV2Repository(); * List<CrossRef_AniDB_TvDBV2> allCrossRefs = repCrossRef.GetAll(); * * List<int> tvDBIDs = new List<int>(); * foreach (CrossRef_AniDB_TvDBV2 xref in allCrossRefs) * { * if (!tvDBIDs.Contains(xref.TvDBID)) tvDBIDs.Add(xref.TvDBID); * } * * DownloadAllEpisodes(tvDBIDs); * } * * public static void DownloadAllEpisodes(List<int> tvDBIDs) * { * foreach (int tvid in tvDBIDs) * { * CommandRequest_TvDBUpdateSeriesAndEpisodes cmd = new CommandRequest_TvDBUpdateSeriesAndEpisodes(tvid, 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 override void ProcessCommand() { logger.Info("Processing CommandRequest_TraktSyncCollectionSeries"); try { AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeSeries series = repSeries.GetByID(AnimeSeriesID); if (series == null) { logger.Error("Could not find anime series: {0}", AnimeSeriesID); return; } TraktTVHelper.SyncCollectionToTrakt_Series(series); } catch (Exception ex) { logger.Error("Error processing CommandRequest_TraktSyncCollectionSeries: {0}", ex.ToString()); 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(); } } }
private System.IO.Stream GetGroupsFromFilter(int userid, string GroupFilterId) { KodiObject ret = new KodiObject(KodiHelper.NewMediaContainer("Filters", true)); if (!ret.Init()) { return(new MemoryStream()); } //List<Joint> retGroups = new List<Joint>(); List <Video> retGroups = new List <Video>(); try { int groupFilterID; int.TryParse(GroupFilterId, out groupFilterID); using (var session = JMMService.SessionFactory.OpenSession()) { if (groupFilterID == -1) { return(new MemoryStream()); } DateTime start = DateTime.Now; GroupFilterRepository repGF = new GroupFilterRepository(); GroupFilter gf; if (groupFilterID == -999) { // all groups gf = new GroupFilter(); gf.GroupFilterName = "All"; } else { gf = repGF.GetByID(session, groupFilterID); if (gf == null) { return(new MemoryStream()); } } ret.MediaContainer.Title2 = ret.MediaContainer.Title1 = gf.GroupFilterName; //Contract_GroupFilterExtended contract = gf.ToContractExtended(user); AnimeGroupRepository repGroups = new AnimeGroupRepository(); List <AnimeGroup> allGrps = repGroups.GetAll(session); 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; if ((StatsCache.Instance.StatUserGroupFilter.ContainsKey(userid)) && (StatsCache.Instance.StatUserGroupFilter[userid].ContainsKey(gf.GroupFilterID))) { HashSet <int> groups = StatsCache.Instance.StatUserGroupFilter[userid][gf.GroupFilterID]; var tas = StatsCache.Instance.StatKodiGroupsCache; foreach (AnimeGroup grp in allGrps) { if (groups.Contains(grp.AnimeGroupID)) { try { //if (grp.GroupName == "Rockman.EXE") //{ // int x = grp.MissingEpisodeCount; //} Video v = StatsCache.Instance.StatKodiGroupsCache[userid][grp.AnimeGroupID]; if (v != null) { //proper naming AniDB_Anime anim = grp.Anime[0]; v.OriginalTitle = ""; foreach (AniDB_Anime_Title title in anim.GetTitles()) { if (title.TitleType == "official" || title.TitleType == "main") { v.OriginalTitle += "{" + title.TitleType + ":" + title.Language + "}" + title.Title + "|"; } } v.OriginalTitle = v.OriginalTitle.Substring(0, v.OriginalTitle.Length - 1); //proper naming end retGroups.Add(v.Clone()); } } catch (Exception e) { int x = retGroups.Count; } } } } 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); if ((groupFilterID == -999) || (gf.SortCriteriaList.Count == 0)) { ret.Childrens = retGroups.OrderBy(a => a.Group.SortName).ToList(); return(ret.GetStream()); } List <Contract_AnimeGroup> grps = retGroups.Select(a => a.Group).ToList(); List <SortPropOrFieldAndDirection> sortCriteria = new List <SortPropOrFieldAndDirection>(); foreach (GroupFilterSortingCriteria g in gf.SortCriteriaList) { sortCriteria.Add(GroupFilterHelper.GetSortDescription(g.SortType, g.SortDirection)); } grps = Sorting.MultiSort(grps, sortCriteria); List <Video> joints2 = new List <Video>(); foreach (Contract_AnimeGroup gr in grps) { foreach (Video j in retGroups) { if (j.Group == gr) { //experiment AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeGroup ag = repGroups.GetByID(gr.AnimeGroupID); List <AnimeSeries> sers = ag.GetAllSeries(); AnimeSeries ser = sers[0]; AniDB_Anime anim = ser.GetAnime(); j.CharactersList = new List <Characters>(); Characters c = new Characters(); c.CharactersList = GetCharactersFromAniDB(anim); j.CharactersList.Add(c); //experimentEND //proper naming j.OriginalTitle = ""; foreach (AniDB_Anime_Title title in anim.GetTitles()) { if (title.TitleType == "official" || title.TitleType == "main") { j.OriginalTitle += "{" + title.TitleType + ":" + title.Language + "}" + title.Title + "|"; } } j.OriginalTitle = j.OriginalTitle.Substring(0, j.OriginalTitle.Length - 1); //proper naming end //community support //CrossRef_AniDB_TraktV2Repository repCrossRef = new CrossRef_AniDB_TraktV2Repository(); //List<CrossRef_AniDB_TraktV2> Trakt = repCrossRef.GetByAnimeID(anim.AnimeID); //if (Trakt != null) //{ // if (Trakt.Count > 0) // { // j.Trakt = Trakt[0].TraktID; // } //} //CrossRef_AniDB_TvDBV2Repository repCrossRefV2 = new CrossRef_AniDB_TvDBV2Repository(); //List<CrossRef_AniDB_TvDBV2> TvDB = repCrossRefV2.GetByAnimeID(anim.AnimeID); //if (TvDB != null) //{ // if (TvDB.Count > 0) // { // j.TvDB = TvDB[0].TvDBID.ToString(); // } //} //community support END joints2.Add(j); retGroups.Remove(j); break; } } } ret.Childrens = joints2; ret.MediaContainer.Art = KodiHelper.GetRandomFanartFromVideoList(ret.Childrens); ts = DateTime.Now - start; msg = string.Format("Got groups final: {0} - {1} in {2} ms", gf.GroupFilterName, retGroups.Count, ts.TotalMilliseconds); logger.Info(msg); return(ret.GetStream()); } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return(new MemoryStream()); }
public override void ProcessCommand() { logger.Info("Processing CommandRequest_GetUpdated"); try { List <int> animeIDsToUpdate = new List <int>(); ScheduledUpdateRepository repSched = new ScheduledUpdateRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); // check the automated update table to see when the last time we ran this command ScheduledUpdate sched = repSched.GetByUpdateType((int)ScheduledUpdateType.AniDBUpdates); if (sched != null) { int freqHours = Utils.GetScheduledHours(ServerSettings.AniDB_Anime_UpdateFrequency); // if we have run this in the last 12 hours and are not forcing it, then exit TimeSpan tsLastRun = DateTime.Now - sched.LastUpdate; if (tsLastRun.TotalHours < freqHours) { if (!ForceRefresh) { return; } } } long webUpdateTime = 0; long webUpdateTimeNew = 0; if (sched == null) { // if this is the first time, lets ask for last 3 days DateTime localTime = DateTime.Now.AddDays(-3); DateTime utcTime = localTime.ToUniversalTime(); webUpdateTime = long.Parse(Utils.AniDBDate(utcTime)); webUpdateTimeNew = long.Parse(Utils.AniDBDate(DateTime.Now.ToUniversalTime())); sched = new ScheduledUpdate(); sched.UpdateType = (int)ScheduledUpdateType.AniDBUpdates; } else { logger.Trace("Last anidb info update was : {0}", sched.UpdateDetails); webUpdateTime = long.Parse(sched.UpdateDetails); webUpdateTimeNew = long.Parse(Utils.AniDBDate(DateTime.Now.ToUniversalTime())); DateTime timeNow = DateTime.Now.ToUniversalTime(); logger.Info(string.Format("{0} since last UPDATED command", Utils.FormatSecondsToDisplayTime(int.Parse((webUpdateTimeNew - webUpdateTime).ToString())))); } // get a list of updates from AniDB // startTime will contain the date/time from which the updates apply to JMMService.AnidbProcessor.GetUpdated(ref animeIDsToUpdate, ref webUpdateTime); // now save the update time from AniDB // we will use this next time as a starting point when querying the web cache sched.LastUpdate = DateTime.Now; sched.UpdateDetails = webUpdateTimeNew.ToString(); repSched.Save(sched); if (animeIDsToUpdate.Count == 0) { logger.Info("No anime to be updated"); return; } int countAnime = 0; int countSeries = 0; foreach (int animeID in animeIDsToUpdate) { // update the anime from HTTP AniDB_Anime anime = repAnime.GetByAnimeID(animeID); if (anime == null) { logger.Trace("No local record found for Anime ID: {0}, so skipping...", animeID); continue; } logger.Info("Updating CommandRequest_GetUpdated: {0} ", animeID); // but only if it hasn't been recently updated TimeSpan ts = DateTime.Now - anime.DateTimeUpdated; if (ts.TotalHours > 4) { CommandRequest_GetAnimeHTTP cmdAnime = new CommandRequest_GetAnimeHTTP(animeID, true, false); cmdAnime.Save(); countAnime++; } // update the group status // this will allow us to determine which anime has missing episodes // so we wonly get by an amime where we also have an associated series AnimeSeries ser = repSeries.GetByAnimeID(animeID); if (ser != null) { CommandRequest_GetReleaseGroupStatus cmdStatus = new CommandRequest_GetReleaseGroupStatus(animeID, true); cmdStatus.Save(); countSeries++; } } logger.Info("Updating {0} anime records, and {1} group status records", countAnime, countSeries); } catch (Exception ex) { logger.Error("Error processing CommandRequest_GetUpdated: {0}", ex.ToString()); return; } }
public void UpdateStats(bool watchedStats, bool missingEpsStats, bool updateAllGroupsAbove) { DateTime start = DateTime.Now; DateTime startOverall = DateTime.Now; logger.Info("Starting Updating STATS for SERIES {0} ({1} - {2} - {3})", this.ToString(), watchedStats, missingEpsStats, updateAllGroupsAbove); AnimeSeries_UserRepository repSeriesUser = new AnimeSeries_UserRepository(); AnimeEpisode_UserRepository repEpisodeUser = new AnimeEpisode_UserRepository(); VideoLocalRepository repVids = new VideoLocalRepository(); CrossRef_File_EpisodeRepository repXrefs = new CrossRef_File_EpisodeRepository(); JMMUserRepository repUsers = new JMMUserRepository(); List <JMMUser> allUsers = repUsers.GetAll(); DateTime startEps = DateTime.Now; List <AnimeEpisode> eps = GetAnimeEpisodes(); TimeSpan tsEps = DateTime.Now - startEps; logger.Trace("Got episodes for SERIES {0} in {1}ms", this.ToString(), tsEps.TotalMilliseconds); DateTime startVids = DateTime.Now; List <VideoLocal> vidsTemp = repVids.GetByAniDBAnimeID(this.AniDB_ID); List <CrossRef_File_Episode> crossRefs = repXrefs.GetByAnimeID(this.AniDB_ID); Dictionary <int, List <CrossRef_File_Episode> > dictCrossRefs = new Dictionary <int, List <CrossRef_File_Episode> >(); foreach (CrossRef_File_Episode xref in crossRefs) { if (!dictCrossRefs.ContainsKey(xref.EpisodeID)) { dictCrossRefs[xref.EpisodeID] = new List <CrossRef_File_Episode>(); } dictCrossRefs[xref.EpisodeID].Add(xref); } Dictionary <string, VideoLocal> dictVids = new Dictionary <string, VideoLocal>(); foreach (VideoLocal vid in vidsTemp) { dictVids[vid.Hash] = vid; } TimeSpan tsVids = DateTime.Now - startVids; logger.Trace("Got video locals for SERIES {0} in {1}ms", this.ToString(), tsVids.TotalMilliseconds); if (watchedStats) { foreach (JMMUser juser in allUsers) { //this.WatchedCount = 0; AnimeSeries_User userRecord = GetUserRecord(juser.JMMUserID); if (userRecord == null) { userRecord = new AnimeSeries_User(juser.JMMUserID, this.AnimeSeriesID); } // reset stats userRecord.UnwatchedEpisodeCount = 0; userRecord.WatchedEpisodeCount = 0; userRecord.WatchedCount = 0; userRecord.WatchedDate = null; DateTime startUser = DateTime.Now; List <AnimeEpisode_User> epUserRecords = repEpisodeUser.GetByUserID(juser.JMMUserID); Dictionary <int, AnimeEpisode_User> dictUserRecords = new Dictionary <int, AnimeEpisode_User>(); foreach (AnimeEpisode_User usrec in epUserRecords) { dictUserRecords[usrec.AnimeEpisodeID] = usrec; } TimeSpan tsUser = DateTime.Now - startUser; logger.Trace("Got user records for SERIES {0}/{1} in {2}ms", this.ToString(), juser.Username, tsUser.TotalMilliseconds); foreach (AnimeEpisode ep in eps) { // if the episode doesn't have any files then it won't count towards watched/unwatched counts List <VideoLocal> epVids = new List <VideoLocal>(); if (dictCrossRefs.ContainsKey(ep.AniDB_EpisodeID)) { foreach (CrossRef_File_Episode xref in dictCrossRefs[ep.AniDB_EpisodeID]) { if (xref.EpisodeID == ep.AniDB_EpisodeID) { if (dictVids.ContainsKey(xref.Hash)) { epVids.Add(dictVids[xref.Hash]); } } } } if (epVids.Count == 0) { continue; } if (ep.EpisodeTypeEnum == AniDBAPI.enEpisodeType.Episode || ep.EpisodeTypeEnum == AniDBAPI.enEpisodeType.Special) { AnimeEpisode_User epUserRecord = null; if (dictUserRecords.ContainsKey(ep.AnimeEpisodeID)) { epUserRecord = dictUserRecords[ep.AnimeEpisodeID]; } if (epUserRecord != null && epUserRecord.WatchedDate.HasValue) { userRecord.WatchedEpisodeCount++; } else { userRecord.UnwatchedEpisodeCount++; } if (epUserRecord != null) { if (userRecord.WatchedDate.HasValue) { if (epUserRecord.WatchedDate > userRecord.WatchedDate) { userRecord.WatchedDate = epUserRecord.WatchedDate; } } else { userRecord.WatchedDate = epUserRecord.WatchedDate; } userRecord.WatchedCount += epUserRecord.WatchedCount; } } } repSeriesUser.Save(userRecord); } } TimeSpan ts = DateTime.Now - start; logger.Trace("Updated WATCHED stats for SERIES {0} in {1}ms", this.ToString(), ts.TotalMilliseconds); start = DateTime.Now; if (missingEpsStats) { enAnimeType animeType = enAnimeType.TVSeries; AniDB_Anime aniDB_Anime = this.GetAnime(); if (aniDB_Anime != null) { animeType = aniDB_Anime.AnimeTypeEnum; } MissingEpisodeCount = 0; MissingEpisodeCountGroups = 0; // get all the group status records AniDB_GroupStatusRepository repGrpStat = new AniDB_GroupStatusRepository(); List <AniDB_GroupStatus> grpStatuses = repGrpStat.GetByAnimeID(this.AniDB_ID); // find all the episodes for which the user has a file // from this we can determine what their latest episode number is // find out which groups the user is collecting List <int> userReleaseGroups = new List <int>(); foreach (AnimeEpisode ep in eps) { List <VideoLocal> vids = new List <VideoLocal>(); if (dictCrossRefs.ContainsKey(ep.AniDB_EpisodeID)) { foreach (CrossRef_File_Episode xref in dictCrossRefs[ep.AniDB_EpisodeID]) { if (xref.EpisodeID == ep.AniDB_EpisodeID) { if (dictVids.ContainsKey(xref.Hash)) { vids.Add(dictVids[xref.Hash]); } } } } //List<VideoLocal> vids = ep.VideoLocals; foreach (VideoLocal vid in vids) { AniDB_File anifile = vid.GetAniDBFile(); if (anifile != null) { if (!userReleaseGroups.Contains(anifile.GroupID)) { userReleaseGroups.Add(anifile.GroupID); } } } } int latestLocalEpNumber = 0; EpisodeList epReleasedList = new EpisodeList(animeType); EpisodeList epGroupReleasedList = new EpisodeList(animeType); foreach (AnimeEpisode ep in eps) { //List<VideoLocal> vids = ep.VideoLocals; if (ep.EpisodeTypeEnum != AniDBAPI.enEpisodeType.Episode) { continue; } List <VideoLocal> vids = new List <VideoLocal>(); if (dictCrossRefs.ContainsKey(ep.AniDB_EpisodeID)) { foreach (CrossRef_File_Episode xref in dictCrossRefs[ep.AniDB_EpisodeID]) { if (xref.EpisodeID == ep.AniDB_EpisodeID) { if (dictVids.ContainsKey(xref.Hash)) { vids.Add(dictVids[xref.Hash]); } } } } AniDB_Episode aniEp = ep.AniDB_Episode; int thisEpNum = aniEp.EpisodeNumber; if (thisEpNum > latestLocalEpNumber && vids.Count > 0) { latestLocalEpNumber = thisEpNum; } // does this episode have a file released // does this episode have a file released by the group the user is collecting bool epReleased = false; bool epReleasedGroup = false; foreach (AniDB_GroupStatus gs in grpStatuses) { if (gs.LastEpisodeNumber >= thisEpNum) { epReleased = true; } if (userReleaseGroups.Contains(gs.GroupID) && gs.HasGroupReleasedEpisode(thisEpNum)) { epReleasedGroup = true; } } try { epReleasedList.Add(ep, (!epReleased || vids.Count != 0)); epGroupReleasedList.Add(ep, (!epReleasedGroup || vids.Count != 0)); } catch (Exception e) { logger.Trace("Error {0}", e.ToString()); throw; } } foreach (EpisodeList.StatEpisodes eplst in epReleasedList) { if (!eplst.Available) { MissingEpisodeCount++; } } foreach (EpisodeList.StatEpisodes eplst in epGroupReleasedList) { if (!eplst.Available) { MissingEpisodeCountGroups++; } } this.LatestLocalEpisodeNumber = latestLocalEpNumber; } ts = DateTime.Now - start; logger.Trace("Updated MISSING EPS stats for SERIES {0} in {1}ms", this.ToString(), ts.TotalMilliseconds); start = DateTime.Now; AnimeSeriesRepository rep = new AnimeSeriesRepository(); rep.Save(this); if (updateAllGroupsAbove) { foreach (AnimeGroup grp in AllGroupsAbove) { grp.UpdateStats(watchedStats, missingEpsStats); } } ts = DateTime.Now - start; logger.Trace("Updated GROUPS ABOVE stats for SERIES {0} in {1}ms", this.ToString(), ts.TotalMilliseconds); start = DateTime.Now; TimeSpan tsOverall = DateTime.Now - startOverall; logger.Info("Finished Updating STATS for SERIES {0} in {1}ms ({2} - {3} - {4})", this.ToString(), tsOverall.TotalMilliseconds, watchedStats, missingEpsStats, updateAllGroupsAbove); }
public GroupStatusCollection GetReleaseGroupStatusUDP(int animeID) { if (!Login()) { return(null); } enHelperActivityType ev = enHelperActivityType.NoSuchCreator; AniDBCommand_GetGroupStatus getCmd = null; lock (lockAniDBConnections) { Pause(); getCmd = new AniDBCommand_GetGroupStatus(); getCmd.Init(animeID); SetWaitingOnResponse(true); ev = getCmd.Process(ref soUdp, ref remoteIpEndPoint, curSessionID, new UnicodeEncoding(true, false)); SetWaitingOnResponse(false); } if (ev == enHelperActivityType.GotGroupStatus && getCmd.GrpStatusCollection != null) { // delete existing records AniDB_GroupStatusRepository repGrpStat = new AniDB_GroupStatusRepository(); AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); AniDB_EpisodeRepository repAniEp = new AniDB_EpisodeRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); repGrpStat.DeleteForAnime(animeID); // save the records foreach (Raw_AniDB_GroupStatus raw in getCmd.GrpStatusCollection.Groups) { AniDB_GroupStatus grpstat = new AniDB_GroupStatus(raw); repGrpStat.Save(grpstat); } // updated cached stats // we don't do it in the save method as it would be too many unecessary updates logger.Trace("Updating group stats by anime from GetReleaseGroupStatusUDP: {0}", animeID); StatsCache.Instance.UpdateUsingAnime(animeID); if (getCmd.GrpStatusCollection.LatestEpisodeNumber > 0) { // update the anime with a record of the latest subbed episode AniDB_Anime anime = repAnime.GetByAnimeID(animeID); if (anime != null) { anime.LatestEpisodeNumber = getCmd.GrpStatusCollection.LatestEpisodeNumber; repAnime.Save(anime); // check if we have this episode in the database // if not get it now by updating the anime record List <AniDB_Episode> eps = repAniEp.GetByAnimeIDAndEpisodeNumber(animeID, getCmd.GrpStatusCollection.LatestEpisodeNumber); if (eps.Count == 0) { CommandRequest_GetAnimeHTTP cr_anime = new CommandRequest_GetAnimeHTTP(animeID, true, false); cr_anime.Save(); } // update the missing episode stats on groups and children AnimeSeries series = repSeries.GetByAnimeID(animeID); if (series != null) { series.UpdateStats(true, true, true); //series.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true, true, true); } } } } return(getCmd.GrpStatusCollection); }
private AniDB_Anime SaveResultsForAnimeXML(ISession session, int animeID, bool downloadRelations, AniDBHTTPCommand_GetFullAnime getAnimeCmd) { AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); AniDB_Anime anime = null; logger.Trace("cmdResult.Anime: {0}", getAnimeCmd.Anime); anime = repAnime.GetByAnimeID(session, animeID); if (anime == null) { anime = new AniDB_Anime(); } anime.PopulateAndSaveFromHTTP(session, getAnimeCmd.Anime, getAnimeCmd.Episodes, getAnimeCmd.Titles, getAnimeCmd.Categories, getAnimeCmd.Tags, getAnimeCmd.Characters, getAnimeCmd.Relations, getAnimeCmd.SimilarAnime, getAnimeCmd.Recommendations, downloadRelations); // Request an image download CommandRequest_DownloadImage cmd = new CommandRequest_DownloadImage(anime.AniDB_AnimeID, JMMImageType.AniDB_Cover, false); cmd.Save(session); // create AnimeEpisode records for all episodes in this anime // only if we have a series AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeSeries ser = repSeries.GetByAnimeID(session, animeID); if (ser != null) { ser.CreateAnimeEpisodes(session); } // update any files, that may have been linked /*CrossRef_File_EpisodeRepository repCrossRefs = new CrossRef_File_EpisodeRepository(); * repCrossRefs.GetByAnimeID(*/ // update cached stats StatsCache.Instance.UpdateUsingAnime(session, anime.AnimeID); StatsCache.Instance.UpdateAnimeContract(session, anime.AnimeID); // download character images foreach (AniDB_Anime_Character animeChar in anime.GetAnimeCharacters(session)) { AniDB_Character chr = animeChar.GetCharacter(session); if (chr == null) { continue; } if (ServerSettings.AniDB_DownloadCharacters) { if (!string.IsNullOrEmpty(chr.PosterPath) && !File.Exists(chr.PosterPath)) { logger.Debug("Downloading character image: {0} - {1}({2}) - {3}", anime.MainTitle, chr.CharName, chr.CharID, chr.PosterPath); cmd = new CommandRequest_DownloadImage(chr.AniDB_CharacterID, JMMImageType.AniDB_Character, false); cmd.Save(); } } if (ServerSettings.AniDB_DownloadCreators) { AniDB_Seiyuu seiyuu = chr.GetSeiyuu(session); if (seiyuu == null || string.IsNullOrEmpty(seiyuu.PosterPath)) { continue; } if (!File.Exists(seiyuu.PosterPath)) { logger.Debug("Downloading seiyuu image: {0} - {1}({2}) - {3}", anime.MainTitle, seiyuu.SeiyuuName, seiyuu.SeiyuuID, seiyuu.PosterPath); cmd = new CommandRequest_DownloadImage(seiyuu.AniDB_SeiyuuID, JMMImageType.AniDB_Creator, false); cmd.Save(); } } } return(anime); }
public override void ProcessCommand() { logger.Info("Get AniDB file info: {0}", VideoLocalID); try { AniDB_FileRepository repAniFile = new AniDB_FileRepository(); VideoLocalRepository repVids = new VideoLocalRepository(); vlocal = repVids.GetByID(VideoLocalID); if (vlocal == null) { return; } AniDB_File aniFile = repAniFile.GetByHashAndFileSize(vlocal.Hash, vlocal.FileSize); /*// get anidb file info from web cache * if (aniFile == null && ServerSettings.WebCache_AniDB_File_Get) * { * AniDB_FileRequest fr = XMLService.Get_AniDB_File(vlocal.Hash, vlocal.FileSize); * if (fr != null) * { * aniFile = new AniDB_File(); * aniFile.Populate(fr); * * //overwrite with local file name * string localFileName = Path.GetFileName(vlocal.FilePath); * aniFile.FileName = localFileName; * * repAniFile.Save(aniFile, false); * aniFile.CreateLanguages(); * aniFile.CreateCrossEpisodes(localFileName); * * StatsCache.Instance.UpdateUsingAniDBFile(vlocal.Hash); * } * }*/ Raw_AniDB_File fileInfo = null; if (aniFile == null || ForceAniDB) { fileInfo = JMMService.AnidbProcessor.GetFileInfo(vlocal); } if (fileInfo != null) { // save to the database if (aniFile == null) { aniFile = new AniDB_File(); } aniFile.Populate(fileInfo); //overwrite with local file name string localFileName = Path.GetFileName(vlocal.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(); } } } AnimeSeriesRepository repo = new AnimeSeriesRepository(); AniDB_AnimeRepository animerepo = new AniDB_AnimeRepository(); AniDB_Anime anime = animerepo.GetByAnimeID(aniFile.AnimeID); if (anime != null) { using (var session = JMMService.SessionFactory.OpenSession()) { anime.UpdateContractDetailed(session); } } AnimeSeries series = repo.GetByAnimeID(aniFile.AnimeID); series.UpdateStats(false, true, true); // StatsCache.Instance.UpdateUsingAniDBFile(vlocal.Hash); } } catch (Exception ex) { logger.Error("Error processing CommandRequest_GetFile: {0} - {1}", VideoLocalID, ex.ToString()); 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) { List <JMMServer.Providers.Azure.CrossRef_File_Episode> xrefs = JMMServer.Providers.Azure.AzureWebAPI.Get_CrossRefFileEpisode(vidLocal); crossRefs = new List <CrossRef_File_Episode>(); if (xrefs == null || xrefs.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 (JMMServer.Providers.Azure.CrossRef_File_Episode xref in xrefs) { CrossRef_File_Episode xrefEnt = new CrossRef_File_Episode(); xrefEnt.Hash = vidLocal.ED2KHash; xrefEnt.FileName = Path.GetFileName(vidLocal.FullServerPath); xrefEnt.FileSize = vidLocal.FileSize; xrefEnt.CrossRefSource = (int)JMMServer.CrossRefSource.WebCache; xrefEnt.AnimeID = animeID; xrefEnt.EpisodeID = xref.EpisodeID; xrefEnt.Percentage = xref.Percentage; xrefEnt.EpisodeOrder = xref.EpisodeOrder; crossRefs.Add(xrefEnt); // in this case we need to save the cross refs manually as AniDB did not provide them repXrefFE.Save(xrefEnt); } } } 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...."); 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) { if (ServerSettings.WebCache_Trakt_Send && !string.IsNullOrEmpty(ServerSettings.Trakt_Username)) { 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(); } }
/// <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 void MoveFileIfRequired() { // check if this file is in the drop folder // otherwise we don't need to move it if (this.ImportFolder.IsDropSource == 0) { return; } if (!File.Exists(this.FullServerPath)) { return; } // find the default destination ImportFolder destFolder = null; ImportFolderRepository repFolders = new ImportFolderRepository(); foreach (ImportFolder fldr in repFolders.GetAll()) { if (fldr.IsDropDestination == 1) { destFolder = fldr; break; } } if (destFolder == null) { return; } if (!Directory.Exists(destFolder.ImportFolderLocation)) { return; } // we can only move the file if it has an anime associated with it List <CrossRef_File_Episode> xrefs = this.EpisodeCrossRefs; if (xrefs.Count == 0) { return; } CrossRef_File_Episode xref = xrefs[0]; // find the series associated with this episode AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeSeries series = repSeries.GetByAnimeID(xref.AnimeID); if (series == null) { return; } // find where the other files are stored for this series // if there are no other files except for this one, it means we need to create a new location bool foundLocation = false; string newFullPath = ""; // sort the episodes by air date, so that we will move the file to the location of the latest episode List <AnimeEpisode> allEps = series.GetAnimeEpisodes(); List <SortPropOrFieldAndDirection> sortCriteria = new List <SortPropOrFieldAndDirection>(); sortCriteria.Add(new SortPropOrFieldAndDirection("AniDB_EpisodeID", true, SortType.eInteger)); allEps = Sorting.MultiSort <AnimeEpisode>(allEps, sortCriteria); foreach (AnimeEpisode ep in allEps) { foreach (VideoLocal vid in ep.GetVideoLocals()) { if (vid.VideoLocalID != this.VideoLocalID) { // make sure this folder is not the drop source if (vid.ImportFolder.IsDropSource == 1) { continue; } string thisFileName = vid.FullServerPath; string folderName = Path.GetDirectoryName(thisFileName); if (Directory.Exists(folderName)) { newFullPath = folderName; foundLocation = true; break; } } } if (foundLocation) { break; } } if (!foundLocation) { // we need to create a new folder string newFolderName = Utils.RemoveInvalidFolderNameCharacters(series.GetAnime().MainTitle); newFullPath = Path.Combine(destFolder.ImportFolderLocation, newFolderName); if (!Directory.Exists(newFullPath)) { Directory.CreateDirectory(newFullPath); } } int newFolderID = 0; string newPartialPath = ""; string newFullServerPath = Path.Combine(newFullPath, Path.GetFileName(this.FullServerPath)); DataAccessHelper.GetShareAndPath(newFullServerPath, repFolders.GetAll(), ref newFolderID, ref newPartialPath); logger.Info("Moving file from {0} to {1}", this.FullServerPath, newFullServerPath); if (File.Exists(newFullServerPath)) { // if the file already exists, we can just delete the source file instead // this is safer than deleting and moving File.Delete(this.FullServerPath); this.ImportFolderID = newFolderID; this.FilePath = newPartialPath; VideoLocalRepository repVids = new VideoLocalRepository(); repVids.Save(this); } else { string originalFileName = this.FullServerPath; FileInfo fi = new FileInfo(originalFileName); // now move the file File.Move(this.FullServerPath, newFullServerPath); this.ImportFolderID = newFolderID; this.FilePath = newPartialPath; VideoLocalRepository repVids = new VideoLocalRepository(); repVids.Save(this); try { // move any subtitle files foreach (string subtitleFile in Utils.GetPossibleSubtitleFiles(originalFileName)) { if (File.Exists(subtitleFile)) { FileInfo fiSub = new FileInfo(subtitleFile); string newSubPath = Path.Combine(Path.GetDirectoryName(newFullServerPath), fiSub.Name); if (File.Exists(newSubPath)) { // if the file already exists, we can just delete the source file instead // this is safer than deleting and moving File.Delete(newSubPath); } else { File.Move(subtitleFile, newSubPath); } } } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } // check for any empty folders in drop folder // only for the drop folder if (this.ImportFolder.IsDropSource == 1) { foreach (string folderName in Directory.GetDirectories(this.ImportFolder.ImportFolderLocation, "*", SearchOption.AllDirectories)) { if (Directory.Exists(folderName)) { if (Directory.GetFiles(folderName, "*", SearchOption.AllDirectories).Length == 0) { try { Directory.Delete(folderName, true); } /*catch (IOException) * { * Thread.Sleep(0); * Directory.Delete(folderName, false); * }*/ catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } } } } } } }
public Contract_Trakt_Friend ToContract() { CrossRef_AniDB_TraktRepository repXrefTrakt = new CrossRef_AniDB_TraktRepository(); CrossRef_AniDB_TvDBRepository repXrefTvDB = new CrossRef_AniDB_TvDBRepository(); AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); Trakt_FriendRepository repFriends = new Trakt_FriendRepository(); Trakt_EpisodeRepository repEpisodes = new Trakt_EpisodeRepository(); Trakt_Friend traktFriend = repFriends.GetByUsername(username); if (traktFriend == null) { return(null); } Contract_Trakt_Friend contract = new Contract_Trakt_Friend(); contract.Trakt_FriendID = traktFriend.Trakt_FriendID; contract.Username = username; contract.Full_name = full_name; contract.Gender = gender; contract.Age = age; contract.Location = location; contract.About = about; contract.Joined = joined; contract.Avatar = avatar; contract.Url = url; contract.JoinedDate = Utils.GetAniDBDateAsDate(joined); contract.WatchedEpisodes = new List <Contract_Trakt_WatchedEpisode>(); // we only care about the watched episodes foreach (TraktTVWatched wtch in watched) { if (wtch.episode != null) { Contract_Trakt_WatchedEpisode watchedEp = new Contract_Trakt_WatchedEpisode(); watchedEp.Watched = wtch.watched; watchedEp.WatchedDate = Utils.GetAniDBDateAsDate(wtch.watched); if (!contract.LastEpisodeWatched.HasValue) { contract.LastEpisodeWatched = watchedEp.WatchedDate; } if (watchedEp.WatchedDate.HasValue && watchedEp.WatchedDate > contract.LastEpisodeWatched) { contract.LastEpisodeWatched = watchedEp.WatchedDate; } watchedEp.AnimeSeriesID = null; watchedEp.Episode_Number = wtch.episode.number; watchedEp.Episode_Overview = wtch.episode.overview; watchedEp.Episode_Season = wtch.episode.season; watchedEp.Episode_Title = wtch.episode.title; watchedEp.Episode_Url = wtch.episode.url; if (wtch.episode.images != null) { watchedEp.Episode_Screenshot = wtch.episode.images.screen; } if (wtch.show != null) { watchedEp.TraktShow = wtch.show.ToContract(); // find the anime and series based on the trakt id int?animeID = null; CrossRef_AniDB_Trakt xref = repXrefTrakt.GetByTraktID(wtch.show.TraktID, int.Parse(wtch.episode.season)); if (xref != null) { animeID = xref.AnimeID; } else { // try the tvdb id instead //TODO /* * CrossRef_AniDB_TvDB xrefTvDB = repXrefTvDB.GetByTvDBID(int.Parse(wtch.show.tvdb_id), int.Parse(wtch.episode.season)); * if (xrefTvDB != null) * animeID = xrefTvDB.AnimeID;*/ } if (animeID.HasValue) { AnimeSeries ser = repSeries.GetByAnimeID(animeID.Value); if (ser != null) { watchedEp.AnimeSeriesID = ser.AnimeSeriesID; } AniDB_Anime anime = repAnime.GetByAnimeID(animeID.Value); if (anime != null) { watchedEp.Anime = anime.ToContract(true, null); } } } contract.WatchedEpisodes.Add(watchedEp); break; // only show the latest show } } List <SortPropOrFieldAndDirection> sortCriteria = new List <SortPropOrFieldAndDirection>(); sortCriteria.Add(new SortPropOrFieldAndDirection("WatchedDate", true, SortType.eDateTime)); contract.WatchedEpisodes = Sorting.MultiSort <Contract_Trakt_WatchedEpisode>(contract.WatchedEpisodes, sortCriteria); return(contract); }
public static List <AnimeGroup> GetRelatedGroupsFromAnimeID(ISession session, int animeid) { // TODO we need to recusrive list at all relations and not just the first one AniDB_AnimeRepository repAniAnime = new AniDB_AnimeRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeGroupRepository repGroups = new AnimeGroupRepository(); List <AnimeGroup> grps = new List <AnimeGroup>(); AniDB_Anime anime = repAniAnime.GetByAnimeID(session, animeid); if (anime == null) { return(grps); } // first check for groups which are directly related List <AniDB_Anime_Relation> relations = anime.GetRelatedAnime(session); foreach (AniDB_Anime_Relation rel in relations) { string relationtype = rel.RelationType.ToLower(); if ((relationtype == "same setting") || (relationtype == "alternative setting") || (relationtype == "character") || (relationtype == "other")) { //Filter these relations these will fix messes, like Gundam , Clamp, etc. continue; } // we actually need to get the series, because it might have been added to another group already AnimeSeries ser = repSeries.GetByAnimeID(session, rel.RelatedAnimeID); if (ser != null) { AnimeGroup grp = repGroups.GetByID(session, ser.AnimeGroupID); if (grp != null) { grps.Add(grp); } } } if (grps.Count > 0) { return(grps); } // if nothing found check by all related anime List <AniDB_Anime> relatedAnime = anime.GetAllRelatedAnime(session); foreach (AniDB_Anime rel in relatedAnime) { // we actually need to get the series, because it might have been added to another group already AnimeSeries ser = repSeries.GetByAnimeID(session, rel.AnimeID); if (ser != null) { AnimeGroup grp = repGroups.GetByID(session, ser.AnimeGroupID); if (grp != null) { grps.Add(grp); } } } return(grps); }
public override void ProcessCommand() { logger.Info("Processing CommandRequest_GetCalendar"); try { // we will always assume that an anime was downloaded via http first ScheduledUpdateRepository repSched = new ScheduledUpdateRepository(); AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); ScheduledUpdate sched = repSched.GetByUpdateType((int)ScheduledUpdateType.AniDBCalendar); if (sched == null) { sched = new ScheduledUpdate(); sched.UpdateType = (int)ScheduledUpdateType.AniDBCalendar; sched.UpdateDetails = ""; } else { int freqHours = Utils.GetScheduledHours(ServerSettings.AniDB_Calendar_UpdateFrequency); // if we have run this in the last 12 hours and are not forcing it, then exit TimeSpan tsLastRun = DateTime.Now - sched.LastUpdate; if (tsLastRun.TotalHours < freqHours) { if (!ForceRefresh) { return; } } } sched.LastUpdate = DateTime.Now; repSched.Save(sched); CalendarCollection colCalendars = JMMService.AnidbProcessor.GetCalendarUDP(); if (colCalendars == null || colCalendars.Calendars == null) { logger.Error("Could not get calendar from AniDB"); return; } foreach (AniDBAPI.Calendar cal in colCalendars.Calendars) { AniDB_Anime anime = repAnime.GetByAnimeID(cal.AnimeID); if (anime != null) { // don't update if the local data is less 2 days old TimeSpan ts = DateTime.Now - anime.DateTimeUpdated; if (ts.TotalDays >= 2) { CommandRequest_GetAnimeHTTP cmdAnime = new CommandRequest_GetAnimeHTTP(cal.AnimeID, true, false); cmdAnime.Save(); } else { // update the release date even if we don't update the anime record if (anime.AirDate != cal.ReleaseDate) { anime.AirDate = cal.ReleaseDate; repAnime.Save(anime); AnimeSeriesRepository srepo = new AnimeSeriesRepository(); AnimeSeries ser = srepo.GetByAnimeID(anime.AnimeID); if (ser != null) { srepo.Save(ser, true, false); } } } } else { CommandRequest_GetAnimeHTTP cmdAnime = new CommandRequest_GetAnimeHTTP(cal.AnimeID, true, false); cmdAnime.Save(); } } } catch (Exception ex) { logger.ErrorException("Error processing CommandRequest_GetCalendar: " + ex.ToString(), ex); return; } }
public System.IO.Stream GetItemsFromSerie(int userid, string SerieId) { KodiObject ret = new KodiObject(KodiHelper.NewMediaContainer("Series", true)); if (!ret.Init()) { return(new MemoryStream()); } enEpisodeType?eptype = null; int serieID; if (SerieId.Contains("_")) { int ept; string[] ndata = SerieId.Split('_'); if (!int.TryParse(ndata[0], out ept)) { return(new MemoryStream()); } eptype = (enEpisodeType)ept; if (!int.TryParse(ndata[1], out serieID)) { return(new MemoryStream()); } } else { if (!int.TryParse(SerieId, out serieID)) { return(new MemoryStream()); } } using (var session = JMMService.SessionFactory.OpenSession()) { if (serieID == -1) { return(new MemoryStream()); } AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeSeries ser = repSeries.GetByID(session, serieID); if (ser == null) { return(new MemoryStream()); } AniDB_Anime anime = ser.GetAnime(); if (anime == null) { return(new MemoryStream()); } ImageDetails fanart = anime.GetDefaultFanartDetailsNoBlanks(session); if (fanart != null) { ret.MediaContainer.Art = fanart.GenArt(); } ret.MediaContainer.Title2 = ret.MediaContainer.Title1 = anime.MainTitle; List <AnimeEpisode> episodes = ser.GetAnimeEpisodes(session).Where(a => a.GetVideoLocals(session).Count > 0).ToList(); if (eptype.HasValue) { episodes = episodes.Where(a => a.EpisodeTypeEnum == eptype.Value).ToList(); } else { List <enEpisodeType> types = episodes.Select(a => a.EpisodeTypeEnum).Distinct().ToList(); if (types.Count > 1) { List <KodiEpisodeType> eps = new List <KodiEpisodeType>(); foreach (enEpisodeType ee in types) { KodiEpisodeType k2 = new KodiEpisodeType(); KodiEpisodeType.EpisodeTypeTranslated(k2, ee, (AnimeTypes)anime.AnimeType, episodes.Count(a => a.EpisodeTypeEnum == ee)); eps.Add(k2); } List <SortPropOrFieldAndDirection> sortCriteria = new List <SortPropOrFieldAndDirection>(); sortCriteria.Add(new SortPropOrFieldAndDirection("Name", SortType.eString)); eps = Sorting.MultiSort(eps, sortCriteria); List <Video> dirs = new List <Video>(); bool isCharacterSetup_ = false; foreach (KodiEpisodeType ee in eps) { Video v = new Directory(); v.Title = ee.Name; v.Type = "season"; v.LeafCount = ee.Count.ToString(); v.ViewedLeafCount = "0"; v.Key = KodiHelper.ServerUrl(int.Parse(ServerSettings.JMMServerPort), MainWindow.PathAddressKodi + "/GetMetadata/" + userid + "/" + (int)JMMType.Serie + "/" + ee.Type + "_" + ser.AnimeSeriesID); v.Thumb = KodiHelper.ServerUrl(int.Parse(ServerSettings.JMMServerPort), MainWindow.PathAddressKodi + "/GetSupportImage/" + ee.Image); if ((ee.AnimeType == AnimeTypes.Movie) || (ee.AnimeType == AnimeTypes.OVA)) { v = KodiHelper.MayReplaceVideo((Directory)v, ser, anime, JMMType.File, userid, false); } //proper naming v.OriginalTitle = ""; foreach (AniDB_Anime_Title title in anime.GetTitles()) { if (title.TitleType == "official" || title.TitleType == "main") { v.OriginalTitle += "{" + title.TitleType + ":" + title.Language + "}" + title.Title + "|"; } } v.OriginalTitle = v.OriginalTitle.Substring(0, v.OriginalTitle.Length - 1); //proper naming end //experiment if (!isCharacterSetup_) { Characters ch = new Characters(); ch.CharactersList = new List <Character>(); ch.CharactersList = GetCharactersFromAniDB(anime); v.CharactersList = new List <Characters>(); v.CharactersList.Add(ch); isCharacterSetup_ = true; } //experimentEND dirs.Add(v); } ret.Childrens = dirs; return(ret.GetStream()); } } List <Video> vids = new List <Video>(); Contract_AnimeSeries cseries = ser.ToContract(ser.GetUserRecord(userid), true); Video nv = KodiHelper.FromSerie(cseries, userid); KodiEpisodeType k = new KodiEpisodeType(); if (eptype.HasValue) { KodiEpisodeType.EpisodeTypeTranslated(k, (enEpisodeType)eptype.Value, (AnimeTypes)anime.AnimeType, episodes.Count); } bool isCharacterSetup = false; foreach (AnimeEpisode ep in episodes) { Video v = new Video(); List <VideoLocal> locals = ep.GetVideoLocals(session); if ((locals == null) || (locals.Count == 0)) { continue; } AniDB_Episode aep = ep.AniDB_Episode; if (aep == null) { continue; } VideoLocal current = locals[0]; try { KodiHelper.PopulateVideo(v, current, ep, ser, anime, nv, JMMType.File, userid); if (eptype.HasValue) { v.ParentTitle = k.Name; } //experiment if (!isCharacterSetup) { Characters c = new Characters(); c.CharactersList = new List <Character>(); c.CharactersList = GetCharactersFromAniDB(anime); v.CharactersList = new List <Characters>(); v.CharactersList.Add(c); isCharacterSetup = true; } //experimentEND vids.Add(v); } catch (Exception e) { //Fast fix if file do not exist, and still is in db. (Xml Serialization of video info will fail on null) } } List <SortPropOrFieldAndDirection> sortCriteria2 = new List <SortPropOrFieldAndDirection>(); sortCriteria2.Add(new SortPropOrFieldAndDirection("EpNumber", SortType.eInteger)); vids = Sorting.MultiSort(vids, sortCriteria2); ret.Childrens = vids; return(ret.GetStream()); } }
public System.IO.Stream Search(string UserId, string limit, string query, bool searchTag) { KodiObject ret = new KodiObject(KodiHelper.NewMediaContainer("Search", false)); ret.MediaContainer.Title2 = "Search Results for '" + query + "'..."; AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); int lim; if (!int.TryParse(limit, out lim)) { lim = 100; } JMMUser user = KodiHelper.GetUser(UserId); if (user == null) { return(new MemoryStream()); } List <Video> ls = new List <Video>(); int cnt = 0; List <AniDB_Anime> animes; if (searchTag) { animes = repAnime.SearchByTag(query); } else { animes = repAnime.SearchByName(query); } foreach (AniDB_Anime anidb_anime in animes) { if (!user.AllowedAnime(anidb_anime)) { continue; } AnimeSeries ser = repSeries.GetByAnimeID(anidb_anime.AnimeID); if (ser != null) { Contract_AnimeSeries cserie = ser.ToContract(ser.GetUserRecord(user.JMMUserID), true); Video v = KodiHelper.FromSerieWithPossibleReplacement(cserie, ser, user.JMMUserID); //proper naming v.OriginalTitle = ""; foreach (AniDB_Anime_Title title in anidb_anime.GetTitles()) { if (title.TitleType == "official" || title.TitleType == "main") { v.OriginalTitle += "{" + title.TitleType + ":" + title.Language + "}" + title.Title + "|"; } } v.OriginalTitle = v.OriginalTitle.Substring(0, v.OriginalTitle.Length - 1); //proper naming end //experiment Characters c = new Characters(); c.CharactersList = new List <Character>(); c.CharactersList = GetCharactersFromAniDB(anidb_anime); v.CharactersList = new List <Characters>(); v.CharactersList.Add(c); //experiment END switch (anidb_anime.AnimeTypeEnum) { case enAnimeType.Movie: v.SourceTitle = "Anime Movies"; break; case enAnimeType.OVA: v.SourceTitle = "Anime Ovas"; break; case enAnimeType.Other: v.SourceTitle = "Anime Others"; break; case enAnimeType.TVSeries: v.SourceTitle = "Anime Series"; break; case enAnimeType.TVSpecial: v.SourceTitle = "Anime Specials"; break; case enAnimeType.Web: v.SourceTitle = "Anime Web Clips"; break; } ls.Add(v); cnt++; if (cnt == lim) { break; } } } ret.MediaContainer.Childrens = ls; return(ret.GetStream()); }
public override void ProcessCommand() { logger.Info("Processing CommandRequest_GetReleaseGroupStatus: {0}", AnimeID); try { // only get group status if we have an associated series AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeSeries series = repSeries.GetByAnimeID(AnimeID); if (series == null) { return; } AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); AniDB_Anime anime = repAnime.GetByAnimeID(AnimeID); if (anime == null) { return; } // don't get group status if the anime has already ended more than 50 days ago bool skip = false; if (!ForceRefresh) { if (anime.EndDate.HasValue) { if (anime.EndDate.Value < DateTime.Now) { TimeSpan ts = DateTime.Now - anime.EndDate.Value; if (ts.TotalDays > 50) { // don't skip if we have never downloaded this info before AniDB_GroupStatusRepository repGrpStatus = new AniDB_GroupStatusRepository(); List <AniDB_GroupStatus> grpStatuses = repGrpStatus.GetByAnimeID(AnimeID); if (grpStatuses != null && grpStatuses.Count > 0) { skip = true; } } } } } if (skip) { logger.Info("Skipping group status command because anime has already ended: {0}", anime.ToString()); return; } GroupStatusCollection grpCol = JMMService.AnidbProcessor.GetReleaseGroupStatusUDP(AnimeID); if (ServerSettings.AniDB_DownloadReleaseGroups) { // save in bulk to improve performance using (var session = JMMService.SessionFactory.OpenSession()) { using (var transaction = session.BeginTransaction()) { foreach (Raw_AniDB_GroupStatus grpStatus in grpCol.Groups) { CommandRequest_GetReleaseGroup cmdRelgrp = new CommandRequest_GetReleaseGroup(grpStatus.GroupID, false); cmdRelgrp.Save(session); } transaction.Commit(); } } } } catch (Exception ex) { logger.Error("Error processing CommandRequest_GetReleaseGroupStatus: {0} - {1}", AnimeID, ex.ToString()); return; } }
public System.IO.Stream VoteAnime(string userid, string objectid, string votevalue, string votetype) { Respond rsp = new Respond(); rsp.code = 500; int objid = 0; int usid = 0; int vt = 0; double vvalue = 0; if (!int.TryParse(objectid, out objid)) { return(KodiHelper.GetStreamFromXmlObject(rsp)); } if (!int.TryParse(userid, out usid)) { return(KodiHelper.GetStreamFromXmlObject(rsp)); } if (!int.TryParse(votetype, out vt)) { return(KodiHelper.GetStreamFromXmlObject(rsp)); } if (!double.TryParse(votevalue, NumberStyles.Any, CultureInfo.InvariantCulture, out vvalue)) { return(KodiHelper.GetStreamFromXmlObject(rsp)); } using (var session = JMMService.SessionFactory.OpenSession()) { if (vt == (int)enAniDBVoteType.Episode) { AnimeEpisodeRepository repEpisodes = new AnimeEpisodeRepository(); AnimeEpisode ep = repEpisodes.GetByID(session, objid); AniDB_Anime anime = ep.GetAnimeSeries().GetAnime(); if (anime == null) { rsp.code = 404; return(KodiHelper.GetStreamFromXmlObject(rsp)); } string msg = string.Format("Voting for anime episode: {0} - Value: {1}", ep.AnimeEpisodeID, vvalue); logger.Info(msg); // lets save to the database and assume it will work AniDB_VoteRepository repVotes = new AniDB_VoteRepository(); List <AniDB_Vote> dbVotes = repVotes.GetByEntity(ep.AnimeEpisodeID); AniDB_Vote thisVote = null; foreach (AniDB_Vote dbVote in dbVotes) { if (dbVote.VoteType == (int)enAniDBVoteType.Episode) { thisVote = dbVote; } } if (thisVote == null) { thisVote = new AniDB_Vote(); thisVote.EntityID = ep.AnimeEpisodeID; } thisVote.VoteType = vt; int iVoteValue = 0; if (vvalue > 0) { iVoteValue = (int)(vvalue * 100); } else { iVoteValue = (int)vvalue; } msg = string.Format("Voting for anime episode Formatted: {0} - Value: {1}", ep.AnimeEpisodeID, iVoteValue); logger.Info(msg); thisVote.VoteValue = iVoteValue; repVotes.Save(thisVote); CommandRequest_VoteAnime cmdVote = new CommandRequest_VoteAnime(anime.AnimeID, vt, Convert.ToDecimal(vvalue)); cmdVote.Save(); } if (vt == (int)enAniDBVoteType.Anime) { AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeSeries ser = repSeries.GetByID(session, objid); AniDB_Anime anime = ser.GetAnime(); if (anime == null) { rsp.code = 404; return(KodiHelper.GetStreamFromXmlObject(rsp)); } string msg = string.Format("Voting for anime: {0} - Value: {1}", anime.AnimeID, vvalue); logger.Info(msg); // lets save to the database and assume it will work AniDB_VoteRepository repVotes = new AniDB_VoteRepository(); List <AniDB_Vote> dbVotes = repVotes.GetByEntity(anime.AnimeID); AniDB_Vote thisVote = null; foreach (AniDB_Vote dbVote in dbVotes) { // we can only have anime permanent or anime temp but not both if (vt == (int)enAniDBVoteType.Anime || vt == (int)enAniDBVoteType.AnimeTemp) { if (dbVote.VoteType == (int)enAniDBVoteType.Anime || dbVote.VoteType == (int)enAniDBVoteType.AnimeTemp) { thisVote = dbVote; } } else { thisVote = dbVote; } } if (thisVote == null) { thisVote = new AniDB_Vote(); thisVote.EntityID = anime.AnimeID; } thisVote.VoteType = vt; int iVoteValue = 0; if (vvalue > 0) { iVoteValue = (int)(vvalue * 100); } else { iVoteValue = (int)vvalue; } msg = string.Format("Voting for anime Formatted: {0} - Value: {1}", anime.AnimeID, iVoteValue); logger.Info(msg); thisVote.VoteValue = iVoteValue; repVotes.Save(thisVote); CommandRequest_VoteAnime cmdVote = new CommandRequest_VoteAnime(anime.AnimeID, vt, Convert.ToDecimal(vvalue)); cmdVote.Save(); } rsp.code = 200; return(KodiHelper.GetStreamFromXmlObject(rsp)); } }