Exemplo n.º 1
0
		private List<string> GetPosterFilenames(ISession session)
		{
			List<string> allPosters = new List<string>();

			// check if user has specied a fanart to always be used
			if (DefaultAnimeSeriesID.HasValue)
			{
				AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
				AnimeSeries defaultSeries = repSeries.GetByID(session, DefaultAnimeSeriesID.Value);
				if (defaultSeries != null)
				{
					AniDB_Anime anime = defaultSeries.GetAnime(session);
					string defPosterPathNoBlanks = anime.GetDefaultPosterPathNoBlanks(session);

					if (!string.IsNullOrEmpty(defPosterPathNoBlanks) && File.Exists(defPosterPathNoBlanks))
					{
						allPosters.Add(defPosterPathNoBlanks);
						return allPosters;
					}
				}
			}

			foreach (AnimeSeries ser in GetAllSeries(session))
			{
				AniDB_Anime anime = ser.GetAnime(session);
				string defPosterPathNoBlanks = anime.GetDefaultPosterPathNoBlanks(session);

				if (!string.IsNullOrEmpty(defPosterPathNoBlanks) && File.Exists(defPosterPathNoBlanks))
					allPosters.Add(defPosterPathNoBlanks);
			}

			return allPosters;
		}
 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);
     }
 }
		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;
			}
		}
Exemplo n.º 4
0
        public List<Contract_AnimeEpisode> GetEpisodesForSeries(int animeSeriesID, int userID)
        {
            List<Contract_AnimeEpisode> eps = new List<Contract_AnimeEpisode>();
            try
            {

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

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

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

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

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

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

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

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

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

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

            return eps;
        }
        public void VoteAnime(string userid, string seriesid, string votevalue, string votetype)
        {
            int serid = 0;
            int usid = 0;
            int vt = 0;
            double vvalue = 0;
            if (!int.TryParse(seriesid, out serid))
                return;
            if (!int.TryParse(userid, out usid))
                return;
            if (!int.TryParse(votetype, out vt))
                return;
            if (!double.TryParse(votevalue, NumberStyles.Any, CultureInfo.InvariantCulture, out vvalue))
                return;
            using (var session = JMMService.SessionFactory.OpenSession())
            {
                
                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                AnimeSeries ser = repSeries.GetByID(session, serid);
                AniDB_Anime anime = ser?.GetAnime();
                if (anime == null)
                    return;
                string msg = string.Format("Voting for anime: {0} - Value: {1}", anime.AnimeID, vvalue);
                logger.Info(msg);

                // lets save to the database and assume it will work
                AniDB_VoteRepository repVotes = new AniDB_VoteRepository();
                List<AniDB_Vote> dbVotes = repVotes.GetByEntity(anime.AnimeID);
                AniDB_Vote thisVote = null;
                foreach (AniDB_Vote dbVote in dbVotes)
                {
                    // we can only have anime permanent or anime temp but not both
                    if (vt == (int) enAniDBVoteType.Anime || vt == (int) enAniDBVoteType.AnimeTemp)
                    {
                        if (dbVote.VoteType == (int) enAniDBVoteType.Anime ||
                            dbVote.VoteType == (int) enAniDBVoteType.AnimeTemp)
                        {
                            thisVote = dbVote;
                        }
                    }
                    else
                    {
                        thisVote = dbVote;
                    }
                }

                if (thisVote == null)
                {
                    thisVote = new AniDB_Vote();
                    thisVote.EntityID = anime.AnimeID;
                }
                thisVote.VoteType = vt;

                int iVoteValue = 0;
                if (vvalue > 0)
                    iVoteValue = (int) (vvalue*100);
                else
                    iVoteValue = (int) vvalue;

                msg = string.Format("Voting for anime Formatted: {0} - Value: {1}", anime.AnimeID, iVoteValue);
                logger.Info(msg);
                thisVote.VoteValue = iVoteValue;
                repVotes.Save(thisVote);
                CommandRequest_VoteAnime cmdVote = new CommandRequest_VoteAnime(anime.AnimeID, vt, Convert.ToDecimal(vvalue));
                cmdVote.Save();
            }
        }
Exemplo n.º 6
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;
            }
        }
Exemplo n.º 7
0
        public Contract_AnimeSeries_SaveResponse MoveSeries(int animeSeriesID, int newAnimeGroupID, int userID)
        {
            Contract_AnimeSeries_SaveResponse contractout = new Contract_AnimeSeries_SaveResponse();
            contractout.ErrorMessage = "";
            contractout.AnimeSeries = null;
            try
            {

                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                AnimeSeries ser = null;

                ser = repSeries.GetByID(animeSeriesID);
                if (ser == null)
                {
                    contractout.ErrorMessage = "Could not find existing series with ID: " + animeSeriesID.ToString();
                    return contractout;
                }

                // make sure the group exists
                AnimeGroupRepository repGroups = new AnimeGroupRepository();
                AnimeGroup grpTemp = repGroups.GetByID(newAnimeGroupID);
                if (grpTemp == null)
                {
                    contractout.ErrorMessage = "Could not find existing group with ID: " + newAnimeGroupID.ToString();
                    return contractout;
                }

                int oldGroupID = ser.AnimeGroupID;
                ser.AnimeGroupID = newAnimeGroupID;
                ser.DateTimeUpdated = DateTime.Now;

                repSeries.Save(ser);

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

                // update stats for old groups
                AnimeGroup grp = repGroups.GetByID(oldGroupID);
                if (grp != null)
                {
                    grp.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true, true, true);
                }

                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;
                }
                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, xrefMovie,
                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;
            }
        }
Exemplo n.º 8
0
        public Contract_AnimeGroup GetTopLevelGroupForSeries(int animeSeriesID, int userID)
        {
            try
            {
                AnimeGroupRepository repGroups = new AnimeGroupRepository();
                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();

                AnimeSeries ser = repSeries.GetByID(animeSeriesID);
                if (ser == null) return null;

                AnimeGroup grp = ser.TopLevelAnimeGroup;
                if (grp == null) return null;

                return grp.ToContract(grp.GetUserRecord(userID));

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

            return null;
        }
Exemplo n.º 9
0
        /// <summary>
        /// Finds the previous episode for use int the next unwatched episode
        /// </summary>
        /// <param name="animeSeriesID"></param>
        /// <param name="userID"></param>
        /// <returns></returns>
        public Contract_AnimeEpisode GetPreviousEpisodeForUnwatched(int animeSeriesID, int userID)
        {
            try
            {
                Contract_AnimeEpisode nextEp = GetNextUnwatchedEpisode(animeSeriesID, userID);
                if (nextEp == null) return null;

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

                if (epNum <= 0) return null;

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

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

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

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

            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return null;
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Gets a list of episodes watched based on the most recently watched series
        /// It will return the next episode to watch in the most recent 10 series
        /// </summary>
        /// <returns></returns>
        public List<Contract_AnimeEpisode> GetEpisodesToWatch_RecentlyWatched(int maxRecords, int jmmuserID)
        {
            List<Contract_AnimeEpisode> retEps = new List<Contract_AnimeEpisode>();
            try
            {
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
                    AnimeSeriesRepository repAnimeSer = new AnimeSeriesRepository();
                    AnimeSeries_UserRepository repSeriesUser = new AnimeSeries_UserRepository();
                    JMMUserRepository repUsers = new JMMUserRepository();

                    DateTime start = DateTime.Now;

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

                    // get a list of series that is applicable
                    List<AnimeSeries_User> allSeriesUser = repSeriesUser.GetMostRecentlyWatched(session, jmmuserID);

                    TimeSpan ts = DateTime.Now - start;
                    logger.Info(string.Format("GetEpisodesToWatch_RecentlyWatched:Series: {0}", ts.TotalMilliseconds));
                    start = DateTime.Now;

                    foreach (AnimeSeries_User userRecord in allSeriesUser)
                    {
                        AnimeSeries series = repAnimeSer.GetByID(session, userRecord.AnimeSeriesID);
                        if (series == null) continue;

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

                        Contract_AnimeEpisode ep = GetNextUnwatchedEpisode(session, userRecord.AnimeSeriesID, jmmuserID);
                        if (ep != null)
                        {
                            retEps.Add(ep);

                            // Lets only return the specified amount
                            if (retEps.Count == maxRecords)
                            {
                                ts = DateTime.Now - start;
                                logger.Info(string.Format("GetEpisodesToWatch_RecentlyWatched:Episodes: {0}", ts.TotalMilliseconds));
                                return retEps;
                            }
                        }
                    }
                    ts = DateTime.Now - start;
                    logger.Info(string.Format("GetEpisodesToWatch_RecentlyWatched:Episodes: {0}", ts.TotalMilliseconds));
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }

            return retEps;
        }
Exemplo n.º 11
0
		public AnimeSeries GetAnimeSeries(ISession session)
		{
			AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
			return repSeries.GetByID(session, this.AnimeSeriesID);
		}
Exemplo n.º 12
0
		public void UpdateUsingSeries(ISession session, int animeSeriesID)
		{
			try
			{
				DateTime start = DateTime.Now;

				AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
				AnimeSeries ser = repSeries.GetByID(session, animeSeriesID);
				if (ser == null) return;

				foreach (AnimeGroup grp in ser.AllGroupsAbove)
				{
					UpdateUsingGroup(session, grp.AnimeGroupID);
				}

				TimeSpan ts = DateTime.Now - start;
				logger.Info("Updated cached stats series ({0}) in {1} ms", ser.GetAnime().MainTitle, ts.TotalMilliseconds);
			}
			catch (Exception ex)
			{
				logger.ErrorException(ex.ToString(), ex);
			}
		}
Exemplo n.º 13
0
        public System.IO.Stream VoteAnime(string userid, string objectid, string votevalue, string votetype)
        {
            Respond rsp = new Respond();
            rsp.code = 500;

            int objid = 0;
            int usid = 0;
            int vt = 0;
            double vvalue = 0;
            if (!int.TryParse(objectid, out objid))
                return KodiHelper.GetStreamFromXmlObject(rsp);
            if (!int.TryParse(userid, out usid))
                return KodiHelper.GetStreamFromXmlObject(rsp);
            if (!int.TryParse(votetype, out vt))
                return KodiHelper.GetStreamFromXmlObject(rsp);
            if (!double.TryParse(votevalue, NumberStyles.Any, CultureInfo.InvariantCulture, out vvalue))
                return KodiHelper.GetStreamFromXmlObject(rsp);
            using (var session = JMMService.SessionFactory.OpenSession())
            {
                if (vt == (int)enAniDBVoteType.Episode)
                {
                    AnimeEpisodeRepository repEpisodes = new AnimeEpisodeRepository();
                    AnimeEpisode ep = repEpisodes.GetByID(session, objid);
                    AniDB_Anime anime = ep.GetAnimeSeries().GetAnime();
                    if (anime == null)
                    {
                        rsp.code = 404;
                        return KodiHelper.GetStreamFromXmlObject(rsp);
                    }
                    string msg = string.Format("Voting for anime episode: {0} - Value: {1}", ep.AnimeEpisodeID, vvalue);
                    logger.Info(msg);

                    // lets save to the database and assume it will work
                    AniDB_VoteRepository repVotes = new AniDB_VoteRepository();
                    List<AniDB_Vote> dbVotes = repVotes.GetByEntity(ep.AnimeEpisodeID);
                    AniDB_Vote thisVote = null;
                    foreach (AniDB_Vote dbVote in dbVotes)
                    {
                        if (dbVote.VoteType == (int)enAniDBVoteType.Episode)
                        {
                            thisVote = dbVote;
                        }
                    }

                    if (thisVote == null)
                    {
                        thisVote = new AniDB_Vote();
                        thisVote.EntityID = ep.AnimeEpisodeID;
                    }
                    thisVote.VoteType = vt;

                    int iVoteValue = 0;
                    if (vvalue > 0)
                        iVoteValue = (int)(vvalue * 100);
                    else
                        iVoteValue = (int)vvalue;

                    msg = string.Format("Voting for anime episode Formatted: {0} - Value: {1}", ep.AnimeEpisodeID, iVoteValue);
                    logger.Info(msg);
                    thisVote.VoteValue = iVoteValue;
                    repVotes.Save(thisVote);
                    CommandRequest_VoteAnime cmdVote = new CommandRequest_VoteAnime(anime.AnimeID, vt, Convert.ToDecimal(vvalue));
                    cmdVote.Save();
                }

                if (vt == (int)enAniDBVoteType.Anime)
                {
                    AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                    AnimeSeries ser = repSeries.GetByID(session, objid);
                    AniDB_Anime anime = ser.GetAnime();
                    if (anime == null)
                    {
                        rsp.code = 404;
                        return KodiHelper.GetStreamFromXmlObject(rsp);
                    }
                    string msg = string.Format("Voting for anime: {0} - Value: {1}", anime.AnimeID, vvalue);
                    logger.Info(msg);

                    // lets save to the database and assume it will work
                    AniDB_VoteRepository repVotes = new AniDB_VoteRepository();
                    List<AniDB_Vote> dbVotes = repVotes.GetByEntity(anime.AnimeID);
                    AniDB_Vote thisVote = null;
                    foreach (AniDB_Vote dbVote in dbVotes)
                    {
                        // we can only have anime permanent or anime temp but not both
                        if (vt == (int)enAniDBVoteType.Anime || vt == (int)enAniDBVoteType.AnimeTemp)
                        {
                            if (dbVote.VoteType == (int)enAniDBVoteType.Anime ||
                                dbVote.VoteType == (int)enAniDBVoteType.AnimeTemp)
                            {
                                thisVote = dbVote;
                            }
                        }
                        else
                        {
                            thisVote = dbVote;
                        }
                    }

                    if (thisVote == null)
                    {
                        thisVote = new AniDB_Vote();
                        thisVote.EntityID = anime.AnimeID;
                    }
                    thisVote.VoteType = vt;

                    int iVoteValue = 0;
                    if (vvalue > 0)
                        iVoteValue = (int)(vvalue * 100);
                    else
                        iVoteValue = (int)vvalue;

                    msg = string.Format("Voting for anime Formatted: {0} - Value: {1}", anime.AnimeID, iVoteValue);
                    logger.Info(msg);
                    thisVote.VoteValue = iVoteValue;
                    repVotes.Save(thisVote);
                    CommandRequest_VoteAnime cmdVote = new CommandRequest_VoteAnime(anime.AnimeID, vt, Convert.ToDecimal(vvalue));
                    cmdVote.Save();
                }
                rsp.code = 200;
                return KodiHelper.GetStreamFromXmlObject(rsp);
            }
        }
Exemplo n.º 14
0
        public System.IO.Stream GetItemsFromSerie(int userid, string SerieId)
        {
            KodiObject ret = new KodiObject(KodiHelper.NewMediaContainer("Series", true));
            if (!ret.Init())
                return new MemoryStream();
            enEpisodeType? eptype = null;
            int serieID ;
            if (SerieId.Contains("_"))
            {
                int ept ;
                string[] ndata = SerieId.Split('_');
                if (!int.TryParse(ndata[0], out ept))
                    return new MemoryStream();
                eptype = (enEpisodeType) ept;
                if (!int.TryParse(ndata[1], out serieID))
                    return new MemoryStream();
            }
            else
            {
                if (!int.TryParse(SerieId, out serieID))
                    return new MemoryStream();
            }

            using (var session = JMMService.SessionFactory.OpenSession())
            {
                if (serieID == -1)
                    return new MemoryStream();
                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                AnimeSeries ser = repSeries.GetByID(session, serieID);
                if (ser == null)
                    return new MemoryStream();
                AniDB_Anime anime = ser.GetAnime();
                if (anime == null)
                    return new MemoryStream();

                ImageDetails fanart = anime.GetDefaultFanartDetailsNoBlanks(session);
                if (fanart != null)
                    ret.MediaContainer.Art = fanart.GenArt();
                ret.MediaContainer.Title2 = ret.MediaContainer.Title1 = anime.MainTitle;
                List<AnimeEpisode> episodes = ser.GetAnimeEpisodes(session).Where(a => a.GetVideoLocals(session).Count > 0).ToList();
                if (eptype.HasValue)
                {
                    episodes = episodes.Where(a => a.EpisodeTypeEnum == eptype.Value).ToList();
                }
                else
                {
                    List<enEpisodeType> types = episodes.Select(a => a.EpisodeTypeEnum).Distinct().ToList();
                    if (types.Count > 1)
                    {
                        List<KodiEpisodeType> eps = new List<KodiEpisodeType>();
                        foreach (enEpisodeType ee in types)
                        {
                            KodiEpisodeType k2 = new KodiEpisodeType();
                            KodiEpisodeType.EpisodeTypeTranslated(k2, ee, (AnimeTypes)anime.AnimeType, episodes.Count(a => a.EpisodeTypeEnum == ee));
                            eps.Add(k2);
                        }
                        List<SortPropOrFieldAndDirection> sortCriteria = new List<SortPropOrFieldAndDirection>();
                        sortCriteria.Add(new SortPropOrFieldAndDirection("Name", SortType.eString));
                        eps = Sorting.MultiSort(eps, sortCriteria);
                        List<Video> dirs= new List<Video>();

                        bool isCharacterSetup_ = false;

                        foreach (KodiEpisodeType ee in  eps)
                        {
                            Video v = new Directory();
                            v.Title = ee.Name;
                            v.Type = "season";
                            v.LeafCount = ee.Count.ToString();
                            v.ViewedLeafCount = "0";
                            v.Key = KodiHelper.ServerUrl(int.Parse(ServerSettings.JMMServerPort), MainWindow.PathAddressKodi + "/GetMetadata/" + userid + "/" + (int)JMMType.Serie + "/" + ee.Type + "_" + ser.AnimeSeriesID);
                            v.Thumb = KodiHelper.ServerUrl(int.Parse(ServerSettings.JMMServerPort),
                                MainWindow.PathAddressKodi + "/GetSupportImage/" + ee.Image);
                            if ((ee.AnimeType==AnimeTypes.Movie) || (ee.AnimeType==AnimeTypes.OVA))
                            {
                                v = KodiHelper.MayReplaceVideo((Directory)v, ser,anime,  JMMType.File, userid, false);
                            }

                            //proper naming
                            v.OriginalTitle = "";
                            foreach (AniDB_Anime_Title title in anime.GetTitles())
                            {
                                if (title.TitleType == "official" || title.TitleType == "main")
                                {
                                    v.OriginalTitle += "{" + title.TitleType + ":" + title.Language + "}" + title.Title + "|";
                                }
                            }
                            v.OriginalTitle = v.OriginalTitle.Substring(0, v.OriginalTitle.Length - 1);
                            //proper naming end

                            //experiment
                            if (!isCharacterSetup_)
                            {
                                Characters ch = new Characters();
                                ch.CharactersList = new List<Character>();
                                ch.CharactersList = GetCharactersFromAniDB(anime);
                                v.CharactersList = new List<Characters>();
                                v.CharactersList.Add(ch);
                                isCharacterSetup_ = true;
                            }
                            //experimentEND

                            dirs.Add(v);
                        }
                        ret.Childrens = dirs;
                        return ret.GetStream();
                    }
                }
                List<Video> vids=new List<Video>();
                Contract_AnimeSeries cseries = ser.ToContract(ser.GetUserRecord(userid), true);
                Video nv = KodiHelper.FromSerie(cseries, userid);
                KodiEpisodeType k = new KodiEpisodeType();
                if (eptype.HasValue)
                {
                    KodiEpisodeType.EpisodeTypeTranslated(k, (enEpisodeType) eptype.Value, (AnimeTypes) anime.AnimeType,
                        episodes.Count);
                }

                bool isCharacterSetup = false;

                foreach (AnimeEpisode ep in episodes)
                {
                    Video v = new Video();
                    List<VideoLocal> locals = ep.GetVideoLocals(session);
                    if ((locals == null) || (locals.Count == 0))
                        continue;
                    AniDB_Episode aep = ep.AniDB_Episode;
                    if (aep == null)
                        continue;
                    VideoLocal current = locals[0];
                    try
                    {
                        KodiHelper.PopulateVideo(v, current, ep, ser, anime, nv, JMMType.File, userid);
                        if (eptype.HasValue)
                        {
                            v.ParentTitle = k.Name;
                        }

                        //experiment
                        if (!isCharacterSetup)
                        {
                            Characters c = new Characters();
                            c.CharactersList = new List<Character>();
                            c.CharactersList = GetCharactersFromAniDB(anime);
                            v.CharactersList = new List<Characters>();
                            v.CharactersList.Add(c);
                            isCharacterSetup = true;
                        }
                        //experimentEND

                        vids.Add(v);
                    }
                    catch (Exception e)
                    {
                        //Fast fix if file do not exist, and still is in db. (Xml Serialization of video info will fail on null)
                    }
                }

                List<SortPropOrFieldAndDirection> sortCriteria2 = new List<SortPropOrFieldAndDirection>();
                sortCriteria2.Add(new SortPropOrFieldAndDirection("EpNumber", SortType.eInteger));
                vids= Sorting.MultiSort(vids, sortCriteria2);
                ret.Childrens = vids;

                return ret.GetStream();
            }
        }
Exemplo n.º 15
0
        public List<Contract_AnimeEpisode> GetEpisodesForSeriesOld(int animeSeriesID)
        {
            List<Contract_AnimeEpisode> eps = new List<Contract_AnimeEpisode>();
            try
            {

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

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

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

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

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

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

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

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

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

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

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

                    DateTime start = DateTime.Now;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

							retAnime.Add(summ);
							numEps++;

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


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

			return retAnime;
		}
Exemplo n.º 18
0
        public Contract_AnimeEpisode GetNextUnwatchedEpisode(ISession session, int animeSeriesID, int userID)
        {
            try
            {
                AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
                AnimeSeriesRepository repAnimeSer = new AnimeSeriesRepository();
                AnimeEpisode_UserRepository repEpUser = new AnimeEpisode_UserRepository();

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

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

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

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

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

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

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

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

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

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

                return null;
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return null;
            }
        }
		public List<MetroContract_Anime_Summary> GetAnimeContinueWatching_old(int maxRecords, int jmmuserID)
		{
			List<MetroContract_Anime_Summary> retAnime = new List<MetroContract_Anime_Summary>();
			try
			{
				using (var session = JMMService.SessionFactory.OpenSession())
				{
					AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
					AnimeSeriesRepository repAnimeSer = new AnimeSeriesRepository();
					AnimeSeries_UserRepository repSeriesUser = new AnimeSeries_UserRepository();
					JMMUserRepository repUsers = new JMMUserRepository();

					DateTime start = DateTime.Now;

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

					// get a list of series that is applicable
					List<AnimeSeries_User> allSeriesUser = repSeriesUser.GetMostRecentlyWatched(session, jmmuserID);

					TimeSpan ts = DateTime.Now - start;
					logger.Info(string.Format("GetAnimeContinueWatching:Series: {0}", ts.TotalMilliseconds));
					

					JMMServiceImplementation imp = new JMMServiceImplementation();
					foreach (AnimeSeries_User userRecord in allSeriesUser)
					{
						start = DateTime.Now;

						AnimeSeries series = repAnimeSer.GetByID(session, userRecord.AnimeSeriesID);
						if (series == null) continue;

						if (!user.AllowedSeries(session, series))
						{
							logger.Info(string.Format("GetAnimeContinueWatching:Skipping Anime - not allowed: {0}", series.AniDB_ID));
							continue;
						}

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

						Contract_AnimeEpisode ep = imp.GetNextUnwatchedEpisode(session, userRecord.AnimeSeriesID, jmmuserID);
						if (ep != null)
						{
							AniDB_Anime anidb_anime = series.GetAnime(session);

							MetroContract_Anime_Summary summ = new MetroContract_Anime_Summary();
							summ.AnimeID = series.AniDB_ID;
							summ.AnimeName = series.GetSeriesName(session);
							summ.AnimeSeriesID = series.AnimeSeriesID;
							summ.BeginYear = anidb_anime.BeginYear;
							summ.EndYear = anidb_anime.EndYear;
							//summ.PosterName = anidb_anime.GetDefaultPosterPathNoBlanks(session);

							if (serUser != null)
								summ.UnwatchedEpisodeCount = serUser.UnwatchedEpisodeCount;
							else
								summ.UnwatchedEpisodeCount = 0;

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

							retAnime.Add(summ);

							ts = DateTime.Now - start;
							logger.Info(string.Format("GetAnimeContinueWatching:Anime: {0} - {1}", summ.AnimeName, ts.TotalMilliseconds));

							// Lets only return the specified amount
							if (retAnime.Count == maxRecords) return retAnime;
						}
						else
							logger.Info(string.Format("GetAnimeContinueWatching:Skipping Anime - no episodes: {0}", series.AniDB_ID));

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

			return retAnime;
		}
Exemplo n.º 20
0
        public Contract_AnimeSeries GetSeries(int animeSeriesID, int userID)
        {
            AnimeSeriesRepository repAnimeSer = new AnimeSeriesRepository();

            try
            {
                AnimeSeries series = repAnimeSer.GetByID(animeSeriesID);
                if (series == null) return null;

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

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

                List<TvDB_Series> sers = new List<TvDB_Series>();
                foreach (CrossRef_AniDB_TvDBV2 xref in xrefs)
                    sers.Add(xref.GetTvDBSeries());
                CrossRef_AniDB_Other xrefMovie = series.CrossRefMovieDB;
                MovieDB_Movie movie = null;
                if (xrefMovie != null)
                    movie = xrefMovie.GetMovieDB_Movie();
                return series.ToContract(anime, xrefs, xrefMovie, series.GetUserRecord(userID),
                    sers, xrefMAL, false, null, null, null, null,movie);
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }
            return null;
        }
Exemplo n.º 21
0
        public string AssociateMultipleFiles(List<int> videoLocalIDs, int animeSeriesID, int startingEpisodeNumber, bool singleEpisode)
        {
            try
            {
                CrossRef_File_EpisodeRepository repXRefs = new CrossRef_File_EpisodeRepository();
                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                VideoLocalRepository repVids = new VideoLocalRepository();
                AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository();
                AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();

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

                int epNumber = startingEpisodeNumber;
                int count = 1;

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

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

                    AniDB_Episode aniep = anieps[0];

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

                    AnimeEpisode ep = eps[0];

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

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

                    repXRefs.Save(xref);

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

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

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

                ser.QueueUpdateStats();

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

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

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

            return "";
        }
Exemplo n.º 22
0
        /// <summary>
        /// Delete a series, and everything underneath it (episodes, files)
        /// </summary>
        /// <param name="animeSeriesID"></param>
        /// <param name="deleteFiles">also delete the physical files</param>
        /// <returns></returns>
        public string DeleteAnimeSeries(int animeSeriesID, bool deleteFiles, bool deleteParentGroup)
        {
            try
            {
                AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
                AnimeSeriesRepository repAnimeSer = new AnimeSeriesRepository();
                VideoLocalRepository repVids = new VideoLocalRepository();
                AnimeGroupRepository repGroups = new AnimeGroupRepository();

                AnimeSeries ser = repAnimeSer.GetByID(animeSeriesID);
                if (ser == null) return "Series does not exist";

                int animeGroupID = ser.AnimeGroupID;

                foreach (AnimeEpisode ep in ser.GetAnimeEpisodes())
                {
                    foreach (VideoLocal vid in ep.GetVideoLocals())
                    {
                        if (deleteFiles)
                        {
                            logger.Info("Deleting video local record and file: {0}", vid.FullServerPath);
                            if (!File.Exists(vid.FullServerPath)) return "File could not be found";
                            File.Delete(vid.FullServerPath);
                        }
                        CommandRequest_DeleteFileFromMyList cmdDel = new CommandRequest_DeleteFileFromMyList(vid.Hash, vid.FileSize);
                        cmdDel.Save();

                        repVids.Delete(vid.VideoLocalID);
                    }

                    repEps.Delete(ep.AnimeEpisodeID);
                }
                repAnimeSer.Delete(ser.AnimeSeriesID);

                // finally update stats
                AnimeGroup grp = repGroups.GetByID(animeGroupID);
                if (grp != null)
                {
                    if (grp.GetAllSeries().Count == 0)
                    {
                        DeleteAnimeGroup(grp.AnimeGroupID, false);
                    }
                    else
                    {
                        grp.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true, true, true);
                        StatsCache.Instance.UpdateUsingGroup(grp.TopLevelAnimeGroup.AnimeGroupID);
                    }
                }

                return "";

            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return ex.Message;
            }
        }
Exemplo n.º 23
0
        public List<Contract_AnimeGroup> GetAllGroupsAboveSeries(int animeSeriesID, int userID)
        {
            List<Contract_AnimeGroup> grps = new List<Contract_AnimeGroup>();
            try
            {
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                    AnimeSeries series = repSeries.GetByID(session, animeSeriesID);
                    if (series == null)
                        return grps;

                    foreach (AnimeGroup grp in series.AllGroupsAbove)
                    {
                        Contract_AnimeGroup contractGrpTemp = grp.ToContract(grp.GetUserRecord(session, userID));
                        grps.Add(contractGrpTemp);
                    }

                    return grps;
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }
            return grps;
        }
Exemplo n.º 24
0
        public string RemoveAssociationOnFile(int videoLocalID, int aniDBEpisodeID)
        {
            try
            {
                VideoLocalRepository repVids = new VideoLocalRepository();
                CrossRef_File_EpisodeRepository repXRefs = new CrossRef_File_EpisodeRepository();

                VideoLocal vid = repVids.GetByID(videoLocalID);
                if (vid == null)
                    return "Could not find video record";

                int? animeSeriesID = null;
                foreach (AnimeEpisode ep in vid.GetAnimeEpisodes())
                {
                    if (ep.AniDB_EpisodeID != aniDBEpisodeID) continue;

                    animeSeriesID = ep.AnimeSeriesID;
                    CrossRef_File_Episode xref = repXRefs.GetByHashAndEpisodeID(vid.Hash, ep.AniDB_EpisodeID);
                    if (xref != null)
                    {
                        if (xref.CrossRefSource == (int)CrossRefSource.AniDB)
                            return "Cannot remove associations created from AniDB data";

                        // delete cross ref from web cache
                        CommandRequest_WebCacheDeleteXRefFileEpisode cr = new CommandRequest_WebCacheDeleteXRefFileEpisode(vid.Hash, ep.AniDB_EpisodeID);
                        cr.Save();

                        repXRefs.Delete(xref.CrossRef_File_EpisodeID);
                    }
                }

                if (animeSeriesID.HasValue)
                {
                    AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                    AnimeSeries ser = repSeries.GetByID(animeSeriesID.Value);
                    if (ser != null)
                        ser.QueueUpdateStats();
                }

                return "";

            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return ex.Message;
            }
        }
Exemplo n.º 25
0
        public string AssociateSingleFileWithMultipleEpisodes(int videoLocalID, int animeSeriesID, int startEpNum, int endEpNum)
        {
            try
            {
                VideoLocalRepository repVids = new VideoLocalRepository();
                VideoLocal vid = repVids.GetByID(videoLocalID);
                if (vid == null)
                    return "Could not find video record";

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

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

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

                    AniDB_Episode aniep = anieps[0];

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

                    AnimeEpisode ep = eps[0];

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

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

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

                ser.QueueUpdateStats();

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

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

                return "";

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

            return "";
        }
Exemplo n.º 26
0
        public void SetDefaultSeriesForGroup(int animeGroupID, int animeSeriesID)
        {
            try
            {
                AnimeGroupRepository repGroups = new AnimeGroupRepository();
                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();

                AnimeGroup grp = repGroups.GetByID(animeGroupID);
                if (grp == null) return;

                AnimeSeries ser = repSeries.GetByID(animeSeriesID);
                if (ser == null) return;

                grp.DefaultAnimeSeriesID = animeSeriesID;
                repGroups.Save(grp);

            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }
        }
Exemplo n.º 27
0
        public System.IO.Stream GetItemsFromSerie(int userid, string SerieId,HistoryInfo info)
        {
            PlexObject ret = null;
            enEpisodeType? eptype = null;
            int serieID ;
            if (SerieId.Contains("_"))
            {
                int ept ;
                string[] ndata = SerieId.Split('_');
                if (!int.TryParse(ndata[0], out ept))
                    return new MemoryStream();
                eptype = (enEpisodeType) ept;
                if (!int.TryParse(ndata[1], out serieID))
                    return new MemoryStream();
            }
            else
            {
                if (!int.TryParse(SerieId, out serieID))
                    return new MemoryStream();
            }

            using (var session = JMMService.SessionFactory.OpenSession())
            {
                if (serieID == -1)
                    return new MemoryStream();
                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                AnimeSeries ser = repSeries.GetByID(session, serieID);
                if (ser == null)
                    return new MemoryStream();
                AniDB_Anime anime = ser.GetAnime();
                if (anime == null)
                    return new MemoryStream();
                Contract_AnimeSeries cseries = ser.ToContract(ser.GetUserRecord(userid), true);
                ImageDetails fanart = anime.GetDefaultFanartDetailsNoBlanks(session);

                //iOS Hack, since it uses the previous thumb, as overlay image on the episodes
                bool iosHack = false;
                if (WebOperationContext.Current != null && WebOperationContext.Current.IncomingRequest.Headers.AllKeys.Contains("X-Plex-Product"))
                {
                    string kh = WebOperationContext.Current.IncomingRequest.Headers.Get("X-Plex-Product").ToUpper();
                    if (kh.Contains(" IOS"))
                        iosHack = true;
                }

                List<AnimeEpisode> episodes = ser.GetAnimeEpisodes(session).Where(a => a.GetVideoLocals(session).Count > 0).ToList();
                if (eptype.HasValue)
                {
                    ret = new PlexObject(PlexHelper.NewMediaContainer(MediaContainerTypes.Episode, info, true));
                    if (!ret.Init())
                        return new MemoryStream();
                    ret.MediaContainer.LeafCount = (cseries.WatchedEpisodeCount + cseries.UnwatchedEpisodeCount).ToString();
                    ret.MediaContainer.ViewedLeafCount = cseries.WatchedEpisodeCount.ToString();
                    episodes = episodes.Where(a => a.EpisodeTypeEnum == eptype.Value).ToList();
                }
                else
                {
                    ret = new PlexObject(PlexHelper.NewMediaContainer(MediaContainerTypes.Show, info, true));
                    if (!ret.Init())
                        return new MemoryStream();

                    ret.MediaContainer.LeafCount = (cseries.WatchedEpisodeCount + cseries.UnwatchedEpisodeCount).ToString();
                    ret.MediaContainer.ViewedLeafCount = cseries.WatchedEpisodeCount.ToString();
                    List<enEpisodeType> types = episodes.Select(a => a.EpisodeTypeEnum).Distinct().ToList();
                    if (types.Count > 1)
                    {
                        List<PlexEpisodeType> eps = new List<PlexEpisodeType>();
                        foreach (enEpisodeType ee in types)
                        {
                            PlexEpisodeType k2 = new PlexEpisodeType();
                            PlexEpisodeType.EpisodeTypeTranslated(k2, ee, (AnimeTypes)anime.AnimeType, episodes.Count(a => a.EpisodeTypeEnum == ee));
                            eps.Add(k2);
                        }
                        List<SortPropOrFieldAndDirection> sortCriteria = new List<SortPropOrFieldAndDirection>();
                        sortCriteria.Add(new SortPropOrFieldAndDirection("Name", SortType.eString));
                        eps = Sorting.MultiSort(eps, sortCriteria);
                        List<Video> dirs= new List<Video>();
                        bool converttoseason = true;

                        foreach (PlexEpisodeType ee in  eps)
                        {
                            Video v = new Directory();
                            if (fanart != null)
                                v.Art = fanart.GenArt();
                            v.Title = ee.Name;
                            v.LeafCount = ee.Count.ToString();
                            v.ChildCount = v.LeafCount;
                            v.ViewedLeafCount = "0";
                            v.Key = PlexHelper.ConstructSerieIdUrl(userid, ee.Type + "_" + ser.AnimeSeriesID);
                            v.Thumb = PlexHelper.ConstructSupportImageLink(ee.Image);
                            if ((ee.AnimeType==AnimeTypes.Movie) || (ee.AnimeType==AnimeTypes.OVA))
                            {
                                v = PlexHelper.MayReplaceVideo(v, ser, cseries, anime,  JMMType.File, userid, false);
                            }
                            dirs.Add(v,info);
                            if (iosHack)
                            {
                                v.Thumb = ret.MediaContainer.ParentThumb;
                                v.ParentThumb = ret.MediaContainer.GrandparentThumb;
                                v.GrandparentThumb = ret.MediaContainer.GrandparentThumb;
                                v.ParentKey = v.GrandparentKey;
                            }
                        }
                        ret.Childrens = dirs;
                        return ret.GetStream();
                    }
                }
                List<Video> vids=new List<Video>();
                Video nv = new Video();
                PlexHelper.FillSerie(nv,ser,anime, cseries, userid);
                foreach (AnimeEpisode ep in episodes)
                {

                    Video v = new Video();
                    List<VideoLocal> locals = ep.GetVideoLocals(session);
                    if ((locals == null) || (locals.Count == 0))
                        continue;
                    AniDB_Episode aep = ep.AniDB_Episode;
                    if (aep == null)
                        continue;
                    VideoLocal current = locals[0];
                    try
                    {
                        PlexHelper.PopulateVideo(v, current, ep, ser, cseries, anime, nv, JMMType.File, userid);
                        vids.Add(v, info);
                        if (iosHack)
                        {
                            v.Art = v.Thumb;
                            v.Thumb = ret.MediaContainer.ParentThumb;
                        }
                    }
                    catch (Exception e)
                    {
                        //Fast fix if file do not exist, and still is in db. (Xml Serialization of video info will fail on null)
                    }
                }

                List<SortPropOrFieldAndDirection> sortCriteria2 = new List<SortPropOrFieldAndDirection>();
                sortCriteria2.Add(new SortPropOrFieldAndDirection("EpNumber", SortType.eInteger));
                vids= Sorting.MultiSort(vids, sortCriteria2);
                ret.Childrens = vids;

                return ret.GetStream();
            }
        }