public void Save(AnimeSeries obj, bool updateStats) { bool updateStatsCache = false; AnimeGroup oldGroup = null; if (obj.AnimeSeriesID == 0) { updateStatsCache = true; // a new series } else { // get the old version from the DB AnimeSeries oldSeries = GetByID(obj.AnimeSeriesID); if (oldSeries != null) { // means we are moving series to a different group if (oldSeries.AnimeGroupID != obj.AnimeGroupID) { AnimeGroupRepository repGroups = new AnimeGroupRepository(); oldGroup = repGroups.GetByID(oldSeries.AnimeGroupID); updateStatsCache = true; } } } using (var session = JMMService.SessionFactory.OpenSession()) { // populate the database using (var transaction = session.BeginTransaction()) { session.SaveOrUpdate(obj); transaction.Commit(); } } if (updateStats) { if (updateStatsCache) { logger.Trace("Updating group stats by series from AnimeSeriesRepository.Save: {0}", obj.AnimeSeriesID); StatsCache.Instance.UpdateUsingSeries(obj.AnimeSeriesID); } if (oldGroup != null) { logger.Trace("Updating group stats by group from AnimeSeriesRepository.Save: {0}", oldGroup.AnimeGroupID); StatsCache.Instance.UpdateUsingGroup(oldGroup.AnimeGroupID); } } }
public void Save(AnimeSeries obj, bool updateStats) { bool updateStatsCache = false; AnimeGroup oldGroup = null; if (obj.AnimeSeriesID == 0) updateStatsCache = true; // a new series else { // get the old version from the DB AnimeSeries oldSeries = GetByID(obj.AnimeSeriesID); if (oldSeries != null) { // means we are moving series to a different group if (oldSeries.AnimeGroupID != obj.AnimeGroupID) { AnimeGroupRepository repGroups = new AnimeGroupRepository(); oldGroup = repGroups.GetByID(oldSeries.AnimeGroupID); updateStatsCache = true; } } } using (var session = JMMService.SessionFactory.OpenSession()) { // populate the database using (var transaction = session.BeginTransaction()) { session.SaveOrUpdate(obj); transaction.Commit(); } } if (updateStats) { if (updateStatsCache) { logger.Trace("Updating group stats by series from AnimeSeriesRepository.Save: {0}", obj.AnimeSeriesID); StatsCache.Instance.UpdateUsingSeries(obj.AnimeSeriesID); } if (oldGroup != null) { logger.Trace("Updating group stats by group from AnimeSeriesRepository.Save: {0}", oldGroup.AnimeGroupID); StatsCache.Instance.UpdateUsingGroup(oldGroup.AnimeGroupID); } } }
public void Delete(int id) { int oldGroupID = 0; using (var session = JMMService.SessionFactory.OpenSession()) { // populate the database using (var transaction = session.BeginTransaction()) { AnimeSeries cr = GetByID(id); if (cr != null) { Cache.Remove(cr); // delete user records AnimeSeries_UserRepository repUsers = new AnimeSeries_UserRepository(); foreach (AnimeSeries_User grpUser in repUsers.GetBySeriesID(id)) { repUsers.Delete(grpUser.AnimeSeries_UserID); } Changes.Remove(cr.AnimeSeriesID); oldGroupID = cr.AnimeGroupID; session.Delete(cr); transaction.Commit(); cr.DeleteFromFilters(); } } } if (oldGroupID > 0) { logger.Trace("Updating group stats by group from AnimeSeriesRepository.Delete: {0}", oldGroupID); AnimeGroupRepository repGroups = new AnimeGroupRepository(); AnimeGroup oldGroup = repGroups.GetByID(oldGroupID); if (oldGroup != null) { repGroups.Save(oldGroup, true, true); } } }
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_AnimeSeries_SaveResponse CreateSeriesFromAnime(int animeID, int? animeGroupID, int userID) { Contract_AnimeSeries_SaveResponse response = new Contract_AnimeSeries_SaveResponse(); response.AnimeSeries = null; response.ErrorMessage = ""; try { using (var session = JMMService.SessionFactory.OpenSession()) { AnimeGroupRepository repGroups = new AnimeGroupRepository(); if (animeGroupID.HasValue) { AnimeGroup grp = repGroups.GetByID(session, animeGroupID.Value); if (grp == null) { response.ErrorMessage = "Could not find the specified group"; return response; } } // make sure a series doesn't already exists for this anime AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeSeries ser = repSeries.GetByAnimeID(session, animeID); if (ser != null) { response.ErrorMessage = "A series already exists for this anime"; return response; } // make sure the anime exists first AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); AniDB_Anime anime = repAnime.GetByAnimeID(session, animeID); if (anime == null) anime = JMMService.AnidbProcessor.GetAnimeInfoHTTP(session, animeID, false, false); if (anime == null) { response.ErrorMessage = "Could not get anime information from AniDB"; return response; } if (animeGroupID.HasValue) { ser = new AnimeSeries(); ser.Populate(anime); ser.AnimeGroupID = animeGroupID.Value; repSeries.Save(ser); } else { ser = anime.CreateAnimeSeriesAndGroup(session); } ser.CreateAnimeEpisodes(session); // 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(session); } ser.QueueUpdateStats(); // check for TvDB associations CommandRequest_TvDBSearchAnime cmd = new CommandRequest_TvDBSearchAnime(anime.AnimeID, false); cmd.Save(session); if (ServerSettings.Trakt_IsEnabled && !string.IsNullOrEmpty(ServerSettings.Trakt_AuthToken)) { // check for Trakt associations CommandRequest_TraktSearchAnime cmd2 = new CommandRequest_TraktSearchAnime(anime.AnimeID, false); cmd2.Save(session); } List<CrossRef_AniDB_TvDBV2> xrefs = ser.GetCrossRefTvDBV2(); List<CrossRef_AniDB_MAL> xrefMAL = ser.CrossRefMAL; List<TvDB_Series> sers = new List<TvDB_Series>(); foreach (CrossRef_AniDB_TvDBV2 xref in xrefs) sers.Add(xref.GetTvDBSeries()); CrossRef_AniDB_Other xrefMovie = ser.CrossRefMovieDB; MovieDB_Movie movie = null; if (xrefMovie != null) movie = xrefMovie.GetMovieDB_Movie(); response.AnimeSeries = ser.ToContract(anime, xrefs, xrefMovie, ser.GetUserRecord(userID), sers, xrefMAL, false, null, null, null, null,movie); return response; } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); response.ErrorMessage = ex.Message; } return response; }
public System.IO.Stream GetItemsFromGroup(int userid, string GroupId, HistoryInfo info) { PlexObject ret=new PlexObject(PlexHelper.NewMediaContainer(MediaContainerTypes.Show,info,false)); if (!ret.Init()) return new MemoryStream(); int groupID; int.TryParse(GroupId, out groupID); List<Video> retGroups = new List<Video>(); if (groupID == -1) return new MemoryStream(); using (var session = JMMService.SessionFactory.OpenSession()) { AnimeGroupRepository repGroups = new AnimeGroupRepository(); AnimeGroup grp = repGroups.GetByID(groupID); if (grp != null) { Contract_AnimeGroup basegrp = grp.ToContract(grp.GetUserRecord(session, userid)); List<AnimeSeries> sers2 = grp.GetSeries(session); foreach (AnimeGroup grpChild in grp.GetChildGroups()) { Video v = StatsCache.Instance.StatPlexGroupsCache[userid][grpChild.AnimeGroupID]; if (v != null) { retGroups.Add(v.Clone(),info); } } foreach (AnimeSeries ser in grp.GetSeries()) { Contract_AnimeSeries cserie = ser.ToContract(ser.GetUserRecord(session, userid), true); Video v = PlexHelper.FromSerieWithPossibleReplacement(cserie, ser, ser.GetAnime(), userid); v.AirDate = ser.AirDate.HasValue ? ser.AirDate.Value : DateTime.MinValue; v.Group = basegrp; retGroups.Add(v,info); } } ret.Childrens = PlexHelper.ConvertToDirectoryIfNotUnique(retGroups.OrderBy(a => a.AirDate).ToList()); return ret.GetStream(); } }
public Contract_AnimeSeries_SaveResponse SaveSeries(Contract_AnimeSeries_Save contract, int userID) { Contract_AnimeSeries_SaveResponse contractout = new Contract_AnimeSeries_SaveResponse(); contractout.ErrorMessage = ""; contractout.AnimeSeries = null; try { AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeSeries ser = null; int? oldGroupID = null; if (contract.AnimeSeriesID.HasValue) { ser = repSeries.GetByID(contract.AnimeSeriesID.Value); if (ser == null) { contractout.ErrorMessage = "Could not find existing series with ID: " + contract.AnimeSeriesID.Value.ToString(); return contractout; } // check if we are moving a series oldGroupID = ser.AnimeGroupID; } else { ser = new AnimeSeries(); ser.DateTimeCreated = DateTime.Now; ser.DefaultAudioLanguage = ""; ser.DefaultSubtitleLanguage = ""; ser.MissingEpisodeCount = 0; ser.MissingEpisodeCountGroups = 0; ser.LatestLocalEpisodeNumber = 0; ser.SeriesNameOverride = ""; } ser.AnimeGroupID = contract.AnimeGroupID; ser.AniDB_ID = contract.AniDB_ID; ser.DefaultAudioLanguage = contract.DefaultAudioLanguage; ser.DefaultSubtitleLanguage = contract.DefaultSubtitleLanguage; ser.DateTimeUpdated = DateTime.Now; ser.SeriesNameOverride = contract.SeriesNameOverride; ser.DefaultFolder = contract.DefaultFolder; AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); AniDB_Anime anime = repAnime.GetByAnimeID(ser.AniDB_ID); if (anime == null) { contractout.ErrorMessage = string.Format("Could not find anime record with ID: {0}", ser.AniDB_ID); return contractout; } repSeries.Save(ser); // update stats for groups //ser.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true ,true, true); ser.QueueUpdateStats(); if (oldGroupID.HasValue) { AnimeGroupRepository repGroups = new AnimeGroupRepository(); AnimeGroup grp = repGroups.GetByID(oldGroupID.Value); if (grp != null) { grp.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true, true, true); } } List<CrossRef_AniDB_TvDBV2> xrefs = ser.GetCrossRefTvDBV2(); List<CrossRef_AniDB_MAL> xrefMAL = ser.CrossRefMAL; List<TvDB_Series> sers = new List<TvDB_Series>(); foreach (CrossRef_AniDB_TvDBV2 xref in xrefs) sers.Add(xref.GetTvDBSeries()); CrossRef_AniDB_Other xrefMovie = ser.CrossRefMovieDB; MovieDB_Movie movie = null; if (xrefMovie != null) movie = xrefMovie.GetMovieDB_Movie(); contractout.AnimeSeries = ser.ToContract(anime, xrefs, ser.CrossRefMovieDB, ser.GetUserRecord(userID), sers, xrefMAL, false, null, null, null, null,movie); return contractout; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); contractout.ErrorMessage = ex.Message; return contractout; } }
public Contract_AnimeSeries_SaveResponse MoveSeries(int animeSeriesID, int newAnimeGroupID, int userID) { Contract_AnimeSeries_SaveResponse contractout = new Contract_AnimeSeries_SaveResponse(); contractout.ErrorMessage = ""; contractout.AnimeSeries = null; try { AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeSeries ser = null; ser = repSeries.GetByID(animeSeriesID); if (ser == null) { contractout.ErrorMessage = "Could not find existing series with ID: " + animeSeriesID.ToString(); return contractout; } // make sure the group exists AnimeGroupRepository repGroups = new AnimeGroupRepository(); AnimeGroup grpTemp = repGroups.GetByID(newAnimeGroupID); if (grpTemp == null) { contractout.ErrorMessage = "Could not find existing group with ID: " + newAnimeGroupID.ToString(); return contractout; } int oldGroupID = ser.AnimeGroupID; ser.AnimeGroupID = newAnimeGroupID; ser.DateTimeUpdated = DateTime.Now; repSeries.Save(ser); // update stats for new groups //ser.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true, true, true); ser.QueueUpdateStats(); // update stats for old groups AnimeGroup grp = repGroups.GetByID(oldGroupID); if (grp != null) { grp.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true, true, true); } AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository(); AniDB_Anime anime = repAnime.GetByAnimeID(ser.AniDB_ID); if (anime == null) { contractout.ErrorMessage = string.Format("Could not find anime record with ID: {0}", ser.AniDB_ID); return contractout; } List<CrossRef_AniDB_TvDBV2> xrefs = ser.GetCrossRefTvDBV2(); List<CrossRef_AniDB_MAL> xrefMAL = ser.CrossRefMAL; List<TvDB_Series> sers = new List<TvDB_Series>(); foreach (CrossRef_AniDB_TvDBV2 xref in xrefs) sers.Add(xref.GetTvDBSeries()); CrossRef_AniDB_Other xrefMovie = ser.CrossRefMovieDB; MovieDB_Movie movie=null; if (xrefMovie != null) movie = xrefMovie.GetMovieDB_Movie(); contractout.AnimeSeries = ser.ToContract(anime, xrefs, xrefMovie, ser.GetUserRecord(userID), sers, xrefMAL, false, null, null, null, null,movie); return contractout; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); contractout.ErrorMessage = ex.Message; return contractout; } }
public List<Contract_AnimeGroup> GetSubGroupsForGroup(int animeGroupID, int userID) { List<Contract_AnimeGroup> retGroups = new List<Contract_AnimeGroup>(); try { AnimeGroupRepository repGroups = new AnimeGroupRepository(); AnimeGroup grp = repGroups.GetByID(animeGroupID); if (grp == null) return retGroups; foreach (AnimeGroup grpChild in grp.GetChildGroups()) retGroups.Add(grpChild.ToContract(grpChild.GetUserRecord(userID))); return retGroups; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return retGroups; }
public void UpdateGroupFilterUsingGroup(int groupid) { AnimeGroupRepository repGroups = new AnimeGroupRepository(); AnimeGroup_UserRepository repUserGroups = new AnimeGroup_UserRepository(); JMMUserRepository repUser = new JMMUserRepository(); GroupFilterRepository repGrpFilter = new GroupFilterRepository(); AnimeGroup grp = repGroups.GetByID(groupid); if (grp.AnimeGroupParentID.HasValue) return; foreach (JMMUser user in repUser.GetAll()) { AnimeGroup_User userRec = repUserGroups.GetByUserAndGroupID(user.JMMUserID, groupid); Dictionary<int, HashSet<int>> groupfilters; if (StatUserGroupFilter.ContainsKey(user.JMMUserID)) groupfilters = StatUserGroupFilter[user.JMMUserID]; else { groupfilters = new Dictionary<int, HashSet<int>>(); StatUserGroupFilter.Add(user.JMMUserID, groupfilters); } List<GroupFilter> gfs = repGrpFilter.GetAll(); GroupFilter gfgf = new GroupFilter(); gfgf.GroupFilterName = "All"; gfs.Add(gfgf); foreach (GroupFilter gf in gfs) { HashSet<int> groups; if (groupfilters.ContainsKey(gf.GroupFilterID)) groups = groupfilters[gf.GroupFilterID]; else { groups = new HashSet<int>(); groupfilters.Add(gf.GroupFilterID, groups); } if (groups.Contains(groupid)) groups.Remove(groupid); if (EvaluateGroupFilter(gf, grp, user, userRec)) groups.Add(grp.AnimeGroupID); } } }
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 System.IO.Stream GetFilters(string uid) { JMMUser user = KodiHelper.GetUser(uid); if (user==null) return new MemoryStream(); int userid = user.JMMUserID; KodiObject ret =new KodiObject(KodiHelper.NewMediaContainer("Anime", false)); if (!ret.Init()) return new MemoryStream(); List<Video> dirs = new List<Video>(); try { using (var session = JMMService.SessionFactory.OpenSession()) { GroupFilterRepository repGF = new GroupFilterRepository(); List<GroupFilter> allGfs = repGF.GetAll(session); Dictionary<int, HashSet<int>> gstats = StatsCache.Instance.StatUserGroupFilter[userid]; foreach (GroupFilter gg in allGfs.ToArray()) { if ((!StatsCache.Instance.StatUserGroupFilter.ContainsKey(userid)) || (!StatsCache.Instance.StatUserGroupFilter[userid].ContainsKey(gg.GroupFilterID))) { allGfs.Remove(gg); } } AnimeGroupRepository repGroups = new AnimeGroupRepository(); allGfs.Insert(0, new GroupFilter() {GroupFilterName = "All", GroupFilterID = -999}); foreach (GroupFilter gg in allGfs) { Random rnd = new Random(123456789); Directory pp = new Directory(); pp.Key = KodiHelper.ServerUrl(int.Parse(ServerSettings.JMMServerPort), MainWindow.PathAddressKodi + "/GetMetadata/" + userid + "/" + (int) JMMType.GroupFilter + "/" + gg.GroupFilterID); pp.PrimaryExtraKey = pp.Key; pp.Title = gg.GroupFilterName; HashSet<int> groups; groups = gg.GroupFilterID == -999 ? new HashSet<int>(repGroups.GetAllTopLevelGroups(session).Select(a => a.AnimeGroupID)) : gstats[gg.GroupFilterID]; if (groups.Count != 0) { bool repeat; int nn = 0; pp.LeafCount = groups.Count.ToString(); pp.ViewedLeafCount = "0"; do { repeat = true; int grp = groups.ElementAt(rnd.Next(groups.Count)); AnimeGroup ag = repGroups.GetByID(grp); List<AnimeSeries> sers = ag.GetSeries(session); if (sers.Count > 0) { AnimeSeries ser = sers[rnd.Next(sers.Count)]; AniDB_Anime anim = ser.GetAnime(session); if (anim != null) { ImageDetails poster = anim.GetDefaultPosterDetailsNoBlanks(session); ImageDetails fanart = anim.GetDefaultFanartDetailsNoBlanks(session); if (poster != null) pp.Thumb = poster.GenPoster(); if (fanart != null) pp.Art = fanart.GenArt(); if (poster != null) repeat = false; } } nn++; if ((repeat) && (nn == 15)) repeat = false; } while (repeat); dirs.Add(pp); } } VideoLocalRepository repVids = new VideoLocalRepository(); List<VideoLocal> vids = repVids.GetVideosWithoutEpisode(); if (vids.Count > 0) { JMMContracts.KodiContracts.Directory pp = new JMMContracts.KodiContracts.Directory(); pp.Key = pp.PrimaryExtraKey = KodiHelper.ServerUrl(int.Parse(ServerSettings.JMMServerPort), MainWindow.PathAddressKodi + "/GetMetadata/0/" + (int) JMMType.GroupUnsort + "/0"); pp.Title = "Unsort"; pp.Thumb = KodiHelper.ServerUrl(int.Parse(ServerSettings.JMMServerPort), MainWindow.PathAddressKodi + "/GetSupportImage/plex_unsort.png"); pp.LeafCount = vids.Count.ToString(); pp.ViewedLeafCount = "0"; dirs.Add(pp); } dirs = dirs.OrderBy(a => a.Title).ToList(); } ret.Childrens = dirs; return ret.GetStream(); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); return new MemoryStream(); } }
public System.IO.Stream GetItemsFromGroup(int userid, string GroupId) { KodiObject ret =new KodiObject(KodiHelper.NewMediaContainer("Groups",true)); if (!ret.Init()) return new MemoryStream(); int groupID; int.TryParse(GroupId, out groupID); List<Video> retGroups = new List<Video>(); if (groupID == -1) return new MemoryStream(); using (var session = JMMService.SessionFactory.OpenSession()) { AnimeGroupRepository repGroups = new AnimeGroupRepository(); AnimeGroup grp = repGroups.GetByID(groupID); if (grp != null) { Contract_AnimeGroup basegrp = grp.ToContract(grp.GetUserRecord(session, userid)); ret.MediaContainer.Title1 = ret.MediaContainer.Title2 = basegrp.GroupName; List<AnimeSeries> sers2 = grp.GetSeries(session); ret.MediaContainer.Art = KodiHelper.GetRandomFanartFromSeries(sers2, session); foreach (AnimeGroup grpChild in grp.GetChildGroups()) { Video v = StatsCache.Instance.StatKodiGroupsCache[userid][grpChild.AnimeGroupID]; v.Type = "show"; if (v != null) retGroups.Add(v.Clone()); } foreach (AnimeSeries ser in grp.GetSeries()) { Contract_AnimeSeries cserie = ser.ToContract(ser.GetUserRecord(session, userid), true); Video v = KodiHelper.FromSerieWithPossibleReplacement(cserie, ser, userid); v.AirDate = ser.AirDate.HasValue ? ser.AirDate.Value : DateTime.MinValue; v.Group = basegrp; retGroups.Add(v); } } ret.Childrens = retGroups.OrderBy(a => a.AirDate).ToList(); return ret.GetStream(); } }
public System.IO.Stream GetFilters(string uid) { int t = 0; int.TryParse(uid, out t); JMMUser user = t > 0 ? PlexHelper.GetJMMUser(uid) : PlexHelper.GetUser(uid); if (user==null) return new MemoryStream(); int userid = user.JMMUserID; HistoryInfo info = new HistoryInfo { Key = PlexHelper.ConstructFiltersUrl(userid), Title = "Anime" }; PlexObject ret = new PlexObject(PlexHelper.NewMediaContainer(MediaContainerTypes.Show,info,false)); if (!ret.Init()) return new MemoryStream(); List<Video> dirs = new List<Video>(); try { using (var session = JMMService.SessionFactory.OpenSession()) { GroupFilterRepository repGF = new GroupFilterRepository(); List<GroupFilter> allGfs = repGF.GetAll(session); Dictionary<int, HashSet<int>> gstats = StatsCache.Instance.StatUserGroupFilter[userid]; foreach (GroupFilter gg in allGfs.ToArray()) { if ((!StatsCache.Instance.StatUserGroupFilter.ContainsKey(userid)) || (!StatsCache.Instance.StatUserGroupFilter[userid].ContainsKey(gg.GroupFilterID))) { allGfs.Remove(gg); } } AnimeGroupRepository repGroups = new AnimeGroupRepository(); allGfs.Insert(0, new GroupFilter() {GroupFilterName = "All", GroupFilterID = -999}); foreach (GroupFilter gg in allGfs) { Random rnd = new Random(123456789); Directory pp = new Directory { Type="show" }; pp.Key = PlexHelper.ConstructFilterIdUrl(userid, gg.GroupFilterID); pp.Title = gg.GroupFilterName; HashSet<int> groups; groups = gg.GroupFilterID == -999 ? new HashSet<int>(repGroups.GetAllTopLevelGroups(session).Select(a => a.AnimeGroupID)) : gstats[gg.GroupFilterID]; if (groups.Count != 0) { bool repeat; int nn = 0; pp.LeafCount = groups.Count.ToString(); pp.ViewedLeafCount = "0"; do { repeat = true; int grp = groups.ElementAt(rnd.Next(groups.Count)); AnimeGroup ag = repGroups.GetByID(grp); List<AnimeSeries> sers = ag.GetSeries(session); if (sers.Count > 0) { AnimeSeries ser = sers[rnd.Next(sers.Count)]; AniDB_Anime anim = ser.GetAnime(session); if (anim != null) { ImageDetails poster = anim.GetDefaultPosterDetailsNoBlanks(session); ImageDetails fanart = anim.GetDefaultFanartDetailsNoBlanks(session); if (poster != null) pp.Thumb = poster.GenPoster(); if (fanart != null) pp.Art = fanart.GenArt(); if (poster != null) repeat = false; } } nn++; if ((repeat) && (nn == 15)) repeat = false; } while (repeat); dirs.Add(pp,info); } } VideoLocalRepository repVids = new VideoLocalRepository(); List<VideoLocal> vids = repVids.GetVideosWithoutEpisode(); if (vids.Count > 0) { Directory pp = new Directory() { Type = "show" }; pp.Key = PlexHelper.ConstructUnsortUrl(userid); pp.Title = "Unsort"; pp.Thumb = PlexHelper.ConstructSupportImageLink("plex_unsort.png"); pp.LeafCount = vids.Count.ToString(); pp.ViewedLeafCount = "0"; dirs.Add(pp, info); } var repPlaylist = new PlaylistRepository(); var playlists = repPlaylist.GetAll(); if (playlists.Count > 0) { Directory pp = new Directory() { Type="show" }; pp.Key = PlexHelper.ConstructPlaylistUrl(userid); pp.Title = "Playlists"; pp.Thumb = PlexHelper.ConstructSupportImageLink("plex_playlists.png"); pp.LeafCount = playlists.Count.ToString(); pp.ViewedLeafCount = "0"; dirs.Add(pp, info); } dirs = dirs.OrderBy(a => a.Title).ToList(); } ret.Childrens = dirs; return ret.GetStream(); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); return new MemoryStream(); } }
public List<Contract_AnimeSeries> GetSeriesForGroupRecursive(int animeGroupID, int userID) { List<Contract_AnimeSeries> series = new List<Contract_AnimeSeries>(); try { AnimeGroupRepository repGroups = new AnimeGroupRepository(); AnimeGroup grp = repGroups.GetByID(animeGroupID); if (grp == null) return series; foreach (AnimeSeries ser in grp.GetAllSeries()) series.Add(ser.ToContract(ser.GetUserRecord(userID))); return series; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); return series; } }
public string DeleteAnimeGroup(int animeGroupID, bool deleteFiles) { try { AnimeSeriesRepository repAnimeSer = new AnimeSeriesRepository(); AnimeGroupRepository repGroups = new AnimeGroupRepository(); AnimeGroup grp = repGroups.GetByID(animeGroupID); if (grp == null) return "Group does not exist"; int? parentGroupID = grp.AnimeGroupParentID; foreach (AnimeSeries ser in grp.GetAllSeries()) { DeleteAnimeSeries(ser.AnimeSeriesID, deleteFiles, false); } // delete all sub groups foreach (AnimeGroup subGroup in grp.GetAllChildGroups()) { DeleteAnimeGroup(subGroup.AnimeGroupID, deleteFiles); } GroupFilterConditionRepository repConditions = new GroupFilterConditionRepository(); // delete any group filter conditions which reference these groups foreach (GroupFilterCondition gfc in repConditions.GetByConditionType(GroupFilterConditionType.AnimeGroup)) { int thisGrpID = 0; int.TryParse(gfc.ConditionParameter, out thisGrpID); if (thisGrpID == animeGroupID) repConditions.Delete(gfc.GroupFilterConditionID); } repGroups.Delete(grp.AnimeGroupID); // finally update stats if (parentGroupID.HasValue) { AnimeGroup grpParent = repGroups.GetByID(parentGroupID.Value); if (grpParent != null) { grpParent.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true, true, true); StatsCache.Instance.UpdateUsingGroup(grpParent.TopLevelAnimeGroup.AnimeGroupID); } } return ""; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); return ex.Message; } }
public void UpdateUsingGroup(ISession session, int animeGroupID) { try { DateTime start = DateTime.Now; AnimeGroupRepository repGroups = new AnimeGroupRepository(); AnimeGroup thisgrp = repGroups.GetByID(session, animeGroupID); if (thisgrp == null) return; AdhocRepository repAdHoc = new AdhocRepository(); // get a list of all the groups including this one and everthing above it the heirarchy List<AnimeGroup> allgroups = new List<AnimeGroup>(); allgroups.Add(thisgrp); int? groupID = thisgrp.AnimeGroupParentID; while (groupID.HasValue) { AnimeGroup grpTemp = repGroups.GetByID(session, groupID.Value); if (grpTemp != null) { allgroups.Add(grpTemp); groupID = grpTemp.AnimeGroupParentID; } else groupID = null; } TimeSpan ts = DateTime.Now - start; logger.Trace("Updating cached stats for GROUP - STEP 1 ({0}) in {1} ms", thisgrp.GroupName, ts.TotalMilliseconds); start = DateTime.Now; VideoLocalRepository repVids = new VideoLocalRepository(); CrossRef_File_EpisodeRepository repXrefs = new CrossRef_File_EpisodeRepository(); foreach (AnimeGroup grp in allgroups) { StatGroupCategories[grp.AnimeGroupID] = grp.CategoriesString; StatGroupTitles[grp.AnimeGroupID] = grp.TitlesString; StatGroupVideoQuality[grp.AnimeGroupID] = grp.VideoQualityString; ts = DateTime.Now - start; logger.Trace("Updating cached stats for GROUP - STEP 2 ({0}) in {1} ms", grp.GroupName, ts.TotalMilliseconds); start = DateTime.Now; DateTime? airDate_Min = null; DateTime? airDate_Max = null; DateTime? endDate = new DateTime(1980, 1, 1); DateTime? seriesCreatedDate = null; bool isComplete = false; bool hasFinishedAiring = false; bool isCurrentlyAiring = false; string videoQualityEpisodes = ""; List<string> audioLanguages = new List<string>(); List<string> subtitleLanguages = new List<string>(); bool hasTvDB = true; bool hasMAL = true; bool hasMovieDB = true; bool hasMovieDBOrTvDB = true; int seriesCount = 0; int epCount = 0; foreach (AnimeSeries series in grp.GetAllSeries(session)) { seriesCount++; List<VideoLocal> vidsTemp = repVids.GetByAniDBAnimeID(session, series.AniDB_ID); List<CrossRef_File_Episode> crossRefs = repXrefs.GetByAnimeID(session, series.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; // All Video Quality Episodes // Try to determine if this anime has all the episodes available at a certain video quality // e.g. the series has all episodes in blu-ray // Also look at languages Dictionary<string, int> vidQualEpCounts = new Dictionary<string,int>(); // video quality, count of episodes foreach (AnimeEpisode ep in series.GetAnimeEpisodes(session)) { if (ep.EpisodeTypeEnum != AniDBAPI.enEpisodeType.Episode) continue; 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]); } } } List<string> qualityAddedSoFar = new List<string>(); // handle mutliple files of the same quality for one episode foreach (VideoLocal vid in epVids) { AniDB_File anifile = vid.GetAniDBFile(session); if (anifile == null) continue; if (!qualityAddedSoFar.Contains(anifile.File_Source)) { if (!vidQualEpCounts.ContainsKey(anifile.File_Source)) vidQualEpCounts[anifile.File_Source] = 1; else vidQualEpCounts[anifile.File_Source]++; qualityAddedSoFar.Add(anifile.File_Source); } } } ts = DateTime.Now - start; logger.Trace("Updating cached stats for GROUP/Series - STEP 3 ({0}/{1}) in {2} ms",grp.GroupName, series.AnimeSeriesID, ts.TotalMilliseconds); start = DateTime.Now; AniDB_Anime anime = series.GetAnime(session); epCount = epCount + anime.EpisodeCountNormal; foreach (KeyValuePair<string, int> kvp in vidQualEpCounts) { int index = videoQualityEpisodes.IndexOf(kvp.Key, 0, StringComparison.InvariantCultureIgnoreCase); if (index > -1) continue; // don't add if we already have it if (anime.EpisodeCountNormal == kvp.Value) { if (videoQualityEpisodes.Length > 0) videoQualityEpisodes += ","; videoQualityEpisodes += kvp.Key; } } ts = DateTime.Now - start; logger.Trace("Updating cached stats for GROUP/Series - STEP 4 ({0}/{1}) in {2} ms", grp.GroupName, series.AnimeSeriesID, ts.TotalMilliseconds); start = DateTime.Now; // audio languages Dictionary<int, LanguageStat> dicAudio = repAdHoc.GetAudioLanguageStatsByAnime(session, anime.AnimeID); foreach (KeyValuePair<int, LanguageStat> kvp in dicAudio) { foreach (string lanName in kvp.Value.LanguageNames) { if (!audioLanguages.Contains(lanName)) audioLanguages.Add(lanName); } } ts = DateTime.Now - start; logger.Trace("Updating cached stats for GROUP/Series - STEP 5 ({0}/{1}) in {2} ms", grp.GroupName, series.AnimeSeriesID, ts.TotalMilliseconds); start = DateTime.Now; // subtitle languages Dictionary<int, LanguageStat> dicSubtitle = repAdHoc.GetSubtitleLanguageStatsByAnime(session, anime.AnimeID); foreach (KeyValuePair<int, LanguageStat> kvp in dicSubtitle) { foreach (string lanName in kvp.Value.LanguageNames) { if (!subtitleLanguages.Contains(lanName)) subtitleLanguages.Add(lanName); } } ts = DateTime.Now - start; logger.Trace("Updating cached stats for GROUP/Series - STEP 6 ({0}/{1}) in {2} ms", grp.GroupName, series.AnimeSeriesID, ts.TotalMilliseconds); start = DateTime.Now; // Calculate Air Date DateTime? thisDate = series.AirDate; if (thisDate.HasValue) { if (airDate_Min.HasValue) { if (thisDate.Value < airDate_Min.Value) airDate_Min = thisDate; } else airDate_Min = thisDate; if (airDate_Max.HasValue) { if (thisDate.Value > airDate_Max.Value) airDate_Max = thisDate; } else airDate_Max = thisDate; } // calculate end date // if the end date is NULL it actually means it is ongoing, so this is the max possible value thisDate = series.EndDate; if (thisDate.HasValue && endDate.HasValue) { if (thisDate.Value > endDate.Value) endDate = thisDate; } else endDate = null; // Note - only one series has to be finished airing to qualify if (series.EndDate.HasValue && series.EndDate.Value < DateTime.Now) hasFinishedAiring = true; // Note - only one series has to be finished airing to qualify if (!series.EndDate.HasValue || series.EndDate.Value > DateTime.Now) isCurrentlyAiring = true; // We evaluate IsComplete as true if // 1. series has finished airing // 2. user has all episodes locally // Note - only one series has to be complete for the group to be considered complete if (series.EndDate.HasValue) { if (series.EndDate.Value < DateTime.Now && series.MissingEpisodeCount == 0 && series.MissingEpisodeCountGroups == 0) { isComplete = true; } } // Calculate Series Created Date thisDate = series.DateTimeCreated; if (thisDate.HasValue) { if (seriesCreatedDate.HasValue) { if (thisDate.Value < seriesCreatedDate.Value) seriesCreatedDate = thisDate; } else seriesCreatedDate = thisDate; } ts = DateTime.Now - start; logger.Trace("Updating cached stats for GROUP/Series - STEP 7 ({0}/{1}) in {2} ms", grp.GroupName, series.AnimeSeriesID, ts.TotalMilliseconds); start = DateTime.Now; // for the group, if any of the series don't have a tvdb link // we will consider the group as not having a tvdb link List<CrossRef_AniDB_TvDBV2> tvXrefs = series.GetCrossRefTvDBV2(); if (tvXrefs == null || tvXrefs.Count == 0) hasTvDB = false; if (series.CrossRefMovieDB == null) hasMovieDB = false; if (series.CrossRefMAL == null) hasMAL = false; if ((tvXrefs == null || tvXrefs.Count == 0) && series.CrossRefMovieDB == null) hasMovieDBOrTvDB = false; } StatGroupIsComplete[grp.AnimeGroupID] = isComplete; StatGroupIsFinishedAiring[grp.AnimeGroupID] = hasFinishedAiring; StatGroupIsCurrentlyAiring[grp.AnimeGroupID] = isCurrentlyAiring; StatGroupHasTvDB[grp.AnimeGroupID] = hasTvDB; StatGroupHasMAL[grp.AnimeGroupID] = hasMAL; StatGroupHasMovieDB[grp.AnimeGroupID] = hasMovieDB; StatGroupHasMovieDBOrTvDB[grp.AnimeGroupID] = hasMovieDBOrTvDB; StatGroupSeriesCount[grp.AnimeGroupID] = seriesCount; StatGroupEpisodeCount[grp.AnimeGroupID] = epCount; StatGroupVideoQualityEpisodes[grp.AnimeGroupID] = videoQualityEpisodes; StatGroupAirDate_Min[grp.AnimeGroupID] = airDate_Min; StatGroupAirDate_Max[grp.AnimeGroupID] = airDate_Max; StatGroupEndDate[grp.AnimeGroupID] = endDate; StatGroupSeriesCreatedDate[grp.AnimeGroupID] = seriesCreatedDate; StatGroupUserVoteOverall[grp.AnimeGroupID] = grp.UserVote; StatGroupUserVotePermanent[grp.AnimeGroupID] = grp.UserVotePermanent; StatGroupUserVoteTemporary[grp.AnimeGroupID] = grp.UserVoteTemporary; StatGroupAniDBRating[grp.AnimeGroupID] = grp.AniDBRating; ts = DateTime.Now - start; logger.Trace("Updating cached stats for GROUP - STEP 8 ({0}) in {1} ms", grp.GroupName, ts.TotalMilliseconds); start = DateTime.Now; string Stat_AudioLanguages = ""; foreach (string audioLan in audioLanguages) { if (Stat_AudioLanguages.Length > 0) Stat_AudioLanguages += ","; Stat_AudioLanguages += audioLan; } this.StatGroupAudioLanguages[grp.AnimeGroupID] = Stat_AudioLanguages; string Stat_SubtitleLanguages = ""; foreach (string subLan in subtitleLanguages) { if (Stat_SubtitleLanguages.Length > 0) Stat_SubtitleLanguages += ","; Stat_SubtitleLanguages += subLan; } this.StatGroupSubtitleLanguages[grp.AnimeGroupID] = Stat_SubtitleLanguages; ts = DateTime.Now - start; logger.Trace("Updating cached stats for GROUP - STEP 9 ({0}) in {1} ms", grp.GroupName, ts.TotalMilliseconds); start = DateTime.Now; UpdateGroupFilterUsingGroup(grp.AnimeGroupID); UpdatePlexAnimeGroup(session, grp,grp.GetAllSeries()); ts = DateTime.Now - start; logger.Trace("Updating cached stats for GROUP - END ({0}) in {1} ms", grp.GroupName, ts.TotalMilliseconds); } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } }
/// <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 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 Contract_AnimeGroup_SaveResponse SaveGroup(Contract_AnimeGroup_Save contract, int userID) { Contract_AnimeGroup_SaveResponse contractout = new Contract_AnimeGroup_SaveResponse(); contractout.ErrorMessage = ""; contractout.AnimeGroup = null; try { AnimeGroupRepository repGroup = new AnimeGroupRepository(); AnimeGroup grp = null; if (contract.AnimeGroupID.HasValue) { grp = repGroup.GetByID(contract.AnimeGroupID.Value); if (grp == null) { contractout.ErrorMessage = "Could not find existing group with ID: " + contract.AnimeGroupID.Value.ToString(); return contractout; } } else { grp = new AnimeGroup(); grp.Description = ""; grp.IsManuallyNamed = 0; grp.DateTimeCreated = DateTime.Now; grp.DateTimeUpdated = DateTime.Now; grp.SortName = ""; grp.MissingEpisodeCount = 0; grp.MissingEpisodeCountGroups = 0; grp.OverrideDescription = 0; } if (string.IsNullOrEmpty(contract.GroupName)) { contractout.ErrorMessage = "Must specify a group name"; return contractout; } grp.AnimeGroupParentID = contract.AnimeGroupParentID; grp.Description = contract.Description; grp.GroupName = contract.GroupName; grp.IsManuallyNamed = contract.IsManuallyNamed; grp.OverrideDescription = 0; if (string.IsNullOrEmpty(contract.SortName)) grp.SortName = contract.GroupName; else grp.SortName = contract.SortName; repGroup.Save(grp); AnimeGroup_User userRecord = grp.GetUserRecord(userID); if (userRecord == null) userRecord = new AnimeGroup_User(userID, grp.AnimeGroupID); userRecord.IsFave = contract.IsFave; AnimeGroup_UserRepository repUserRecords = new AnimeGroup_UserRepository(); repUserRecords.Save(userRecord); Contract_AnimeGroup contractGrp = grp.ToContract(grp.GetUserRecord(userID)); contractout.AnimeGroup = contractGrp; return contractout; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); contractout.ErrorMessage = ex.Message; return contractout; } }
public static void GetAnimeSeriesRecursive(ISession session, int animeGroupID, ref List<AnimeSeries> seriesList) { AnimeGroupRepository rep = new AnimeGroupRepository(); AnimeGroup grp = rep.GetByID(session, animeGroupID); if (grp == null) return; // get the series for this group List<AnimeSeries> thisSeries = grp.GetSeries(session); seriesList.AddRange(thisSeries); foreach (AnimeGroup childGroup in grp.GetChildGroups(session)) { GetAnimeSeriesRecursive(session, childGroup.AnimeGroupID, ref seriesList); } }
public void SetDefaultSeriesForGroup(int animeGroupID, int animeSeriesID) { try { AnimeGroupRepository repGroups = new AnimeGroupRepository(); AnimeSeriesRepository repSeries = new AnimeSeriesRepository(); AnimeGroup grp = repGroups.GetByID(animeGroupID); if (grp == null) return; AnimeSeries ser = repSeries.GetByID(animeSeriesID); if (ser == null) return; grp.DefaultAnimeSeriesID = animeSeriesID; repGroups.Save(grp); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } }
public List<Contract_AnimeGroup> GetAllGroupsAboveGroupInclusive(int animeGroupID, int userID) { List<Contract_AnimeGroup> grps = new List<Contract_AnimeGroup>(); try { using (var session = JMMService.SessionFactory.OpenSession()) { AnimeGroupRepository repGroups = new AnimeGroupRepository(); AnimeGroup grp = repGroups.GetByID(session, animeGroupID); if (grp == null) return grps; Contract_AnimeGroup contractGrp = grp.ToContract(grp.GetUserRecord(session, userID)); grps.Add(contractGrp); int? groupID = grp.AnimeGroupParentID; while (groupID.HasValue) { AnimeGroup grpTemp = repGroups.GetByID(session, groupID.Value); if (grpTemp != null) { Contract_AnimeGroup contractGrpTemp = grpTemp.ToContract(grpTemp.GetUserRecord(session, userID)); grps.Add(contractGrpTemp); groupID = grpTemp.AnimeGroupParentID; } else { groupID = null; } } return grps; } } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return grps; }
public void Save(AnimeSeries obj, bool updateGroups, bool onlyupdatestats, bool skipgroupfilters = false) { bool newSeries = false; AnimeGroup oldGroup = null; AnimeGroupRepository repGroups = new AnimeGroupRepository(); bool isMigrating = false; lock (obj) { if (obj.AnimeSeriesID == 0) { newSeries = true; // a new series } else { // get the old version from the DB AnimeSeries oldSeries; using (var session = JMMService.SessionFactory.OpenSession()) { oldSeries = session.Get <AnimeSeries>(obj.AnimeSeriesID); } if (oldSeries != null) { // means we are moving series to a different group if (oldSeries.AnimeGroupID != obj.AnimeGroupID) { oldGroup = repGroups.GetByID(oldSeries.AnimeGroupID); AnimeGroup newGroup = repGroups.GetByID(obj.AnimeGroupID); if (newGroup != null && newGroup.GroupName.Equals("AAA Migrating Groups AAA")) { isMigrating = true; } newSeries = true; } } } if (newSeries && !isMigrating) { using (var session = JMMService.SessionFactory.OpenSession()) { obj.Contract = null; // populate the database using (var transaction = session.BeginTransaction()) { session.SaveOrUpdate(obj); transaction.Commit(); } } } HashSet <GroupFilterConditionType> types = obj.UpdateContract(onlyupdatestats); using (var session = JMMService.SessionFactory.OpenSession()) { // populate the database using (var transaction = session.BeginTransaction()) { session.SaveOrUpdate(obj); transaction.Commit(); } } if (!skipgroupfilters && !isMigrating) { GroupFilterRepository.CreateOrVerifyTagsAndYearsFilters(false, obj.Contract?.AniDBAnime?.AniDBAnime?.AllTags, obj.Contract?.AniDBAnime?.AniDBAnime?.AirDate); //This call will create extra years or tags if the Group have a new year or tag obj.UpdateGroupFilters(types, null); } Cache.Update(obj); Changes.AddOrUpdate(obj.AnimeSeriesID); } if (updateGroups && !isMigrating) { if (newSeries) { logger.Trace("Updating group stats by series from AnimeSeriesRepository.Save: {0}", obj.AnimeSeriesID); AnimeGroup grp = repGroups.GetByID(obj.AnimeGroupID); if (grp != null) { repGroups.Save(grp, true, true); } } if (oldGroup != null) { logger.Trace("Updating group stats by group from AnimeSeriesRepository.Save: {0}", oldGroup.AnimeGroupID); repGroups.Save(oldGroup, true, true); } } }
public Contract_AnimeGroup GetGroup(int animeGroupID, int userID) { try { AnimeGroupRepository repGroups = new AnimeGroupRepository(); AnimeGroup grp = repGroups.GetByID(animeGroupID); if (grp == null) return null; Contract_AnimeGroup contractGrpTemp = grp.ToContract(grp.GetUserRecord(userID)); return contractGrpTemp; } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); } return null; }