Ejemplo n.º 1
0
		public bool AllowedSeries(AnimeSeries ser)
		{
			using (var session = JMMService.SessionFactory.OpenSession())
			{
				return AllowedSeries(session, ser);
			}
		}
        public Contract_AniDB_Anime_Relation ToContract(AniDB_Anime anime, AnimeSeries ser, int userID)
        {
            Contract_AniDB_Anime_Relation contract = new Contract_AniDB_Anime_Relation();

            contract.AniDB_Anime_RelationID = this.AniDB_Anime_RelationID;
            contract.AnimeID = this.AnimeID;
            contract.RelationType = this.RelationType;
            contract.RelatedAnimeID = this.RelatedAnimeID;

            contract.AniDB_Anime = anime?.Contract?.AniDBAnime;
            contract.AnimeSeries = ser?.GetUserContract(userID);
            return contract;
        }
        public Contract_AniDB_Anime_Similar ToContract(AniDB_Anime anime, AnimeSeries ser, int userID)
        {
            Contract_AniDB_Anime_Similar contract = new Contract_AniDB_Anime_Similar();

            contract.AniDB_Anime_SimilarID = this.AniDB_Anime_SimilarID;
            contract.AnimeID = this.AnimeID;
            contract.SimilarAnimeID = this.SimilarAnimeID;
            contract.Approval = this.Approval;
            contract.Total = this.Total;
            contract.AniDB_Anime = anime?.Contract?.AniDBAnime;
            contract.AnimeSeries = ser?.GetUserContract(userID);
            return contract;
        }
Ejemplo n.º 4
0
        public void Save(AnimeSeries obj, bool updateStats)
        {
            bool       updateStatsCache = false;
            AnimeGroup oldGroup         = null;

            if (obj.AnimeSeriesID == 0)
            {
                updateStatsCache = true;                                     // a new series
            }
            else
            {
                // get the old version from the DB
                AnimeSeries oldSeries = GetByID(obj.AnimeSeriesID);
                if (oldSeries != null)
                {
                    // means we are moving series to a different group
                    if (oldSeries.AnimeGroupID != obj.AnimeGroupID)
                    {
                        AnimeGroupRepository repGroups = new AnimeGroupRepository();
                        oldGroup         = repGroups.GetByID(oldSeries.AnimeGroupID);
                        updateStatsCache = true;
                    }
                }
            }


            using (var session = JMMService.SessionFactory.OpenSession())
            {
                // populate the database
                using (var transaction = session.BeginTransaction())
                {
                    session.SaveOrUpdate(obj);
                    transaction.Commit();
                }
            }

            if (updateStats)
            {
                if (updateStatsCache)
                {
                    logger.Trace("Updating group stats by series from AnimeSeriesRepository.Save: {0}", obj.AnimeSeriesID);
                    StatsCache.Instance.UpdateUsingSeries(obj.AnimeSeriesID);
                }

                if (oldGroup != null)
                {
                    logger.Trace("Updating group stats by group from AnimeSeriesRepository.Save: {0}", oldGroup.AnimeGroupID);
                    StatsCache.Instance.UpdateUsingGroup(oldGroup.AnimeGroupID);
                }
            }
        }
Ejemplo n.º 5
0
        public async Task <ActionResult> Details(int id)
        {
            AnimeSeries animeSeries = await _context.AnimeSeries.Include(se => se.SeasonsEpisodes).Include(pic => pic.Picture).FirstOrDefaultAsync(s => s.Id == id);

            if (animeSeries == null)
            {
                return(Ok(new AnimeResponse {
                    Success = false, Error = "Invalid Anime ID"
                }));
            }
            return(Ok(new AnimeResponse {
                Success = true, AnimeSeries = animeSeries
            }));
        }
 private void UpdatePlexKodiContracts(AnimeSeries_User ugrp)
 {
     using (var session = JMMService.SessionFactory.OpenSession())
     {
         AnimeSeriesRepository repo = new AnimeSeriesRepository();
         AnimeSeries           ser  = repo.GetByID(ugrp.AnimeSeriesID);
         Contract_AnimeSeries  con  = ser?.GetUserContract(ugrp.JMMUserID);
         if (con == null)
         {
             return;
         }
         ugrp.PlexContract = Helper.GenerateFromSeries(con, ser, ser.GetAnime(session), ugrp.JMMUserID);
     }
 }
Ejemplo n.º 7
0
        public static void CleanUpMemory()
        {
            AniDB_Anime.GetAll().ForEach(a => a.CollectContractMemory());
            VideoLocal.GetAll().ForEach(a => a.CollectContractMemory());
            AnimeEpisode.GetAll().ForEach(a => a.CollectContractMemory());
            AnimeEpisode_User.GetAll().ForEach(a => a.CollectContractMemory());
            AnimeSeries.GetAll().ForEach(a => a.CollectContractMemory());
            AnimeSeries_User.GetAll().ForEach(a => a.CollectContractMemory());
            AnimeGroup.GetAll().ForEach(a => a.CollectContractMemory());
            AnimeGroup_User.GetAll().ForEach(a => a.CollectContractMemory());

            GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
            GC.Collect();
        }
Ejemplo n.º 8
0
        private TraktEpisodeSync CreateSyncData(AnimeSeries series, List <AnimeEpisode> episodes)
        {
            if (series == null || series.TvDB_ID == null)
            {
                return(null);
            }

            // set series properties for episodes
            TraktEpisodeSync traktSync = new TraktEpisodeSync
            {
                Password = TraktSettings.Password,
                UserName = TraktSettings.Username,
                SeriesID = series.TvDB_ID.ToString(),
                Year     = GetStartYear(series),
                Title    = series.SeriesName
            };

            // get list of episodes for series
            List <TraktEpisodeSync.Episode> epList = new List <TraktEpisodeSync.Episode>();

            foreach (AnimeEpisode episode in episodes.Where(e => e.Series.TvDB_ID == series.TvDB_ID))
            {
                TraktEpisodeSync.Episode ep = new TraktEpisodeSync.Episode();

                string seriesid   = series.TvDB_ID.ToString();
                int    seasonidx  = 0;
                int    episodeidx = 0;

                if (GetTVDBEpisodeInfo(episode, out seriesid, out seasonidx, out episodeidx))
                {
                    ep.SeasonIndex  = seasonidx.ToString();
                    ep.EpisodeIndex = episodeidx.ToString();
                    epList.Add(ep);
                }
                else
                {
                    TraktLogger.Info("Unable to find match for episode: '{0} | airDate: {1}'", episode.ToString(), episode.AniDB_Episode.AirDateAsDate.ToString("yyyy-MM-dd"));
                }
            }

            if (epList.Count == 0)
            {
                TraktLogger.Warning("Unable to find any matching TVDb episodes for series '{0}', confirm Absolute Order and/or Episode Names and/or AirDates for episodes are correct on http://theTVDb.com and your database.", series.SeriesName);
                return(null);
            }

            traktSync.EpisodeList = epList;
            return(traktSync);
        }
Ejemplo n.º 9
0
		/// <summary>
		/// Returns whether a user is allowed to view this series
		/// </summary>
		/// <param name="ser"></param>
		/// <returns></returns>
		public bool AllowedSeries(ISession session, AnimeSeries ser)
		{
			if (string.IsNullOrEmpty(HideCategories)) return true;

			string[] cats = HideCategories.ToLower().Split(',');
			string[] animeCats = ser.GetAnime(session).AllCategories.ToLower().Split('|');
			foreach (string cat in cats)
			{
				if (!string.IsNullOrEmpty(cat) && animeCats.Contains(cat))
				{
					return false;
				}
			}

			return true;
		}
Ejemplo n.º 10
0
 private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
 {
     comboBox1.Items.Clear();
     if (listBox1.SelectedIndex >= 0)
     {
         SelectedSeries = Searched[listBox1.SelectedIndex];
         long size = 0;
         foreach (AnimeSeason s in SelectedSeries.Seasons)
         {
             size += s.Size;
             comboBox1.Items.Add(s.SeasonPath.Name);
         }
         label3.Text             = $"Name:{SelectedSeries.Name}\r\nSeasons:{SelectedSeries.Seasons.Count}\r\nSize: {Utils.BytesToString(size)}";
         comboBox1.SelectedIndex = 0;
     }
 }
Ejemplo n.º 11
0
		public void Save(AnimeSeries obj, bool updateStats)
		{
			bool updateStatsCache = false;
			AnimeGroup oldGroup = null;
			if (obj.AnimeSeriesID == 0) updateStatsCache = true; // a new series
			else
			{
				// get the old version from the DB
				AnimeSeries oldSeries = GetByID(obj.AnimeSeriesID);
				if (oldSeries != null)
				{
					// means we are moving series to a different group
					if (oldSeries.AnimeGroupID != obj.AnimeGroupID)
					{
						AnimeGroupRepository repGroups = new AnimeGroupRepository();
						oldGroup = repGroups.GetByID(oldSeries.AnimeGroupID);
						updateStatsCache = true;
					}
				}
			}


			using (var session = JMMService.SessionFactory.OpenSession())
			{
				// populate the database
				using (var transaction = session.BeginTransaction())
				{
					session.SaveOrUpdate(obj);
					transaction.Commit();
				}
			}

			if (updateStats)
			{
				if (updateStatsCache)
				{
					logger.Trace("Updating group stats by series from AnimeSeriesRepository.Save: {0}", obj.AnimeSeriesID);
					StatsCache.Instance.UpdateUsingSeries(obj.AnimeSeriesID);
				}

				if (oldGroup != null)
				{
					logger.Trace("Updating group stats by group from AnimeSeriesRepository.Save: {0}", oldGroup.AnimeGroupID);
					StatsCache.Instance.UpdateUsingGroup(oldGroup.AnimeGroupID);
				}
			}
		}
        private void AnimeSeriesContainerControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            // check the type of content
            try
            {
                if (DataContext == null)
                {
                    return;
                }

                if (DataContext.GetType().Equals(typeof(VM_AnimeSeries_User)))
                {
                    VM_AnimeSeries_User ser = DataContext as VM_AnimeSeries_User;
                    if (AppSettings.DisplaySeriesSimple)
                    {
                        AnimeSeriesSimplifiedControl ctrl = new AnimeSeriesSimplifiedControl();
                        ctrl.DataContext = ser;
                        DataContext      = ctrl;
                    }
                    else
                    {
                        AnimeSeries ctrl = new AnimeSeries();
                        ctrl.DataContext = ser;
                        DataContext      = ctrl;
                    }
                }

                if (DataContext.GetType().Equals(typeof(AnimeSeriesSimplifiedControl)))
                {
                    //Console.WriteLine("simple");
                    AnimeSeriesSimplifiedControl ctrl = DataContext as AnimeSeriesSimplifiedControl;

                    ctrl.btnBack.Visibility       = Visibility.Collapsed;
                    ctrl.btnSwitchView.Visibility = Visibility.Visible;
                }

                if (DataContext.GetType().Equals(typeof(AnimeSeries)))
                {
                    Console.WriteLine("full");
                }
            }
            catch (Exception ex)
            {
                LogManager.GetCurrentClassLogger().Error(ex);
            }
        }
Ejemplo n.º 13
0
        public async Task CreateAsync_WithValidObject()
        {
            var testTitle = "fefckejfke";

            var test = new AnimeSeries()
            {
                DateCreatedAt = DateTime.UtcNow,
                Description   = "wgehwajew",
                ImageUrl      = DbConstants.Default_Avatar_Url,
                Title         = testTitle,
            };

            await this.AnimeService.CreateAsync(test);

            var anime = this.Context.AnimeSeries.FirstOrDefault(p => p.Title == testTitle);

            Assert.IsNotNull(anime);
        }
Ejemplo n.º 14
0
        void EpisodeDetail_Loaded(object sender, RoutedEventArgs e)
        {
            DependencyObject parentObject = VisualTreeHelper.GetParent(this);

            while (parentObject != null)
            {
                parentObject = VisualTreeHelper.GetParent(parentObject);
                AnimeSeries seriesControl = parentObject as AnimeSeries;
                if (seriesControl != null)
                {
                    SetBinding(WidthProperty, new Binding("ActualWidth")
                    {
                        Source = seriesControl, Converter = ArithmeticConverter.Instance, ConverterParameter = 40, IsAsync = true
                    });
                    return;
                }
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Gets or creates an <see cref="AnimeGroup"/> for the specified series.
        /// </summary>
        /// <param name="session">The NHibernate session.</param>
        /// <param name="series">The series for which the group is to be created/retrieved (Must be initialised first).</param>
        /// <returns>The <see cref="AnimeGroup"/> to use for the specified series.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="session"/> or <paramref name="series"/> is <c>null</c>.</exception>
        public AnimeGroup GetOrCreateSingleGroupForSeries(ISessionWrapper session, AnimeSeries series)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            if (series == null)
            {
                throw new ArgumentNullException(nameof(series));
            }

            AnimeGroup animeGroup = null;

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

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

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

            return(animeGroup);
        }
Ejemplo n.º 16
0
        public static bool PopulateVideo(Video l, VideoLocal v, JMMType type, int userid)
        {
            PopulateVideoEpisodeFromVideoLocal(l, v, type);
            List <AnimeEpisode> eps = v.GetAnimeEpisodes();

            if (eps.Count > 0)
            {
                PopulateVideoEpisodeFromAnimeEpisode(l, eps[0], userid);
                AnimeSeries series = eps[0].GetAnimeSeries();
                if (series != null)
                {
                    Contract_AnimeSeries cseries = series.ToContract(series.GetUserRecord(userid), true);
                    Video       nv  = FromSerie(cseries, userid);
                    AniDB_Anime ani = series.GetAnime();
                    return(PopulateVideoEpisodeFromAnime(l, ani, nv));
                }
            }
            return(false);
        }
        private void AnimeSeriesContainerControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            // check the type of content
            try
            {
                if (this.DataContext == null)
                {
                    return;
                }

                if (this.DataContext.GetType().Equals(typeof(AnimeSeriesVM)))
                {
                    AnimeSeriesVM ser = this.DataContext as AnimeSeriesVM;
                    if (AppSettings.DisplaySeriesSimple)
                    {
                        AnimeSeriesSimplifiedControl ctrl = new AnimeSeriesSimplifiedControl();
                        ctrl.DataContext = ser;
                        this.DataContext = ctrl;
                    }
                    else
                    {
                        AnimeSeries ctrl = new AnimeSeries();
                        ctrl.DataContext = ser;
                        this.DataContext = ctrl;
                    }
                }

                if (this.DataContext.GetType().Equals(typeof(AnimeSeriesSimplifiedControl)))
                {
                    //Console.WriteLine("simple");
                    AnimeSeriesSimplifiedControl ctrl = this.DataContext as AnimeSeriesSimplifiedControl;

                    ctrl.btnBack.Visibility       = Visibility.Collapsed;
                    ctrl.btnSwitchView.Visibility = Visibility.Visible;
                }

                if (this.DataContext.GetType().Equals(typeof(AnimeSeries)))
                {
                    Console.WriteLine("full");
                }
            }
            catch { }
        }
Ejemplo n.º 18
0
		public Contract_AniDB_Anime_Relation ToContract(AniDB_Anime anime, AnimeSeries ser, int userID)
		{
			Contract_AniDB_Anime_Relation contract = new Contract_AniDB_Anime_Relation();

			contract.AniDB_Anime_RelationID = this.AniDB_Anime_RelationID;
			contract.AnimeID = this.AnimeID;
			contract.RelationType = this.RelationType;
			contract.RelatedAnimeID = this.RelatedAnimeID;

			contract.AniDB_Anime = null;
			if (anime != null)
				contract.AniDB_Anime = anime.ToContract();

			contract.AnimeSeries = null;
			if (ser != null)
				contract.AnimeSeries = ser.ToContract(ser.GetUserRecord(userID));

			return contract;
		}
Ejemplo n.º 19
0
        void EpisodeDetail_Loaded(object sender, RoutedEventArgs e)
        {
            DependencyObject parentObject = VisualTreeHelper.GetParent(this);

            while (parentObject != null)
            {
                parentObject = VisualTreeHelper.GetParent(parentObject);
                AnimeSeries seriesControl = parentObject as AnimeSeries;
                if (seriesControl != null)
                {
                    double gridWidth = seriesControl.ActualWidth - 40;
                    if (gridWidth > 0)
                    {
                        epDetailMainGrid.Width = gridWidth;
                    }
                    return;
                }
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Creates <see cref="AnimeGroup"/> that contain <see cref="AnimeSeries"/> that appear to be related.
        /// </summary>
        /// <remarks>
        /// This method assumes that there are no active transactions on the specified <paramref name="session"/>.
        /// </remarks>
        /// <param name="session">The NHibernate session.</param>
        /// <param name="seriesList">The list of <see cref="AnimeSeries"/> to create groups for.</param>
        /// <returns>A sequence of the created <see cref="AnimeGroup"/>s.</returns>
        private IEnumerable <AnimeGroup> AutoCreateGroupsWithRelatedSeries(ISessionWrapper session, IReadOnlyCollection <AnimeSeries> seriesList)
        {
            _log.Info("Auto-generating AnimeGroups for {0} AnimeSeries based on aniDB relationships", seriesList.Count);

            DateTime now           = DateTime.Now;
            var      grpCalculator = AutoAnimeGroupCalculator.CreateFromServerSettings(session);

            _log.Info("The following exclusions will be applied when generating the groups: " + grpCalculator.Exclusions);

            // Group all of the specified series into their respective groups (keyed by the groups main anime ID)
            var seriesByGroup     = seriesList.ToLookup(s => grpCalculator.GetGroupAnimeId(s.AniDB_ID));
            var newGroupsToSeries = new List <Tuple <AnimeGroup, IReadOnlyCollection <AnimeSeries> > >(seriesList.Count);

            foreach (var groupAndSeries in seriesByGroup)
            {
                int         mainAnimeId = groupAndSeries.Key;
                AnimeSeries mainSeries  = groupAndSeries.FirstOrDefault(series => series.AniDB_ID == mainAnimeId);
                AnimeGroup  animeGroup  = CreateAnimeGroup(session, mainSeries, mainAnimeId, now);

                newGroupsToSeries.Add(new Tuple <AnimeGroup, IReadOnlyCollection <AnimeSeries> >(animeGroup, groupAndSeries.AsReadOnlyCollection()));
            }

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

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

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

            return(newGroupsToSeries.Select(gts => gts.Item1));
        }
Ejemplo n.º 21
0
		public Contract_AniDB_Anime_Similar ToContract(AniDB_Anime anime, AnimeSeries ser, int userID)
		{
			Contract_AniDB_Anime_Similar contract = new Contract_AniDB_Anime_Similar();

			contract.AniDB_Anime_SimilarID = this.AniDB_Anime_SimilarID;
			contract.AnimeID = this.AnimeID;
			contract.SimilarAnimeID = this.SimilarAnimeID;
			contract.Approval = this.Approval;
			contract.Total = this.Total;

			contract.AniDB_Anime = null;
			if (anime != null)
				contract.AniDB_Anime = anime.ToContract();

			contract.AnimeSeries = null;
			if (ser != null)
				contract.AnimeSeries = ser.ToContract(ser.GetUserRecord(userID));

			return contract;
		}
Ejemplo n.º 22
0
        private void UpdateAnimeSeriesContractsAndSave(ISessionWrapper session, IReadOnlyCollection <AnimeSeries> series)
        {
            _log.Info("Updating contracts for AnimeSeries");

            // Update batches of AnimeSeries contracts in parallel. Each parallel branch requires it's own session since NHibernate sessions aren't thread safe.
            // The reason we're doing this in parallel is because updating contacts does a reasonable amount of work (including LZ4 compression)
            Parallel.ForEach(series.Batch(DefaultBatchSize), new ParallelOptions {
                MaxDegreeOfParallelism = 4
            },
                             localInit: () => DatabaseFactory.SessionFactory.OpenStatelessSession(),
                             body: (seriesBatch, state, localSession) =>
            {
                AnimeSeries.BatchUpdateContracts(localSession.Wrap(), seriesBatch);
                return(localSession);
            },
                             localFinally: localSession => { localSession.Dispose(); });

            _animeSeriesRepo.UpdateBatch(session, series);
            _log.Info("AnimeSeries contracts have been updated");
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Syncronize our collection on trakt
        /// </summary>
        /// <param name="episodes">local tvseries dbepisode list</param>
        /// <param name="mode">trakt sync mode</param>
        private void SyncLibrary(List <FileLocal> episodes, TraktSyncModes mode)
        {
            if (episodes.Count == 0)
            {
                return;
            }

            // get unique series ids
            var uniqueSeries = (from s in episodes where (s.AniDB_File != null && s.AniDB_File.AnimeSeries.TvDB_ID > 0) select s.AniDB_File.AnimeSeries.TvDB_ID).Distinct().ToList();

            if (uniqueSeries.Count == 0)
            {
                TraktLogger.Info("TVDb info not available for series, can not sync '{0}' with trakt.", mode.ToString());
            }

            // go over each series, can only send one series at a time
            foreach (int seriesid in uniqueSeries)
            {
                // There should only be one series
                List <AnimeSeries> series = AnimeSeries.GetSeriesWithSpecificTvDB(seriesid);
                if (series == null)
                {
                    continue;
                }

                TraktLogger.Info("Synchronizing '{0}' episodes for series '{1}'.", mode.ToString(), series[0].ToString());

                // upload to trakt
                TraktEpisodeSync episodeSync = CreateSyncData(series[0], episodes);
                if (episodeSync != null)
                {
                    TraktResponse response = TraktAPI.TraktAPI.SyncEpisodeLibrary(episodeSync, mode);

                    // check for any error and log result
                    TraktAPI.TraktAPI.LogTraktResponse(response);

                    // wait a short period before uploading another series
                    Thread.Sleep(2000);
                }
            }
        }
Ejemplo n.º 24
0
        public static Video GenerateFromSeries(Contract_AnimeSeries cserie, AnimeSeries ser, AniDB_Anime anidb,
                                               int userid)
        {
            Video v = new Directory();
            Dictionary <AnimeEpisode, Contract_AnimeEpisode> episodes = ser.GetAnimeEpisodes()
                                                                        .ToDictionary(a => a, a => a.GetUserContract(userid));

            episodes = episodes.Where(a => a.Value == null || a.Value.LocalFileCount > 0)
                       .ToDictionary(a => a.Key, a => a.Value);
            FillSerie(v, ser, episodes, anidb, cserie, userid);
            if (ser.GetAnimeNumberOfEpisodeTypes() > 1)
            {
                v.Type = "show";
            }
            else if ((cserie.AniDBAnime.AniDBAnime.AnimeType == (int)enAnimeType.Movie) ||
                     (cserie.AniDBAnime.AniDBAnime.AnimeType == (int)enAnimeType.OVA))
            {
                v = MayReplaceVideo(v, ser, cserie, userid);
            }
            return(v);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Gets or creates an <see cref="AnimeGroup"/> for the specified series.
        /// </summary>
        /// <param name="session">The NHibernate session.</param>
        /// <param name="series">The series for which the group is to be created/retrieved (Must be initialised first).</param>
        /// <returns>The <see cref="AnimeGroup"/> to use for the specified series.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="session"/> or <paramref name="series"/> is <c>null</c>.</exception>
        public AnimeGroup GetOrCreateSingleGroupForSeries(ISessionWrapper session, AnimeSeries series)
        {
            if (session == null)
                throw new ArgumentNullException(nameof(session));
            if (series == null)
                throw new ArgumentNullException(nameof(series));

            AnimeGroup animeGroup = null;

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

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

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

            return animeGroup;
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Get Episode Info for selected object
        /// </summary>
        public static bool GetEpisodeInfo(Object obj, out string title, out string tvdb, out string seasonidx, out string episodeidx)
        {
            title      = string.Empty;
            tvdb       = string.Empty;
            seasonidx  = string.Empty;
            episodeidx = string.Empty;

            if (obj == null)
            {
                return(false);
            }

            AnimeEpisode episode = obj as AnimeEpisode;

            if (episode == null)
            {
                return(false);
            }

            AnimeSeries series = episode.Series;

            if (series == null)
            {
                return(false);
            }

            title = series.SeriesName;
            tvdb  = series.TvDB_ID.HasValue ? series.TvDB_ID.Value.ToString() : null;
            int iSeasonidx  = 0;
            int iEpisodeidx = 0;

            if (GetTVDBEpisodeInfo(episode, out tvdb, out iSeasonidx, out iEpisodeidx))
            {
                seasonidx  = iSeasonidx.ToString();
                episodeidx = iEpisodeidx.ToString();
                return(true);
            }
            return(false);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Get Series Info for selected object
        /// </summary>
        public static bool GetSeriesInfo(Object obj, out string title, out string tvdb)
        {
            title = string.Empty;
            tvdb  = string.Empty;

            if (obj == null)
            {
                return(false);
            }

            AnimeSeries series = obj as AnimeSeries;

            if (series == null)
            {
                return(false);
            }

            title = series.SeriesName;
            tvdb  = series.TvDB_ID.HasValue ? series.TvDB_ID.Value.ToString() : null;

            return(true);
        }
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_TraktSyncCollectionSeries");

            try
            {
                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                AnimeSeries           series    = repSeries.GetByID(AnimeSeriesID);
                if (series == null)
                {
                    logger.Error("Could not find anime series: {0}", AnimeSeriesID);
                    return;
                }

                TraktTVHelper.SyncCollectionToTrakt_Series(series);
            }
            catch (Exception ex)
            {
                logger.Error("Error processing CommandRequest_TraktSyncCollectionSeries: {0}", ex.ToString());
                return;
            }
        }
Ejemplo n.º 29
0
        private TraktRateSeries CreateSeriesRateData(AnimeSeries series, string rateValue)
        {
            if (series == null || series.TvDB_ID == null)
            {
                return(null);
            }

            string rating = Convert.ToInt32(rateValue).ToString();

            TraktRateSeries seriesData = new TraktRateSeries()
            {
                Rating   = rating,
                SeriesID = series.TvDB_ID.ToString(),
                Year     = GetStartYear(series),
                Title    = series.TvDB_Name,
                UserName = TraktSettings.Username,
                Password = TraktSettings.Password,
            };

            TraktLogger.Info("Rating '{0}' as '{1}'", series.TvDB_Name, rating.ToString());
            return(seriesData);
        }
Ejemplo n.º 30
0
        public void Delete(int id)
        {
            int oldGroupID = 0;

            using (var session = JMMService.SessionFactory.OpenSession())
            {
                // populate the database
                using (var transaction = session.BeginTransaction())
                {
                    AnimeSeries cr = GetByID(id);
                    if (cr != null)
                    {
                        Cache.Remove(cr);
                        // delete user records
                        AnimeSeries_UserRepository repUsers = new AnimeSeries_UserRepository();
                        foreach (AnimeSeries_User grpUser in repUsers.GetBySeriesID(id))
                        {
                            repUsers.Delete(grpUser.AnimeSeries_UserID);
                        }
                        Changes.Remove(cr.AnimeSeriesID);
                        oldGroupID = cr.AnimeGroupID;
                        session.Delete(cr);
                        transaction.Commit();
                        cr.DeleteFromFilters();
                    }
                }
            }
            if (oldGroupID > 0)
            {
                logger.Trace("Updating group stats by group from AnimeSeriesRepository.Delete: {0}", oldGroupID);
                AnimeGroupRepository repGroups = new AnimeGroupRepository();
                AnimeGroup           oldGroup  = repGroups.GetByID(oldGroupID);
                if (oldGroup != null)
                {
                    repGroups.Save(oldGroup, true, true);
                }
            }
        }
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_MALUpdatedWatchedStatus: {0}", AnimeID);

            try
            {
                // find the latest eps to update
                AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
                AniDB_Anime           anime    = repAnime.GetByAnimeID(AnimeID);
                if (anime == null)
                {
                    return;
                }

                List <CrossRef_AniDB_MAL> crossRefs = anime.GetCrossRefMAL();
                if (crossRefs == null || crossRefs.Count == 0)
                {
                    return;
                }

                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                AnimeSeries           ser       = repSeries.GetByAnimeID(AnimeID);
                if (ser == null)
                {
                    return;
                }

                MALHelper.UpdateMALSeries(ser);
            }
            catch (Exception ex)
            {
                logger.Error("Error processing CommandRequest_MALUpdatedWatchedStatus: {0} - {1}", AnimeID,
                             ex.ToString());
                return;
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Creates an <see cref="AnimeGroup"/> instance.
        /// </summary>
        /// <remarks>
        /// This method only creates an <see cref="AnimeGroup"/> instance. It does NOT save it to the database.
        /// </remarks>
        /// <param name="session">The NHibernate session.</param>
        /// <param name="mainSeries">The <see cref="AnimeSeries"/> whose name will represent the group (Optional. Pass <c>null</c> if not available).</param>
        /// <param name="mainAnimeId">The ID of the anime whose name will represent the group if <paramref name="mainSeries"/> is <c>null</c>.</param>
        /// <param name="now">The current date/time.</param>
        /// <returns>The created <see cref="AnimeGroup"/>.</returns>
        private AnimeGroup CreateAnimeGroup(ISessionWrapper session, AnimeSeries mainSeries, int mainAnimeId, DateTime now)
        {
            AnimeGroup animeGroup = new AnimeGroup();
            string     groupName  = null;

            if (mainSeries != null)
            {
                animeGroup.Populate(mainSeries, now);
                groupName = mainSeries.GetSeriesName(session);
            }
            else // The anime chosen as the group's main anime doesn't actually have a series
            {
                AniDB_Anime mainAnime = _aniDbAnimeRepo.GetByAnimeID(mainAnimeId);

                animeGroup.Populate(mainAnime, now);
                groupName = mainAnime.GetFormattedTitle();
            }

            groupName            = _truncateYearRegex.Replace(groupName, String.Empty); // If the title appears to end with a year suffix, then remove it
            animeGroup.GroupName = groupName;
            animeGroup.SortName  = groupName;

            return(animeGroup);
        }
Ejemplo n.º 33
0
        private TraktRateSeries CreateSeriesRateData(AnimeSeries series, string rateValue)
        {
            if (series == null || series.TvDB_ID == null) return null;

            TraktRateValue loveorhate = Convert.ToDouble(rateValue) >= 7.0 ? TraktRateValue.love : TraktRateValue.hate;

            TraktRateSeries seriesData = new TraktRateSeries()
            {
                Rating = loveorhate.ToString(),
                SeriesID = series.TvDB_ID.ToString(),
                Year = GetStartYear(series),
                Title = series.TvDB_Name,
                UserName = TraktSettings.Username,
                Password = TraktSettings.Password,
            };

            TraktLogger.Info("Rating '{0}' as '{1}'", series.TvDB_Name, loveorhate.ToString());
            return seriesData;
        }
Ejemplo n.º 34
0
        public Contract_AnimeSeries_SaveResponse SaveSeries(Contract_AnimeSeries_Save contract, int userID)
        {
            Contract_AnimeSeries_SaveResponse contractout = new Contract_AnimeSeries_SaveResponse();
            contractout.ErrorMessage = "";
            contractout.AnimeSeries = null;
            try
            {
                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                AnimeSeries ser = null;

                int? oldGroupID = null;
                if (contract.AnimeSeriesID.HasValue)
                {
                    ser = repSeries.GetByID(contract.AnimeSeriesID.Value);
                    if (ser == null)
                    {
                        contractout.ErrorMessage = "Could not find existing series with ID: " + contract.AnimeSeriesID.Value.ToString();
                        return contractout;
                    }

                    // check if we are moving a series
                    oldGroupID = ser.AnimeGroupID;
                }
                else
                {
                    ser = new AnimeSeries();
                    ser.DateTimeCreated = DateTime.Now;
                    ser.DefaultAudioLanguage = "";
                    ser.DefaultSubtitleLanguage = "";
                    ser.MissingEpisodeCount = 0;
                    ser.MissingEpisodeCountGroups = 0;
                    ser.LatestLocalEpisodeNumber = 0;
                    ser.SeriesNameOverride = "";
                }

                ser.AnimeGroupID = contract.AnimeGroupID;
                ser.AniDB_ID = contract.AniDB_ID;
                ser.DefaultAudioLanguage = contract.DefaultAudioLanguage;
                ser.DefaultSubtitleLanguage = contract.DefaultSubtitleLanguage;
                ser.DateTimeUpdated = DateTime.Now;
                ser.SeriesNameOverride = contract.SeriesNameOverride;
                ser.DefaultFolder = contract.DefaultFolder;

                AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
                AniDB_Anime anime = repAnime.GetByAnimeID(ser.AniDB_ID);
                if (anime == null)
                {
                    contractout.ErrorMessage = string.Format("Could not find anime record with ID: {0}", ser.AniDB_ID);
                    return contractout;
                }

                repSeries.Save(ser);

                // update stats for groups
                //ser.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true ,true, true);
                ser.QueueUpdateStats();

                if (oldGroupID.HasValue)
                {
                    AnimeGroupRepository repGroups = new AnimeGroupRepository();
                    AnimeGroup grp = repGroups.GetByID(oldGroupID.Value);
                    if (grp != null)
                    {
                        grp.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true, true, true);
                    }
                }
                List<CrossRef_AniDB_TvDBV2> xrefs = ser.GetCrossRefTvDBV2();
                List<CrossRef_AniDB_MAL> xrefMAL = ser.CrossRefMAL;

                List<TvDB_Series> sers = new List<TvDB_Series>();
                foreach (CrossRef_AniDB_TvDBV2 xref in xrefs)
                    sers.Add(xref.GetTvDBSeries());
                CrossRef_AniDB_Other xrefMovie = ser.CrossRefMovieDB;
                MovieDB_Movie movie = null;
                if (xrefMovie != null)
                    movie = xrefMovie.GetMovieDB_Movie();
                contractout.AnimeSeries = ser.ToContract(anime, xrefs, ser.CrossRefMovieDB, ser.GetUserRecord(userID),
                    sers, xrefMAL, false, null, null, null, null,movie);

                return contractout;
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                contractout.ErrorMessage = ex.Message;
                return contractout;
            }
        }
Ejemplo n.º 35
0
        public Contract_AnimeSeries_SaveResponse CreateSeriesFromAnime(int animeID, int? animeGroupID, int userID)
        {
            Contract_AnimeSeries_SaveResponse response = new Contract_AnimeSeries_SaveResponse();
            response.AnimeSeries = null;
            response.ErrorMessage = "";
            try
            {
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    AnimeGroupRepository repGroups = new AnimeGroupRepository();
                    if (animeGroupID.HasValue)
                    {
                        AnimeGroup grp = repGroups.GetByID(session, animeGroupID.Value);
                        if (grp == null)
                        {
                            response.ErrorMessage = "Could not find the specified group";
                            return response;
                        }
                    }

                    // make sure a series doesn't already exists for this anime
                    AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                    AnimeSeries ser = repSeries.GetByAnimeID(session, animeID);
                    if (ser != null)
                    {
                        response.ErrorMessage = "A series already exists for this anime";
                        return response;
                    }

                    // make sure the anime exists first
                    AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
                    AniDB_Anime anime = repAnime.GetByAnimeID(session, animeID);
                    if (anime == null)
                        anime = JMMService.AnidbProcessor.GetAnimeInfoHTTP(session, animeID, false, false);

                    if (anime == null)
                    {
                        response.ErrorMessage = "Could not get anime information from AniDB";
                        return response;
                    }

                    if (animeGroupID.HasValue)
                    {
                        ser = new AnimeSeries();
                        ser.Populate(anime);
                        ser.AnimeGroupID = animeGroupID.Value;
                        repSeries.Save(ser);
                    }
                    else
                    {
                        ser = anime.CreateAnimeSeriesAndGroup(session);
                    }

                    ser.CreateAnimeEpisodes(session);

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

                    ser.QueueUpdateStats();

                    // check for TvDB associations
                    CommandRequest_TvDBSearchAnime cmd = new CommandRequest_TvDBSearchAnime(anime.AnimeID, false);
                    cmd.Save(session);

                    if (ServerSettings.Trakt_IsEnabled && !string.IsNullOrEmpty(ServerSettings.Trakt_AuthToken))
                    {
                        // check for Trakt associations
                        CommandRequest_TraktSearchAnime cmd2 = new CommandRequest_TraktSearchAnime(anime.AnimeID, false);
                        cmd2.Save(session);
                    }

                    List<CrossRef_AniDB_TvDBV2> xrefs = ser.GetCrossRefTvDBV2();
                    List<CrossRef_AniDB_MAL> xrefMAL = ser.CrossRefMAL;

                    List<TvDB_Series> sers = new List<TvDB_Series>();
                    foreach (CrossRef_AniDB_TvDBV2 xref in xrefs)
                        sers.Add(xref.GetTvDBSeries());
                    CrossRef_AniDB_Other xrefMovie = ser.CrossRefMovieDB;
                    MovieDB_Movie movie = null;
                    if (xrefMovie != null)
                        movie = xrefMovie.GetMovieDB_Movie();
                    response.AnimeSeries = ser.ToContract(anime, xrefs, xrefMovie, ser.GetUserRecord(userID),
                        sers, xrefMAL, false, null, null, null, null,movie);
                    return response;
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                response.ErrorMessage = ex.Message;
            }

            return response;
        }
        public Contract_AnimeSeries_SaveResponse CreateSeriesFromAnime(int animeID, int? animeGroupID, int userID)
        {
            Contract_AnimeSeries_SaveResponse response = new Contract_AnimeSeries_SaveResponse();
            response.AnimeSeries = null;
            response.ErrorMessage = "";
            try
            {
                using (var session = DatabaseFactory.SessionFactory.OpenSession())
                {
                    ISessionWrapper sessionWrapper = session.Wrap();
                    if (animeGroupID.HasValue)
                    {
                        AnimeGroup grp = RepoFactory.AnimeGroup.GetByID(animeGroupID.Value);
                        if (grp == null)
                        {
                            response.ErrorMessage = "Could not find the specified group";
                            return response;
                        }
                    }

                    // make sure a series doesn't already exists for this anime
                    AnimeSeries ser = RepoFactory.AnimeSeries.GetByAnimeID(animeID);
                    if (ser != null)
                    {
                        response.ErrorMessage = "A series already exists for this anime";
                        return response;
                    }

                    // make sure the anime exists first
                    AniDB_Anime anime = RepoFactory.AniDB_Anime.GetByAnimeID(sessionWrapper, animeID);
                    if (anime == null)
                        anime = JMMService.AnidbProcessor.GetAnimeInfoHTTP(session, animeID, false, false);

                    if (anime == null)
                    {
                        response.ErrorMessage = "Could not get anime information from AniDB";
                        return response;
                    }

                    if (animeGroupID.HasValue)
                    {
                        ser = new AnimeSeries();
                        ser.Populate(anime);
                        ser.AnimeGroupID = animeGroupID.Value;
                        RepoFactory.AnimeSeries.Save(ser, false);
                    }
                    else
                    {
                        ser = anime.CreateAnimeSeriesAndGroup(sessionWrapper);
                    }

                    ser.CreateAnimeEpisodes(session);

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

                    ser.UpdateStats(true, true, true);

                    // check for TvDB associations
                    CommandRequest_TvDBSearchAnime cmd = new CommandRequest_TvDBSearchAnime(anime.AnimeID, false);
                    cmd.Save(session);

                    if (ServerSettings.Trakt_IsEnabled && !string.IsNullOrEmpty(ServerSettings.Trakt_AuthToken))
                    {
                        // check for Trakt associations
                        CommandRequest_TraktSearchAnime cmd2 = new CommandRequest_TraktSearchAnime(anime.AnimeID, false);
                        cmd2.Save(session);
                    }
                    response.AnimeSeries = ser.GetUserContract(userID);
                    return response;
                }
            }
            catch (Exception ex)
            {
                logger.Error( ex,ex.ToString());
                response.ErrorMessage = ex.Message;
            }

            return response;
        }
Ejemplo n.º 37
0
        public AnimeSeries CreateAnimeSeriesAndGroup(ISession session)
        {
            // create a new AnimeSeries record
            AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
            AnimeGroupRepository repGroups = new AnimeGroupRepository();

            AnimeSeries ser = new AnimeSeries();
            ser.Populate(this);

            JMMUserRepository repUsers = new JMMUserRepository();
            List<JMMUser> allUsers = repUsers.GetAll(session);

            // create the AnimeGroup record
            // check if there are any existing groups we could add this series to
            bool createNewGroup = true;

            if (ServerSettings.AutoGroupSeries)
            {
                List<AnimeGroup> grps = AnimeGroup.GetRelatedGroupsFromAnimeID(session, ser.AniDB_ID);

                // only use if there is just one result
                if (grps != null && grps.Count > 0)
                {
                    ser.AnimeGroupID = grps[0].AnimeGroupID;
                    createNewGroup = false;
                }
            }

            if (createNewGroup)
            {
                AnimeGroup anGroup = new AnimeGroup();
                anGroup.Populate(ser);
                repGroups.Save(anGroup);

                ser.AnimeGroupID = anGroup.AnimeGroupID;
            }

            repSeries.Save(ser);

            // check for TvDB associations
            CommandRequest_TvDBSearchAnime cmd = new CommandRequest_TvDBSearchAnime(this.AnimeID, false);
            cmd.Save();

            // check for Trakt associations
            if (ServerSettings.Trakt_IsEnabled && !string.IsNullOrEmpty(ServerSettings.Trakt_AuthToken))
            {
                CommandRequest_TraktSearchAnime cmd2 = new CommandRequest_TraktSearchAnime(this.AnimeID, false);
                cmd2.Save();
            }

            return ser;
        }
Ejemplo n.º 38
0
        private TraktRateSeries CreateSeriesRateData(AnimeSeries series, string rateValue)
        {
            if (series == null || series.TvDB_ID == null) return null;

            string rating = Convert.ToInt32(rateValue).ToString();

            TraktRateSeries seriesData = new TraktRateSeries()
            {
                Rating = rating,
                SeriesID = series.TvDB_ID.ToString(),
                Year = GetStartYear(series),
                Title = series.TvDB_Name,
                UserName = TraktSettings.Username,
                Password = TraktSettings.Password,
            };

            TraktLogger.Info("Rating '{0}' as '{1}'", series.TvDB_Name, rating.ToString());
            return seriesData;
        }
Ejemplo n.º 39
0
        private void OnRateSeries(AnimeSeries series, string rateValue)
        {
            if (TraktSettings.AccountStatus != ConnectionState.Connected) return;

            TraktLogger.Info("Received rating event for series from my anime");

            Thread rateThread = new Thread(delegate()
            {
                TraktRateSeries seriesRateData = CreateSeriesRateData(series, rateValue);
                if (seriesRateData == null) return;
                TraktRateResponse response = TraktAPI.TraktAPI.RateSeries(seriesRateData);

                // check for any error and notify
                TraktAPI.TraktAPI.LogTraktResponse(response);
            })
            {
                IsBackground = true,
                Name = "Rate"
            };

            rateThread.Start();
        }
Ejemplo n.º 40
0
        public Serie GenerateFromAnimeSeries(AnimeSeries ser, int uid, int nocast, int notag, int level, int all)
        {
            Serie sr = new Serie();

            Video nv = ser.GetPlexContract(uid);

            sr.id = ser.AnimeSeriesID;
            sr.type = nv.Type;
            sr.summary = nv.Summary;
            sr.year = nv.Year;
            sr.air = nv.AirDate.ToString("dd-MM-yyyy");
            sr.size = nv.LeafCount;
            sr.localsize = nv.ChildCount;
            sr.viewed = nv.ViewedLeafCount;
            sr.rating = nv.Rating;
            sr.userrating = nv.UserRating;
            sr.titles = nv.Titles;
            sr.title = nv.Title;
            sr.season = nv.Season;

            // until fanart refactor this will be good for start
            if (!String.IsNullOrEmpty(nv.Thumb)) { sr.art.thumb.Add(new Art() { url = APIHelper.ConstructImageLinkFromRest(nv.Thumb), index = 0 }); }
            if (!String.IsNullOrEmpty(nv.Banner)) { sr.art.banner.Add(new Art() { url = APIHelper.ConstructImageLinkFromRest(nv.Banner), index = 0 }); }
            if (!String.IsNullOrEmpty(nv.Art)) { sr.art.fanart.Add(new Art() { url = APIHelper.ConstructImageLinkFromRest(nv.Art), index = 0 }); }

            if (nocast == 0)
            {
                if (nv.Roles != null)
                {
                    foreach (RoleTag rtg in nv.Roles)
                    {
                        Role new_role = new Role();
                        if (!String.IsNullOrEmpty(rtg.Value)) { new_role.name = rtg.Value; } else { new_role.name = ""; }
                        if (!String.IsNullOrEmpty(rtg.TagPicture)) { new_role.namepic = APIHelper.ConstructImageLinkFromRest(rtg.TagPicture); } else { new_role.namepic = ""; }
                        if (!String.IsNullOrEmpty(rtg.Role)) { new_role.role = rtg.Role; } else { rtg.Role = ""; }
                        if (!String.IsNullOrEmpty(rtg.RoleDescription)) { new_role.roledesc = rtg.RoleDescription; } else { new_role.roledesc = ""; }
                        if (!String.IsNullOrEmpty(rtg.RolePicture)) { new_role.rolepic = APIHelper.ConstructImageLinkFromRest(rtg.RolePicture); } else { new_role.rolepic = ""; }
                        sr.roles.Add(new_role);
                    }
                }
            }

            if (notag == 0)
            {
                if (nv.Genres != null)
                {
                    foreach (JMMContracts.PlexAndKodi.Tag otg in nv.Genres)
                    {
                        Tag new_tag = new Tag();
                        new_tag.tag = otg.Value;
                        sr.tags.Add(new_tag);
                    }
                }
            }

            if (level != 1)
            {
                List<AnimeEpisode> ael = ser.GetAnimeEpisodes();
                if (ael.Count > 0)
                {
                    sr.eps = new List<Episode>();
                    foreach (AnimeEpisode ae in ael)
                    {
                        Episode new_ep = new Episode().GenerateFromAnimeEpisode(ae, uid, (level - 1), all);
                        if (new_ep != null)
                        {
                            sr.eps.Add(new_ep);
                        }
                    }
                }
            }

            return sr;
        }
Ejemplo n.º 41
0
        public void Save(AnimeSeries obj, bool updateGroups, bool onlyupdatestats, bool skipgroupfilters = false)
        {
            bool                 newSeries   = false;
            AnimeGroup           oldGroup    = null;
            AnimeGroupRepository repGroups   = new AnimeGroupRepository();
            bool                 isMigrating = false;

            lock (obj)
            {
                if (obj.AnimeSeriesID == 0)
                {
                    newSeries = true; // a new series
                }
                else
                {
                    // get the old version from the DB
                    AnimeSeries oldSeries;
                    using (var session = JMMService.SessionFactory.OpenSession())
                    {
                        oldSeries = session.Get <AnimeSeries>(obj.AnimeSeriesID);
                    }
                    if (oldSeries != null)
                    {
                        // means we are moving series to a different group
                        if (oldSeries.AnimeGroupID != obj.AnimeGroupID)
                        {
                            oldGroup = repGroups.GetByID(oldSeries.AnimeGroupID);
                            AnimeGroup newGroup = repGroups.GetByID(obj.AnimeGroupID);
                            if (newGroup != null && newGroup.GroupName.Equals("AAA Migrating Groups AAA"))
                            {
                                isMigrating = true;
                            }
                            newSeries = true;
                        }
                    }
                }
                if (newSeries && !isMigrating)
                {
                    using (var session = JMMService.SessionFactory.OpenSession())
                    {
                        obj.Contract = null;
                        // populate the database
                        using (var transaction = session.BeginTransaction())
                        {
                            session.SaveOrUpdate(obj);
                            transaction.Commit();
                        }
                    }
                }
                HashSet <GroupFilterConditionType> types = obj.UpdateContract(onlyupdatestats);
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    // populate the database
                    using (var transaction = session.BeginTransaction())
                    {
                        session.SaveOrUpdate(obj);
                        transaction.Commit();
                    }
                }
                if (!skipgroupfilters && !isMigrating)
                {
                    GroupFilterRepository.CreateOrVerifyTagsAndYearsFilters(false,
                                                                            obj.Contract?.AniDBAnime?.AniDBAnime?.AllTags, obj.Contract?.AniDBAnime?.AniDBAnime?.AirDate);
                    //This call will create extra years or tags if the Group have a new year or tag
                    obj.UpdateGroupFilters(types, null);
                }
                Cache.Update(obj);
                Changes.AddOrUpdate(obj.AnimeSeriesID);
            }
            if (updateGroups && !isMigrating)
            {
                if (newSeries)
                {
                    logger.Trace("Updating group stats by series from AnimeSeriesRepository.Save: {0}",
                                 obj.AnimeSeriesID);
                    AnimeGroup grp = repGroups.GetByID(obj.AnimeGroupID);
                    if (grp != null)
                    {
                        repGroups.Save(grp, true, true);
                    }
                }

                if (oldGroup != null)
                {
                    logger.Trace("Updating group stats by group from AnimeSeriesRepository.Save: {0}",
                                 oldGroup.AnimeGroupID);
                    repGroups.Save(oldGroup, true, true);
                }
            }
        }
Ejemplo n.º 42
0
        public AnimeSeries CreateAnimeSeriesAndGroup(ISessionWrapper session)
        {
            // Create a new AnimeSeries record
            AnimeSeries series = new AnimeSeries();

            series.Populate(this);

            AnimeGroup grp = new AnimeGroupCreator().GetOrCreateSingleGroupForSeries(session, series);

            series.AnimeGroupID = grp.AnimeGroupID;
            RepoFactory.AnimeSeries.Save(series, false, false);

            // check for TvDB associations
            CommandRequest_TvDBSearchAnime cmd = new CommandRequest_TvDBSearchAnime(AnimeID, forced: false);
            cmd.Save();

            // check for Trakt associations
            if (ServerSettings.Trakt_IsEnabled && !String.IsNullOrEmpty(ServerSettings.Trakt_AuthToken))
            {
                CommandRequest_TraktSearchAnime cmd2 = new CommandRequest_TraktSearchAnime(AnimeID, forced: false);
                cmd2.Save();
            }

            return series;
        }
Ejemplo n.º 43
0
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_GetReleaseGroupStatus: {0}", AnimeID);

            try
            {
                // only get group status if we have an associated series
                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                AnimeSeries           series    = repSeries.GetByAnimeID(AnimeID);
                if (series == null)
                {
                    return;
                }

                AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
                AniDB_Anime           anime    = repAnime.GetByAnimeID(AnimeID);
                if (anime == null)
                {
                    return;
                }

                // don't get group status if the anime has already ended more than 50 days ago
                bool skip = false;
                if (!ForceRefresh)
                {
                    if (anime.EndDate.HasValue)
                    {
                        if (anime.EndDate.Value < DateTime.Now)
                        {
                            TimeSpan ts = DateTime.Now - anime.EndDate.Value;
                            if (ts.TotalDays > 50)
                            {
                                // don't skip if we have never downloaded this info before
                                AniDB_GroupStatusRepository repGrpStatus = new AniDB_GroupStatusRepository();
                                List <AniDB_GroupStatus>    grpStatuses  = repGrpStatus.GetByAnimeID(AnimeID);
                                if (grpStatuses != null && grpStatuses.Count > 0)
                                {
                                    skip = true;
                                }
                            }
                        }
                    }
                }

                if (skip)
                {
                    logger.Info("Skipping group status command because anime has already ended: {0}", anime.ToString());
                    return;
                }

                GroupStatusCollection grpCol = JMMService.AnidbProcessor.GetReleaseGroupStatusUDP(AnimeID);

                if (ServerSettings.AniDB_DownloadReleaseGroups)
                {
                    // save in bulk to improve performance
                    using (var session = JMMService.SessionFactory.OpenSession())
                    {
                        using (var transaction = session.BeginTransaction())
                        {
                            foreach (Raw_AniDB_GroupStatus grpStatus in grpCol.Groups)
                            {
                                CommandRequest_GetReleaseGroup cmdRelgrp = new CommandRequest_GetReleaseGroup(grpStatus.GroupID, false);
                                cmdRelgrp.Save(session);
                            }

                            transaction.Commit();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error processing CommandRequest_GetReleaseGroupStatus: {0} - {1}", AnimeID, ex.ToString());
                return;
            }
        }
Ejemplo n.º 44
0
        public bool Init(AnimeEpisode aniepisode)
        {
            try
            {
                if (string.IsNullOrEmpty(ServerSettings.Trakt_Username) || string.IsNullOrEmpty(ServerSettings.Trakt_Password))
                {
                    return(false);
                }

                username = ServerSettings.Trakt_Username;
                password = Utils.CalculateSHA1(ServerSettings.Trakt_Password, Encoding.Default);

                imdb_id = "";
                AnimeSeries ser = aniepisode.GetAnimeSeries();
                if (ser == null)
                {
                    return(false);
                }

                CrossRef_AniDB_TraktRepository repCrossRef = new CrossRef_AniDB_TraktRepository();
                CrossRef_AniDB_Trakt           xref        = repCrossRef.GetByAnimeID(ser.AniDB_ID);
                if (xref == null)
                {
                    return(false);
                }

                Trakt_ShowRepository repShows = new Trakt_ShowRepository();
                Trakt_Show           show     = repShows.GetByTraktID(xref.TraktID);
                if (show == null)
                {
                    return(false);
                }
                if (!show.TvDB_ID.HasValue)
                {
                    return(false);
                }

                tvdb_id = show.TvDB_ID.Value.ToString();
                title   = show.Title;
                year    = show.Year;

                int retEpNum = 0, retSeason = 0;
                GetTraktEpisodeNumber(aniepisode, show, xref.TraktSeasonNumber, ref retEpNum, ref retSeason);
                if (retEpNum < 0)
                {
                    return(false);
                }

                episode = retEpNum.ToString();
                season  = retSeason.ToString();

                AniDB_Episode aniep = aniepisode.AniDB_Episode;
                if (aniep != null)
                {
                    TimeSpan t         = TimeSpan.FromSeconds(aniep.LengthSeconds + 14);
                    int      toMinutes = int.Parse(Math.Round(t.TotalMinutes).ToString());
                    duration = toMinutes.ToString();
                }
                else
                {
                    duration = "25";
                }

                progress = "100";

                plugin_version       = "0.4";
                media_center_version = "1.2.0.1";
                media_center_date    = "Dec 17 2010";
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return(false);
            }

            return(true);
        }
        public Contract_AnimeSeries_SaveResponse SaveSeries(Contract_AnimeSeries_Save contract, int userID)
        {
            Contract_AnimeSeries_SaveResponse contractout = new Contract_AnimeSeries_SaveResponse();
            contractout.ErrorMessage = "";
            contractout.AnimeSeries = null;
            try
            {

                AnimeSeries ser = null;

                int? oldGroupID = null;
                if (contract.AnimeSeriesID.HasValue)
                {
                    ser = RepoFactory.AnimeSeries.GetByID(contract.AnimeSeriesID.Value);
                    if (ser == null)
                    {
                        contractout.ErrorMessage = "Could not find existing series with ID: " +
                                                   contract.AnimeSeriesID.Value.ToString();
                        return contractout;
                    }

                    // check if we are moving a series
                    oldGroupID = ser.AnimeGroupID;
                }
                else
                {
                    ser = new AnimeSeries();
                    ser.DateTimeCreated = DateTime.Now;
                    ser.DefaultAudioLanguage = "";
                    ser.DefaultSubtitleLanguage = "";
                    ser.MissingEpisodeCount = 0;
                    ser.MissingEpisodeCountGroups = 0;
                    ser.LatestLocalEpisodeNumber = 0;
                    ser.SeriesNameOverride = "";
                }

                ser.AnimeGroupID = contract.AnimeGroupID;
                ser.AniDB_ID = contract.AniDB_ID;
                ser.DefaultAudioLanguage = contract.DefaultAudioLanguage;
                ser.DefaultSubtitleLanguage = contract.DefaultSubtitleLanguage;
                ser.DateTimeUpdated = DateTime.Now;
                ser.SeriesNameOverride = contract.SeriesNameOverride;
                ser.DefaultFolder = contract.DefaultFolder;

                AniDB_Anime anime = RepoFactory.AniDB_Anime.GetByAnimeID(ser.AniDB_ID);
                if (anime == null)
                {
                    contractout.ErrorMessage = string.Format("Could not find anime record with ID: {0}", ser.AniDB_ID);
                    return contractout;
                }

                // update stats for groups
                //ser.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true ,true, true);

                //Update and Save
                ser.UpdateStats(true, true, true);

                if (oldGroupID.HasValue)
                {
                    AnimeGroup grp = RepoFactory.AnimeGroup.GetByID(oldGroupID.Value);
                    if (grp != null)
                    {
                        grp.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true, true, true);
                    }
                }
                contractout.AnimeSeries = ser.GetUserContract(userID);
                return contractout;
            }
            catch (Exception ex)
            {
                logger.Error( ex,ex.ToString());
                contractout.ErrorMessage = ex.Message;
                return contractout;
            }
        }
Ejemplo n.º 46
0
		public static void SyncCollectionToTrakt_Series(AnimeSeries series)
		{
			try
			{
				// check that we have at least one user nominated for Trakt
				JMMUserRepository repUsers = new JMMUserRepository();
				List<JMMUser> traktUsers = repUsers.GetTraktUsers();
				if (traktUsers.Count == 0) return;

				string url = string.Format(Constants.TraktTvURLs.URLPostShowEpisodeLibrary, Constants.TraktTvURLs.APIKey);
				string urlSeen = string.Format(Constants.TraktTvURLs.URLPostShowEpisodeSeen, Constants.TraktTvURLs.APIKey);

				int retEpNum = 0, retSeason = 0;

				CrossRef_AniDB_Trakt xref = series.CrossRefTrakt;
				if (xref == null) return;

				Trakt_ShowRepository repShows = new Trakt_ShowRepository();
				Trakt_Show show = repShows.GetByTraktID(xref.TraktID);
				if (show == null) return;
				if (!show.TvDB_ID.HasValue) return;

				Dictionary<int, int> dictTraktSeasons = null;
				Dictionary<int, Trakt_Episode> dictTraktEpisodes = null;
				Dictionary<int, Trakt_Episode> dictTraktSpecials = null;
				GetDictTraktEpisodesAndSeasons(show, ref dictTraktEpisodes, ref dictTraktSpecials, ref dictTraktSeasons);


				TraktTVPost_ShowEpisodeLibrary postLibrary = new TraktTVPost_ShowEpisodeLibrary();
				postLibrary.episodes = new List<TraktTVSeasonEpisode>();
				postLibrary.SetCredentials();
				postLibrary.imdb_id = "";
				postLibrary.title = show.Title;
				postLibrary.year = show.Year;
				postLibrary.tvdb_id = show.TvDB_ID.Value.ToString();

				TraktTVPost_ShowEpisodeSeen postSeen = new TraktTVPost_ShowEpisodeSeen();
				postSeen.episodes = new List<TraktTVSeasonEpisode>();
				postSeen.SetCredentials();
				postSeen.imdb_id = "";
				postSeen.title = show.Title;
				postSeen.year = show.Year;
				postSeen.tvdb_id = show.TvDB_ID.Value.ToString();

				foreach (AnimeEpisode ep in series.GetAnimeEpisodes())
				{
					if (ep.GetVideoLocals().Count > 0)
					{
						retEpNum = -1;
						retSeason = -1;

						GetTraktEpisodeNumber(ep, series, show, xref.TraktSeasonNumber, ref retEpNum, ref retSeason, dictTraktEpisodes, dictTraktSpecials, dictTraktSeasons);
						if (retEpNum < 0) continue;

						TraktTVSeasonEpisode traktEp = new TraktTVSeasonEpisode();
						traktEp.episode = retEpNum.ToString();
						traktEp.season = retSeason.ToString();
						postLibrary.episodes.Add(traktEp);

						AnimeEpisode_User userRecord = null;
						foreach (JMMUser juser in traktUsers)
						{
							userRecord = ep.GetUserRecord(juser.JMMUserID);
							if (userRecord != null) break;
						}

						if (userRecord != null) 
							postSeen.episodes.Add(traktEp);
					}
				}

				if (postLibrary.episodes.Count > 0)
				{
					logger.Info("PostShowEpisodeLibrary: {0}/{1}/{2} eps", show.Title, show.TraktID, postLibrary.episodes.Count);

					string json = JSONHelper.Serialize<TraktTVPost_ShowEpisodeLibrary>(postLibrary);
					string jsonResponse = SendData(url, json);
					logger.Info("PostShowEpisodeLibrary RESPONSE: {0}", jsonResponse);
				}

				if (postSeen.episodes.Count > 0)
				{
					logger.Info("PostShowEpisodeSeen: {0}/{1}/{2} eps", show.Title, show.TraktID, postSeen.episodes.Count);

					string json = JSONHelper.Serialize<TraktTVPost_ShowEpisodeSeen>(postSeen);
					string jsonResponse = SendData(urlSeen, json);
					logger.Info("PostShowEpisodeSeen RESPONSE: {0}", jsonResponse);
				}
			}
			catch (Exception ex)
			{
				logger.ErrorException("Error in TraktTVHelper.SyncCollectionToTrakt_Series: " + ex.ToString(), ex);
			}
		}
Ejemplo n.º 47
0
		// Removes all Trakt information from a series, bringing it back to a blank state.
		public static void RemoveLinkAniDBTrakt(AnimeSeries ser)
		{
			CrossRef_AniDB_TraktRepository repCrossRef = new CrossRef_AniDB_TraktRepository();
			CrossRef_AniDB_Trakt xref = repCrossRef.GetByAnimeID(ser.AniDB_ID);
			if (xref == null) return;

			repCrossRef.Delete(xref.CrossRef_AniDB_TraktID);

			CommandRequest_WebCacheDeleteXRefAniDBTrakt req = new CommandRequest_WebCacheDeleteXRefAniDBTrakt(ser.AniDB_ID);
			req.Save();
		}
Ejemplo n.º 48
0
        public Serie GenerateFromAnimeSeries(AnimeSeries ser, int uid, int nocast, int notag, int level)
        {
            Serie sr = new Serie();

            Video nv = ser.GetPlexContract(uid);

            sr.id      = ser.AnimeSeriesID;
            sr.type    = nv.Type;
            sr.summary = nv.Summary;
            sr.year    = nv.Year;
            sr.air     = nv.AirDate.ToString();
            sr.size    = nv.LeafCount;
            sr.viewed  = nv.ViewedLeafCount;
            sr.rating  = nv.Rating;
            sr.titles  = nv.Titles;
            sr.title   = nv.Title;

            // until fanart refactor this will be good for start
            if (!String.IsNullOrEmpty(nv.Thumb))
            {
                sr.art.thumb.Add(new Art()
                {
                    url = APIHelper.ConstructImageLinkFromRest(nv.Thumb), index = 0
                });
            }
            if (!String.IsNullOrEmpty(nv.Banner))
            {
                sr.art.banner.Add(new Art()
                {
                    url = APIHelper.ConstructImageLinkFromRest(nv.Banner), index = 0
                });
            }
            if (!String.IsNullOrEmpty(nv.Art))
            {
                sr.art.fanart.Add(new Art()
                {
                    url = APIHelper.ConstructImageLinkFromRest(nv.Art), index = 0
                });
            }

            if (nocast == 0)
            {
                if (nv.Roles != null)
                {
                    foreach (RoleTag rtg in nv.Roles)
                    {
                        Role new_role = new Role();
                        if (!String.IsNullOrEmpty(rtg.Value))
                        {
                            new_role.name = rtg.Value;
                        }
                        else
                        {
                            new_role.name = "";
                        }
                        if (!String.IsNullOrEmpty(rtg.TagPicture))
                        {
                            new_role.namepic = APIHelper.ConstructImageLinkFromRest(rtg.TagPicture);
                        }
                        else
                        {
                            new_role.namepic = "";
                        }
                        if (!String.IsNullOrEmpty(rtg.Role))
                        {
                            new_role.role = rtg.Role;
                        }
                        else
                        {
                            rtg.Role = "";
                        }
                        if (!String.IsNullOrEmpty(rtg.RoleDescription))
                        {
                            new_role.roledesc = rtg.RoleDescription;
                        }
                        else
                        {
                            new_role.roledesc = "";
                        }
                        if (!String.IsNullOrEmpty(rtg.RolePicture))
                        {
                            new_role.rolepic = APIHelper.ConstructImageLinkFromRest(rtg.RolePicture);
                        }
                        else
                        {
                            new_role.rolepic = "";
                        }
                        sr.roles.Add(new_role);
                    }
                }
            }

            if (notag == 0)
            {
                if (nv.Genres != null)
                {
                    foreach (JMMContracts.PlexAndKodi.Tag otg in nv.Genres)
                    {
                        Tag new_tag = new Tag();
                        new_tag.tag = otg.Value;
                        sr.tags.Add(new_tag);
                    }
                }
            }

            if (level != 1)
            {
                List <AnimeEpisode> ael = ser.GetAnimeEpisodes();
                if (ael.Count > 0)
                {
                    sr.eps = new List <Episode>();
                    foreach (AnimeEpisode ae in ael)
                    {
                        sr.eps.Add(new Episode().GenerateFromAnimeEpisode(ae, uid, (level - 1)));
                    }
                }
            }

            return(sr);
        }
Ejemplo n.º 49
0
        /*public static void UpdateWatchedStatus(int animeID, enEpisodeType epType, int lastWatchedEpNumber)
        {
            try
            {
                if (string.IsNullOrEmpty(ServerSettings.MAL_Username) || string.IsNullOrEmpty(ServerSettings.MAL_Password))
                    return;

                AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository();
                List<AniDB_Episode> aniEps = repAniEps.GetByAnimeIDAndEpisodeTypeNumber(animeID, epType, lastWatchedEpNumber);
                if (aniEps.Count == 0) return;

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

                MALHelper.UpdateMAL(ep);
            }
            catch (Exception ex)
            {
                logger.Error( ex,ex.ToString());
            }
        }*/
        public static void UpdateMALSeries(AnimeSeries ser)
        {
            try
            {
                if (string.IsNullOrEmpty(ServerSettings.MAL_Username) ||
                    string.IsNullOrEmpty(ServerSettings.MAL_Password))
                    return;

                // Populate MAL animelist hashtable if isNeverDecreaseWatched set
                Hashtable animeListHashtable = new Hashtable();
                myanimelist malAnimeList = GetMALAnimeList();
                if (ServerSettings.MAL_NeverDecreaseWatchedNums)
                    //if set, check watched number before update: take some time, as user anime list must be loaded
                {
                    if (malAnimeList != null && malAnimeList.anime != null)
                    {
                        for (int i = 0; i < malAnimeList.anime.Length; i++)
                        {
                            animeListHashtable.Add(malAnimeList.anime[i].series_animedb_id, malAnimeList.anime[i]);
                        }
                    }
                }

                // look for MAL Links
                List<CrossRef_AniDB_MAL> crossRefs = ser.GetAnime().GetCrossRefMAL();
                if (crossRefs == null || crossRefs.Count == 0)
                {
                    logger.Warn("Could not find MAL link for : {0} ({1})", ser.GetAnime().GetFormattedTitle(),
                        ser.GetAnime().AnimeID);
                    return;
                }

                List<AnimeEpisode> eps = ser.GetAnimeEpisodes();

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

                JMMUser user = aniDBUsers[0];

                int score = 0;
                if (ser.GetAnime().UserVote != null)
                    score = (int) (ser.GetAnime().UserVote.VoteValue/100);

                // e.g.
                // AniDB - Code Geass R2
                // MAL Equivalent = AniDB Normal Eps 1 - 25 / Code Geass: Hangyaku no Lelouch R2 / hxxp://myanimelist.net/anime/2904/Code_Geass:_Hangyaku_no_Lelouch_R2
                // MAL Equivalent = AniDB Special Eps 1 - 9 / Code Geass: Hangyaku no Lelouch R2 Picture Drama / hxxp://myanimelist.net/anime/5163/Code_Geass:_Hangyaku_no_Lelouch_R2_Picture_Drama
                // MAL Equivalent = AniDB Special Eps 9 - 18 / Code Geass: Hangyaku no Lelouch R2: Flash Specials / hxxp://myanimelist.net/anime/9591/Code_Geass:_Hangyaku_no_Lelouch_R2:_Flash_Specials
                // MAL Equivalent = AniDB Special Eps 20 / Code Geass: Hangyaku no Lelouch - Kiseki no Birthday Picture Drama / hxxp://myanimelist.net/anime/8728/Code_Geass:_Hangyaku_no_Lelouch_-_Kiseki_no_Birthday_Picture_Drama

                foreach (CrossRef_AniDB_MAL xref in crossRefs)
                {
                    // look for the right MAL id
                    int malID = -1;
                    int epNumber = -1;
                    int totalEpCount = -1;

                    List<string> fanSubGroups = new List<string>();

                    // for each cross ref (which is a series on MAL) we need to update the data
                    // so find all the episodes which apply to this cross ref
                    int lastWatchedEpNumber = 0;
                    int downloadedEps = 0;

                    foreach (AnimeEpisode ep in eps)
                    {
                        int epNum = ep.AniDB_Episode.EpisodeNumber;
                        if (xref.StartEpisodeType == (int) ep.EpisodeTypeEnum && epNum >= xref.StartEpisodeNumber &&
                            epNum <= GetUpperEpisodeLimit(crossRefs, xref))
                        {
                            malID = xref.MALID;
                            epNumber = epNum - xref.StartEpisodeNumber + 1;

                            // find the total episode count
                            if (totalEpCount < 0)
                            {
                                if (ep.EpisodeTypeEnum == AniDBAPI.enEpisodeType.Episode)
                                    totalEpCount = ser.GetAnime().EpisodeCountNormal;
                                if (ep.EpisodeTypeEnum == AniDBAPI.enEpisodeType.Special)
                                    totalEpCount = ser.GetAnime().EpisodeCountSpecial;
                                totalEpCount = totalEpCount - xref.StartEpisodeNumber + 1;
                            }

                            // any episodes here belong to the MAL series
                            // find the latest watched episod enumber
                            AnimeEpisode_User usrRecord = ep.GetUserRecord(user.JMMUserID);
                            if (usrRecord != null && usrRecord.WatchedDate.HasValue && epNum > lastWatchedEpNumber)
                            {
                                lastWatchedEpNumber = epNum;
                            }

                            List<Contract_VideoDetailed> contracts = ep.GetVideoDetailedContracts(user.JMMUserID);

                            // find the latest episode number in the collection
                            if (contracts.Count > 0)
                                downloadedEps++;

                            foreach (Contract_VideoDetailed contract in contracts)
                            {
                                if (!string.IsNullOrEmpty(contract.AniDB_Anime_GroupNameShort) &&
                                    !fanSubGroups.Contains(contract.AniDB_Anime_GroupNameShort))
                                    fanSubGroups.Add(contract.AniDB_Anime_GroupNameShort);
                            }
                        }
                    }

                    string fanSubs = "";
                    foreach (string fgrp in fanSubGroups)
                    {
                        if (!string.IsNullOrEmpty(fanSubs)) fanSubs += ",";
                        fanSubs += fgrp;
                    }

                    // determine status
                    int status = 1; //watching
                    if (animeListHashtable.ContainsKey(malID))
                    {
                        myanimelistAnime animeInList = (myanimelistAnime) animeListHashtable[malID];
                        status = animeInList.my_status;
                    }

                    // over-ride is user has watched an episode
                    // don't override on hold (3) or dropped (4) but do override plan to watch (6)
                    if (status == 6 && lastWatchedEpNumber > 0) status = 1; //watching
                    if (lastWatchedEpNumber == totalEpCount) status = 2; //completed

                    if (lastWatchedEpNumber > totalEpCount)
                    {
                        logger.Error("updateMAL, episode number > matching anime episode total : {0} ({1}) / {2}",
                            ser.GetAnime().GetFormattedTitle(), ser.GetAnime().AnimeID, epNumber);
                        continue;
                    }

                    if (malID <= 0 || totalEpCount <= 0)
                    {
                        logger.Warn("Could not find MAL link for : {0} ({1})", ser.GetAnime().GetFormattedTitle(),
                            ser.GetAnime().AnimeID);
                        continue;
                    }

                    string confirmationMessage = "";
                    if (animeListHashtable.ContainsKey(malID))
                    {
                        ModifyAnime(malID, lastWatchedEpNumber, status, score, downloadedEps, fanSubs);
                        confirmationMessage = string.Format("MAL successfully updated (MAL MODIFY), mal id: {0}, ep: {1}, score: {2}", malID,
                            lastWatchedEpNumber, score);
                    }
                    else
                    {
                        AddAnime(malID, lastWatchedEpNumber, status, score, downloadedEps, fanSubs);
                        confirmationMessage = string.Format("MAL successfully updated (MAL ADD), mal id: {0}, ep: {1}, score: {2}", malID,
                            lastWatchedEpNumber, score);
                    }
                    logger.Trace(confirmationMessage);
                }
            }
            catch (Exception ex)
            {
                logger.Error( ex,ex.ToString());
            }
        }
Ejemplo n.º 50
0
        public static void SyncCollectionToTrakt_Series(AnimeSeries series)
        {
            try
            {
                // check that we have at least one user nominated for Trakt
                JMMUserRepository repUsers = new JMMUserRepository();
                List<JMMUser> traktUsers = repUsers.GetTraktUsers();
                if (traktUsers.Count == 0) return;

                AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
                AniDB_Anime anime = repAnime.GetByAnimeID(series.AniDB_ID);
                if (anime == null) return;

                TraktSummaryContainer traktSummary = new TraktSummaryContainer();
                traktSummary.Populate(series.AniDB_ID);
                if (traktSummary.CrossRefTraktV2 == null || traktSummary.CrossRefTraktV2.Count == 0) return;

                // now get the full users collection from Trakt
                List<TraktV2ShowCollectedResult> collected = new List<TraktV2ShowCollectedResult>();
                List<TraktV2ShowWatchedResult> watched = new List<TraktV2ShowWatchedResult>();

                if (!GetTraktCollectionInfo(ref collected, ref watched)) return;

                foreach (AnimeEpisode ep in series.GetAnimeEpisodes())
                {
                    if (ep.EpisodeTypeEnum == enEpisodeType.Episode || ep.EpisodeTypeEnum == enEpisodeType.Special)
                    {
                        ReconSyncTraktEpisode(series, ep, traktSummary, traktUsers, collected, watched, true);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException("Error in TraktTVHelper.SyncCollectionToTrakt_Series: " + ex.ToString(), ex);
            }
        }
Ejemplo n.º 51
0
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_GetUpdated");

            try
            {
                List <int> animeIDsToUpdate         = new List <int>();
                ScheduledUpdateRepository repSched  = new ScheduledUpdateRepository();
                AnimeSeriesRepository     repSeries = new AnimeSeriesRepository();
                AniDB_AnimeRepository     repAnime  = new AniDB_AnimeRepository();

                // check the automated update table to see when the last time we ran this command
                ScheduledUpdate sched = repSched.GetByUpdateType((int)ScheduledUpdateType.AniDBUpdates);
                if (sched != null)
                {
                    int freqHours = Utils.GetScheduledHours(ServerSettings.AniDB_Anime_UpdateFrequency);

                    // if we have run this in the last 12 hours and are not forcing it, then exit
                    TimeSpan tsLastRun = DateTime.Now - sched.LastUpdate;
                    if (tsLastRun.TotalHours < freqHours)
                    {
                        if (!ForceRefresh)
                        {
                            return;
                        }
                    }
                }



                long webUpdateTime    = 0;
                long webUpdateTimeNew = 0;
                if (sched == null)
                {
                    // if this is the first time, lets ask for last 3 days
                    DateTime localTime = DateTime.Now.AddDays(-3);
                    DateTime utcTime   = localTime.ToUniversalTime();
                    webUpdateTime    = long.Parse(Utils.AniDBDate(utcTime));
                    webUpdateTimeNew = long.Parse(Utils.AniDBDate(DateTime.Now.ToUniversalTime()));

                    sched            = new ScheduledUpdate();
                    sched.UpdateType = (int)ScheduledUpdateType.AniDBUpdates;
                }
                else
                {
                    logger.Trace("Last anidb info update was : {0}", sched.UpdateDetails);
                    webUpdateTime    = long.Parse(sched.UpdateDetails);
                    webUpdateTimeNew = long.Parse(Utils.AniDBDate(DateTime.Now.ToUniversalTime()));

                    DateTime timeNow = DateTime.Now.ToUniversalTime();
                    logger.Info(string.Format("{0} since last UPDATED command",
                                              Utils.FormatSecondsToDisplayTime(int.Parse((webUpdateTimeNew - webUpdateTime).ToString()))));
                }

                // get a list of updates from AniDB
                // startTime will contain the date/time from which the updates apply to
                JMMService.AnidbProcessor.GetUpdated(ref animeIDsToUpdate, ref webUpdateTime);

                // now save the update time from AniDB
                // we will use this next time as a starting point when querying the web cache
                sched.LastUpdate    = DateTime.Now;
                sched.UpdateDetails = webUpdateTimeNew.ToString();
                repSched.Save(sched);

                if (animeIDsToUpdate.Count == 0)
                {
                    logger.Info("No anime to be updated");
                    return;
                }


                int countAnime  = 0;
                int countSeries = 0;
                foreach (int animeID in animeIDsToUpdate)
                {
                    // update the anime from HTTP
                    AniDB_Anime anime = repAnime.GetByAnimeID(animeID);
                    if (anime == null)
                    {
                        logger.Trace("No local record found for Anime ID: {0}, so skipping...", animeID);
                        continue;
                    }

                    logger.Info("Updating CommandRequest_GetUpdated: {0} ", animeID);

                    // but only if it hasn't been recently updated
                    TimeSpan ts = DateTime.Now - anime.DateTimeUpdated;
                    if (ts.TotalHours > 4)
                    {
                        CommandRequest_GetAnimeHTTP cmdAnime = new CommandRequest_GetAnimeHTTP(animeID, true, false);
                        cmdAnime.Save();
                        countAnime++;
                    }

                    // update the group status
                    // this will allow us to determine which anime has missing episodes
                    // so we wonly get by an amime where we also have an associated series
                    AnimeSeries ser = repSeries.GetByAnimeID(animeID);
                    if (ser != null)
                    {
                        CommandRequest_GetReleaseGroupStatus cmdStatus = new CommandRequest_GetReleaseGroupStatus(animeID, true);
                        cmdStatus.Save();
                        countSeries++;
                    }
                }

                logger.Info("Updating {0} anime records, and {1} group status records", countAnime, countSeries);
            }
            catch (Exception ex)
            {
                logger.Error("Error processing CommandRequest_GetUpdated: {0}", ex.ToString());
                return;
            }
        }
Ejemplo n.º 52
0
        private TraktEpisodeSync CreateSyncData(AnimeSeries series, List<AnimeEpisode> episodes)
        {
            if (series == null || series.TvDB_ID == null) return null;

            // set series properties for episodes
            TraktEpisodeSync traktSync = new TraktEpisodeSync
            {
                Password = TraktSettings.Password,
                UserName = TraktSettings.Username,
                SeriesID = series.TvDB_ID.ToString(),
                Year = GetStartYear(series),
                Title = series.SeriesName
            };

            // get list of episodes for series
            List<TraktEpisodeSync.Episode> epList = new List<TraktEpisodeSync.Episode>();

            foreach (AnimeEpisode episode in episodes.Where(e => e.Series.TvDB_ID == series.TvDB_ID))
            {
                TraktEpisodeSync.Episode ep = new TraktEpisodeSync.Episode();

                string seriesid = series.TvDB_ID.ToString();
                int seasonidx = 0;
                int episodeidx = 0;

                if (GetTVDBEpisodeInfo(episode, out seriesid, out seasonidx, out episodeidx))
                {
                    ep.SeasonIndex = seasonidx.ToString();
                    ep.EpisodeIndex = episodeidx.ToString();
                    epList.Add(ep);
                }
                else
                {
                    TraktLogger.Info("Unable to find match for episode: '{0} | airDate: {1}'", episode.ToString(), episode.AniDB_Episode.AirDateAsDate.ToString("yyyy-MM-dd"));
                }
            }

            if (epList.Count == 0)
            {
                TraktLogger.Warning("Unable to find any matching TVDb episodes for series '{0}', confirm Absolute Order and/or Episode Names and/or AirDates for episodes are correct on http://theTVDb.com and your database.", series.SeriesName);
                return null;
            }

            traktSync.EpisodeList = epList;
            return traktSync;
        }
Ejemplo n.º 53
0
		private static void GetTraktEpisodeNumber(AnimeEpisode aniepisode, AnimeSeries ser, Trakt_Show show, int season, ref int traktEpNum, ref int traktSeason)
		{
			Dictionary<int, int> dictTraktSeasons = null;
			Dictionary<int, Trakt_Episode> dictTraktEpisodes = null;
			Dictionary<int, Trakt_Episode> dictTraktSpecials = null;
			GetDictTraktEpisodesAndSeasons(show, ref dictTraktEpisodes, ref dictTraktSpecials, ref dictTraktSeasons);

			GetTraktEpisodeNumber(aniepisode, ser, show, season, ref traktEpNum, ref traktSeason, dictTraktEpisodes, dictTraktSpecials, dictTraktSeasons);
		}
Ejemplo n.º 54
0
		private static void GetTraktEpisodeNumber(AnimeEpisode aniepisode, AnimeSeries ser, Trakt_Show show, int season, ref int traktEpNum, ref int traktSeason,
			Dictionary<int, Trakt_Episode> dictTraktEpisodes, Dictionary<int, Trakt_Episode> dictTraktSpecials, Dictionary<int, int> dictTraktSeasons)
		{
			try
			{
				traktEpNum = -1;
				traktSeason = -1;

				int epNum = aniepisode.AniDB_Episode.EpisodeNumber;

				if (season > 0)
				{
					//episode
					if (aniepisode.EpisodeTypeEnum == AniDBAPI.enEpisodeType.Episode)
					{
						if (dictTraktEpisodes != null && dictTraktSeasons != null)
						{
							if (dictTraktSeasons.ContainsKey(season))
							{
								int absEpisodeNumber = dictTraktSeasons[season] + epNum - 1;
								if (dictTraktEpisodes.ContainsKey(absEpisodeNumber))
								{
									Trakt_Episode tvep = dictTraktEpisodes[absEpisodeNumber];
									traktEpNum = tvep.EpisodeNumber;
									traktSeason = tvep.Season;
								}
							}
						}
					}

					if (aniepisode.EpisodeTypeEnum == AniDBAPI.enEpisodeType.Special)
					{
						traktSeason = 0;
						traktEpNum = epNum;
					}
				}
				else
				{
					traktSeason = 0;
					traktEpNum = epNum;
				}

				return;
			}
			catch (Exception ex)
			{
				logger.ErrorException(ex.ToString(), ex);
				return;
			}
		}
Ejemplo n.º 55
0
        private static EpisodeSyncDetails ReconSyncTraktEpisode(AnimeSeries ser, AnimeEpisode ep, TraktSummaryContainer traktSummary, List<JMMUser> traktUsers,
            List<TraktV2ShowCollectedResult> collected, List<TraktV2ShowWatchedResult> watched, bool sendNow)
        {
            try
            {
                // get the Trakt Show ID for this episode
                string traktShowID = string.Empty;
                int season = -1;
                int epNumber = -1;

                GetTraktEpisodeIdV2(ep, ref traktShowID, ref season, ref epNumber);
                if (string.IsNullOrEmpty(traktShowID) || season < 0 || epNumber < 0) return null;

                // get the current collected records for this series on Trakt
                TraktV2CollectedEpisode epTraktCol = null;
                TraktV2ShowCollectedResult col = collected.FirstOrDefault(x => x.show.ids.slug == traktShowID);
                if (col != null)
                {
                    TraktV2CollectedSeason sea = col.seasons.FirstOrDefault(x => x.number == season);
                    if (sea != null)
                    {
                        epTraktCol = sea.episodes.FirstOrDefault(x => x.number == epNumber);
                    }
                }

                bool onlineCollection = epTraktCol != null;

                // get the current watched records for this series on Trakt
                TraktV2WatchedEpisode epTraktWatched = null;
                TraktV2ShowWatchedResult wtc = watched.FirstOrDefault(x => x.show.ids.slug == traktShowID);
                if (wtc != null)
                {
                    TraktV2WatchedSeason sea = wtc.seasons.FirstOrDefault(x => x.number == season);
                    if (sea != null)
                    {
                        epTraktWatched = sea.episodes.FirstOrDefault(x => x.number == epNumber);
                    }
                }

                bool onlineWatched = epTraktWatched != null;

                bool localCollection = false;
                bool localWatched = false;

                if (ep.GetVideoLocals().Count > 0)
                {
                    // let's check if this episode has a user record against it
                    // if it does, it means a user has watched it
                    localCollection = true;

                    AnimeEpisode_User userRecord = null;
                    foreach (JMMUser juser in traktUsers)
                    {
                        userRecord = ep.GetUserRecord(juser.JMMUserID);
                        if (userRecord != null) break;
                    }

                    if (userRecord != null) localWatched = true;
                }

                string msg1 = string.Format("Sync Check Status:  AniDB: {0} - {1} - {2} - Collection: {3} - Watched: {4}", ser.AniDB_ID, ep.EpisodeTypeEnum, ep.AniDB_EpisodeID, localCollection, localWatched);
                string msg2 = string.Format("Sync Check Status:  Trakt: {0} - S:{1} - EP:{2} - Collection: {3} - Watched: {4}", traktShowID, season, epNumber, onlineCollection, onlineWatched);

                logger.Trace(msg1);
                logger.Trace(msg2);

                // sync the collection status
                if (localCollection)
                {
                    // is in the local collection, but not Trakt, so let's ADD it
                    if (!onlineCollection)
                    {
                        string msg = string.Format("SYNC LOCAL: Adding to Trakt Collection:  Slug: {0} - S:{1} - EP:{2}", traktShowID, season, epNumber);
                        logger.Trace(msg);
                        DateTime epDate = GetEpisodeDateForSync(ep, TraktSyncType.CollectionAdd);
                        if (sendNow)
                            SyncEpisodeToTrakt(TraktSyncType.CollectionAdd, traktShowID, season, epNumber, epDate, false);
                        else
                            return new EpisodeSyncDetails(TraktSyncType.CollectionAdd, traktShowID, season, epNumber, epDate);
                    }
                }
                else
                {
                    // is in the trakt collection, but not local, so let's REMOVE it
                    if (onlineCollection)
                    {
                        string msg = string.Format("SYNC LOCAL: Removing from Trakt Collection:  Slug: {0} - S:{1} - EP:{2}", traktShowID, season, epNumber);
                        logger.Trace(msg);
                        DateTime epDate = GetEpisodeDateForSync(ep, TraktSyncType.CollectionRemove);
                        if (sendNow)
                            SyncEpisodeToTrakt(TraktSyncType.CollectionRemove, traktShowID, season, epNumber, epDate, false);
                        else
                            return new EpisodeSyncDetails(TraktSyncType.CollectionRemove, traktShowID, season, epNumber, epDate);
                    }

                }

                // sync the watched status
                if (localWatched)
                {
                    // is watched locally, but not Trakt, so let's ADD it
                    if (!onlineWatched)
                    {
                        string msg = string.Format("SYNC LOCAL: Adding to Trakt History:  Slug: {0} - S:{1} - EP:{2}", traktShowID, season, epNumber);
                        logger.Trace(msg);
                        DateTime epDate = GetEpisodeDateForSync(ep, TraktSyncType.HistoryAdd);
                        if (sendNow)
                            SyncEpisodeToTrakt(TraktSyncType.HistoryAdd, traktShowID, season, epNumber, epDate, false);
                        else
                            return new EpisodeSyncDetails(TraktSyncType.HistoryAdd, traktShowID, season, epNumber, epDate);
                    }
                }
                else
                {
                    // is watched on trakt, but not locally, so let's REMOVE it
                    if (onlineWatched)
                    {
                        string msg = string.Format("SYNC LOCAL: Removing from Trakt History:  Slug: {0} - S:{1} - EP:{2}", traktShowID, season, epNumber);
                        logger.Trace(msg);
                        DateTime epDate = GetEpisodeDateForSync(ep, TraktSyncType.HistoryRemove);
                        if (sendNow)
                            SyncEpisodeToTrakt(TraktSyncType.HistoryRemove, traktShowID, season, epNumber, epDate, false);
                        else
                            return new EpisodeSyncDetails(TraktSyncType.HistoryRemove, traktShowID, season, epNumber, epDate);
                    }

                }

                return null;
            }
            catch (Exception ex)
            {
                logger.ErrorException("Error in TraktTVHelper.SyncTraktEpisode: " + ex.ToString(), ex);
                return null;
            }
        }
Ejemplo n.º 56
0
 /// <summary>
 /// Anime Year is in form StartYear-LastYear
 /// </summary>
 public static string GetStartYear(AnimeSeries series)
 {
     if (series.Year.Contains('-'))
         return series.Year.Split('-')[0];
     return series.Year;
 }
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_GetCalendar");

            try
            {
                // we will always assume that an anime was downloaded via http first
                ScheduledUpdateRepository repSched = new ScheduledUpdateRepository();
                AniDB_AnimeRepository     repAnime = new AniDB_AnimeRepository();

                ScheduledUpdate sched = repSched.GetByUpdateType((int)ScheduledUpdateType.AniDBCalendar);
                if (sched == null)
                {
                    sched               = new ScheduledUpdate();
                    sched.UpdateType    = (int)ScheduledUpdateType.AniDBCalendar;
                    sched.UpdateDetails = "";
                }
                else
                {
                    int freqHours = Utils.GetScheduledHours(ServerSettings.AniDB_Calendar_UpdateFrequency);

                    // if we have run this in the last 12 hours and are not forcing it, then exit
                    TimeSpan tsLastRun = DateTime.Now - sched.LastUpdate;
                    if (tsLastRun.TotalHours < freqHours)
                    {
                        if (!ForceRefresh)
                        {
                            return;
                        }
                    }
                }

                sched.LastUpdate = DateTime.Now;
                repSched.Save(sched);

                CalendarCollection colCalendars = JMMService.AnidbProcessor.GetCalendarUDP();
                if (colCalendars == null || colCalendars.Calendars == null)
                {
                    logger.Error("Could not get calendar from AniDB");
                    return;
                }
                foreach (AniDBAPI.Calendar cal in colCalendars.Calendars)
                {
                    AniDB_Anime anime = repAnime.GetByAnimeID(cal.AnimeID);
                    if (anime != null)
                    {
                        // don't update if the local data is less 2 days old
                        TimeSpan ts = DateTime.Now - anime.DateTimeUpdated;
                        if (ts.TotalDays >= 2)
                        {
                            CommandRequest_GetAnimeHTTP cmdAnime = new CommandRequest_GetAnimeHTTP(cal.AnimeID, true,
                                                                                                   false);
                            cmdAnime.Save();
                        }
                        else
                        {
                            // update the release date even if we don't update the anime record
                            if (anime.AirDate != cal.ReleaseDate)
                            {
                                anime.AirDate = cal.ReleaseDate;
                                repAnime.Save(anime);
                                AnimeSeriesRepository srepo = new AnimeSeriesRepository();
                                AnimeSeries           ser   = srepo.GetByAnimeID(anime.AnimeID);
                                if (ser != null)
                                {
                                    srepo.Save(ser, true, false);
                                }
                            }
                        }
                    }
                    else
                    {
                        CommandRequest_GetAnimeHTTP cmdAnime = new CommandRequest_GetAnimeHTTP(cal.AnimeID, true, false);
                        cmdAnime.Save();
                    }
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException("Error processing CommandRequest_GetCalendar: " + ex.ToString(), ex);
                return;
            }
        }
Ejemplo n.º 58
0
        /// <summary>
        /// Creates an <see cref="AnimeGroup"/> instance.
        /// </summary>
        /// <remarks>
        /// This method only creates an <see cref="AnimeGroup"/> instance. It does NOT save it to the database.
        /// </remarks>
        /// <param name="session">The NHibernate session.</param>
        /// <param name="mainSeries">The <see cref="AnimeSeries"/> whose name will represent the group (Optional. Pass <c>null</c> if not available).</param>
        /// <param name="mainAnimeId">The ID of the anime whose name will represent the group if <paramref name="mainSeries"/> is <c>null</c>.</param>
        /// <param name="now">The current date/time.</param>
        /// <returns>The created <see cref="AnimeGroup"/>.</returns>
        private AnimeGroup CreateAnimeGroup(ISessionWrapper session, AnimeSeries mainSeries, int mainAnimeId, DateTime now)
        {
            AnimeGroup animeGroup = new AnimeGroup();
            string groupName = null;

            if (mainSeries != null)
            {
                animeGroup.Populate(mainSeries, now);
                groupName = mainSeries.GetSeriesName(session);
            }
            else // The anime chosen as the group's main anime doesn't actually have a series
            {
                AniDB_Anime mainAnime = _aniDbAnimeRepo.GetByAnimeID(mainAnimeId);

                animeGroup.Populate(mainAnime, now);
                groupName = mainAnime.GetFormattedTitle();
            }

            groupName = _truncateYearRegex.Replace(groupName, String.Empty); // If the title appears to end with a year suffix, then remove it
            animeGroup.GroupName = groupName;
            animeGroup.SortName = groupName;

            return animeGroup;
        }
Ejemplo n.º 59
0
		public void Populate(AnimeSeries series)
		{
			this.Description = series.GetAnime().Description;
			this.GroupName = series.GetAnime().PreferredTitle;
			this.SortName = series.GetAnime().PreferredTitle;
			this.DateTimeUpdated = DateTime.Now;
			this.DateTimeCreated = DateTime.Now;
		}
Ejemplo n.º 60
0
		public void Save(AnimeSeries obj)
		{
			Save(obj, true);
		}