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; } }
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); } }
/// <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; } }
public Contract_AnimeEpisode GetEpisodeByAniDBEpisodeID(int episodeID, int userID) { try { AnimeEpisodeRepository repEps = new AnimeEpisodeRepository(); AnimeEpisode ep = repEps.GetByAniDBEpisodeID(episodeID); if (ep == null) return null; return ep.ToContract(userID); } catch (Exception ex) { logger.ErrorException(ex.ToString(), ex); return null; } }
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); }
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; }