public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_TraktSearchAnime: {0}", AnimeID);

            try
            {
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    // first check if the user wants to use the web cache
                    if (ServerSettings.WebCache_TvDB_Get)
                    {
                        try
                        {
                            CrossRef_AniDB_TraktResult crossRef = XMLService.Get_CrossRef_AniDB_Trakt(AnimeID);
                            if (crossRef != null)
                            {
                                TraktTVShow showInfo = TraktTVHelper.GetShowInfo(crossRef.TraktID);
                                if (showInfo != null)
                                {
                                    logger.Trace("Found trakt match on web cache for {0} - id = {1}", AnimeID, showInfo.title);
                                    TraktTVHelper.LinkAniDBTrakt(AnimeID, crossRef.TraktID, crossRef.TraktSeasonNumber, true);
                                    return;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            logger.ErrorException(ex.ToString(), ex);
                        }
                    }


                    // lets try to see locally if we have a tvDB link for this anime
                    // Trakt allows the use of TvDB ID's or their own Trakt ID's
                    CrossRef_AniDB_TvDBV2Repository repCrossRefTvDB = new CrossRef_AniDB_TvDBV2Repository();
                    List <CrossRef_AniDB_TvDBV2>    xrefTvDBs       = repCrossRefTvDB.GetByAnimeID(session, AnimeID);
                    if (xrefTvDBs != null && xrefTvDBs.Count == 1)                      //TODO this is temporary code, until trakt also allows multiple links
                    {
                        TraktTVShow showInfo = TraktTVHelper.GetShowInfo(xrefTvDBs[0].TvDBID);
                        if (showInfo != null)
                        {
                            // make sure the season specified by TvDB also exists on Trakt
                            Trakt_ShowRepository repShow   = new Trakt_ShowRepository();
                            Trakt_Show           traktShow = repShow.GetByTraktID(session, showInfo.TraktID);
                            if (traktShow != null)
                            {
                                Trakt_SeasonRepository repSeasons  = new Trakt_SeasonRepository();
                                Trakt_Season           traktSeason = repSeasons.GetByShowIDAndSeason(session, traktShow.Trakt_ShowID, xrefTvDBs[0].TvDBSeasonNumber);
                                if (traktSeason != null)
                                {
                                    logger.Trace("Found trakt match using TvDBID locally {0} - id = {1}", AnimeID, showInfo.title);
                                    TraktTVHelper.LinkAniDBTrakt(AnimeID, showInfo.TraktID, traktSeason.Season, true);
                                    return;
                                }
                            }
                        }
                    }

                    // if not lets try the tvdb web cache based on the same reasoning
                    if (ServerSettings.WebCache_TvDB_Get)
                    {
                        List <JMMServer.Providers.Azure.CrossRef_AniDB_TvDB> cacheResults = JMMServer.Providers.Azure.AzureWebAPI.Get_CrossRefAniDBTvDB(AnimeID);
                        if (cacheResults != null && cacheResults.Count > 0)
                        {
                            TraktTVShow showInfo = TraktTVHelper.GetShowInfo(cacheResults[0].TvDBID);
                            if (showInfo != null)
                            {
                                // make sure the season specified by TvDB also exists on Trakt
                                Trakt_ShowRepository repShow   = new Trakt_ShowRepository();
                                Trakt_Show           traktShow = repShow.GetByTraktID(session, showInfo.TraktID);
                                if (traktShow != null)
                                {
                                    Trakt_SeasonRepository repSeasons  = new Trakt_SeasonRepository();
                                    Trakt_Season           traktSeason = repSeasons.GetByShowIDAndSeason(session, traktShow.Trakt_ShowID, cacheResults[0].TvDBSeasonNumber);
                                    if (traktSeason != null)
                                    {
                                        logger.Trace("Found trakt match on web cache by using TvDBID {0} - id = {1}", AnimeID, showInfo.title);
                                        TraktTVHelper.LinkAniDBTrakt(AnimeID, showInfo.TraktID, traktSeason.Season, true);
                                        return;
                                    }
                                }
                            }
                        }
                    }

                    // finally lets try searching Trakt directly
                    string searchCriteria          = "";
                    AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
                    AniDB_Anime           anime    = repAnime.GetByAnimeID(session, AnimeID);
                    if (anime == null)
                    {
                        return;
                    }

                    searchCriteria = anime.MainTitle;

                    // if not wanting to use web cache, or no match found on the web cache go to TvDB directly
                    List <TraktTVShow> results = TraktTVHelper.SearchShow(searchCriteria);
                    logger.Trace("Found {0} trakt results for {1} ", results.Count, searchCriteria);
                    if (ProcessSearchResults(session, results, searchCriteria))
                    {
                        return;
                    }


                    if (results.Count == 0)
                    {
                        foreach (AniDB_Anime_Title title in anime.GetTitles(session))
                        {
                            if (title.TitleType.ToUpper() != Constants.AnimeTitleType.Official.ToUpper())
                            {
                                continue;
                            }

                            if (searchCriteria.ToUpper() == title.Title.ToUpper())
                            {
                                continue;
                            }

                            results = TraktTVHelper.SearchShow(searchCriteria);
                            logger.Trace("Found {0} trakt results for search on {1}", results.Count, title.Title);
                            if (ProcessSearchResults(session, results, title.Title))
                            {
                                return;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error processing CommandRequest_TvDBSearchAnime: {0} - {1}", AnimeID, ex.ToString());
                return;
            }
        }
Example #2
0
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_TraktSearchAnime: {0}", AnimeID);

            try
            {
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    // first check if the user wants to use the web cache
                    if (ServerSettings.WebCache_Trakt_Get)
                    {
                        try
                        {
                            List <Contract_Azure_CrossRef_AniDB_Trakt> contracts =
                                new List <Contract_Azure_CrossRef_AniDB_Trakt>();

                            List <JMMServer.Providers.Azure.CrossRef_AniDB_Trakt> resultsCache =
                                JMMServer.Providers.Azure.AzureWebAPI.Get_CrossRefAniDBTrakt(AnimeID);
                            if (resultsCache != null && resultsCache.Count > 0)
                            {
                                foreach (JMMServer.Providers.Azure.CrossRef_AniDB_Trakt xref in resultsCache)
                                {
                                    TraktV2ShowExtended showInfo = TraktTVHelper.GetShowInfoV2(xref.TraktID);
                                    if (showInfo != null)
                                    {
                                        logger.Trace("Found trakt match on web cache for {0} - id = {1}", AnimeID,
                                                     showInfo.title);
                                        TraktTVHelper.LinkAniDBTrakt(AnimeID, (enEpisodeType)xref.AniDBStartEpisodeType,
                                                                     xref.AniDBStartEpisodeNumber,
                                                                     xref.TraktID, xref.TraktSeasonNumber, xref.TraktStartEpisodeNumber, true);
                                        return;
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            logger.ErrorException(ex.ToString(), ex);
                        }
                    }


                    // lets try to see locally if we have a tvDB link for this anime
                    // Trakt allows the use of TvDB ID's or their own Trakt ID's
                    CrossRef_AniDB_TvDBV2Repository repCrossRefTvDB = new CrossRef_AniDB_TvDBV2Repository();
                    List <CrossRef_AniDB_TvDBV2>    xrefTvDBs       = repCrossRefTvDB.GetByAnimeID(session, AnimeID);
                    if (xrefTvDBs != null && xrefTvDBs.Count > 0)
                    {
                        foreach (CrossRef_AniDB_TvDBV2 tvXRef in xrefTvDBs)
                        {
                            // first search for this show by the TvDB ID
                            List <TraktV2SearchTvDBIDShowResult> searchResults =
                                TraktTVHelper.SearchShowByIDV2(TraktSearchIDType.tvdb,
                                                               tvXRef.TvDBID.ToString());
                            if (searchResults != null && searchResults.Count > 0)
                            {
                                // since we are searching by ID, there will only be one 'show' result
                                TraktV2Show resShow = null;
                                foreach (TraktV2SearchTvDBIDShowResult res in searchResults)
                                {
                                    if (res.ResultType == SearchIDType.Show)
                                    {
                                        resShow = res.show;
                                        break;
                                    }
                                }

                                if (resShow != null)
                                {
                                    TraktV2ShowExtended showInfo = TraktTVHelper.GetShowInfoV2(resShow.ids.slug);
                                    if (showInfo != null && showInfo.ids != null)
                                    {
                                        // make sure the season specified by TvDB also exists on Trakt
                                        Trakt_ShowRepository repShow   = new Trakt_ShowRepository();
                                        Trakt_Show           traktShow = repShow.GetByTraktSlug(session, showInfo.ids.slug);
                                        if (traktShow != null)
                                        {
                                            Trakt_SeasonRepository repSeasons  = new Trakt_SeasonRepository();
                                            Trakt_Season           traktSeason = repSeasons.GetByShowIDAndSeason(session,
                                                                                                                 traktShow.Trakt_ShowID,
                                                                                                                 xrefTvDBs[0].TvDBSeasonNumber);
                                            if (traktSeason != null)
                                            {
                                                logger.Trace("Found trakt match using TvDBID locally {0} - id = {1}",
                                                             AnimeID, showInfo.title);
                                                TraktTVHelper.LinkAniDBTrakt(AnimeID,
                                                                             (AniDBAPI.enEpisodeType)tvXRef.AniDBStartEpisodeType,
                                                                             tvXRef.AniDBStartEpisodeNumber, showInfo.ids.slug,
                                                                             tvXRef.TvDBSeasonNumber, tvXRef.TvDBStartEpisodeNumber,
                                                                             true);
                                                return;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // finally lets try searching Trakt directly
                    string searchCriteria          = "";
                    AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
                    AniDB_Anime           anime    = repAnime.GetByAnimeID(session, AnimeID);
                    if (anime == null)
                    {
                        return;
                    }

                    searchCriteria = anime.MainTitle;

                    // if not wanting to use web cache, or no match found on the web cache go to TvDB directly
                    List <TraktV2SearchShowResult> results = TraktTVHelper.SearchShowV2(searchCriteria);
                    logger.Trace("Found {0} trakt results for {1} ", results.Count, searchCriteria);
                    if (ProcessSearchResults(session, results, searchCriteria))
                    {
                        return;
                    }


                    if (results.Count == 0)
                    {
                        foreach (AniDB_Anime_Title title in anime.GetTitles(session))
                        {
                            if (title.TitleType.ToUpper() != Constants.AnimeTitleType.Official.ToUpper())
                            {
                                continue;
                            }

                            if (searchCriteria.ToUpper() == title.Title.ToUpper())
                            {
                                continue;
                            }

                            results = TraktTVHelper.SearchShowV2(searchCriteria);
                            logger.Trace("Found {0} trakt results for search on {1}", results.Count, title.Title);
                            if (ProcessSearchResults(session, results, title.Title))
                            {
                                return;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error processing CommandRequest_TvDBSearchAnime: {0} - {1}", AnimeID, ex.ToString());
                return;
            }
        }
Example #3
0
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_TvDBSearchAnime: {0}", AnimeID);

            try
            {
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    // first check if the user wants to use the web cache
                    if (ServerSettings.WebCache_TvDB_Get)
                    {
                        try
                        {
                            List <JMMServer.Providers.Azure.CrossRef_AniDB_TvDB> cacheResults =
                                JMMServer.Providers.Azure.AzureWebAPI.Get_CrossRefAniDBTvDB(AnimeID);
                            if (cacheResults != null && cacheResults.Count > 0)
                            {
                                // check again to see if there are any links, user may have manually added links while
                                // this command was in the queue
                                List <CrossRef_AniDB_TvDBV2> xrefTemp = RepoFactory.CrossRef_AniDB_TvDBV2.GetByAnimeID(AnimeID);
                                if (xrefTemp != null && xrefTemp.Count > 0)
                                {
                                    return;
                                }

                                foreach (JMMServer.Providers.Azure.CrossRef_AniDB_TvDB xref in cacheResults)
                                {
                                    TvDB_Series tvser = TvDBHelper.GetSeriesInfoOnline(xref.TvDBID);
                                    if (tvser != null)
                                    {
                                        logger.Trace("Found tvdb match on web cache for {0}", AnimeID);
                                        TvDBHelper.LinkAniDBTvDB(AnimeID,
                                                                 (AniDBAPI.enEpisodeType)xref.AniDBStartEpisodeType,
                                                                 xref.AniDBStartEpisodeNumber,
                                                                 xref.TvDBID, xref.TvDBSeasonNumber,
                                                                 xref.TvDBStartEpisodeNumber, true);
                                    }
                                    else
                                    {
                                        //if we got a TvDB ID from the web cache, but couldn't find it on TheTvDB.com, it could mean 2 things
                                        //1. thetvdb.com is offline
                                        //2. the id is no longer valid
                                        // if the id is no longer valid we should remove it from the web cache

                                        /*if (TvDBHelper.ConfirmTvDBOnline())
                                         *                                      {
                                         *
                                         *                                      }*/
                                    }
                                }
                                return;
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }

                    string      searchCriteria = "";
                    AniDB_Anime anime          = RepoFactory.AniDB_Anime.GetByAnimeID(AnimeID);
                    if (anime == null)
                    {
                        return;
                    }

                    searchCriteria = anime.MainTitle;

                    // if not wanting to use web cache, or no match found on the web cache go to TvDB directly
                    List <TVDBSeriesSearchResult> results = JMMService.TvdbHelper.SearchSeries(searchCriteria);
                    logger.Trace("Found {0} tvdb results for {1} on TheTvDB", results.Count, searchCriteria);
                    if (ProcessSearchResults(results, searchCriteria))
                    {
                        return;
                    }


                    if (results.Count == 0)
                    {
                        foreach (AniDB_Anime_Title title in anime.GetTitles())
                        {
                            if (title.TitleType.ToUpper() != Constants.AnimeTitleType.Official.ToUpper())
                            {
                                continue;
                            }

                            if (searchCriteria.ToUpper() == title.Title.ToUpper())
                            {
                                continue;
                            }

                            results = JMMService.TvdbHelper.SearchSeries(title.Title);
                            logger.Trace("Found {0} tvdb results for search on {1}", results.Count, title.Title);
                            if (ProcessSearchResults(results, title.Title))
                            {
                                return;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error processing CommandRequest_TvDBSearchAnime: {0} - {1}", AnimeID, ex.ToString());
                return;
            }
        }
Example #4
0
        private static void FillSerie(Video p, AnimeSeries aser, Dictionary <AnimeEpisode, Contract_AnimeEpisode> eps,
                                      AniDB_Anime anidb, Contract_AnimeSeries ser, int userid)
        {
            using (ISession session = JMMService.SessionFactory.OpenSession())
            {
                Contract_AniDBAnime anime = ser.AniDBAnime.AniDBAnime;
                p.Id        = ser.AnimeSeriesID.ToString();
                p.AnimeType = JMMContracts.PlexAndKodi.AnimeTypes.AnimeSerie.ToString();
                if (ser.AniDBAnime.AniDBAnime.Restricted > 0)
                {
                    p.ContentRating = "R";
                }
                p.Title   = aser.GetSeriesName(session);
                p.Summary = SummaryFromAnimeContract(ser);
                p.Type    = "show";
                p.AirDate = DateTime.MinValue;
                TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
                if (anime.AllTags.Count > 0)
                {
                    p.Genres = new List <Tag>();
                    anime.AllTags.ToList().ForEach(a => p.Genres.Add(new Tag {
                        Value = textInfo.ToTitleCase(a.Trim())
                    }));
                }
                //p.OriginalTitle
                if (anime.AirDate.HasValue)
                {
                    p.AirDate = anime.AirDate.Value;
                    p.OriginallyAvailableAt = anime.AirDate.Value.ToPlexDate();
                    p.Year = anime.AirDate.Value.Year.ToString();
                }
                p.LeafCount = anime.EpisodeCount.ToString();
                //p.ChildCount = p.LeafCount;
                p.ViewedLeafCount = ser.WatchedEpisodeCount.ToString();
                p.Rating          = (anime.Rating / 100F).ToString(CultureInfo.InvariantCulture);
                List <Contract_CrossRef_AniDB_TvDBV2> ls = ser.CrossRefAniDBTvDBV2;
                if (ls != null && ls.Count > 0)
                {
                    foreach (Contract_CrossRef_AniDB_TvDBV2 c in ls)
                    {
                        if (c.TvDBSeasonNumber != 0)
                        {
                            p.Season = c.TvDBSeasonNumber.ToString();
                            p.Index  = p.Season;
                        }
                    }
                }
                p.Thumb = p.ParentThumb = anime.DefaultImagePoster.GenPoster();
                p.Art   = anime?.DefaultImageFanart?.GenArt();
                if (eps != null)
                {
                    List <enEpisodeType> types = eps.Keys.Select(a => a.EpisodeTypeEnum).Distinct().ToList();
                    p.ChildCount = types.Count > 1 ? types.Count.ToString() : eps.Keys.Count.ToString();
                }
                p.Roles = new List <RoleTag>();

                //TODO Character implementation is limited in JMM, One Character, could have more than one Seiyuu
                if (anidb.Contract?.AniDBAnime?.Characters != null)
                {
                    foreach (Contract_AniDB_Character c in anidb.Contract.AniDBAnime.Characters)
                    {
                        string ch = c?.CharName;
                        Contract_AniDB_Seiyuu seiyuu = c?.Seiyuu;
                        if (!string.IsNullOrEmpty(ch))
                        {
                            RoleTag t = new RoleTag();
                            t.Value = seiyuu?.SeiyuuName;
                            if (seiyuu != null)
                            {
                                t.TagPicture = Helper.ConstructSeiyuuImage(seiyuu.AniDB_SeiyuuID);
                            }
                            t.Role            = ch;
                            t.RoleDescription = c?.CharDescription;
                            t.RolePicture     = Helper.ConstructCharacterImage(c.CharID);
                            p.Roles.Add(t);
                        }
                    }
                }
                p.Titles = new List <AnimeTitle>();
                foreach (AniDB_Anime_Title title in anidb.GetTitles())
                {
                    p.Titles.Add(new AnimeTitle {
                        Language = title.Language, Title = title.Title, Type = title.TitleType
                    });
                }
            }
        }
        private System.IO.Stream GetGroupsFromFilter(int userid, string GroupFilterId)
        {
            KodiObject ret = new KodiObject(KodiHelper.NewMediaContainer("Filters", true));

            if (!ret.Init())
            {
                return(new MemoryStream());
            }
            //List<Joint> retGroups = new List<Joint>();
            List <Video> retGroups = new List <Video>();

            try
            {
                int groupFilterID;
                int.TryParse(GroupFilterId, out groupFilterID);
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    if (groupFilterID == -1)
                    {
                        return(new MemoryStream());
                    }
                    DateTime start = DateTime.Now;
                    GroupFilterRepository repGF = new GroupFilterRepository();

                    GroupFilter gf;

                    if (groupFilterID == -999)
                    {
                        // all groups
                        gf = new GroupFilter();
                        gf.GroupFilterName = "All";
                    }
                    else
                    {
                        gf = repGF.GetByID(session, groupFilterID);
                        if (gf == null)
                        {
                            return(new MemoryStream());
                        }
                    }
                    ret.MediaContainer.Title2 = ret.MediaContainer.Title1 = gf.GroupFilterName;
                    //Contract_GroupFilterExtended contract = gf.ToContractExtended(user);

                    AnimeGroupRepository repGroups = new AnimeGroupRepository();
                    List <AnimeGroup>    allGrps   = repGroups.GetAll(session);



                    TimeSpan ts  = DateTime.Now - start;
                    string   msg = string.Format("Got groups for filter DB: {0} - {1} in {2} ms", gf.GroupFilterName,
                                                 allGrps.Count, ts.TotalMilliseconds);
                    logger.Info(msg);
                    start = DateTime.Now;



                    if ((StatsCache.Instance.StatUserGroupFilter.ContainsKey(userid)) &&
                        (StatsCache.Instance.StatUserGroupFilter[userid].ContainsKey(gf.GroupFilterID)))
                    {
                        HashSet <int> groups = StatsCache.Instance.StatUserGroupFilter[userid][gf.GroupFilterID];
                        var           tas    = StatsCache.Instance.StatKodiGroupsCache;
                        foreach (AnimeGroup grp in allGrps)
                        {
                            if (groups.Contains(grp.AnimeGroupID))
                            {
                                try {
                                    //if (grp.GroupName == "Rockman.EXE")
                                    //{
                                    //    int x = grp.MissingEpisodeCount;
                                    //}
                                    Video v = StatsCache.Instance.StatKodiGroupsCache[userid][grp.AnimeGroupID];
                                    if (v != null)
                                    {
                                        //proper naming
                                        AniDB_Anime anim = grp.Anime[0];
                                        v.OriginalTitle = "";
                                        foreach (AniDB_Anime_Title title in anim.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

                                        retGroups.Add(v.Clone());
                                    }
                                }
                                catch (Exception e)
                                {
                                    int x = retGroups.Count;
                                }
                            }
                        }
                    }
                    ts  = DateTime.Now - start;
                    msg = string.Format("Got groups for filter EVAL: {0} - {1} in {2} ms", gf.GroupFilterName,
                                        retGroups.Count, ts.TotalMilliseconds);
                    logger.Info(msg);
                    if ((groupFilterID == -999) || (gf.SortCriteriaList.Count == 0))
                    {
                        ret.Childrens = retGroups.OrderBy(a => a.Group.SortName).ToList();
                        return(ret.GetStream());
                    }
                    List <Contract_AnimeGroup>         grps         = retGroups.Select(a => a.Group).ToList();
                    List <SortPropOrFieldAndDirection> sortCriteria = new List <SortPropOrFieldAndDirection>();
                    foreach (GroupFilterSortingCriteria g in gf.SortCriteriaList)
                    {
                        sortCriteria.Add(GroupFilterHelper.GetSortDescription(g.SortType, g.SortDirection));
                    }
                    grps = Sorting.MultiSort(grps, sortCriteria);
                    List <Video> joints2 = new List <Video>();
                    foreach (Contract_AnimeGroup gr in grps)
                    {
                        foreach (Video j in retGroups)
                        {
                            if (j.Group == gr)
                            {
                                //experiment
                                AniDB_AnimeRepository repAnime  = new AniDB_AnimeRepository();
                                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                                AnimeGroup            ag        = repGroups.GetByID(gr.AnimeGroupID);
                                List <AnimeSeries>    sers      = ag.GetAllSeries();
                                AnimeSeries           ser       = sers[0];
                                AniDB_Anime           anim      = ser.GetAnime();

                                j.CharactersList = new List <Characters>();
                                Characters c = new Characters();
                                c.CharactersList = GetCharactersFromAniDB(anim);
                                j.CharactersList.Add(c);
                                //experimentEND

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

                                //community support

                                //CrossRef_AniDB_TraktV2Repository repCrossRef = new CrossRef_AniDB_TraktV2Repository();
                                //List<CrossRef_AniDB_TraktV2> Trakt = repCrossRef.GetByAnimeID(anim.AnimeID);
                                //if (Trakt != null)
                                //{
                                //    if (Trakt.Count > 0)
                                //    {
                                //        j.Trakt = Trakt[0].TraktID;
                                //    }
                                //}

                                //CrossRef_AniDB_TvDBV2Repository repCrossRefV2 = new CrossRef_AniDB_TvDBV2Repository();
                                //List<CrossRef_AniDB_TvDBV2> TvDB = repCrossRefV2.GetByAnimeID(anim.AnimeID);
                                //if (TvDB != null)
                                //{
                                //    if (TvDB.Count > 0)
                                //    {
                                //        j.TvDB = TvDB[0].TvDBID.ToString();
                                //    }
                                //}

                                //community support END

                                joints2.Add(j);
                                retGroups.Remove(j);
                                break;
                            }
                        }
                    }
                    ret.Childrens          = joints2;
                    ret.MediaContainer.Art = KodiHelper.GetRandomFanartFromVideoList(ret.Childrens);
                    ts  = DateTime.Now - start;
                    msg = string.Format("Got groups final: {0} - {1} in {2} ms", gf.GroupFilterName,
                                        retGroups.Count, ts.TotalMilliseconds);
                    logger.Info(msg);
                    return(ret.GetStream());
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }
            return(new MemoryStream());
        }
        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());
            }
        }
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_MovieDBSearchAnime: {0}", AnimeID);

            try
            {
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    // first check if the user wants to use the web cache
                    if (ServerSettings.WebCache_TvDB_Get)
                    {
                        try
                        {
                            MovieDB_MovieRepository repMovies = new MovieDB_MovieRepository();

                            JMMServer.Providers.Azure.CrossRef_AniDB_Other crossRef =
                                JMMServer.Providers.Azure.AzureWebAPI.Get_CrossRefAniDBOther(AnimeID,
                                                                                             CrossRefType.MovieDB);
                            if (crossRef != null)
                            {
                                int           movieID = int.Parse(crossRef.CrossRefID);
                                MovieDB_Movie movie   = repMovies.GetByOnlineID(session, movieID);
                                if (movie == null)
                                {
                                    // update the info from online
                                    MovieDBHelper.UpdateMovieInfo(session, movieID, true);
                                    movie = repMovies.GetByOnlineID(movieID);
                                }

                                if (movie != null)
                                {
                                    // since we are using the web cache result, let's save it
                                    MovieDBHelper.LinkAniDBMovieDB(AnimeID, movieID, true);
                                    return;
                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }

                    string searchCriteria          = "";
                    AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
                    AniDB_Anime           anime    = repAnime.GetByAnimeID(session, AnimeID);
                    if (anime == null)
                    {
                        return;
                    }

                    searchCriteria = anime.MainTitle;

                    // if not wanting to use web cache, or no match found on the web cache go to TvDB directly
                    List <MovieDB_Movie_Result> results = MovieDBHelper.Search(searchCriteria);
                    logger.Trace("Found {0} moviedb results for {1} on TheTvDB", results.Count, searchCriteria);
                    if (ProcessSearchResults(session, results, searchCriteria))
                    {
                        return;
                    }


                    if (results.Count == 0)
                    {
                        foreach (AniDB_Anime_Title title in anime.GetTitles(session))
                        {
                            if (title.TitleType.ToUpper() != Constants.AnimeTitleType.Official.ToUpper())
                            {
                                continue;
                            }

                            if (searchCriteria.ToUpper() == title.Title.ToUpper())
                            {
                                continue;
                            }

                            results = MovieDBHelper.Search(title.Title);
                            logger.Trace("Found {0} moviedb results for search on {1}", results.Count, title.Title);
                            if (ProcessSearchResults(session, results, title.Title))
                            {
                                return;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error processing CommandRequest_TvDBSearchAnime: {0} - {1}", AnimeID, ex.ToString());
                return;
            }
        }