コード例 #1
0
ファイル: MainWindow.xaml.cs プロジェクト: dizzydezz/jmm
		void workerMyAnime2_DoWork(object sender, DoWorkEventArgs e)
		{
			MA2Progress ma2Progress = new MA2Progress();
			ma2Progress.CurrentFile = 0;
			ma2Progress.ErrorMessage = "";
			ma2Progress.MigratedFiles = 0;
			ma2Progress.TotalFiles = 0;

			try
			{
				string databasePath = e.Argument as string;

				string connString = string.Format(@"data source={0};useutf16encoding=True", databasePath);
				SQLiteConnection myConn = new SQLiteConnection(connString);
				myConn.Open();

				// get a list of unlinked files
				VideoLocalRepository repVids = new VideoLocalRepository();
				AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository();
				AniDB_AnimeRepository repAniAnime = new AniDB_AnimeRepository();
				AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
				AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();

				List<VideoLocal> vids = repVids.GetVideosWithoutEpisode();
				ma2Progress.TotalFiles = vids.Count;

				foreach (VideoLocal vid in vids)
				{
					ma2Progress.CurrentFile = ma2Progress.CurrentFile + 1;
					workerMyAnime2.ReportProgress(0, ma2Progress);

					// search for this file in the XrossRef table in MA2
					string sql = string.Format("SELECT AniDB_EpisodeID from CrossRef_Episode_FileHash WHERE Hash = '{0}' AND FileSize = {1}", vid.ED2KHash, vid.FileSize);
					SQLiteCommand sqCommand = new SQLiteCommand(sql);
					sqCommand.Connection = myConn;

					SQLiteDataReader myReader = sqCommand.ExecuteReader();
					while (myReader.Read())
					{
						int episodeID = 0;
						if (!int.TryParse(myReader.GetValue(0).ToString(), out episodeID)) continue;
						if (episodeID <= 0) continue;

						sql = string.Format("SELECT AnimeID from AniDB_Episode WHERE EpisodeID = {0}", episodeID);
						sqCommand = new SQLiteCommand(sql);
						sqCommand.Connection = myConn;

						SQLiteDataReader myReader2 = sqCommand.ExecuteReader();
						while (myReader2.Read())
						{
							int animeID = myReader2.GetInt32(0);

							// so now we have all the needed details we can link the file to the episode
							// as long as wehave the details in JMM
							AniDB_Anime anime = null;
							AniDB_Episode ep = repAniEps.GetByEpisodeID(episodeID);
							if (ep == null)
							{
								logger.Debug("Getting Anime record from AniDB....");
								anime = JMMService.AnidbProcessor.GetAnimeInfoHTTP(animeID, true, ServerSettings.AutoGroupSeries);
							}
							else
								anime = repAniAnime.GetByAnimeID(animeID);

							// create the group/series/episode records if needed
							AnimeSeries ser = null;
							if (anime == null) continue;

							logger.Debug("Creating groups, series and episodes....");
							// check if there is an AnimeSeries Record associated with this AnimeID
							ser = repSeries.GetByAnimeID(animeID);
							if (ser == null)
							{
								// create a new AnimeSeries record
								ser = anime.CreateAnimeSeriesAndGroup();
							}


							ser.CreateAnimeEpisodes();

							// check if we have any group status data for this associated anime
							// if not we will download it now
							AniDB_GroupStatusRepository repStatus = new AniDB_GroupStatusRepository();
							if (repStatus.GetByAnimeID(anime.AnimeID).Count == 0)
							{
								CommandRequest_GetReleaseGroupStatus cmdStatus = new CommandRequest_GetReleaseGroupStatus(anime.AnimeID, false);
								cmdStatus.Save();
							}

							// update stats
							ser.EpisodeAddedDate = DateTime.Now;
							repSeries.Save(ser);

							AnimeGroupRepository repGroups = new AnimeGroupRepository();
							foreach (AnimeGroup grp in ser.AllGroupsAbove)
							{
								grp.EpisodeAddedDate = DateTime.Now;
								repGroups.Save(grp);
							}


							AnimeEpisode epAnime = repEps.GetByAniDBEpisodeID(episodeID);
							if (epAnime == null)
								continue;

							CrossRef_File_EpisodeRepository repXRefs = new CrossRef_File_EpisodeRepository();
							CrossRef_File_Episode xref = new CrossRef_File_Episode();

							try
							{
								xref.PopulateManually(vid, epAnime);
							}
							catch (Exception ex)
							{
								string msg = string.Format("Error populating XREF: {0} - {1}", vid.ToStringDetailed(), ex.ToString());
								throw;
							}

							repXRefs.Save(xref);

							vid.RenameIfRequired();
							vid.MoveFileIfRequired();

							// update stats for groups and series
							if (ser != null)
							{
								// update all the groups above this series in the heirarchy
								ser.UpdateStats(true, true, true);
								StatsCache.Instance.UpdateUsingSeries(ser.AnimeSeriesID);
							}


							// Add this file to the users list
							if (ServerSettings.AniDB_MyList_AddFiles)
							{
								CommandRequest_AddFileToMyList cmd = new CommandRequest_AddFileToMyList(vid.ED2KHash);
								cmd.Save();
							}

							ma2Progress.MigratedFiles = ma2Progress.MigratedFiles + 1;
							workerMyAnime2.ReportProgress(0, ma2Progress);

						}
						myReader2.Close();


						//Console.WriteLine(myReader.GetString(0));
					}
					myReader.Close();
				}


				myConn.Close();

				ma2Progress.CurrentFile = ma2Progress.CurrentFile + 1;
				workerMyAnime2.ReportProgress(0, ma2Progress);

			}
			catch (Exception ex)
			{
				logger.ErrorException(ex.ToString(), ex);
				ma2Progress.ErrorMessage = ex.Message;
				workerMyAnime2.ReportProgress(0, ma2Progress);
			}
		}
コード例 #2
0
        /// <summary>
        /// Finds the previous episode for use int the next unwatched episode
        /// </summary>
        /// <param name="animeSeriesID"></param>
        /// <param name="userID"></param>
        /// <returns></returns>
        public Contract_AnimeEpisode GetPreviousEpisodeForUnwatched(int animeSeriesID, int userID)
        {
            try
            {
                Contract_AnimeEpisode nextEp = GetNextUnwatchedEpisode(animeSeriesID, userID);
                if (nextEp == null) return null;

                int epType = nextEp.EpisodeType;
                int epNum = nextEp.EpisodeNumber - 1;

                if (epNum <= 0) return null;

                AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository();
                AnimeSeriesRepository repAnimeSer = new AnimeSeriesRepository();
                AnimeSeries series = repAnimeSer.GetByID(animeSeriesID);
                if (series == null) return null;

                List<AniDB_Episode> anieps = repAniEps.GetByAnimeIDAndEpisodeTypeNumber(series.AniDB_ID, (enEpisodeType)epType, epNum);
                if (anieps.Count == 0) return null;

                AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
                AnimeEpisode ep = repEps.GetByAniDBEpisodeID(anieps[0].EpisodeID);
                if (ep == null) return null;

                return ep.ToContract(true, userID, null);

            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return null;
            }
        }
コード例 #3
0
        public string RemoveLinkAniDBTvDBEpisode(int aniDBEpisodeID)
        {
            try
            {
                CrossRef_AniDB_TvDB_EpisodeRepository repXrefs = new CrossRef_AniDB_TvDB_EpisodeRepository();
                AniDB_EpisodeRepository repEps = new AniDB_EpisodeRepository();
                AniDB_Episode ep = repEps.GetByEpisodeID(aniDBEpisodeID);

                if (ep == null) return "Could not find Episode";

                CrossRef_AniDB_TvDB_Episode xref = repXrefs.GetByAniDBEpisodeID(aniDBEpisodeID);
                if (xref == null) return "Could not find Link!";

                repXrefs.Delete(xref.CrossRef_AniDB_TvDB_EpisodeID);

                return "";
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return ex.Message;
            }
        }
コード例 #4
0
        /// <summary>
        /// Get all the release groups for an episode for which the user is collecting
        /// </summary>
        /// <param name="aniDBEpisodeID"></param>
        /// <returns></returns>
        public List<Contract_AniDBReleaseGroup> GetMyReleaseGroupsForAniDBEpisode(int aniDBEpisodeID)
        {
            DateTime start = DateTime.Now;

            List<Contract_AniDBReleaseGroup> relGroups = new List<Contract_AniDBReleaseGroup>();

            try
            {
                AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository();
                AniDB_Episode aniEp = repAniEps.GetByEpisodeID(aniDBEpisodeID);
                if (aniEp == null) return relGroups;
                if (aniEp.EpisodeTypeEnum != AniDBAPI.enEpisodeType.Episode) return relGroups;

                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                AnimeSeries series = repSeries.GetByAnimeID(aniEp.AnimeID);
                if (series == null) return relGroups;

                // get a list of all the release groups the user is collecting
                Dictionary<int, int> userReleaseGroups = new Dictionary<int, int>();
                foreach (AnimeEpisode ep in series.GetAnimeEpisodes())
                {
                    List<VideoLocal> vids = ep.GetVideoLocals();
                    foreach (VideoLocal vid in vids)
                    {
                        AniDB_File anifile = vid.GetAniDBFile();
                        if (anifile != null)
                        {
                            if (!userReleaseGroups.ContainsKey(anifile.GroupID))
                                userReleaseGroups[anifile.GroupID] = 0;

                            userReleaseGroups[anifile.GroupID] = userReleaseGroups[anifile.GroupID] + 1;
                        }
                    }
                }

                // get all the release groups for this series
                AniDB_GroupStatusRepository repGrpStatus = new AniDB_GroupStatusRepository();
                List<AniDB_GroupStatus> grpStatuses = repGrpStatus.GetByAnimeID(aniEp.AnimeID);
                foreach (AniDB_GroupStatus gs in grpStatuses)
                {
                    if (userReleaseGroups.ContainsKey(gs.GroupID))
                    {
                        if (gs.HasGroupReleasedEpisode(aniEp.EpisodeNumber))
                        {
                            Contract_AniDBReleaseGroup contract = new Contract_AniDBReleaseGroup();
                            contract.GroupID = gs.GroupID;
                            contract.GroupName = gs.GroupName;
                            contract.UserCollecting = true;
                            contract.EpisodeRange = gs.EpisodeRange;
                            contract.FileCount = userReleaseGroups[gs.GroupID];
                            relGroups.Add(contract);
                        }
                    }
                }
                TimeSpan ts = DateTime.Now - start;
                logger.Info("GetMyReleaseGroupsForAniDBEpisode  in {0} ms", ts.TotalMilliseconds);
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }
            return relGroups;
        }
コード例 #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;
            }
        }
コード例 #6
0
ファイル: Importer.cs プロジェクト: dizzydezz/jmm
		public static void RunImport_IntegrityCheck()
		{
			VideoLocalRepository repVidLocals = new VideoLocalRepository();
			AniDB_FileRepository repAniFile = new AniDB_FileRepository();
			AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository();
			AniDB_AnimeRepository repAniAnime = new AniDB_AnimeRepository();


			// files which don't have a valid import folder
			List<VideoLocal> filesToDelete = repVidLocals.GetVideosWithoutImportFolder();
			foreach (VideoLocal vl in filesToDelete)
				repVidLocals.Delete(vl.VideoLocalID);
				

			// files which have not been hashed yet
			// or files which do not have a VideoInfo record
			List<VideoLocal> filesToHash = repVidLocals.GetVideosWithoutHash();
			Dictionary<int, VideoLocal> dictFilesToHash = new Dictionary<int, VideoLocal>();
			foreach (VideoLocal vl in filesToHash)
			{

				dictFilesToHash[vl.VideoLocalID] = vl;
				CommandRequest_HashFile cmd = new CommandRequest_HashFile(vl.FullServerPath, false);
				cmd.Save();
			}

			List<VideoLocal> filesToRehash = repVidLocals.GetVideosWithoutVideoInfo();
			Dictionary<int, VideoLocal> dictFilesToRehash = new Dictionary<int, VideoLocal>();
			foreach (VideoLocal vl in filesToHash)
			{
				dictFilesToRehash[vl.VideoLocalID] = vl;
				// don't use if it is in the previous list
				if (!dictFilesToHash.ContainsKey(vl.VideoLocalID))
				{
					try
					{
						CommandRequest_HashFile cmd = new CommandRequest_HashFile(vl.FullServerPath, false);
						cmd.Save();
					}
					catch (Exception ex)
					{
						string msg = string.Format("Error RunImport_IntegrityCheck XREF: {0} - {1}", vl.ToStringDetailed(), ex.ToString());
						logger.Info(msg);
					}
				}
			}

			// files which have been hashed, but don't have an associated episode
			List<VideoLocal> filesWithoutEpisode = repVidLocals.GetVideosWithoutEpisode();
			Dictionary<int, VideoLocal> dictFilesWithoutEpisode = new Dictionary<int, VideoLocal>();
			foreach (VideoLocal vl in filesWithoutEpisode)
				dictFilesWithoutEpisode[vl.VideoLocalID] = vl;


			// check that all the episode data is populated
			List<VideoLocal> filesAll = repVidLocals.GetAll();
			Dictionary<string, VideoLocal> dictFilesAllExisting = new Dictionary<string, VideoLocal>();
			foreach (VideoLocal vl in filesAll)
			{
				try
				{
					dictFilesAllExisting[vl.FullServerPath] = vl;
				}
				catch (Exception ex)
				{
					string msg = string.Format("Error RunImport_IntegrityCheck XREF: {0} - {1}", vl.ToStringDetailed(), ex.ToString());
					logger.Error(msg);
					continue;
				}

				// check if it has an episode
				if (dictFilesWithoutEpisode.ContainsKey(vl.VideoLocalID))
				{
					CommandRequest_ProcessFile cmd = new CommandRequest_ProcessFile(vl.VideoLocalID, false);
					cmd.Save();
					continue;
				}

				// if the file is not manually associated, then check for AniDB_File info
				AniDB_File aniFile = repAniFile.GetByHash(vl.Hash);
				foreach (CrossRef_File_Episode xref in vl.EpisodeCrossRefs)
				{
					if (xref.CrossRefSource != (int)CrossRefSource.AniDB) continue;
					if (aniFile == null)
					{
						CommandRequest_ProcessFile cmd = new CommandRequest_ProcessFile(vl.VideoLocalID, false);
						cmd.Save();
						continue;
					}
				}

				if (aniFile == null) continue;

				// the cross ref is created before the actually episode data is downloaded
				// so lets check for that
				bool missingEpisodes = false;
				foreach (CrossRef_File_Episode xref in aniFile.EpisodeCrossRefs)
				{
					AniDB_Episode ep = repAniEps.GetByEpisodeID(xref.EpisodeID);
					if (ep == null) missingEpisodes = true;
				}

				if (missingEpisodes)
				{
					// this will then download the anime etc
					CommandRequest_ProcessFile cmd = new CommandRequest_ProcessFile(vl.VideoLocalID, false);
					cmd.Save();
					continue;
				}
			}
		}
コード例 #7
0
        public List<Contract_MissingFile> GetMyListFilesForRemoval(int userID)
        {
            List<Contract_MissingFile> contracts = new List<Contract_MissingFile>();

            /*Contract_MissingFile missingFile2 = new Contract_MissingFile();
            missingFile2.AnimeID = 1;
            missingFile2.AnimeTitle = "Gundam Age";
            missingFile2.EpisodeID = 2;
            missingFile2.EpisodeNumber = 7;
            missingFile2.FileID = 8;
            missingFile2.AnimeSeries = null;
            contracts.Add(missingFile2);

            Thread.Sleep(5000);

            return contracts;*/

            AniDB_FileRepository repAniFile = new AniDB_FileRepository();
            CrossRef_File_EpisodeRepository repFileEp = new CrossRef_File_EpisodeRepository();
            AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
            AniDB_EpisodeRepository repEpisodes = new AniDB_EpisodeRepository();
            VideoLocalRepository repVids = new VideoLocalRepository();
            AnimeSeriesRepository repSeries = new AnimeSeriesRepository();

            Dictionary<int, AniDB_Anime> animeCache = new Dictionary<int, AniDB_Anime>();
            Dictionary<int, AnimeSeries> animeSeriesCache = new Dictionary<int, AnimeSeries>();

            try
            {
                AniDBHTTPCommand_GetMyList cmd = new AniDBHTTPCommand_GetMyList();
                cmd.Init(ServerSettings.AniDB_Username, ServerSettings.AniDB_Password);
                enHelperActivityType ev = cmd.Process();
                if (ev == enHelperActivityType.GotMyListHTTP)
                {
                    foreach (Raw_AniDB_MyListFile myitem in cmd.MyListItems)
                    {
                        // let's check if the file on AniDB actually exists in the user's local collection
                        string hash = string.Empty;

                        AniDB_File anifile = repAniFile.GetByFileID(myitem.FileID);
                        if (anifile != null)
                            hash = anifile.Hash;
                        else
                        {
                            // look for manually linked files
                            List<CrossRef_File_Episode> xrefs = repFileEp.GetByEpisodeID(myitem.EpisodeID);
                            foreach (CrossRef_File_Episode xref in xrefs)
                            {
                                if (xref.CrossRefSource != (int)CrossRefSource.AniDB)
                                {
                                    hash = xref.Hash;
                                    break;
                                }
                            }
                        }

                        bool fileMissing = false;
                        if (string.IsNullOrEmpty(hash))
                            fileMissing = true;
                        else
                        {
                            // now check if the file actually exists on disk
                            VideoLocal vid = repVids.GetByHash(hash);

                            if (vid != null && !File.Exists(vid.FullServerPath))
                                fileMissing = true;
                        }

                        if (fileMissing)
                        {

                            // this means we can't find the file
                            AniDB_Anime anime = null;
                            if (animeCache.ContainsKey(myitem.AnimeID))
                                anime = animeCache[myitem.AnimeID];
                            else
                            {
                                anime = repAnime.GetByAnimeID(myitem.AnimeID);
                                animeCache[myitem.AnimeID] = anime;
                            }

                            AnimeSeries ser = null;
                            if (animeSeriesCache.ContainsKey(myitem.AnimeID))
                                ser = animeSeriesCache[myitem.AnimeID];
                            else
                            {
                                ser = repSeries.GetByAnimeID(myitem.AnimeID);
                                animeSeriesCache[myitem.AnimeID] = ser;
                            }

                            Contract_MissingFile missingFile = new Contract_MissingFile();
                            missingFile.AnimeID = myitem.AnimeID;
                            missingFile.AnimeTitle = "Data Missing";
                            if (anime != null) missingFile.AnimeTitle = anime.MainTitle;
                            missingFile.EpisodeID = myitem.EpisodeID;
                            AniDB_Episode ep = repEpisodes.GetByEpisodeID(myitem.EpisodeID);
                            missingFile.EpisodeNumber = -1;
                            missingFile.EpisodeType = 1;
                            if (ep != null)
                            {
                                missingFile.EpisodeNumber = ep.EpisodeNumber;
                                missingFile.EpisodeType = ep.EpisodeType;
                            }
                            missingFile.FileID = myitem.FileID;

                            if (ser == null) missingFile.AnimeSeries = null;
                            else missingFile.AnimeSeries = ser.ToContract(ser.GetUserRecord(userID));

                            contracts.Add(missingFile);
                        }
                    }
                }

                if (contracts.Count > 0)
                {
                    List<SortPropOrFieldAndDirection> sortCriteria = new List<SortPropOrFieldAndDirection>();
                    sortCriteria.Add(new SortPropOrFieldAndDirection("AnimeTitle", false, SortType.eString));
                    sortCriteria.Add(new SortPropOrFieldAndDirection("EpisodeID", false, SortType.eInteger));
                    contracts = Sorting.MultiSort<Contract_MissingFile>(contracts, sortCriteria);
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }
            return contracts;
        }
コード例 #8
0
        public string AssociateSingleFileWithMultipleEpisodes(int videoLocalID, int animeSeriesID, int startEpNum, int endEpNum)
        {
            try
            {
                VideoLocalRepository repVids = new VideoLocalRepository();
                VideoLocal vid = repVids.GetByID(videoLocalID);
                if (vid == null)
                    return "Could not find video record";

                AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository();
                CrossRef_File_EpisodeRepository repXRefs = new CrossRef_File_EpisodeRepository();

                AnimeSeries ser = repSeries.GetByID(animeSeriesID);
                if (ser == null)
                    return "Could not find anime series record";

                for (int i = startEpNum; i <= endEpNum; i++)
                {
                    List<AniDB_Episode> anieps = repAniEps.GetByAnimeIDAndEpisodeNumber(ser.AniDB_ID, i);
                    if (anieps.Count == 0)
                        return "Could not find the AniDB episode record";

                    AniDB_Episode aniep = anieps[0];

                    List<AnimeEpisode> eps = repEps.GetByAniEpisodeIDAndSeriesID(aniep.EpisodeID, ser.AnimeSeriesID);
                    if (eps.Count == 0)
                        return "Could not find episode record";

                    AnimeEpisode ep = eps[0];

                    CrossRef_File_Episode xref = new CrossRef_File_Episode();
                    xref.PopulateManually(vid, ep);
                    repXRefs.Save(xref);

                    CommandRequest_WebCacheSendXRefFileEpisode cr = new CommandRequest_WebCacheSendXRefFileEpisode(xref.CrossRef_File_EpisodeID);
                    cr.Save();
                }

                vid.RenameIfRequired();
                vid.MoveFileIfRequired();

                ser.QueueUpdateStats();

                // update epidsode added stats
                ser.EpisodeAddedDate = DateTime.Now;
                repSeries.Save(ser);

                AnimeGroupRepository repGroups = new AnimeGroupRepository();
                foreach (AnimeGroup grp in ser.AllGroupsAbove)
                {
                    grp.EpisodeAddedDate = DateTime.Now;
                    repGroups.Save(grp);
                }

                return "";

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

            return "";
        }
コード例 #9
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;
        }
コード例 #10
0
        public string AssociateMultipleFiles(List<int> videoLocalIDs, int animeSeriesID, int startingEpisodeNumber, bool singleEpisode)
        {
            try
            {
                CrossRef_File_EpisodeRepository repXRefs = new CrossRef_File_EpisodeRepository();
                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                VideoLocalRepository repVids = new VideoLocalRepository();
                AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository();
                AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();

                AnimeSeries ser = repSeries.GetByID(animeSeriesID);
                if (ser == null)
                    return "Could not find anime series record";

                int epNumber = startingEpisodeNumber;
                int count = 1;

                foreach (int videoLocalID in videoLocalIDs)
                {
                    VideoLocal vid = repVids.GetByID(videoLocalID);
                    if (vid == null)
                        return "Could not find video local record";

                    List<AniDB_Episode> anieps = repAniEps.GetByAnimeIDAndEpisodeNumber(ser.AniDB_ID, epNumber);
                    if (anieps.Count == 0)
                        return "Could not find the AniDB episode record";

                    AniDB_Episode aniep = anieps[0];

                    List<AnimeEpisode> eps = repEps.GetByAniEpisodeIDAndSeriesID(aniep.EpisodeID, ser.AnimeSeriesID);
                    if (eps.Count == 0)
                        return "Could not find episode record";

                    AnimeEpisode ep = eps[0];

                    CrossRef_File_Episode xref = new CrossRef_File_Episode();
                    xref.PopulateManually(vid, ep);

                    // TODO do this properly
                    if (singleEpisode)
                    {
                        xref.EpisodeOrder = count;
                        if (videoLocalIDs.Count > 5)
                            xref.Percentage = 100;
                        else
                            xref.Percentage = GetEpisodePercentages(videoLocalIDs.Count)[count - 1];
                    }

                    repXRefs.Save(xref);

                    vid.RenameIfRequired();
                    vid.MoveFileIfRequired();

                    CommandRequest_WebCacheSendXRefFileEpisode cr = new CommandRequest_WebCacheSendXRefFileEpisode(xref.CrossRef_File_EpisodeID);
                    cr.Save();

                    count++;
                    if (!singleEpisode) epNumber++;
                }

                ser.QueueUpdateStats();

                // update epidsode added stats
                ser.EpisodeAddedDate = DateTime.Now;
                repSeries.Save(ser);

                AnimeGroupRepository repGroups = new AnimeGroupRepository();
                foreach (AnimeGroup grp in ser.AllGroupsAbove)
                {
                    grp.EpisodeAddedDate = DateTime.Now;
                    repGroups.Save(grp);
                }

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

            return "";
        }
コード例 #11
0
        public List<Contract_AniDB_Episode> GetAniDBEpisodesForAnime(int animeID)
        {
            List<Contract_AniDB_Episode> eps = new List<Contract_AniDB_Episode>();
            try
            {
                AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository();
                List<AniDB_Episode> aniEpList = repAniEps.GetByAnimeID(animeID);

                foreach (AniDB_Episode ep in aniEpList)
                    eps.Add(ep.ToContract());

                List<SortPropOrFieldAndDirection> sortCriteria = new List<SortPropOrFieldAndDirection>();
                sortCriteria.Add(new SortPropOrFieldAndDirection("EpisodeType", false, SortType.eInteger));
                sortCriteria.Add(new SortPropOrFieldAndDirection("EpisodeNumber", false, SortType.eInteger));
                eps = Sorting.MultiSort<Contract_AniDB_Episode>(eps, sortCriteria);

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

            return eps;
        }
コード例 #12
0
		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;
			}
		}
コード例 #13
0
 public List<AniDB_Episode> GetAniDBEpisodes(ISession session)
 {
     AniDB_EpisodeRepository repEps = new AniDB_EpisodeRepository();
     return repEps.GetByAnimeID(session, AnimeID);
 }
コード例 #14
0
        private void CreateEpisodes(ISession session, List<Raw_AniDB_Episode> eps)
        {
            if (eps == null) return;

            AniDB_EpisodeRepository repEps = new AniDB_EpisodeRepository();

            this.EpisodeCountSpecial = 0;
            this.EpisodeCountNormal = 0;

            List<AnimeEpisode> animeEpsToDelete = new List<AnimeEpisode>();
            List<AniDB_Episode> aniDBEpsToDelete = new List<AniDB_Episode>();

            foreach (Raw_AniDB_Episode epraw in eps)
            {
                //List<AniDB_Episode> existingEps = repEps.GetByAnimeIDAndEpisodeTypeNumber(epraw.AnimeID, (enEpisodeType)epraw.EpisodeType, epraw.EpisodeNumber);
                // we need to do this check because some times AniDB will replace an existing episode with a new episode

                var tempEps = session
                    .CreateCriteria(typeof(AniDB_Episode))
                    .Add(Restrictions.Eq("AnimeID", epraw.AnimeID))
                    .Add(Restrictions.Eq("EpisodeNumber", epraw.EpisodeNumber))
                    .Add(Restrictions.Eq("EpisodeType", epraw.EpisodeType))
                    .List<AniDB_Episode>();

                List<AniDB_Episode> existingEps = new List<AniDB_Episode>(tempEps);

                // delete any old records
                foreach (AniDB_Episode epOld in existingEps)
                {
                    if (epOld.EpisodeID != epraw.EpisodeID)
                    {
                        // first delete any AnimeEpisode records that point to the new anidb episode
                        AnimeEpisodeRepository repAnimeEps = new AnimeEpisodeRepository();
                        AnimeEpisode aniep = repAnimeEps.GetByAniDBEpisodeID(session, epOld.EpisodeID);
                        if (aniep != null)
                        {
                            //repAnimeEps.Delete(aniep.AnimeEpisodeID);
                            animeEpsToDelete.Add(aniep);
                        }

                        //repEps.Delete(epOld.AniDB_EpisodeID);
                        aniDBEpsToDelete.Add(epOld);
                    }
                }
            }
            using (var transaction = session.BeginTransaction())
            {
                foreach (AnimeEpisode ep in animeEpsToDelete)
                    session.Delete(ep);

                transaction.Commit();
            }

            using (var transaction = session.BeginTransaction())
            {
                foreach (AniDB_Episode ep in aniDBEpsToDelete)
                    session.Delete(ep);

                transaction.Commit();
            }

            List<AniDB_Episode> epsToSave = new List<AniDB_Episode>();
            foreach (Raw_AniDB_Episode epraw in eps)
            {
                AniDB_Episode epNew = session
                    .CreateCriteria(typeof(AniDB_Episode))
                    .Add(Restrictions.Eq("EpisodeID", epraw.EpisodeID))
                    .UniqueResult<AniDB_Episode>();

                if (epNew == null) epNew = new AniDB_Episode();

                epNew.Populate(epraw);
                epsToSave.Add(epNew);

                // since the HTTP api doesn't return a count of the number of specials, we will calculate it here
                if (epNew.EpisodeTypeEnum == AniDBAPI.enEpisodeType.Episode)
                    this.EpisodeCountNormal++;

                if (epNew.EpisodeTypeEnum == AniDBAPI.enEpisodeType.Special)
                    this.EpisodeCountSpecial++;
            }
            using (var transaction = session.BeginTransaction())
            {
                foreach (AniDB_Episode rec in epsToSave)
                    session.SaveOrUpdate(rec);

                transaction.Commit();
            }

            this.EpisodeCount = EpisodeCountSpecial + EpisodeCountNormal;
        }
コード例 #15
0
		private void ProcessFile_AniDB(VideoLocal vidLocal)
		{
			logger.Trace("Checking for AniDB_File record for: {0} --- {1}", vidLocal.Hash, vidLocal.FilePath);
			// check if we already have this AniDB_File info in the database
			
			AniDB_FileRepository repAniFile = new AniDB_FileRepository();
			AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository();
			AniDB_AnimeRepository repAniAnime = new AniDB_AnimeRepository();
			AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
			VideoLocalRepository repVidLocals = new VideoLocalRepository();
			AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
			CrossRef_File_EpisodeRepository repXrefFE = new CrossRef_File_EpisodeRepository();

			AniDB_File aniFile = null;

			if (!ForceAniDB)
			{
				aniFile = repAniFile.GetByHashAndFileSize(vidLocal.Hash, vlocal.FileSize);

				if (aniFile == null)
					logger.Trace("AniDB_File record not found");
			}

			int animeID = 0;

			if (aniFile == null)
			{
				// get info from AniDB
				logger.Debug("Getting AniDB_File record from AniDB....");
				Raw_AniDB_File fileInfo = JMMService.AnidbProcessor.GetFileInfo(vidLocal);
				if (fileInfo != null)
				{
					// check if we already have a record
					aniFile = repAniFile.GetByHashAndFileSize(vidLocal.Hash, vlocal.FileSize);

					if (aniFile == null)
						aniFile = new AniDB_File();

					aniFile.Populate(fileInfo);

					//overwrite with local file name
					string localFileName = Path.GetFileName(vidLocal.FilePath);
					aniFile.FileName = localFileName;

					repAniFile.Save(aniFile, false);
					aniFile.CreateLanguages();
					aniFile.CreateCrossEpisodes(localFileName);

                    if (!string.IsNullOrEmpty(fileInfo.OtherEpisodesRAW))
                    {
                        string[] epIDs = fileInfo.OtherEpisodesRAW.Split(',');
                        foreach (string epid in epIDs)
                        {
                            int id = 0;
                            if (int.TryParse(epid, out id))
                            {
                                CommandRequest_GetEpisode cmdEp = new CommandRequest_GetEpisode(id);
                                cmdEp.Save();
                            }
                        }
                    }

					animeID = aniFile.AnimeID;
				}
			}

			bool missingEpisodes = false;

			// if we still haven't got the AniDB_File Info we try the web cache or local records
			if (aniFile == null)
			{
				// check if we have any records from previous imports
				List<CrossRef_File_Episode> crossRefs = repXrefFE.GetByHash(vidLocal.Hash);
				if (crossRefs == null || crossRefs.Count == 0)
				{
					// lets see if we can find the episode/anime info from the web cache
					if (ServerSettings.WebCache_XRefFileEpisode_Get)
					{
						crossRefs = XMLService.Get_CrossRef_File_Episode(vidLocal);
						if (crossRefs == null || crossRefs.Count == 0)
						{
							logger.Debug("Cannot find AniDB_File record or get cross ref from web cache record so exiting: {0}", vidLocal.ED2KHash);
							return;
						}
						else
						{
							foreach (CrossRef_File_Episode xref in crossRefs)
							{
								// in this case we need to save the cross refs manually as AniDB did not provide them
								repXrefFE.Save(xref);
							}
						}
					}
					else
					{
						logger.Debug("Cannot get AniDB_File record so exiting: {0}", vidLocal.ED2KHash);
						return;
					}
				}

				// we assume that all episodes belong to the same anime
				foreach (CrossRef_File_Episode xref in crossRefs)
				{
					animeID = xref.AnimeID;
					
					AniDB_Episode ep = repAniEps.GetByEpisodeID(xref.EpisodeID);
					if (ep == null) missingEpisodes = true;
				}
			}
			else
			{
				// check if we have the episode info
				// if we don't, we will need to re-download the anime info (which also has episode info)

				if (aniFile.EpisodeCrossRefs.Count == 0)
				{
					animeID = aniFile.AnimeID;

					// if we have the anidb file, but no cross refs it means something has been broken
					logger.Debug("Could not find any cross ref records for: {0}", vidLocal.ED2KHash);
					missingEpisodes = true;
				}
				else
				{
					foreach (CrossRef_File_Episode xref in aniFile.EpisodeCrossRefs)
					{
						AniDB_Episode ep = repAniEps.GetByEpisodeID(xref.EpisodeID);
						if (ep == null)
							missingEpisodes = true;

						animeID = xref.AnimeID;
					}
				}
			}

			// get from DB
			AniDB_Anime anime = repAniAnime.GetByAnimeID(animeID);
			bool animeRecentlyUpdated = false;

			if (anime != null)
			{
				TimeSpan ts = DateTime.Now - anime.DateTimeUpdated;
				if (ts.TotalHours < 4) animeRecentlyUpdated = true;
			}

			// even if we are missing episode info, don't get data  more than once every 4 hours
			// this is to prevent banning
			if (missingEpisodes && !animeRecentlyUpdated)
			{
				logger.Debug("Getting Anime record from AniDB....");

				// try using the cache first
				using (var session = JMMService.SessionFactory.OpenSession())
				{
					anime = JMMService.AnidbProcessor.GetAnimeInfoHTTPFromCache(session, animeID, ServerSettings.AutoGroupSeries);
				}

				// if not in cache try from AniDB
				if (anime == null)
					anime = JMMService.AnidbProcessor.GetAnimeInfoHTTP(animeID, true, ServerSettings.AutoGroupSeries);
			}

			// create the group/series/episode records if needed
			AnimeSeries ser = null;
			if (anime != null)
			{
				logger.Debug("Creating groups, series and episodes....");
				// check if there is an AnimeSeries Record associated with this AnimeID
				ser = repSeries.GetByAnimeID(animeID);
				if (ser == null)
				{
					// create a new AnimeSeries record
					ser = anime.CreateAnimeSeriesAndGroup();
				}

				
				ser.CreateAnimeEpisodes();

				// check if we have any group status data for this associated anime
				// if not we will download it now
				AniDB_GroupStatusRepository repStatus = new AniDB_GroupStatusRepository();
				if (repStatus.GetByAnimeID(anime.AnimeID).Count == 0)
				{
					CommandRequest_GetReleaseGroupStatus cmdStatus = new CommandRequest_GetReleaseGroupStatus(anime.AnimeID, false);
					cmdStatus.Save();
				}

				// update stats
				ser.EpisodeAddedDate = DateTime.Now;
				repSeries.Save(ser);

				AnimeGroupRepository repGroups = new AnimeGroupRepository();
				foreach (AnimeGroup grp in ser.AllGroupsAbove)
				{
					grp.EpisodeAddedDate = DateTime.Now;
					repGroups.Save(grp);
				}
			}

			vidLocal.RenameIfRequired();
			vidLocal.MoveFileIfRequired();
			

			// update stats for groups and series
			if (ser != null)
			{
				// update all the groups above this series in the heirarchy
				ser.UpdateStats(true, true, true);
				StatsCache.Instance.UpdateUsingSeries(ser.AnimeSeriesID);
			}
			

			// Add this file to the users list
			if (ServerSettings.AniDB_MyList_AddFiles)
			{
				CommandRequest_AddFileToMyList cmd = new CommandRequest_AddFileToMyList(vidLocal.ED2KHash);
				cmd.Save();
			}

			// lets also try adding to the users trakt collecion by sync'ing the series
			if (ser != null)
			{
				CommandRequest_TraktSyncCollectionSeries cmdTrakt = new CommandRequest_TraktSyncCollectionSeries(ser.AnimeSeriesID, ser.GetAnime().MainTitle);
				cmdTrakt.Save();
			}

			// sync the series on MAL
			if (ser != null)
			{
				CommandRequest_MALUpdatedWatchedStatus cmdMAL = new CommandRequest_MALUpdatedWatchedStatus(ser.AniDB_ID);
				cmdMAL.Save();
			}
		}
コード例 #16
0
        public List<Contract_AnimeEpisode> GetEpisodesForSeriesOld(int animeSeriesID)
        {
            List<Contract_AnimeEpisode> eps = new List<Contract_AnimeEpisode>();
            try
            {

                DateTime start = DateTime.Now;
                AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
                AnimeSeriesRepository repAnimeSer = new AnimeSeriesRepository();
                CrossRef_File_EpisodeRepository repCrossRefs = new CrossRef_File_EpisodeRepository();

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

                List<AnimeEpisode> epList = repEps.GetBySeriesID(animeSeriesID);

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

                List<CrossRef_File_Episode> crossRefList = repCrossRefs.GetByAnimeID(series.AniDB_ID);

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

                start = DateTime.Now;
                foreach (AnimeEpisode ep in epList)
                {
                    List<CrossRef_File_Episode> xrefs = new List<CrossRef_File_Episode>();
                    foreach (CrossRef_File_Episode xref in crossRefList)
                    {
                        if (ep.AniDB_EpisodeID == xref.EpisodeID)
                            xrefs.Add(xref);
                    }

                    if (dictAniEps.ContainsKey(ep.AniDB_EpisodeID))
                        eps.Add(ep.ToContractOld(dictAniEps[ep.AniDB_EpisodeID]));
                }

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

            return eps;
        }
コード例 #17
0
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_MALDownloadStatusFromMAL");

            try
            {
                if (string.IsNullOrEmpty(ServerSettings.MAL_Username) || string.IsNullOrEmpty(ServerSettings.MAL_Password))
                    return;

                // find the latest eps to update
                AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();

                myanimelist mal = MALHelper.GetMALAnimeList();
                if (mal == null) return;
                if (mal.anime == null) return;

                CrossRef_AniDB_MALRepository repCrossRef = new CrossRef_AniDB_MALRepository();
                AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository();
                AnimeEpisodeRepository repEp = new AnimeEpisodeRepository();

                // find the anidb user
                JMMUserRepository repUsers = new JMMUserRepository();
                List<JMMUser> aniDBUsers = repUsers.GetAniDBUsers();
                if (aniDBUsers.Count == 0) return;

                JMMUser user = aniDBUsers[0];

                foreach (myanimelistAnime malAnime in mal.anime)
                {
                    // look up the anime
                    CrossRef_AniDB_MAL xref = repCrossRef.GetByMALID(malAnime.series_animedb_id);
                    if (xref == null) continue;

                    if (malAnime.series_animedb_id == 8107 || malAnime.series_animedb_id == 10737)
                    {
                        Console.Write("");
                    }

                    // check if this anime has any other links
                    List<CrossRef_AniDB_MAL> allXrefs = repCrossRef.GetByAnimeID(xref.AnimeID);
                    if (allXrefs.Count == 0) continue;

                    // find the range of watched episodes that this applies to
                    int startEpNumber = xref.StartEpisodeNumber;
                    int endEpNumber = GetUpperEpisodeLimit(allXrefs, xref);

                    List<AniDB_Episode> aniEps = repAniEps.GetByAnimeID(xref.AnimeID);
                    foreach (AniDB_Episode aniep in aniEps)
                    {
                        if (aniep.EpisodeType != xref.StartEpisodeType) continue;

                        AnimeEpisode ep = repEp.GetByAniDBEpisodeID(aniep.EpisodeID);
                        if (ep == null) continue;

                        int adjustedWatchedEps = malAnime.my_watched_episodes + xref.StartEpisodeNumber - 1;
                        int epNum = aniep.EpisodeNumber;

                        if (epNum < startEpNumber || epNum > endEpNumber) continue;

                        AnimeEpisode_User usrRec = ep.GetUserRecord(user.JMMUserID);

                        if (epNum <= adjustedWatchedEps)
                        {
                            // update if the user doesn't have a record (means not watched)
                            // or it is currently un-watched
                            bool update = false;
                            if (usrRec == null) update = true;
                            else
                            {
                                if (!usrRec.WatchedDate.HasValue) update = true;
                            }

                            if (update) ep.ToggleWatchedStatus(true, true, DateTime.Now, user.JMMUserID, false);
                        }
                        else
                        {
                            bool update = false;
                            if (usrRec != null)
                            {
                                if (usrRec.WatchedDate.HasValue) update = true;
                            }

                            if (update) ep.ToggleWatchedStatus(false, true, DateTime.Now, user.JMMUserID, false);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error processing CommandRequest_MALDownloadStatusFromMAL: {0}", ex.ToString());
                return;
            }
        }
コード例 #18
0
ファイル: AniDBHelper.cs プロジェクト: maz0r/jmmserver
		public GroupStatusCollection GetReleaseGroupStatusUDP(int animeID)
		{
			if (!Login()) return null;

			enHelperActivityType ev = enHelperActivityType.NoSuchCreator;
			AniDBCommand_GetGroupStatus getCmd = null;
			lock (lockAniDBConnections)
			{
				Pause();

				getCmd = new AniDBCommand_GetGroupStatus();
				getCmd.Init(animeID);
				SetWaitingOnResponse(true);
				ev = getCmd.Process(ref soUdp, ref remoteIpEndPoint, curSessionID, new UnicodeEncoding(true, false));
				SetWaitingOnResponse(false);
			}

			if (ev == enHelperActivityType.GotGroupStatus && getCmd.GrpStatusCollection != null)
			{
				// delete existing records
				AniDB_GroupStatusRepository repGrpStat = new AniDB_GroupStatusRepository();
				AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
				AniDB_EpisodeRepository repAniEp = new AniDB_EpisodeRepository();
				AnimeSeriesRepository repSeries = new AnimeSeriesRepository();

				repGrpStat.DeleteForAnime(animeID);

				// save the records
				foreach (Raw_AniDB_GroupStatus raw in getCmd.GrpStatusCollection.Groups)
				{
					AniDB_GroupStatus grpstat = new AniDB_GroupStatus(raw);
					repGrpStat.Save(grpstat);
				}

				// updated cached stats
				// we don't do it in the save method as it would be too many unecessary updates
				logger.Trace("Updating group stats by anime from GetReleaseGroupStatusUDP: {0}", animeID);
				StatsCache.Instance.UpdateUsingAnime(animeID);
				
				if (getCmd.GrpStatusCollection.LatestEpisodeNumber > 0)
				{
					// update the anime with a record of the latest subbed episode
					AniDB_Anime anime = repAnime.GetByAnimeID(animeID);
					if (anime != null)
					{
						anime.LatestEpisodeNumber = getCmd.GrpStatusCollection.LatestEpisodeNumber;
						repAnime.Save(anime);

						// check if we have this episode in the database
						// if not get it now by updating the anime record
						List<AniDB_Episode> eps = repAniEp.GetByAnimeIDAndEpisodeNumber(animeID, getCmd.GrpStatusCollection.LatestEpisodeNumber);
						if (eps.Count == 0)
						{
							CommandRequest_GetAnimeHTTP cr_anime = new CommandRequest_GetAnimeHTTP(animeID, true, false);
							cr_anime.Save();
						}

						// update the missing episode stats on groups and children
						AnimeSeries series = repSeries.GetByAnimeID(animeID);
						if (series != null)
						{
                            series.QueueUpdateStats();
							//series.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true, true, true);
						}

					}
				}
			}

			return getCmd.GrpStatusCollection;
		}