Beispiel #1
0
        /// <summary>
        /// Calculates what groups should belong to tag related group filters.
        /// </summary>
        /// <param name="session">The NHibernate session.</param>
        /// <returns>A <see cref="ILookup{TKey,TElement}"/> that maps group filter ID to anime group IDs.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="session"/> is <c>null</c>.</exception>
        public ILookup <int, int> CalculateAnimeGroupsPerTagGroupFilter(ISessionWrapper session)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }

            var groupsByFilter = session.CreateSQLQuery(@"
                SELECT DISTINCT grpFilter.GroupFilterID, grp.AnimeGroupID
                    FROM AnimeGroup grp
                        INNER JOIN AnimeSeries series
                            ON series.AnimeGroupID = grp.AnimeGroupID
                        INNER JOIN AniDB_Anime_Tag anidbTag
                            ON anidbTag.AnimeID = series.AniDB_ID
                        INNER JOIN AniDB_Tag tag
                            ON tag.TagID = anidbTag.TagID
                        INNER JOIN GroupFilter grpFilter
                            ON grpFilter.GroupFilterName = tag.TagName
                                AND grpFilter.FilterType = :tagType
                    ORDER BY grpFilter.GroupFilterID, grp.AnimeGroupID")
                                 .AddScalar("GroupFilterID", NHibernateUtil.Int32)
                                 .AddScalar("AnimeGroupID", NHibernateUtil.Int32)
                                 .SetInt32("tagType", (int)GroupFilterType.Tag)
                                 .List <object[]>()
                                 .ToLookup(r => (int)r[0], r => (int)r[1]);

            return(groupsByFilter);
        }
        public void UpdateBatch(ISessionWrapper session, IReadOnlyCollection <SVR_AnimeGroup> groups)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            if (groups == null)
            {
                throw new ArgumentNullException(nameof(groups));
            }

            foreach (SVR_AnimeGroup group in groups)
            {
                lock (globalDBLock)
                {
                    lock (group)
                    {
                        session.Update(group);
                        lock (Cache)
                        {
                            Cache.Update(group);
                        }
                    }
                }
            }
            Changes.AddOrUpdateRange(groups.Select(g => g.AnimeGroupID));
        }
        /// <summary>
        /// Inserts a batch of <see cref="AnimeGroup_User"/> into the database.
        /// </summary>
        /// <remarks>
        /// <para>It is up to the caller of this method to manage transactions, etc.</para>
        /// <para>Group Filters, etc. will not be updated by this method.</para>
        /// </remarks>
        /// <param name="session">The NHibernate session.</param>
        /// <param name="groupUsers">The batch of <see cref="AnimeGroup_User"/> to insert into the database.</param>
        /// <exception cref="ArgumentNullException"><paramref name="session"/> or <paramref name="groupUsers"/> is <c>null</c>.</exception>
        public void UpdateBatch(ISessionWrapper session, IEnumerable <AnimeGroup_User> groupUsers)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            if (groupUsers == null)
            {
                throw new ArgumentNullException(nameof(groupUsers));
            }

            foreach (AnimeGroup_User groupUser in groupUsers)
            {
                session.Update(groupUser);

                ChangeTracker <int> changeTracker;

                if (!Changes.TryGetValue(groupUser.JMMUserID, out changeTracker))
                {
                    changeTracker = new ChangeTracker <int>();
                    Changes[groupUser.JMMUserID] = changeTracker;
                }

                changeTracker.AddOrUpdate(groupUser.AnimeGroupID);
            }
        }
        /// <summary>
        /// Deletes all AnimeGroup_User records.
        /// </summary>
        /// <remarks>
        /// This method also makes sure that the cache is cleared.
        /// </remarks>
        /// <param name="session">The NHibernate session.</param>
        /// <exception cref="ArgumentNullException"><paramref name="session"/> is <c>null</c>.</exception>
        public void DeleteAll(ISessionWrapper session)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }

            // First, get all of the current user/groups so that we can inform the change tracker that they have been removed later
            var usrGrpMap = GetAll()
                            .GroupBy(g => g.JMMUserID, g => g.AnimeGroupID);

            // Then, actually delete the AnimeGroup_Users
            session.CreateQuery("delete AnimeGroup_User agu")
            .ExecuteUpdate();

            // Now, update the change trackers with all removed records
            foreach (var grp in usrGrpMap)
            {
                int jmmUserId = grp.Key;
                ChangeTracker <int> changeTracker;

                if (!Changes.TryGetValue(jmmUserId, out changeTracker))
                {
                    changeTracker      = new ChangeTracker <int>();
                    Changes[jmmUserId] = changeTracker;
                }

                changeTracker.RemoveRange(grp);
            }

            // Finally, we need to clear the cache so that it is in sync with the database
            ClearCache();
        }
        public void BatchDelete(ISessionWrapper session, IEnumerable <SVR_GroupFilter> groupFilters)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            if (groupFilters == null)
            {
                throw new ArgumentNullException(nameof(groupFilters));
            }

            lock (globalDBLock)
            {
                lock (Cache)
                {
                    foreach (SVR_GroupFilter groupFilter in groupFilters)
                    {
                        lock (groupFilter)
                        {
                            try
                            {
                                session.Delete(groupFilter);
                                Cache.Remove(groupFilter);
                            }
                            catch (Exception e)
                            {
                                logger.Error(
                                    $"Unable to delete group filter: {groupFilter.GroupFilterName}|{groupFilter.GroupFilterID}");
                            }
                        }
                    }
                }
            }
        }
Beispiel #6
0
 public SVR_AniDB_Anime GetByAnimeID(ISessionWrapper session, int id)
 {
     lock (Cache)
     {
         return(Animes.GetOne(id));
     }
 }
Beispiel #7
0
        private static string getTransientProperties(ISessionWrapper session)
        {
            int    index = 0;
            string key   = String.Format("TransientProperties{0}", index);
            string value = String.Empty;
            bool   end   = false;

            do
            {
                string currentValue = session.Get(key);
                if (!String.IsNullOrEmpty(currentValue))
                {
                    if (!value.EndsWith(";"))
                    {
                        value = value + ";";
                    }

                    value += currentValue;
                    index++;
                    key = String.Format("TransientProperties{0}", index);
                }
                else
                {
                    end = true;
                }
            } while (!end);

            return(value.Substring(1));
        }
        public ILookup <int, MovieDB_Fanart> GetByAnimeIDs(ISessionWrapper session, int[] animeIds)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            if (animeIds == null)
            {
                throw new ArgumentNullException(nameof(animeIds));
            }

            if (animeIds.Length == 0)
            {
                return(EmptyLookup <int, MovieDB_Fanart> .Instance);
            }

            var fanartByAnime = session.CreateSQLQuery(@"
                SELECT DISTINCT adbOther.AnimeID, {mdbFanart.*}
                    FROM CrossRef_AniDB_Other AS adbOther
                        INNER JOIN MovieDB_Fanart AS mdbFanart
                            ON mdbFanart.MovieId = adbOther.CrossRefID
                    WHERE adbOther.CrossRefType = :crossRefType AND adbOther.AnimeID IN (:animeIds)")
                                .AddScalar("AnimeID", NHibernateUtil.Int32)
                                .AddEntity("mdbFanart", typeof(MovieDB_Fanart))
                                .SetInt32("crossRefType", (int)CrossRefType.MovieDB)
                                .SetParameterList("animeIds", animeIds)
                                .List <object[]>()
                                .ToLookup(r => (int)r[0], r => (MovieDB_Fanart)r[1]);

            return(fanartByAnime);
        }
Beispiel #9
0
        public HashSet <string> GetAllVideoQualityForAnime(ISessionWrapper session, int animeID)
        {
            HashSet <string> vidQuals = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase);

            System.Data.IDbCommand command = session.Connection.CreateCommand();
            command.CommandText = "SELECT anifile.File_Source "
                                  + "FROM AnimeSeries ser "
                                  + "INNER JOIN AniDB_Anime anime on anime.AnimeID = ser.AniDB_ID "
                                  + "INNER JOIN AnimeEpisode ep on ep.AnimeSeriesID = ser.AnimeSeriesID "
                                  + "INNER JOIN AniDB_Episode aniep on ep.AniDB_EpisodeID = aniep.EpisodeID "
                                  + "INNER JOIN CrossRef_File_Episode xref on aniep.EpisodeID = xref.EpisodeID "
                                  + "INNER JOIN AniDB_File anifile on anifile.Hash = xref.Hash "
                                  + "INNER JOIN CrossRef_Subtitles_AniDB_File subt on subt.FileID = anifile.FileID ";
            // See Note 1
            command.CommandText += "where anime.AnimeID = " + animeID.ToString()
                                   + " GROUP BY anifile.File_Source ";

            using (IDataReader rdr = command.ExecuteReader())
            {
                while (rdr.Read())
                {
                    string vidQual = rdr[0].ToString().Trim();
                    if (!vidQuals.Contains(vidQual))
                    {
                        vidQuals.Add(vidQual);
                    }
                }
            }
            return(vidQuals);
        }
        /// <summary>
        /// Inserts a batch of <see cref="SVR_GroupFilter"/>s.
        /// </summary>
        /// <remarks>
        /// This method ONLY updates existing <see cref="SVR_GroupFilter"/>s. It will not insert any that don't already exist.
        /// </remarks>
        /// <param name="session">The NHibernate session.</param>
        /// <param name="groupFilters">The batch of <see cref="SVR_GroupFilter"/>s to update.</param>
        /// <exception cref="ArgumentNullException"><paramref name="session"/> or <paramref name="groupFilters"/> is <c>null</c>.</exception>
        public void BatchInsert(ISessionWrapper session, IEnumerable <SVR_GroupFilter> groupFilters)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            if (groupFilters == null)
            {
                throw new ArgumentNullException(nameof(groupFilters));
            }

            lock (globalDBLock)
            {
                lock (Cache)
                {
                    foreach (SVR_GroupFilter groupFilter in groupFilters)
                    {
                        lock (groupFilter)
                        {
                            session.Insert(groupFilter);
                            Cache.Update(groupFilter);
                        }
                    }
                }
            }
        }
        public void UpdateBatch(ISessionWrapper session, IReadOnlyCollection <SVR_AnimeSeries> seriesBatch)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            if (seriesBatch == null)
            {
                throw new ArgumentNullException(nameof(seriesBatch));
            }

            if (seriesBatch.Count == 0)
            {
                return;
            }

            foreach (SVR_AnimeSeries series in seriesBatch)
            {
                lock (globalDBLock)
                {
                    session.Update(series);
                    lock (Cache)
                    {
                        Cache.Update(series);
                    }
                }
                Changes.AddOrUpdate(series.AnimeSeriesID);
            }
        }
Beispiel #12
0
        public static void ExecuteDumpPropertiesToCustomActiondata(ISessionWrapper session)
        {
            string transientProperties = getTransientProperties(session);

            string[] parts = transientProperties.Split(';');
            var      sb    = new StringBuilder();

            foreach (string key in parts)
            {
                if (String.IsNullOrEmpty(key))
                {
                    continue;
                }

                string value = session.Get(key);
                if (!string.IsNullOrEmpty(value))
                {
                    value = Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
                }

                sb.AppendFormat("{0}={1};", key, value);
            }

            session.Set("CUSTOM_ACTION_DATA", sb.ToString());
        }
Beispiel #13
0
        public ILookup <int, CrossRef_AniDB_MAL> GetByAnimeIDs(ISessionWrapper session, int[] animeIds)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            if (animeIds == null)
            {
                throw new ArgumentNullException(nameof(animeIds));
            }

            if (animeIds.Length == 0)
            {
                return(EmptyLookup <int, CrossRef_AniDB_MAL> .Instance);
            }

            var xrefByAnime = session.CreateCriteria <CrossRef_AniDB_MAL>()
                              .Add(Restrictions.In(nameof(CrossRef_AniDB_MAL.AnimeID), animeIds))
                              .AddOrder(Order.Asc(nameof(CrossRef_AniDB_MAL.StartEpisodeType)))
                              .AddOrder(Order.Asc(nameof(CrossRef_AniDB_MAL.StartEpisodeNumber)))
                              .List <CrossRef_AniDB_MAL>()
                              .ToLookup(cr => cr.AnimeID);

            return(xrefByAnime);
        }
 public TvDB_Series GetByTvDBID(ISessionWrapper session, int id)
 {
     return(session
            .CreateCriteria(typeof(TvDB_Series))
            .Add(Restrictions.Eq("SeriesID", id))
            .UniqueResult <TvDB_Series>());
 }
        /// <summary>
        /// Gets other cross references by anime ID.
        /// </summary>
        /// <param name="session">The NHibernate session.</param>
        /// <param name="animeIds">An optional list of anime IDs whose cross references are to be retrieved.
        /// Can be <c>null</c> to get cross references for ALL anime.</param>
        /// <param name="xrefTypes">The types of cross references to find.</param>
        /// <returns>A <see cref="ILookup{TKey,TElement}"/> that maps anime ID to their associated other cross references.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="session"/> is <c>null</c>.</exception>
        public ILookup <int, CrossRef_AniDB_Other> GetByAnimeIDsAndType(ISessionWrapper session,
                                                                        IReadOnlyCollection <int> animeIds,
                                                                        params CrossRefType[] xrefTypes)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }

            if (xrefTypes == null || xrefTypes.Length == 0 || animeIds?.Count == 0)
            {
                return(EmptyLookup <int, CrossRef_AniDB_Other> .Instance);
            }

            ICriteria criteria = session.CreateCriteria <CrossRef_AniDB_Other>()
                                 .Add(Restrictions.In(nameof(CrossRef_AniDB_Other.CrossRefType), xrefTypes));

            if (animeIds != null)
            {
                criteria = criteria.Add(Restrictions.InG(nameof(CrossRef_AniDB_Other.AnimeID), animeIds));
            }

            var crossRefs = criteria.List <CrossRef_AniDB_Other>()
                            .ToLookup(cr => cr.AnimeID);

            return(crossRefs);
        }
Beispiel #16
0
 public virtual IReadOnlyList <T> GetAll(ISessionWrapper session)
 {
     lock (globalDBLock)
     {
         return(session.CreateCriteria(typeof(T)).List <T>().ToList());
     }
 }
Beispiel #17
0
        public ILookup <int, AniDB_Tag> GetByAnimeIDs(ISessionWrapper session, int[] ids)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            if (ids == null)
            {
                throw new ArgumentNullException(nameof(ids));
            }

            if (ids.Length == 0)
            {
                return(EmptyLookup <int, AniDB_Tag> .Instance);
            }

            var tags = session
                       .CreateQuery(
                "Select xref.AnimeID, tag FROM AniDB_Tag as tag, AniDB_Anime_Tag as xref WHERE tag.TagID = xref.TagID AND xref.AnimeID IN (:animeIDs)")
                       .SetParameterList("animeIDs", ids)
                       .List <object[]>()
                       .ToLookup(t => (int)t[0], t => (AniDB_Tag)t[1]);

            return(tags);
        }
        public ILookup <int, AniDB_Anime_Title> GetByAnimeIDs([NotNull] ISessionWrapper session, ICollection <int> ids)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            if (ids == null)
            {
                throw new ArgumentNullException(nameof(ids));
            }

            if (ids.Count == 0)
            {
                return(EmptyLookup <int, AniDB_Anime_Title> .Instance);
            }

            lock (globalDBLock)
            {
                var titles = session.CreateCriteria <AniDB_Anime_Title>()
                             .Add(Restrictions.InG(nameof(AniDB_Anime_Title.AnimeID), ids))
                             .List <AniDB_Anime_Title>()
                             .ToLookup(t => t.AnimeID);

                return(titles);
            }
        }
        public CL_AnimeEpisode_User GetUserContract(int userid, ISessionWrapper session = null)
        {
            lock (_lock) //Make it atomic on creation
            {
                SVR_AnimeEpisode_User rr = GetUserRecord(userid);
                if (rr != null)
                {
                    return(rr.Contract);
                }
                rr = new SVR_AnimeEpisode_User
                {
                    PlayedCount    = 0,
                    StoppedCount   = 0,
                    WatchedCount   = 0,
                    AnimeEpisodeID = this.AnimeEpisodeID,
                    AnimeSeriesID  = this.AnimeSeriesID,
                    JMMUserID      = userid,
                    WatchedDate    = null
                };
                if (session != null)
                {
                    RepoFactory.AnimeEpisode_User.SaveWithOpenTransaction(session, rr);
                }
                else
                {
                    RepoFactory.AnimeEpisode_User.Save(rr);
                }

                return(rr.Contract);
            }
        }
Beispiel #20
0
        private Dictionary <int, LanguageStat> GetAudioLanguageStatsByAnimeResults(ISessionWrapper session,
                                                                                   string animeIdPredicate)
        {
            Dictionary <int, LanguageStat> dictStats = new Dictionary <int, LanguageStat>();
            string query = GetAudioLanguageStatsByAnimeSQL(animeIdPredicate);

            var rows = session.CreateSQLQuery(query)
                       .AddScalar("AnimeID", NHibernateUtil.Int32)
                       .AddScalar("MainTitle", NHibernateUtil.String)
                       .AddScalar("LanguageName", NHibernateUtil.String)
                       .List <object[]>();

            foreach (object[] cols in rows)
            {
                int    animeID   = Convert.ToInt32(cols[0]);
                string mainTitle = cols[1].ToString().Trim();
                string lanName   = cols[2].ToString().Trim();

                if (!dictStats.TryGetValue(animeID, out LanguageStat stat))
                {
                    stat = new LanguageStat
                    {
                        AnimeID       = animeID,
                        MainTitle     = mainTitle,
                        LanguageNames = new List <string>()
                    };
                    dictStats.Add(animeID, stat);
                }

                stat.LanguageNames.Add(lanName);
            }

            return(dictStats);
        }
Beispiel #21
0
        public static CL_AniDB_Anime_DefaultImage ToClient(this AniDB_Anime_DefaultImage defaultImage,
                                                           ISessionWrapper session)
        {
            ImageEntityType imgType     = (ImageEntityType)defaultImage.ImageParentType;
            IImageEntity    parentImage = null;

            switch (imgType)
            {
            case ImageEntityType.TvDB_Banner:
                parentImage = RepoFactory.TvDB_ImageWideBanner.GetByID(session, defaultImage.ImageParentID);
                break;

            case ImageEntityType.TvDB_Cover:
                parentImage = RepoFactory.TvDB_ImagePoster.GetByID(session, defaultImage.ImageParentID);
                break;

            case ImageEntityType.TvDB_FanArt:
                parentImage = RepoFactory.TvDB_ImageFanart.GetByID(session, defaultImage.ImageParentID);
                break;

            case ImageEntityType.MovieDB_Poster:
                parentImage = RepoFactory.MovieDB_Poster.GetByID(session, defaultImage.ImageParentID);
                break;

            case ImageEntityType.MovieDB_FanArt:
                parentImage = RepoFactory.MovieDB_Fanart.GetByID(session, defaultImage.ImageParentID);
                break;
            }

            return(defaultImage.ToClient(parentImage));
        }
Beispiel #22
0
        /// <summary>
        /// Updates all Group Filters. This should be done as the last step.
        /// </summary>
        /// <remarks>
        /// Assumes that all caches are up to date.
        /// </remarks>
        private void UpdateGroupFilters(ISessionWrapper session)
        {
            _log.Info("Updating Group Filters");
            _log.Info("Calculating Tag Filters");
            _groupFilterRepo.CalculateAnimeSeriesPerTagGroupFilter(session);
            _log.Info("Calculating All Other Filters");
            IEnumerable <SVR_GroupFilter> grpFilters = _groupFilterRepo.GetAll(session).Where(a =>
                                                                                              a.FilterType != (int)GroupFilterType.Tag &&
                                                                                              ((GroupFilterType)a.FilterType & GroupFilterType.Directory) == 0).ToList();

            // The main reason for doing this in parallel is because UpdateEntityReferenceStrings does JSON encoding
            // and is enough work that it can benefit from running in parallel
            Parallel.ForEach(
                grpFilters, filter =>
            {
                filter.SeriesIds.Clear();
                filter.CalculateGroupsAndSeries();

                filter.UpdateEntityReferenceStrings();
            });

            using (ITransaction trans = session.BeginTransaction())
            {
                _groupFilterRepo.BatchUpdate(session, grpFilters);
                trans.Commit();
            }

            _log.Info("Group Filters updated");
        }
Beispiel #23
0
        public List <PermissionTokenModel> Login(ISessionWrapper session, string account, string pasuwado)
        {
            if (null == session)
            {
                return(null);
            }
            CustUserSet set = QueryData(new object[] { account });

            if (null == set)
            {
                return(null);
            }
            if (!BizAccountLogin.CheckAccountPasuwado(set, pasuwado))
            {
                return(null);
            }
            using RoleRepository rep = new RoleRepository(DataAccess);
            foreach (var custUserRole in set.CustUserRoleList)
            {
                custUserRole.Permissions = rep.QueryData(new object[] { custUserRole.RoleId }).RolePermission;
            }
            List <IRoleModel> UserRoles = set.CustUserRoleList.Cast <IRoleModel>().ToList();

            session.User = set.CustUser;
            List <PermissionTokenModel> permissions = BizAccountLogin.GetRolePermissionsToken(session.SessionId, UserRoles);

            return(permissions);
        }
Beispiel #24
0
 public virtual T GetByID(ISessionWrapper session, S id)
 {
     lock (globalDBLock)
     {
         return(session.Get <T>(id));
     }
 }
        /// <summary>
        /// Creates a new <see cref="AutoAnimeGroupCalculator"/> using relationships stored in the database.
        /// </summary>
        /// <param name="session">The NHibernate session.</param>
        /// <returns>The created <see cref="AutoAnimeGroupCalculator"/>.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="session"/> is <c>null</c>.</exception>
        public static AutoAnimeGroupCalculator CreateFromServerSettings(ISessionWrapper session)
        {
            string                     exclusionsSetting          = ServerSettings.AutoGroupSeriesRelationExclusions;
            AutoGroupExclude           exclusions                 = AutoGroupExclude.None;
            AnimeRelationType          relationsToFuzzyTitleTest  = AnimeRelationType.None;
            MainAnimeSelectionStrategy mainAnimeSelectionStrategy = ServerSettings.AutoGroupSeriesUseScoreAlgorithm
                ? MainAnimeSelectionStrategy.Weighted
                : MainAnimeSelectionStrategy.MinAirDate;

            if (!String.IsNullOrEmpty(exclusionsSetting))
            {
                var exclusionTokens = exclusionsSetting
                                      .Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
                                      .Select(s => s.Trim())
                                      .Where(s => s.Length > 0)
                                      .ToList();

                exclusions = exclusionTokens
                             .Select(s =>
                {
                    s = s.Replace(" ", String.Empty);
                    Enum.TryParse(s, true, out AutoGroupExclude exclude);

                    return(exclude);
                })
                             .Aggregate(AutoGroupExclude.None, (exclude, allExcludes) => allExcludes | exclude);

                if (exclusionTokens.Contains("AllowDissimilarTitleExclusion", StringComparer.OrdinalIgnoreCase))
                {
                    relationsToFuzzyTitleTest = AnimeRelationType.SecondaryRelations;
                }
            }

            return(Create(session, exclusions, relationsToFuzzyTitleTest, mainAnimeSelectionStrategy));
        }
        /// <summary>
        /// Inserts a batch of <see cref="SVR_AnimeGroup_User"/> into the database.
        /// </summary>
        /// <remarks>
        /// <para>This method should NOT be used for updating existing entities.</para>
        /// <para>It is up to the caller of this method to manage transactions, etc.</para>
        /// <para>Group Filters, etc. will not be updated by this method.</para>
        /// </remarks>
        /// <param name="session">The NHibernate session.</param>
        /// <param name="groupUsers">The batch of <see cref="SVR_AnimeGroup_User"/> to insert into the database.</param>
        /// <exception cref="ArgumentNullException"><paramref name="session"/> or <paramref name="groupUsers"/> is <c>null</c>.</exception>
        public void InsertBatch(ISessionWrapper session, IEnumerable <SVR_AnimeGroup_User> groupUsers)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            if (groupUsers == null)
            {
                throw new ArgumentNullException(nameof(groupUsers));
            }

            foreach (SVR_AnimeGroup_User groupUser in groupUsers)
            {
                lock (globalDBLock)
                {
                    session.Insert(groupUser);
                    lock (Cache)
                    {
                        Cache.Update(groupUser);
                    }
                }

                if (!Changes.TryGetValue(groupUser.JMMUserID, out ChangeTracker <int> changeTracker))
                {
                    changeTracker = new ChangeTracker <int>();
                    Changes[groupUser.JMMUserID] = changeTracker;

                    changeTracker.AddOrUpdate(groupUser.AnimeGroupID);
                }
            }
        }
Beispiel #27
0
 public UnitOfWork(ILogWriter logWriter, ISessionFactory sessionFactory, ISessionWrapper wrapper)
 //: base(new uNhAddIns.SessionEasier.SessionFactoryProvider(provider), wrapper)
 {
     SessionFactory = sessionFactory;
     _wrapper       = wrapper;
     _logWriter     = logWriter;
 }
Beispiel #28
0
        public ILookup <int, TvDB_ImageFanart> GetByAnimeIDs(ISessionWrapper session, int[] animeIds)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            if (animeIds == null)
            {
                throw new ArgumentNullException(nameof(animeIds));
            }

            if (animeIds.Length == 0)
            {
                return(EmptyLookup <int, TvDB_ImageFanart> .Instance);
            }

            var fanartByAnime = session.CreateSQLQuery(@"
                SELECT DISTINCT crAdbTvTb.AnimeID, {tvdbFanart.*}
                   FROM CrossRef_AniDB_TvDBV2 AS crAdbTvTb
                      INNER JOIN TvDB_ImageFanart AS tvdbFanart
                         ON tvdbFanart.SeriesID = crAdbTvTb.TvDBID
                   WHERE crAdbTvTb.AnimeID IN (:animeIds)")
                                .AddScalar("AnimeID", NHibernateUtil.Int32)
                                .AddEntity("tvdbFanart", typeof(TvDB_ImageFanart))
                                .SetParameterList("animeIds", animeIds)
                                .List <object[]>()
                                .ToLookup(r => (int)r[0], r => (TvDB_ImageFanart)r[1]);

            return(fanartByAnime);
        }
Beispiel #29
0
        /// <summary>
        /// Creates a single <see cref="SVR_AnimeGroup"/> for each <see cref="SVR_AnimeSeries"/> in <paramref name="seriesList"/>.
        /// </summary>
        /// <remarks>
        /// This method assumes that there are no active transactions on the specified <paramref name="session"/>.
        /// </remarks>
        /// <param name="session">The NHibernate session.</param>
        /// <param name="seriesList">The list of <see cref="SVR_AnimeSeries"/> to create groups for.</param>
        /// <returns>A sequence of the created <see cref="SVR_AnimeGroup"/>s.</returns>
        private IEnumerable <SVR_AnimeGroup> CreateGroupPerSeries(ISessionWrapper session,
                                                                  IReadOnlyList <SVR_AnimeSeries> seriesList)
        {
            _log.Info("Generating AnimeGroups for {0} AnimeSeries", seriesList.Count);

            DateTime now = DateTime.Now;
            var      newGroupsToSeries = new Tuple <SVR_AnimeGroup, SVR_AnimeSeries> [seriesList.Count];

            // Create one group per series
            for (int grp = 0; grp < seriesList.Count; grp++)
            {
                SVR_AnimeGroup  group  = new SVR_AnimeGroup();
                SVR_AnimeSeries series = seriesList[grp];

                group.Populate(series, now);
                newGroupsToSeries[grp] = new Tuple <SVR_AnimeGroup, SVR_AnimeSeries>(group, series);
            }

            using (ITransaction trans = session.BeginTransaction())
            {
                _animeGroupRepo.InsertBatch(session, newGroupsToSeries.Select(gts => gts.Item1).AsReadOnlyCollection());
                trans.Commit();
            }

            // Anime groups should have IDs now they've been inserted. Now assign the group ID's to their respective series
            // (The caller of this method will be responsible for saving the AnimeSeries)
            foreach (Tuple <SVR_AnimeGroup, SVR_AnimeSeries> groupAndSeries in newGroupsToSeries)
            {
                groupAndSeries.Item2.AnimeGroupID = groupAndSeries.Item1.AnimeGroupID;
            }

            _log.Info("Generated {0} AnimeGroups", newGroupsToSeries.Length);

            return(newGroupsToSeries.Select(gts => gts.Item1));
        }
Beispiel #30
0
        private Dictionary <int, LanguageStat> GetAudioLanguageStatsByAnimeResults(ISessionWrapper session, string animeIdPredicate)
        {
            Dictionary <int, LanguageStat> dictStats = new Dictionary <int, LanguageStat>();

            using (IDbCommand command = session.Connection.CreateCommand())
            {
                command.CommandText = GetAudioLanguageStatsByAnimeSQL(animeIdPredicate);

                using (IDataReader rdr = command.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        int          animeID   = Convert.ToInt32(rdr[0]);
                        string       mainTitle = rdr[1].ToString().Trim();
                        string       lanName   = rdr[2].ToString().Trim();
                        LanguageStat stat      = null;

                        if (!dictStats.TryGetValue(animeID, out stat))
                        {
                            stat = new LanguageStat
                            {
                                AnimeID       = animeID,
                                MainTitle     = mainTitle,
                                LanguageNames = new List <string>()
                            };
                            dictStats.Add(animeID, stat);
                        }

                        stat.LanguageNames.Add(lanName);
                    }
                }
            }

            return(dictStats);
        }
 public CommonController(ILog logger,
     ISessionWrapper sessionWrapper,
     ICookieWrapper cookieWrapper)
 {
     _logger = logger;
     _cookieWrapper = cookieWrapper;
     _sessionWrapper = sessionWrapper;
 }
        public void setup()
        {
            var container = IoC.Initialize();
            ServiceLocator.SetLocatorProvider(() => new StructureMapServiceLocator(container));

            _dbSession = ServiceLocator.Current.GetInstance<ISessionWrapper>();
            _dbSession.BindToCurrentContext();
        }
 public AccountController(ILog logger,
     IUserService userService,
     ISessionWrapper sessionWrapper,
     ICookieWrapper cookieWrapper)
 {
     _logger = logger;
     _userService = userService;
     _cookieWrapper = cookieWrapper;
     _sessionWrapper = sessionWrapper;
 }
Beispiel #34
0
 public UserService(IUnitOfWork unitOfWork,
     ILog logger,
     IWebHelper webHelper,
     ISessionWrapper sessionWrapper)
 {
     _unitOfWork = unitOfWork;
     _logger = logger;
     _webHelper = webHelper;
     _sessionWrapper = sessionWrapper;
 }
		public DefaultConversationFactory(ISessionFactoryProvider factoriesProvider, ISessionWrapper wrapper)
		{
			if (factoriesProvider == null)
			{
				throw new ArgumentNullException("factoriesProvider");
			}
			if (wrapper == null)
			{
				throw new ArgumentNullException("wrapper");
			}
			this.factoriesProvider = factoriesProvider;
			this.wrapper = wrapper;
		}
Beispiel #36
0
		public NhConversation(ISessionFactoryProvider factoriesProvider, ISessionWrapper wrapper, string id)
			: base(id)
		{
			if (factoriesProvider == null)
			{
				throw new ArgumentNullException("factoriesProvider");
			}
			if (wrapper == null)
			{
				throw new ArgumentNullException("wrapper");
			}
			this.factoriesProvider = factoriesProvider;
			Wrapper = wrapper;
		}
        /// <summary>
        /// Gets or creates an <see cref="AnimeGroup"/> for the specified series.
        /// </summary>
        /// <param name="session">The NHibernate session.</param>
        /// <param name="series">The series for which the group is to be created/retrieved (Must be initialised first).</param>
        /// <returns>The <see cref="AnimeGroup"/> to use for the specified series.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="session"/> or <paramref name="series"/> is <c>null</c>.</exception>
        public AnimeGroup GetOrCreateSingleGroupForSeries(ISessionWrapper session, AnimeSeries series)
        {
            if (session == null)
                throw new ArgumentNullException(nameof(session));
            if (series == null)
                throw new ArgumentNullException(nameof(series));

            AnimeGroup animeGroup = null;

            if (_autoGroupSeries)
            {
                var grpCalculator = AutoAnimeGroupCalculator.CreateFromServerSettings(session);
                IReadOnlyList<int> grpAnimeIds = grpCalculator.GetIdsOfAnimeInSameGroup(series.AniDB_ID);
                // Try to find an existing AnimeGroup to add the series to
                // We basically pick the first group that any of the related series belongs to already
                animeGroup = grpAnimeIds.Select(id => RepoFactory.AnimeSeries.GetByAnimeID(id))
                    .Where(s => s != null)
                    .Select(s => RepoFactory.AnimeGroup.GetByID(s.AnimeGroupID))
                    .FirstOrDefault();

                if (animeGroup == null)
                {
                    // No existing group was found, so create a new one
                    int mainAnimeId = grpCalculator.GetGroupAnimeId(series.AniDB_ID);
                    AnimeSeries mainSeries = _animeSeriesRepo.GetByAnimeID(mainAnimeId);

                    animeGroup = CreateAnimeGroup(session, mainSeries, mainAnimeId, DateTime.Now);
                    RepoFactory.AnimeGroup.Save(animeGroup, true, true);
                }
            }
            else // We're not auto grouping (e.g. we're doing group per series)
            {
                animeGroup = new AnimeGroup();
                animeGroup.Populate(series, DateTime.Now);
                RepoFactory.AnimeGroup.Save(animeGroup, true, true);
            }

            return animeGroup;
        }
 public ContactRepository(ISessionWrapper session, IComicService comicService)
 {
     _session = session;
     _comicService = comicService;
 }
 public StudentRepository(ISessionWrapper wrapper)
 {
     _session = wrapper;
 }
        public Contract_AnimeEpisode GetNextUnwatchedEpisode(ISessionWrapper session, int animeSeriesID, int userID)
        {
            try
            {

                // get all the data first
                // we do this to reduce the amount of database calls, which makes it a lot faster
                AnimeSeries series = RepoFactory.AnimeSeries.GetByID(animeSeriesID);
                if (series == null) return null;

                //List<AnimeEpisode> epList = repEps.GetUnwatchedEpisodes(animeSeriesID, userID);
                List<AnimeEpisode> epList = new List<AnimeEpisode>();
                Dictionary<int, AnimeEpisode_User> dictEpUsers = new Dictionary<int, AnimeEpisode_User>();
                foreach (
                    AnimeEpisode_User userRecord in RepoFactory.AnimeEpisode_User.GetByUserIDAndSeriesID(userID, animeSeriesID))
                    dictEpUsers[userRecord.AnimeEpisodeID] = userRecord;

                foreach (AnimeEpisode animeep in RepoFactory.AnimeEpisode.GetBySeriesID(animeSeriesID))
                {
                    if (!dictEpUsers.ContainsKey(animeep.AnimeEpisodeID))
                    {
                        epList.Add(animeep);
                        continue;
                    }

                    AnimeEpisode_User usrRec = dictEpUsers[animeep.AnimeEpisodeID];
                    if (usrRec.WatchedCount == 0 || !usrRec.WatchedDate.HasValue)
                        epList.Add(animeep);
                }

                List<AniDB_Episode> aniEpList = RepoFactory.AniDB_Episode.GetByAnimeID(series.AniDB_ID);
                Dictionary<int, AniDB_Episode> dictAniEps = new Dictionary<int, AniDB_Episode>();
                foreach (AniDB_Episode aniep in aniEpList)
                    dictAniEps[aniep.EpisodeID] = aniep;

                List<Contract_AnimeEpisode> candidateEps = new List<Contract_AnimeEpisode>();
                foreach (AnimeEpisode ep in epList)
                {
                    if (dictAniEps.ContainsKey(ep.AniDB_EpisodeID))
                    {
                        AniDB_Episode anidbep = dictAniEps[ep.AniDB_EpisodeID];
                        if (anidbep.EpisodeType == (int) enEpisodeType.Episode ||
                            anidbep.EpisodeType == (int) enEpisodeType.Special)
                        {
                            AnimeEpisode_User userRecord = null;
                            if (dictEpUsers.ContainsKey(ep.AnimeEpisodeID))
                                userRecord = dictEpUsers[ep.AnimeEpisodeID];

                            Contract_AnimeEpisode epContract = ep.GetUserContract(userID);
                            if (epContract != null)
                                candidateEps.Add(epContract);
                        }
                    }
                }

                if (candidateEps.Count == 0) return null;

                // this will generate a lot of queries when the user doesn have files
                // for these episodes
                foreach (Contract_AnimeEpisode canEp in candidateEps.OrderBy(a=>a.EpisodeType).ThenBy(a=>a.EpisodeNumber))
                {
                    // now refresh from the database to get file count
                    AnimeEpisode epFresh = RepoFactory.AnimeEpisode.GetByID(canEp.AnimeEpisodeID);
                    if (epFresh.GetVideoLocals().Count > 0)
                        return epFresh.GetUserContract(userID);
                }

                return null;
            }
            catch (Exception ex)
            {
                logger.Error( ex,ex.ToString());
                return null;
            }
        }
Beispiel #41
0
 public Conversation(ISessionFactoryProvider provider, ISessionWrapper wrapper, string conversationId)
     : base(provider, wrapper, conversationId)
 {
     _provider = provider;
     _wrapper = wrapper;
 }
 public CrossRef_AniDB_Other GetCrossRefMovieDB(ISessionWrapper criteriaFactory)
 {
     return RepoFactory.CrossRef_AniDB_Other.GetByAnimeIDAndType(criteriaFactory, this.AnimeID, CrossRefType.MovieDB);
 }
 public void UpdatePlexKodiContracts(ISessionWrapper session = null)
 {
     AnimeGroup grp = RepoFactory.AnimeGroup.GetByID(AnimeGroupID);
     if (grp == null)
         return;
     List<AnimeSeries> series = grp.GetAllSeries();
     PlexContract = Helper.GenerateFromAnimeGroup(grp, JMMUserID, series, session);
 }
 public Dictionary<int, LanguageStat> GetSubtitleLanguageStatsByAnime(ISessionWrapper session, int aID)
 {
     return GetSubtitleLanguageStatsByAnimeResults(session, " = " + aID);
 }
 public List<CrossRef_AniDB_TvDBV2> GetCrossRefTvDBV2(ISessionWrapper session)
 {
     return RepoFactory.CrossRef_AniDB_TvDBV2.GetByAnimeID(session, this.AnimeID);
 }
        public Dictionary<int, AnimeVideoQualityStat> GetEpisodeVideoQualityStatsByAnime(ISessionWrapper session, IReadOnlyCollection<int> animeIds = null)
        {
            Dictionary<int, AnimeVideoQualityStat> dictStats = new Dictionary<int, AnimeVideoQualityStat>();

            using (IDbCommand command = session.Connection.CreateCommand())
            {
                command.CommandText = "SELECT anime.AnimeID, anime.MainTitle, anifile.File_Source, aniep.EpisodeNumber "
                    + "FROM AnimeSeries ser "
                    + "INNER JOIN AniDB_Anime anime on anime.AnimeID = ser.AniDB_ID "
                    + "INNER JOIN AnimeEpisode ep on ep.AnimeSeriesID = ser.AnimeSeriesID "
                    + "INNER JOIN AniDB_Episode aniep on ep.AniDB_EpisodeID = aniep.EpisodeID "
                    + "INNER JOIN CrossRef_File_Episode xref on aniep.EpisodeID = xref.EpisodeID "
                    + "INNER JOIN AniDB_File anifile on anifile.Hash = xref.Hash "
                    + "INNER JOIN CrossRef_Subtitles_AniDB_File subt on subt.FileID = anifile.FileID ";
                // See Note 1
                command.CommandText += "WHERE aniep.EpisodeType = 1 "; // normal episodes only

                if (animeIds != null)
                {
                    if (animeIds.Count == 0)
                    {
                        return dictStats; // No anime IDs means no results. So, no need to perform query
                    }

                    command.CommandText += "AND anime.AnimeID IN (" + String.Join(",", animeIds) + ") ";
                }

                command.CommandText += "GROUP BY anime.AnimeID, anime.MainTitle, anifile.File_Source, aniep.EpisodeNumber "
                    + "ORDER BY anime.AnimeID, anime.MainTitle, anifile.File_Source, aniep.EpisodeNumber ";

                using (IDataReader rdr = command.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        int animeID = Convert.ToInt32(rdr[0]);
                        string mainTitle = rdr[1].ToString().Trim();
                        string vidQual = rdr[2].ToString().Trim();
                        int epNumber = Convert.ToInt32(rdr[3]);
                        AnimeVideoQualityStat stat;

                        if (!dictStats.TryGetValue(animeID, out stat))
                        {
                            stat = new AnimeVideoQualityStat
                                {
                                    AnimeID = animeID,
                                    MainTitle = mainTitle,
                                    VideoQualityEpisodeCount = new Dictionary<string, int>()
                                };
                            dictStats.Add(animeID, stat);
                        }

                        int epCount;

                        stat.VideoQualityEpisodeCount.TryGetValue(vidQual, out epCount);
                        stat.VideoQualityEpisodeCount[vidQual] = epCount + 1;
                    }
                }
            }

            return dictStats;
        }
        public AnimeVideoQualityStat GetEpisodeVideoQualityStatsForAnime(ISessionWrapper session, int aID)
        {
            AnimeVideoQualityStat stat = new AnimeVideoQualityStat();
            stat.VideoQualityEpisodeCount = new Dictionary<string, int>();

            System.Data.IDbCommand command = session.Connection.CreateCommand();
            command.CommandText = "SELECT anime.AnimeID, anime.MainTitle, anifile.File_Source, aniep.EpisodeNumber "
                + "from AnimeSeries ser "
                + "INNER JOIN AniDB_Anime anime on anime.AnimeID = ser.AniDB_ID "
                + "INNER JOIN AnimeEpisode ep on ep.AnimeSeriesID = ser.AnimeSeriesID "
                + "INNER JOIN AniDB_Episode aniep on ep.AniDB_EpisodeID = aniep.EpisodeID "
                + "INNER JOIN CrossRef_File_Episode xref on aniep.EpisodeID = xref.EpisodeID "
                + "INNER JOIN AniDB_File anifile on anifile.Hash = xref.Hash "
                + "INNER JOIN CrossRef_Subtitles_AniDB_File subt on subt.FileID = anifile.FileID ";
            // See Note 1
            command.CommandText += "WHERE aniep.EpisodeType = 1 " // normal episodes only
                + "AND anime.AnimeID =  " + aID.ToString()
                + " GROUP BY anime.AnimeID, anime.MainTitle, anifile.File_Source, aniep.EpisodeNumber ";

            using (IDataReader rdr = command.ExecuteReader())
            {
                while (rdr.Read())
                {
                    stat.AnimeID = int.Parse(rdr[0].ToString());
                    stat.MainTitle = rdr[1].ToString().Trim();

                    string vidQual = rdr[2].ToString().Trim();
                    int epNumber = int.Parse(rdr[3].ToString());

                    if (!stat.VideoQualityEpisodeCount.ContainsKey(vidQual))
                        stat.VideoQualityEpisodeCount[vidQual] = 1;
                    else
                        stat.VideoQualityEpisodeCount[vidQual]++;
                }
            }

            return stat;
        }
        public HashSet<string> GetAllVideoQualityForAnime(ISessionWrapper session, int animeID)
        {
            HashSet<string> vidQuals = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);

            System.Data.IDbCommand command = session.Connection.CreateCommand();
            command.CommandText = "SELECT anifile.File_Source "
               + "FROM AnimeSeries ser "
               + "INNER JOIN AniDB_Anime anime on anime.AnimeID = ser.AniDB_ID "
               + "INNER JOIN AnimeEpisode ep on ep.AnimeSeriesID = ser.AnimeSeriesID "
               + "INNER JOIN AniDB_Episode aniep on ep.AniDB_EpisodeID = aniep.EpisodeID "
               + "INNER JOIN CrossRef_File_Episode xref on aniep.EpisodeID = xref.EpisodeID "
               + "INNER JOIN AniDB_File anifile on anifile.Hash = xref.Hash "
               + "INNER JOIN CrossRef_Subtitles_AniDB_File subt on subt.FileID = anifile.FileID ";
            // See Note 1
            command.CommandText += "where anime.AnimeID = " + animeID.ToString()
                + " GROUP BY anifile.File_Source ";

            using (IDataReader rdr = command.ExecuteReader())
            {
                while (rdr.Read())
                {
                    string vidQual = rdr[0].ToString().Trim();
                    if (!vidQuals.Contains(vidQual))
                    {
                        vidQuals.Add(vidQual);
                    }
                }
            }
            return vidQuals;
        }
        /// <summary>
        /// Gets All video quality by group.
        /// </summary>
        /// <param name="session">The NHibernate session.</param>
        /// <param name="animeGroupIds">The optional list of group IDs to limit the results to.
        /// If <c>null</c> is specified, then results for ALL groups will be returned.</param>
        /// <returns>A <see cref="ILookup{TKey,TElement}"/> containing all video quality grouped by anime group ID.</returns>
        public ILookup<int, string> GetAllVideoQualityByGroup(ISessionWrapper session, IReadOnlyCollection<int> animeGroupIds = null)
        {
            if (session == null)
                throw new ArgumentNullException(nameof(session));

            if (animeGroupIds != null && animeGroupIds.Count == 0)
            {
                return EmptyLookup<int, string>.Instance;
            }

            string query = @"
                SELECT DISTINCT ag.AnimeGroupID, anifile.File_Source
                    FROM AnimeGroup ag
                        INNER JOIN AnimeSeries ser
                            ON ser.AnimeGroupID = ag.AnimeGroupID
                        INNER JOIN AnimeEpisode ep
                            ON ep.AnimeSeriesID = ser.AnimeSeriesID
                        INNER JOIN AniDB_Episode aniep
                            ON ep.AniDB_EpisodeID = aniep.EpisodeID
                        INNER JOIN CrossRef_File_Episode xref
                            ON aniep.EpisodeID = xref.EpisodeID
                        INNER JOIN AniDB_File anifile
                            ON anifile.Hash = xref.Hash
                        INNER JOIN CrossRef_Subtitles_AniDB_File subt
                            ON subt.FileID = anifile.FileID";

            if (animeGroupIds != null)
            {
                query += @"
                    WHERE ag.AnimeGroupID IN (" + String.Join(",", animeGroupIds) + ")";
            }

            var results = session.CreateSQLQuery(query)
                .AddScalar("AnimeGroupID", NHibernateUtil.Int32)
                .AddScalar("File_Source", NHibernateUtil.String)
                .List<object[]>()
                .ToLookup(r => (int)r[0], r => (string)r[1]);

            return results;
        }
        public Dictionary<int, HashSet<string>> GetAllVideoQualityByAnime(ISessionWrapper session, ICollection<int> animeIDs)
        {
            if (session == null)
                throw new ArgumentNullException(nameof(session));
            if (animeIDs == null)
                throw new ArgumentNullException(nameof(animeIDs));

            if (animeIDs.Count == 0)
            {
                return new Dictionary<int, HashSet<string>>();
            }

            using (IDbCommand command = session.Connection.CreateCommand())
            {
                command.CommandText = @"SELECT anime.AnimeID, anifile.File_Source
                    FROM AnimeSeries ser
                    INNER JOIN AniDB_Anime anime on anime.AnimeID = ser.AniDB_ID
                    INNER JOIN AnimeEpisode ep on ep.AnimeSeriesID = ser.AnimeSeriesID
                    INNER JOIN AniDB_Episode aniep on ep.AniDB_EpisodeID = aniep.EpisodeID
                    INNER JOIN CrossRef_File_Episode xref on aniep.EpisodeID = xref.EpisodeID
                    INNER JOIN AniDB_File anifile on anifile.Hash = xref.Hash
                    INNER JOIN CrossRef_Subtitles_AniDB_File subt on subt.FileID = anifile.FileID
                    WHERE anime.AnimeID IN (" + String.Join(",", animeIDs) + @")
                    GROUP BY anime.AnimeID, anifile.File_Source ";

                var allVidQualPerAnime = new Dictionary<int, HashSet<string>>();

                using (IDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        int animeId = Convert.ToInt32(reader[0]);
                        string vidQual = reader[1].ToString().Trim();
                        HashSet<string> vidQualSet;

                        if (!allVidQualPerAnime.TryGetValue(animeId, out vidQualSet))
                        {
                            vidQualSet = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
                            allVidQualPerAnime.Add(animeId, vidQualSet);
                        }

                        vidQualSet.Add(vidQual);
                    }
                }

                return allVidQualPerAnime;
            }
        }
        public ImageDetails GetDefaultFanartDetailsNoBlanks(ISessionWrapper session)
        {
            Random fanartRandom = new Random();

            ImageDetails details = null;
            if (GetDefaultFanart(session) == null)
            {
                List<Contract_AniDB_Anime_DefaultImage> fanarts = Contract.AniDBAnime.Fanarts;
                if (fanarts == null || fanarts.Count == 0) return null;
                Contract_AniDB_Anime_DefaultImage art = fanarts[fanartRandom.Next(0, fanarts.Count)];
                details = new ImageDetails()
                {
                    ImageID = art.AniDB_Anime_DefaultImageID,
                    ImageType = (JMMImageType)art.ImageType
                };
                return details;
            }
            else
            {
                // TODO Move this to contract as well
                AniDB_Anime_DefaultImage fanart = GetDefaultFanart();
                ImageEntityType imageType = (ImageEntityType) fanart.ImageParentType;

                switch (imageType)
                {
                    case ImageEntityType.TvDB_FanArt:

                        TvDB_ImageFanart tvFanart = RepoFactory.TvDB_ImageFanart.GetByID(session, fanart.ImageParentID);
                        if (tvFanart != null)
                            details = new ImageDetails()
                            {
                                ImageType = JMMImageType.TvDB_FanArt,
                                ImageID = tvFanart.TvDB_ImageFanartID
                            };

                        return details;

                    case ImageEntityType.Trakt_Fanart:

                        Trakt_ImageFanart traktFanart = RepoFactory.Trakt_ImageFanart.GetByID(session, fanart.ImageParentID);
                        if (traktFanart != null)
                            details = new ImageDetails()
                            {
                                ImageType = JMMImageType.Trakt_Fanart,
                                ImageID = traktFanart.Trakt_ImageFanartID
                            };

                        return details;

                    case ImageEntityType.MovieDB_FanArt:

                        MovieDB_Fanart movieFanart = RepoFactory.MovieDB_Fanart.GetByID(session, fanart.ImageParentID);
                        if (movieFanart != null)
                            details = new ImageDetails()
                            {
                                ImageType = JMMImageType.MovieDB_FanArt,
                                ImageID = movieFanart.MovieDB_FanartID
                            };

                        return details;
                }
            }

            return null;
        }
        public Dictionary<int, LanguageStat> GetSubtitleLanguageStatsByAnime(ISessionWrapper session, ICollection<int> aIDs)
        {
            if (aIDs.Count == 0)
            {
                return new Dictionary<int, LanguageStat>();
            }

            string predicate = " IN (" + String.Join(",", aIDs) + ") ";

            return GetSubtitleLanguageStatsByAnimeResults(session, predicate);
        }
 public AniDB_Anime_DefaultImage GetDefaultFanart(ISessionWrapper factory)
 {
     return RepoFactory.AniDB_Anime_DefaultImage.GetByAnimeIDAndImagezSizeType(factory, this.AnimeID, (int) ImageSizeType.Fanart);
 }
        private Dictionary<int, LanguageStat> GetAudioLanguageStatsByAnimeResults(ISessionWrapper session, string animeIdPredicate)
        {
            Dictionary<int, LanguageStat> dictStats = new Dictionary<int, LanguageStat>();
            string query = GetAudioLanguageStatsByAnimeSQL(animeIdPredicate);

            var rows = session.CreateSQLQuery(query)
                .AddScalar("AnimeID", NHibernateUtil.Int32)
                .AddScalar("MainTitle", NHibernateUtil.String)
                .AddScalar("LanguageName", NHibernateUtil.String)
                .List<object[]>();

            foreach (object[] cols in rows)
            {
                int animeID = Convert.ToInt32(cols[0]);
                string mainTitle = cols[1].ToString().Trim();
                string lanName = cols[2].ToString().Trim();
                LanguageStat stat = null;

                if (!dictStats.TryGetValue(animeID, out stat))
                {
                    stat = new LanguageStat
                    {
                        AnimeID = animeID,
                        MainTitle = mainTitle,
                        LanguageNames = new List<string>()
                    };
                    dictStats.Add(animeID, stat);
                }

                stat.LanguageNames.Add(lanName);
            }

            return dictStats;
        }
 public StudentDownloadRepository(ISessionWrapper session)
 {
     _session = session;
 }
        private Dictionary<int, LanguageStat> GetSubtitleLanguageStatsByAnimeResults(ISessionWrapper session, string animeIdPredicate)
        {
            Dictionary<int, LanguageStat> dictStats = new Dictionary<int, LanguageStat>();
            string query = "SELECT DISTINCT anime.AnimeID, anime.MainTitle, lan.LanguageName "
                + "FROM AnimeSeries ser  "
                + "INNER JOIN AniDB_Anime anime on anime.AnimeID = ser.AniDB_ID "
                + "INNER JOIN AnimeEpisode ep on ep.AnimeSeriesID = ser.AnimeSeriesID "
                + "INNER JOIN AniDB_Episode aniep on ep.AniDB_EpisodeID = aniep.EpisodeID "
                + "INNER JOIN CrossRef_File_Episode xref on aniep.EpisodeID = xref.EpisodeID "
                + "INNER JOIN AniDB_File anifile on anifile.Hash = xref.Hash "
                + "INNER JOIN CrossRef_Subtitles_AniDB_File subt on subt.FileID = anifile.FileID "
                + "INNER JOIN Language lan on subt.LanguageID = lan.LanguageID "
                + "WHERE anime.AnimeID " + animeIdPredicate;

            var rows = session.CreateSQLQuery(query)
                .AddScalar("AnimeID", NHibernateUtil.Int32)
                .AddScalar("MainTitle", NHibernateUtil.String)
                .AddScalar("LanguageName", NHibernateUtil.String)
                .List<object[]>();

            foreach (object[] cols in rows)
            {
                int animeID = Convert.ToInt32(cols[0]);
                string mainTitle = cols[1].ToString().Trim();
                string lanName = cols[2].ToString().Trim();
                LanguageStat stat = null;

                if (!dictStats.TryGetValue(animeID, out stat))
                {
                    stat = new LanguageStat
                    {
                        AnimeID = animeID,
                        MainTitle = mainTitle,
                        LanguageNames = new List<string>()
                    };
                    dictStats.Add(animeID, stat);
                }

                stat.LanguageNames.Add(lanName);
            }

            return dictStats;
        }
        public Contract_AniDB_Anime_DefaultImage ToContract(ISessionWrapper session)
        {
            JMMImageType imgType = (JMMImageType)ImageParentType;
            IImageEntity parentImage = null;

            switch (imgType)
            {
                case JMMImageType.TvDB_Banner:
                    parentImage = RepoFactory.TvDB_ImageWideBanner.GetByID(session, ImageParentID);
                    break;
                case JMMImageType.TvDB_Cover:
                    parentImage = RepoFactory.TvDB_ImagePoster.GetByID(session, ImageParentID);
                    break;
                case JMMImageType.TvDB_FanArt:
                    parentImage = RepoFactory.TvDB_ImageFanart.GetByID(session, ImageParentID);
                    break;
                case JMMImageType.MovieDB_Poster:
                    parentImage = RepoFactory.MovieDB_Poster.GetByID(session, ImageParentID);
                    break;
                case JMMImageType.MovieDB_FanArt:
                    parentImage = RepoFactory.MovieDB_Fanart.GetByID(session, ImageParentID);
                    break;
                case JMMImageType.Trakt_Fanart:
                    parentImage = RepoFactory.Trakt_ImageFanart.GetByID(session, ImageParentID);
                    break;
                case JMMImageType.Trakt_Poster:
                    parentImage = RepoFactory.Trakt_ImagePoster.GetByID(session, ImageParentID);
                    break;
            }

            return ToContract(parentImage);
        }
 public TitleRepository(ISessionWrapper session)
 {
     _session = session;
 }
 public TvDB_Series GetTvDBSeries(ISessionWrapper session)
 {
     return RepoFactory.TvDB_Series.GetByTvDBID(session, TvDBID);
 }
 public StudentErrorRepository(ISessionWrapper session)
 {
     _session = session;
 }