public void Delete(int id)
        {
            AnimeEpisode cr = GetByID(id);

            if (cr != null)
            {
                // delete user records
                AnimeEpisode_UserRepository repUsers = new AnimeEpisode_UserRepository();
                foreach (AnimeEpisode_User epuser in repUsers.GetByEpisodeID(id))
                {
                    repUsers.Delete(epuser.AnimeEpisode_UserID);
                }
            }

            using (var session = JMMService.SessionFactory.OpenSession())
            {
                // populate the database
                using (var transaction = session.BeginTransaction())
                {
                    if (cr != null)
                    {
                        Cache.Remove(cr);
                        session.Delete(cr);
                        transaction.Commit();
                    }
                }
            }
        }
        public static void InitCache()
        {
            string t = "AnimeEpisodes_User";

            ServerState.Instance.CurrentSetupStatus = string.Format(JMMServer.Properties.Resources.Database_Cache, t, string.Empty);
            AnimeEpisode_UserRepository repo = new AnimeEpisode_UserRepository();

            Cache         = new PocoCache <int, AnimeEpisode_User>(repo.InternalGetAll(), a => a.AnimeEpisode_UserID);
            Series        = Cache.CreateIndex(a => a.AnimeSeriesID);
            UsersEpisodes = Cache.CreateIndex(a => a.JMMUserID, a => a.AnimeEpisodeID);
            Users         = Cache.CreateIndex(a => a.JMMUserID);
            Episodes      = Cache.CreateIndex(a => a.AnimeEpisodeID);
            UsersSeries   = Cache.CreateIndex(a => a.JMMUserID, a => a.AnimeSeriesID);
            int cnt = 0;
            List <AnimeEpisode_User> sers =
                Cache.Values.Where(a => a.ContractVersion < AnimeEpisode_User.CONTRACT_VERSION || a.AnimeEpisode_UserID == 0).ToList();
            int max = sers.Count;

            foreach (AnimeEpisode_User g in sers)
            {
                repo.Save(g);
                cnt++;
                if (cnt % 10 == 0)
                {
                    ServerState.Instance.CurrentSetupStatus = string.Format(JMMServer.Properties.Resources.Database_Cache, t,
                                                                            " DbRegen - " + cnt + "/" + max);
                }
            }
            ServerState.Instance.CurrentSetupStatus = string.Format(JMMServer.Properties.Resources.Database_Cache, t,
                                                                    " DbRegen - " + max + "/" + max);
        }
Esempio n. 3
0
        public string DeleteUser(int userID)
        {
            JMMUserRepository repUsers = new JMMUserRepository();

            try
            {
                JMMUser jmmUser = repUsers.GetByID(userID);
                if (jmmUser == null) return "User not found";

                // make sure that at least one user is an admin
                if (jmmUser.IsAdmin == 1)
                {
                    bool adminExists = false;
                    List<JMMUser> users = repUsers.GetAll();
                    foreach (JMMUser userOld in users)
                    {
                        if (userOld.IsAdmin == 1)
                        {
                            if (userOld.JMMUserID != jmmUser.JMMUserID) adminExists = true;
                        }
                    }

                    if (!adminExists) return "At least one user must be an administrator";
                }

                repUsers.Delete(userID);

                // delete all user records
                AnimeSeries_UserRepository repSeries = new AnimeSeries_UserRepository();
                foreach (AnimeSeries_User ser in repSeries.GetByUserID(userID))
                    repSeries.Delete(ser.AnimeSeries_UserID);

                AnimeGroup_UserRepository repGroup = new AnimeGroup_UserRepository();
                foreach (AnimeGroup_User grp in repGroup.GetByUserID(userID))
                    repGroup.Delete(grp.AnimeGroup_UserID);

                AnimeEpisode_UserRepository repEpisode = new AnimeEpisode_UserRepository();
                foreach (AnimeEpisode_User ep in repEpisode.GetByUserID(userID))
                    repEpisode.Delete(ep.AnimeEpisode_UserID);

                VideoLocal_UserRepository repVids = new VideoLocal_UserRepository();
                foreach (VideoLocal_User vid in repVids.GetByUserID(userID))
                    repVids.Delete(vid.VideoLocal_UserID);
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return ex.Message;
            }

            return "";
        }
Esempio n. 4
0
        public void IncrementEpisodeStats(int animeEpisodeID, int userID, int statCountType)
        {
            try
            {
                AnimeEpisodeRepository repEpisodes = new AnimeEpisodeRepository();
                AnimeEpisode ep = repEpisodes.GetByID(animeEpisodeID);
                if (ep == null) return;

                AnimeEpisode_UserRepository repEpisodeUsers = new AnimeEpisode_UserRepository();
                AnimeEpisode_User epUserRecord = ep.GetUserRecord(userID);

                if (epUserRecord == null)
                {
                    epUserRecord = new AnimeEpisode_User();
                    epUserRecord.PlayedCount = 0;
                    epUserRecord.StoppedCount = 0;
                    epUserRecord.WatchedCount = 0;
                }
                epUserRecord.AnimeEpisodeID = ep.AnimeEpisodeID;
                epUserRecord.AnimeSeriesID = ep.AnimeSeriesID;
                epUserRecord.JMMUserID = userID;
                //epUserRecord.WatchedDate = DateTime.Now;

                switch ((StatCountType)statCountType)
                {
                    case StatCountType.Played: epUserRecord.PlayedCount++; break;
                    case StatCountType.Stopped: epUserRecord.StoppedCount++; break;
                    case StatCountType.Watched: epUserRecord.WatchedCount++; break;
                }

                repEpisodeUsers.Save(epUserRecord);

                AnimeSeries ser = ep.GetAnimeSeries();
                if (ser == null) return;

                AnimeSeries_UserRepository repSeriesUser = new AnimeSeries_UserRepository();
                AnimeSeries_User userRecord = ser.GetUserRecord(userID);
                if (userRecord == null)
                    userRecord = new AnimeSeries_User(userID, ser.AnimeSeriesID);

                switch ((StatCountType)statCountType)
                {
                    case StatCountType.Played: userRecord.PlayedCount++; break;
                    case StatCountType.Stopped: userRecord.StoppedCount++; break;
                    case StatCountType.Watched: userRecord.WatchedCount++; break;
                }

                repSeriesUser.Save(userRecord);
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }
        }
Esempio n. 5
0
        public Contract_AnimeEpisode GetNextUnwatchedEpisode(ISession session, int animeSeriesID, int userID)
        {
            try
            {
                AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
                AnimeSeriesRepository repAnimeSer = new AnimeSeriesRepository();
                AnimeEpisode_UserRepository repEpUser = new AnimeEpisode_UserRepository();

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

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

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

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

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

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

                            Contract_AnimeEpisode epContract = ep.ToContract(anidbep, new List<VideoLocal>(), userRecord, series.GetUserRecord(session, userID));
                            candidateEps.Add(epContract);
                        }
                    }
                }

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

                // sort by episode type and number to find the next episode
                List<SortPropOrFieldAndDirection> sortCriteria = new List<SortPropOrFieldAndDirection>();
                sortCriteria.Add(new SortPropOrFieldAndDirection("EpisodeType", false, SortType.eInteger));
                sortCriteria.Add(new SortPropOrFieldAndDirection("EpisodeNumber", false, SortType.eInteger));
                candidateEps = Sorting.MultiSort<Contract_AnimeEpisode>(candidateEps, sortCriteria);

                // this will generate a lot of queries when the user doesn have files
                // for these episodes
                foreach (Contract_AnimeEpisode canEp in candidateEps)
                {
                    // now refresh from the database to get file count
                    AnimeEpisode epFresh = repEps.GetByID(canEp.AnimeEpisodeID);
                    if (epFresh.GetVideoLocals().Count > 0)
                        return epFresh.ToContract(true, userID, series.GetUserRecord(session, userID));
                }

                return null;
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return null;
            }
        }
Esempio n. 6
0
        public Contract_AnimeEpisode GetLastWatchedEpisodeForSeries(int animeSeriesID, int jmmuserID)
        {
            try
            {
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
                    AnimeEpisode_UserRepository repEpUser = new AnimeEpisode_UserRepository();
                    JMMUserRepository repUsers = new JMMUserRepository();

                    JMMUser user = repUsers.GetByID(session, jmmuserID);
                    if (user == null) return null;

                    List<AnimeEpisode_User> userRecords = repEpUser.GetLastWatchedEpisodeForSeries(session, animeSeriesID, jmmuserID);
                    if (userRecords == null || userRecords.Count == 0) return null;

                    AnimeEpisode ep = repEps.GetByID(session, userRecords[0].AnimeEpisodeID);
                    if (ep == null) return null;

                    return ep.ToContract(session, jmmuserID);
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }

            return null;
        }
Esempio n. 7
0
        public List<Contract_AnimeEpisode> GetEpisodesRecentlyWatched(int maxRecords, int jmmuserID)
        {
            List<Contract_AnimeEpisode> retEps = new List<Contract_AnimeEpisode>();
            try
            {
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
                    AnimeEpisode_UserRepository repEpUser = new AnimeEpisode_UserRepository();
                    JMMUserRepository repUsers = new JMMUserRepository();

                    JMMUser user = repUsers.GetByID(session, jmmuserID);
                    if (user == null) return retEps;

                    // get a list of series that is applicable
                    List<AnimeEpisode_User> allEpUserRecs = repEpUser.GetMostRecentlyWatched(session, jmmuserID);
                    foreach (AnimeEpisode_User userRecord in allEpUserRecs)
                    {
                        AnimeEpisode ep = repEps.GetByID(session, userRecord.AnimeEpisodeID);
                        if (ep == null) continue;

                        Contract_AnimeEpisode epContract = ep.ToContract(session, jmmuserID);
                        if (epContract != null)
                        {
                            retEps.Add(epContract);

                            // Lets only return the specified amount
                            if (retEps.Count == maxRecords) return retEps;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }

            return retEps;
        }
Esempio n. 8
0
        public List<Contract_AnimeEpisode> GetEpisodesRecentlyAddedSummary(int maxRecords, int jmmuserID)
        {
            List<Contract_AnimeEpisode> retEps = new List<Contract_AnimeEpisode>();
            try
            {
                AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
                AnimeEpisode_UserRepository repEpUser = new AnimeEpisode_UserRepository();
                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                JMMUserRepository repUsers = new JMMUserRepository();
                VideoLocalRepository repVids = new VideoLocalRepository();

                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    JMMUser user = repUsers.GetByID(session, jmmuserID);
                    if (user == null) return retEps;

                    DateTime start = DateTime.Now;

                    string sql = "Select ae.AnimeSeriesID, max(vl.DateTimeCreated) as MaxDate " +
                            "From VideoLocal vl " +
                            "INNER JOIN CrossRef_File_Episode xref ON vl.Hash = xref.Hash " +
                            "INNER JOIN AnimeEpisode ae ON ae.AniDB_EpisodeID = xref.EpisodeID " +
                            "GROUP BY ae.AnimeSeriesID " +
                            "ORDER BY MaxDate desc ";
                    ArrayList results = DatabaseHelper.GetData(sql);

                    TimeSpan ts2 = DateTime.Now - start; logger.Info("GetEpisodesRecentlyAddedSummary:RawData in {0} ms", ts2.TotalMilliseconds); start = DateTime.Now;

                    int numEps = 0;
                    foreach (object[] res in results)
                    {
                        int animeSeriesID = int.Parse(res[0].ToString());

                        AnimeSeries ser = repSeries.GetByID(session, animeSeriesID);
                        if (ser == null) continue;

                        if (!user.AllowedSeries(ser)) continue;

                        List<VideoLocal> vids = repVids.GetMostRecentlyAddedForAnime(session, 1, ser.AniDB_ID);
                        if (vids.Count == 0) continue;

                        List<AnimeEpisode> eps = vids[0].GetAnimeEpisodes(session);
                        if (eps.Count == 0) continue;

                        Contract_AnimeEpisode epContract = eps[0].ToContract(session, jmmuserID);
                        if (epContract != null)
                        {
                            retEps.Add(epContract);
                            numEps++;

                            // Lets only return the specified amount
                            if (retEps.Count == maxRecords)
                            {
                                ts2 = DateTime.Now - start; logger.Info("GetEpisodesRecentlyAddedSummary:Episodes in {0} ms", ts2.TotalMilliseconds); start = DateTime.Now;
                                return retEps;
                            }
                        }

                    }
                    ts2 = DateTime.Now - start; logger.Info("GetEpisodesRecentlyAddedSummary:Episodes in {0} ms", ts2.TotalMilliseconds); start = DateTime.Now;
                }

            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }

            return retEps;
        }
Esempio n. 9
0
		public void SaveWatchedStatus(bool watched, int userID, DateTime? watchedDate, bool updateWatchedDate)
		{
			AnimeEpisode_UserRepository repEpisodeUsers = new AnimeEpisode_UserRepository();
			AnimeEpisode_User epUserRecord = this.GetUserRecord(userID);

			if (watched)
			{
				// lets check if an update is actually required
				if (epUserRecord != null)
				{
					if (epUserRecord.WatchedDate.HasValue && watchedDate.HasValue &&
						epUserRecord.WatchedDate.Value.Equals(watchedDate.Value))
					{
						// this will happen when we are adding a new file for an episode where we already had another file
						// and the file/episode was watched already
						return;
					}
				}

				if (epUserRecord == null)
				{
					epUserRecord = new AnimeEpisode_User();
					epUserRecord.PlayedCount = 0;
					epUserRecord.StoppedCount = 0;
					epUserRecord.WatchedCount = 0;
				}
				epUserRecord.AnimeEpisodeID = this.AnimeEpisodeID;
				epUserRecord.AnimeSeriesID = this.AnimeSeriesID;
				epUserRecord.JMMUserID = userID;
				epUserRecord.WatchedCount++;

				if (watchedDate.HasValue)
				{
					if (updateWatchedDate)
						epUserRecord.WatchedDate = watchedDate.Value;
				}

				if (!epUserRecord.WatchedDate.HasValue) epUserRecord.WatchedDate = DateTime.Now;

				repEpisodeUsers.Save(epUserRecord);
			}
			else
			{
				if (epUserRecord != null)
					repEpisodeUsers.Delete(epUserRecord.AnimeEpisode_UserID);
			}
		}
Esempio n. 10
0
        public List<Contract_AnimeEpisode> GetEpisodesForSeries(int animeSeriesID, int userID)
        {
            List<Contract_AnimeEpisode> eps = new List<Contract_AnimeEpisode>();
            try
            {

                DateTime start = DateTime.Now;
                AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
                AnimeEpisode_UserRepository repEpUsers = new AnimeEpisode_UserRepository();
                AnimeSeriesRepository repAnimeSer = new AnimeSeriesRepository();
                VideoLocalRepository repVids = new VideoLocalRepository();
                CrossRef_File_EpisodeRepository repCrossRefs = new CrossRef_File_EpisodeRepository();

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

                List<AnimeEpisode> epList = repEps.GetBySeriesID(animeSeriesID);
                List<AnimeEpisode_User> userRecordList = repEpUsers.GetByUserIDAndSeriesID(userID, animeSeriesID);
                Dictionary<int, AnimeEpisode_User> dictUserRecords = new Dictionary<int, AnimeEpisode_User>();
                foreach (AnimeEpisode_User epuser in userRecordList)
                    dictUserRecords[epuser.AnimeEpisodeID] = epuser;

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

                // get all the video local records and cross refs
                List<VideoLocal> vids = repVids.GetByAniDBAnimeID(series.AniDB_ID);
                List<CrossRef_File_Episode> crossRefs = repCrossRefs.GetByAnimeID(series.AniDB_ID);

                TimeSpan ts = DateTime.Now - start;
                logger.Info("GetEpisodesForSeries: {0} (Database) in {1} ms", series.GetAnime().MainTitle, ts.TotalMilliseconds);

                start = DateTime.Now;
                foreach (AnimeEpisode ep in epList)
                {
                    if (dictAniEps.ContainsKey(ep.AniDB_EpisodeID))
                    {
                        List<VideoLocal> epVids = new List<VideoLocal>();
                        foreach (CrossRef_File_Episode xref in crossRefs)
                        {
                            if (xref.EpisodeID == dictAniEps[ep.AniDB_EpisodeID].EpisodeID)
                            {
                                // don't add the same file twice, this will occur when
                                // one file appears over more than one episodes
                                Dictionary<string, string> addedFiles = new Dictionary<string, string>();
                                foreach (VideoLocal vl in vids)
                                {
                                    if (string.Equals(xref.Hash, vl.Hash, StringComparison.InvariantCultureIgnoreCase))
                                    {
                                        if (!addedFiles.ContainsKey(xref.Hash.Trim().ToUpper()))
                                        {
                                            addedFiles[xref.Hash.Trim().ToUpper()] = xref.Hash.Trim().ToUpper();
                                            epVids.Add(vl);
                                        }
                                    }
                                }
                            }
                        }

                        AnimeEpisode_User epuser = null;
                        if (dictUserRecords.ContainsKey(ep.AnimeEpisodeID))
                            epuser = dictUserRecords[ep.AnimeEpisodeID];

                        eps.Add(ep.ToContract(dictAniEps[ep.AniDB_EpisodeID], epVids, epuser, null));
                    }
                }

                ts = DateTime.Now - start;
                logger.Info("GetEpisodesForSeries: {0} (Contracts) in {1} ms", series.GetAnime().MainTitle, ts.TotalMilliseconds);
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }

            return eps;
        }
		public MetroContract_Anime_Detail GetAnimeDetail(int animeID, int jmmuserID, int maxEpisodeRecords)
		{
			try
			{
				using (var session = JMMService.SessionFactory.OpenSession())
				{
					AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
					AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();

					AniDB_Anime anime = repAnime.GetByAnimeID(session, animeID);
					if (anime == null) return null;

					AnimeSeries ser = repSeries.GetByAnimeID(session, animeID);

					MetroContract_Anime_Detail ret = new MetroContract_Anime_Detail();
					ret.AnimeID = anime.AnimeID;

					if (ser != null)
						ret.AnimeName = ser.GetSeriesName(session);
					else
						ret.AnimeName = anime.MainTitle;

					if (ser != null)
						ret.AnimeSeriesID = ser.AnimeSeriesID;
					else
						ret.AnimeSeriesID = 0;

					ret.BeginYear = anime.BeginYear;
					ret.EndYear = anime.EndYear;

					ImageDetails imgDet = anime.GetDefaultPosterDetailsNoBlanks(session);
					ret.PosterImageType = (int)imgDet.ImageType;
					ret.PosterImageID = imgDet.ImageID;

					ImageDetails imgDetFan = anime.GetDefaultFanartDetailsNoBlanks(session);
					if (imgDetFan != null)
					{
						ret.FanartImageType = (int)imgDetFan.ImageType;
						ret.FanartImageID = imgDetFan.ImageID;
					}
					else
					{
						ret.FanartImageType = 0;
						ret.FanartImageID = 0;
					}

					ret.AnimeType = anime.AnimeTypeDescription;
					ret.Description = anime.Description;
					ret.EpisodeCountNormal = anime.EpisodeCountNormal;
					ret.EpisodeCountSpecial = anime.EpisodeCountSpecial;


					ret.AirDate = anime.AirDate;
					ret.EndDate = anime.EndDate;

					ret.OverallRating = anime.AniDBRating;
					ret.TotalVotes = anime.AniDBTotalVotes;
					ret.AllTags = anime.TagsString;

					ret.NextEpisodesToWatch = new List<MetroContract_Anime_Episode>();
					if (ser != null)
					{
						AnimeSeries_User serUserRec = ser.GetUserRecord(session, jmmuserID);
						if (ser != null)
							ret.UnwatchedEpisodeCount = serUserRec.UnwatchedEpisodeCount;
						else
							ret.UnwatchedEpisodeCount = 0;

						AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
						AnimeEpisode_UserRepository repEpUser = new AnimeEpisode_UserRepository();

						List<AnimeEpisode> epList = new List<AnimeEpisode>();
						Dictionary<int, AnimeEpisode_User> dictEpUsers = new Dictionary<int, AnimeEpisode_User>();
						foreach (AnimeEpisode_User userRecord in repEpUser.GetByUserIDAndSeriesID(session, jmmuserID, ser.AnimeSeriesID))
							dictEpUsers[userRecord.AnimeEpisodeID] = userRecord;

						foreach (AnimeEpisode animeep in repEps.GetBySeriesID(session, ser.AnimeSeriesID))
						{
							if (!dictEpUsers.ContainsKey(animeep.AnimeEpisodeID))
							{
								epList.Add(animeep);
								continue;
							}

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

						AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository();
						List<AniDB_Episode> aniEpList = repAniEps.GetByAnimeID(session, ser.AniDB_ID);
						Dictionary<int, AniDB_Episode> dictAniEps = new Dictionary<int, AniDB_Episode>();
						foreach (AniDB_Episode aniep in aniEpList)
							dictAniEps[aniep.EpisodeID] = aniep;

						List<Contract_AnimeEpisode> candidateEps = new List<Contract_AnimeEpisode>();

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

									Contract_AnimeEpisode epContract = ep.ToContract(anidbep, new List<VideoLocal>(), userRecord, serUserRec);
									candidateEps.Add(epContract);
								}
							}
						}

						if (candidateEps.Count > 0)
						{
                            TvDBSummary tvSummary = new TvDBSummary();
                            tvSummary.Populate(ser.AniDB_ID);

							// sort by episode type and number to find the next episode
							List<SortPropOrFieldAndDirection> sortCriteria = new List<SortPropOrFieldAndDirection>();
							sortCriteria.Add(new SortPropOrFieldAndDirection("EpisodeType", false, SortType.eInteger));
							sortCriteria.Add(new SortPropOrFieldAndDirection("EpisodeNumber", false, SortType.eInteger));
							candidateEps = Sorting.MultiSort<Contract_AnimeEpisode>(candidateEps, sortCriteria);

							// this will generate a lot of queries when the user doesn have files
							// for these episodes
							int cnt = 0;
							foreach (Contract_AnimeEpisode canEp in candidateEps)
							{

								if (dictAniEps.ContainsKey(canEp.AniDB_EpisodeID))
								{
									AniDB_Episode anidbep = dictAniEps[canEp.AniDB_EpisodeID];

									AnimeEpisode_User userEpRecord = null;
									if (dictEpUsers.ContainsKey(canEp.AnimeEpisodeID))
										userEpRecord = dictEpUsers[canEp.AnimeEpisodeID];

									// now refresh from the database to get file count
									AnimeEpisode epFresh = repEps.GetByID(session, canEp.AnimeEpisodeID);

									int fileCount = epFresh.GetVideoLocals(session).Count;
									if (fileCount > 0)
									{
										MetroContract_Anime_Episode contract = new MetroContract_Anime_Episode();
										contract.AnimeEpisodeID = epFresh.AnimeEpisodeID;
										contract.LocalFileCount = fileCount;

										if (userEpRecord == null)
											contract.IsWatched = false;
										else
											contract.IsWatched = userEpRecord.WatchedCount > 0;

										// anidb
										contract.EpisodeNumber = anidbep.EpisodeNumber;
										contract.EpisodeName = anidbep.RomajiName;
										if (!string.IsNullOrEmpty(anidbep.EnglishName))
											contract.EpisodeName = anidbep.EnglishName;

										contract.EpisodeType = anidbep.EpisodeType;
										contract.LengthSeconds = anidbep.LengthSeconds;
										contract.AirDate = anidbep.AirDateFormatted;

										// tvdb
                                        SetTvDBInfo(tvSummary, anidbep, ref contract);
										

										ret.NextEpisodesToWatch.Add(contract);
										cnt++;
									}
								}
								if (cnt == maxEpisodeRecords) break;
							}
						}
					}

					return ret;
				}

			}
			catch (Exception ex)
			{
				logger.ErrorException(ex.ToString(), ex);
				return null;
			}
		}
		public List<MetroContract_Anime_Summary> GetAnimeWithNewEpisodes(int maxRecords, int jmmuserID)
		{
			List<MetroContract_Anime_Summary> retAnime = new List<MetroContract_Anime_Summary>();
			try
			{
				using (var session = JMMService.SessionFactory.OpenSession())
				{
					AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
					AnimeEpisode_UserRepository repEpUser = new AnimeEpisode_UserRepository();
					AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
					JMMUserRepository repUsers = new JMMUserRepository();
					VideoLocalRepository repVids = new VideoLocalRepository();

					JMMUser user = repUsers.GetByID(session, jmmuserID);
					if (user == null) return retAnime;

					string sql = "Select ae.AnimeSeriesID, max(vl.DateTimeCreated) as MaxDate " +
							"From VideoLocal vl " +
							"INNER JOIN CrossRef_File_Episode xref ON vl.Hash = xref.Hash " +
							"INNER JOIN AnimeEpisode ae ON ae.AniDB_EpisodeID = xref.EpisodeID " +
							"GROUP BY ae.AnimeSeriesID " +
							"ORDER BY MaxDate desc ";
					ArrayList results = DatabaseHelper.GetData(sql);

					int numEps = 0;
					foreach (object[] res in results)
					{
						int animeSeriesID = int.Parse(res[0].ToString());

						AnimeSeries ser = repSeries.GetByID(session, animeSeriesID);
						if (ser == null) continue;

						if (!user.AllowedSeries(session, ser)) continue;

						AnimeSeries_User serUser = ser.GetUserRecord(session, jmmuserID);

						List<VideoLocal> vids = repVids.GetMostRecentlyAddedForAnime(session, 1, ser.AniDB_ID);
						if (vids.Count == 0) continue;

						List<AnimeEpisode> eps = vids[0].GetAnimeEpisodes(session);
						if (eps.Count == 0) continue;

						Contract_AnimeEpisode epContract = eps[0].ToContract(session, jmmuserID);
						if (epContract != null)
						{
							AniDB_Anime anidb_anime = ser.GetAnime(session);

							MetroContract_Anime_Summary summ = new MetroContract_Anime_Summary();
							summ.AnimeID = ser.AniDB_ID;
							summ.AnimeName = ser.GetSeriesName(session);
							summ.AnimeSeriesID = ser.AnimeSeriesID;
							summ.BeginYear = anidb_anime.BeginYear;
							summ.EndYear = anidb_anime.EndYear;
							//summ.PosterName = anidb_anime.GetDefaultPosterPathNoBlanks(session);
							if (serUser != null)
								summ.UnwatchedEpisodeCount = serUser.UnwatchedEpisodeCount;
							else
								summ.UnwatchedEpisodeCount = 0;

							ImageDetails imgDet = anidb_anime.GetDefaultPosterDetailsNoBlanks(session);
							summ.ImageType = (int)imgDet.ImageType;
							summ.ImageID = imgDet.ImageID;

							retAnime.Add(summ);
							numEps++;

							// Lets only return the specified amount
							if (retAnime.Count == maxRecords) return retAnime;
						}


					}
				}
			}
			catch (Exception ex)
			{
				logger.ErrorException(ex.ToString(), ex);
			}

			return retAnime;
		}
Esempio n. 13
0
		public void ToggleWatchedStatus(bool watched, bool updateOnline, DateTime? watchedDate, bool updateStats, bool updateStatsCache, int userID, 
			bool scrobbleTrakt, bool updateWatchedDate)
		{
			VideoLocalRepository repVids = new VideoLocalRepository();
			AnimeEpisodeRepository repEpisodes = new AnimeEpisodeRepository();
			AniDB_FileRepository repAniFile = new AniDB_FileRepository();
			CrossRef_File_EpisodeRepository repCross = new CrossRef_File_EpisodeRepository();
			VideoLocal_UserRepository repVidUsers = new VideoLocal_UserRepository();
			JMMUserRepository repUsers = new JMMUserRepository();
			AnimeEpisode_UserRepository repEpisodeUsers = new AnimeEpisode_UserRepository();

			JMMUser user = repUsers.GetByID(userID);
			if (user == null) return;

			List<JMMUser> aniDBUsers = repUsers.GetAniDBUsers();

			// update the video file to watched
			int mywatched = watched ? 1 : 0;

			if (user.IsAniDBUser == 0)
				SaveWatchedStatus(watched, userID, watchedDate, updateWatchedDate);
			else
			{
				// if the user is AniDB user we also want to update any other AniDB
				// users to keep them in sync
				foreach (JMMUser juser in aniDBUsers)
				{
					if (juser.IsAniDBUser == 1)
						SaveWatchedStatus(watched, juser.JMMUserID, watchedDate, updateWatchedDate);
				}
			}
			

			// now lets find all the associated AniDB_File record if there is one
			if (user.IsAniDBUser == 1)
			{
				AniDB_File aniFile = repAniFile.GetByHash(this.Hash);
				if (aniFile != null)
				{
					aniFile.IsWatched = mywatched;

					if (watched)
					{
						if (watchedDate.HasValue)
							aniFile.WatchedDate = watchedDate;
						else
							aniFile.WatchedDate = DateTime.Now;
					}
					else
						aniFile.WatchedDate = null;


					repAniFile.Save(aniFile, false);

					
				}

				if (updateOnline)
				{
					if ((watched && ServerSettings.AniDB_MyList_SetWatched) || (!watched && ServerSettings.AniDB_MyList_SetUnwatched))
					{
						CommandRequest_UpdateMyListFileStatus cmd = new CommandRequest_UpdateMyListFileStatus(this.Hash, watched, false, 
							watchedDate.HasValue ? Utils.GetAniDBDateAsSeconds(watchedDate) : 0);
						cmd.Save();
					}
				}
			}

			// now find all the episode records associated with this video file
			// but we also need to check if theer are any other files attached to this episode with a watched
			// status, 


			AnimeSeries ser = null;
			// get all files associated with this episode
			List<CrossRef_File_Episode> xrefs = repCross.GetByHash(this.Hash);
			if (watched)
			{
				// find the total watched percentage
				// eg one file can have a % = 100
				// or if 2 files make up one episodes they will each have a % = 50

				foreach (CrossRef_File_Episode xref in xrefs)
				{
					// get the episode for this file
					AnimeEpisode ep = repEpisodes.GetByAniDBEpisodeID(xref.EpisodeID);
					if (ep == null) continue;

					// get all the files for this episode
					int epPercentWatched = 0;
					foreach (CrossRef_File_Episode filexref in ep.FileCrossRefs)
					{
						VideoLocal_User vidUser = filexref.GetVideoLocalUserRecord(userID);
						if (vidUser != null)
						{
							// if not null means it is watched
							epPercentWatched += filexref.Percentage;
						}

						if (epPercentWatched > 95) break;
					}

					if (epPercentWatched > 95)
					{
						ser = ep.GetAnimeSeries();

						if (user.IsAniDBUser == 0)
							ep.SaveWatchedStatus(true, userID, watchedDate, updateWatchedDate);
						else
						{
							// if the user is AniDB user we also want to update any other AniDB
							// users to keep them in sync
							foreach (JMMUser juser in aniDBUsers)
							{
								if (juser.IsAniDBUser == 1)
									ep.SaveWatchedStatus(true, juser.JMMUserID, watchedDate, updateWatchedDate);
							}
						}

						if (scrobbleTrakt && !string.IsNullOrEmpty(ServerSettings.Trakt_Username) && !string.IsNullOrEmpty(ServerSettings.Trakt_Password))
						{
							CommandRequest_TraktShowScrobble cmdScrobble = new CommandRequest_TraktShowScrobble(ep.AnimeEpisodeID);
							cmdScrobble.Save();
						}

						if (!string.IsNullOrEmpty(ServerSettings.MAL_Username) && !string.IsNullOrEmpty(ServerSettings.MAL_Password))
						{
							CommandRequest_MALUpdatedWatchedStatus cmdMAL = new CommandRequest_MALUpdatedWatchedStatus(ser.AniDB_ID);
							cmdMAL.Save();
						}
					}
				}

				
			}
			else
			{
				// if setting a file to unwatched only set the episode unwatched, if ALL the files are unwatched
				foreach (CrossRef_File_Episode xrefEp in xrefs)
				{
					AnimeEpisode ep = repEpisodes.GetByAniDBEpisodeID(xrefEp.EpisodeID);
					if (ep == null) continue;
					ser = ep.GetAnimeSeries();

					// get all the files for this episode
					int epPercentWatched = 0;
					foreach (CrossRef_File_Episode filexref in ep.FileCrossRefs)
					{
						VideoLocal_User vidUser = filexref.GetVideoLocalUserRecord(userID);
						if (vidUser != null)
							epPercentWatched += filexref.Percentage;

						if (epPercentWatched > 95) break;
					}

					if (epPercentWatched < 95)
					{
						if (user.IsAniDBUser == 0)
							ep.SaveWatchedStatus(false, userID, watchedDate, true);
						else
						{
							// if the user is AniDB user we also want to update any other AniDB
							// users to keep them in sync
							foreach (JMMUser juser in aniDBUsers)
							{
								if (juser.IsAniDBUser == 1)
									ep.SaveWatchedStatus(false, juser.JMMUserID, watchedDate, true);
							}
						}

						CommandRequest_TraktShowEpisodeUnseen cmdUnseen = new CommandRequest_TraktShowEpisodeUnseen(ep.AnimeEpisodeID);
						cmdUnseen.Save();
					}
				}

				if (!string.IsNullOrEmpty(ServerSettings.MAL_Username) && !string.IsNullOrEmpty(ServerSettings.MAL_Password))
				{
					CommandRequest_MALUpdatedWatchedStatus cmdMAL = new CommandRequest_MALUpdatedWatchedStatus(ser.AniDB_ID);
					cmdMAL.Save();
				}
			}
			

			// update stats for groups and series
			if (ser != null && updateStats)
			{
				// update all the groups above this series in the heirarchy
				ser.UpdateStats(true, true, true);
				//ser.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true, true, true);
			}

			if (ser != null && updateStatsCache)
				StatsCache.Instance.UpdateUsingSeries(ser.AnimeSeriesID);
		}
Esempio n. 14
0
		public AnimeEpisode_User GetUserRecord(ISession session, int userID)
		{
			AnimeEpisode_UserRepository repEpUser = new AnimeEpisode_UserRepository();
			return repEpUser.GetByUserIDAndEpisodeID(session, userID, this.AnimeEpisodeID);
		}
Esempio n. 15
0
        public List<Contract_AnimeEpisode> GetEpisodesRecentlyAdded(int maxRecords, int jmmuserID)
        {
            List<Contract_AnimeEpisode> retEps = new List<Contract_AnimeEpisode>();
            try
            {
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
                    AnimeEpisode_UserRepository repEpUser = new AnimeEpisode_UserRepository();
                    JMMUserRepository repUsers = new JMMUserRepository();
                    VideoLocalRepository repVids = new VideoLocalRepository();

                    JMMUser user = repUsers.GetByID(session, jmmuserID);
                    if (user == null) return retEps;

                    List<VideoLocal> vids = repVids.GetMostRecentlyAdded(session, maxRecords);
                    int numEps = 0;
                    foreach (VideoLocal vid in vids)
                    {
                        foreach (AnimeEpisode ep in vid.GetAnimeEpisodes(session))
                        {
                            if (user.AllowedSeries(ep.GetAnimeSeries(session)))
                            {
                                Contract_AnimeEpisode epContract = ep.ToContract(session, jmmuserID);
                                if (epContract != null)
                                {
                                    retEps.Add(epContract);
                                    numEps++;

                                    // Lets only return the specified amount
                                    if (retEps.Count == maxRecords) return retEps;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }

            return retEps;
        }
Esempio n. 16
0
        public static UserInfo GetUserInfoData(string dashType = "", string vidPlayer = "")
        {
            try
            {
                if (string.IsNullOrEmpty(ServerSettings.AniDB_Username)) return null;

                UserInfo uinfo = new UserInfo();

                uinfo.DateTimeUpdated = DateTime.Now;
                uinfo.DateTimeUpdatedUTC = 0;

                // Optional JMM Desktop data
                uinfo.DashboardType = null;
                uinfo.VideoPlayer = vidPlayer;

                System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
                try
                {
                    if (a != null) uinfo.JMMServerVersion = Utils.GetApplicationVersion(a);
                }
                catch {}

                uinfo.UsernameHash = Utils.GetMd5Hash(ServerSettings.AniDB_Username);
                uinfo.DatabaseType = ServerSettings.DatabaseType;
                uinfo.WindowsVersion = Utils.GetOSInfo();
                uinfo.TraktEnabled = ServerSettings.Trakt_IsEnabled ? 1 : 0;
                uinfo.MALEnabled = string.IsNullOrEmpty(ServerSettings.MAL_Username) ? 0 : 1;

                uinfo.CountryLocation = "";
                
                // this field is not actually used
                uinfo.LastEpisodeWatchedAsDate = DateTime.Now.AddDays(-5);

                JMMUserRepository repUsers = new JMMUserRepository();
                uinfo.LocalUserCount = (int)(repUsers.GetTotalRecordCount());

                VideoLocalRepository repVids = new VideoLocalRepository();
                uinfo.FileCount = repVids.GetTotalRecordCount();

                AnimeEpisode_UserRepository repEps = new AnimeEpisode_UserRepository();
                List<AnimeEpisode_User> recs = repEps.GetLastWatchedEpisode();
                uinfo.LastEpisodeWatched = 0;
                if (recs.Count > 0)
                    uinfo.LastEpisodeWatched = Utils.GetAniDBDateAsSeconds(recs[0].WatchedDate);

                return uinfo;
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return null;
            }
        }
Esempio n. 17
0
		public void Delete(int id)
		{
			AnimeEpisode cr = GetByID(id);
			if (cr != null)
			{
				// delete user records
				AnimeEpisode_UserRepository repUsers = new AnimeEpisode_UserRepository();
				foreach (AnimeEpisode_User epuser in repUsers.GetByEpisodeID(id))
					repUsers.Delete(epuser.AnimeEpisode_UserID);
			}

			using (var session = JMMService.SessionFactory.OpenSession())
			{
				// populate the database
				using (var transaction = session.BeginTransaction())
				{
					if (cr != null)
					{
						session.Delete(cr);
						transaction.Commit();
					}
				}
			}
		}