public string GetImagePath(string ImageType, string ImageID, bool thumnbnailOnly)
        {
            JMMImageType imageType = (JMMImageType)int.Parse(ImageType);

            switch (imageType)
            {
            case JMMImageType.AniDB_Cover:

                AniDB_Anime anime = RepoFactory.AniDB_Anime.GetByAnimeID(int.Parse(ImageID));
                if (anime == null)
                {
                    return(null);
                }

                if (File.Exists(anime.PosterPath))
                {
                    return(anime.PosterPath);
                }
                else
                {
                    logger.Trace("Could not find AniDB_Cover image: {0}", anime.PosterPath);
                    return("");
                }

            case JMMImageType.AniDB_Character:

                AniDB_Character chr = RepoFactory.AniDB_Character.GetByID(int.Parse(ImageID));
                if (chr == null)
                {
                    return(null);
                }

                if (File.Exists(chr.PosterPath))
                {
                    return(chr.PosterPath);
                }
                else
                {
                    logger.Trace("Could not find AniDB_Character image: {0}", chr.PosterPath);
                    return("");
                }

            case JMMImageType.AniDB_Creator:

                AniDB_Seiyuu creator = RepoFactory.AniDB_Seiyuu.GetByID(int.Parse(ImageID));
                if (creator == null)
                {
                    return("");
                }

                if (File.Exists(creator.PosterPath))
                {
                    return(creator.PosterPath);
                }
                else
                {
                    logger.Trace("Could not find AniDB_Creator image: {0}", creator.PosterPath);
                    return("");
                }

            case JMMImageType.TvDB_Cover:

                TvDB_ImagePoster poster = RepoFactory.TvDB_ImagePoster.GetByID(int.Parse(ImageID));
                if (poster == null)
                {
                    return(null);
                }

                if (File.Exists(poster.FullImagePath))
                {
                    return(poster.FullImagePath);
                }
                else
                {
                    logger.Trace("Could not find TvDB_Cover image: {0}", poster.FullImagePath);
                    return("");
                }

            case JMMImageType.TvDB_Banner:

                TvDB_ImageWideBanner wideBanner = RepoFactory.TvDB_ImageWideBanner.GetByID(int.Parse(ImageID));
                if (wideBanner == null)
                {
                    return(null);
                }

                if (File.Exists(wideBanner.FullImagePath))
                {
                    return(wideBanner.FullImagePath);
                }
                else
                {
                    logger.Trace("Could not find TvDB_Banner image: {0}", wideBanner.FullImagePath);
                    return("");
                }

            case JMMImageType.TvDB_Episode:

                TvDB_Episode ep = RepoFactory.TvDB_Episode.GetByID(int.Parse(ImageID));
                if (ep == null)
                {
                    return(null);
                }

                if (File.Exists(ep.FullImagePath))
                {
                    return(ep.FullImagePath);
                }
                else
                {
                    logger.Trace("Could not find TvDB_Episode image: {0}", ep.FullImagePath);
                    return("");
                }

            case JMMImageType.TvDB_FanArt:

                TvDB_ImageFanart fanart = RepoFactory.TvDB_ImageFanart.GetByID(int.Parse(ImageID));
                if (fanart == null)
                {
                    return(null);
                }

                if (thumnbnailOnly)
                {
                    if (File.Exists(fanart.FullThumbnailPath))
                    {
                        return(fanart.FullThumbnailPath);
                    }
                    else
                    {
                        logger.Trace("Could not find TvDB_FanArt image: {0}", fanart.FullThumbnailPath);
                        return("");
                    }
                }
                else
                {
                    if (File.Exists(fanart.FullImagePath))
                    {
                        return(fanart.FullImagePath);
                    }
                    else
                    {
                        logger.Trace("Could not find TvDB_FanArt image: {0}", fanart.FullImagePath);
                        return("");
                    }
                }

            case JMMImageType.MovieDB_Poster:

                MovieDB_Poster mPoster = RepoFactory.MovieDB_Poster.GetByID(int.Parse(ImageID));
                if (mPoster == null)
                {
                    return(null);
                }

                // now find only the original size
                mPoster = RepoFactory.MovieDB_Poster.GetByOnlineID(mPoster.URL);
                if (mPoster == null)
                {
                    return(null);
                }

                if (File.Exists(mPoster.FullImagePath))
                {
                    return(mPoster.FullImagePath);
                }
                else
                {
                    logger.Trace("Could not find MovieDB_Poster image: {0}", mPoster.FullImagePath);
                    return("");
                }

            case JMMImageType.MovieDB_FanArt:

                MovieDB_Fanart mFanart = RepoFactory.MovieDB_Fanart.GetByID(int.Parse(ImageID));
                if (mFanart == null)
                {
                    return(null);
                }

                mFanart = RepoFactory.MovieDB_Fanart.GetByOnlineID(mFanart.URL);
                if (mFanart == null)
                {
                    return(null);
                }

                if (File.Exists(mFanart.FullImagePath))
                {
                    return(mFanart.FullImagePath);
                }
                else
                {
                    logger.Trace("Could not find MovieDB_FanArt image: {0}", mFanart.FullImagePath);
                    return("");
                }

            case JMMImageType.Trakt_Fanart:

                Trakt_ImageFanart tFanart = RepoFactory.Trakt_ImageFanart.GetByID(int.Parse(ImageID));
                if (tFanart == null)
                {
                    return(null);
                }

                if (File.Exists(tFanart.FullImagePath))
                {
                    return(tFanart.FullImagePath);
                }
                else
                {
                    logger.Trace("Could not find Trakt_Fanart image: {0}", tFanart.FullImagePath);
                    return("");
                }

            case JMMImageType.Trakt_Poster:

                Trakt_ImagePoster tPoster = RepoFactory.Trakt_ImagePoster.GetByID(int.Parse(ImageID));
                if (tPoster == null)
                {
                    return(null);
                }

                if (File.Exists(tPoster.FullImagePath))
                {
                    return(tPoster.FullImagePath);
                }
                else
                {
                    logger.Trace("Could not find Trakt_Poster image: {0}", tPoster.FullImagePath);
                    return("");
                }

            case JMMImageType.Trakt_Episode:
            case JMMImageType.Trakt_WatchedEpisode:

                Trakt_Episode tEpisode = RepoFactory.Trakt_Episode.GetByID(int.Parse(ImageID));
                if (tEpisode == null)
                {
                    return(null);
                }

                if (File.Exists(tEpisode.FullImagePath))
                {
                    return(tEpisode.FullImagePath);
                }
                else
                {
                    logger.Trace("Could not find Trakt_Episode image: {0}", tEpisode.FullImagePath);
                    return("");
                }

            default:
                return("");
            }
        }
Ejemplo n.º 2
0
        public static List <AnimeGroup> GetRelatedGroupsFromAnimeID(ISession session, int animeid)
        {
            AniDB_AnimeRepository repAniAnime = new AniDB_AnimeRepository();
            AnimeSeriesRepository repSeries   = new AnimeSeriesRepository();
            AnimeGroupRepository  repGroups   = new AnimeGroupRepository();

            List <AnimeGroup> grps = new List <AnimeGroup>();

            AniDB_Anime anime = repAniAnime.GetByAnimeID(session, animeid);

            if (anime == null)
            {
                return(grps);
            }

            // first check for groups which are directly related
            List <AniDB_Anime_Relation> relations = anime.GetRelatedAnime(session);

            foreach (AniDB_Anime_Relation rel in relations)
            {
                string relationtype = rel.RelationType.ToLower();
                if ((relationtype == "same setting") || (relationtype == "alternative setting") ||
                    (relationtype == "character") || (relationtype == "other"))
                {
                    //Filter these relations these will fix messes, like Gundam , Clamp, etc.
                    continue;
                }

                // we actually need to get the series, because it might have been added to another group already
                AnimeSeries ser = repSeries.GetByAnimeID(session, rel.RelatedAnimeID);
                if (ser != null)
                {
                    AnimeGroup grp = repGroups.GetByID(session, ser.AnimeGroupID);
                    if (grp != null)
                    {
                        grps.Add(grp);
                    }
                }
            }
            if (grps.Count > 0)
            {
                return(grps);
            }

            // if nothing found check by all related anime
            List <AniDB_Anime> relatedAnime = anime.GetAllRelatedAnime(session);

            foreach (AniDB_Anime rel in relatedAnime)
            {
                // we actually need to get the series, because it might have been added to another group already
                AnimeSeries ser = repSeries.GetByAnimeID(session, rel.AnimeID);
                if (ser != null)
                {
                    AnimeGroup grp = repGroups.GetByID(session, ser.AnimeGroupID);
                    if (grp != null)
                    {
                        grps.Add(grp);
                    }
                }
            }

            return(grps);
        }
Ejemplo n.º 3
0
        public byte[] GetImage(string entityID, int entityType, bool thumnbnailOnly)
        {
            AniDB_AnimeRepository          repAnime       = new AniDB_AnimeRepository();
            TvDB_ImagePosterRepository     repPosters     = new TvDB_ImagePosterRepository();
            TvDB_EpisodeRepository         repEpisodes    = new TvDB_EpisodeRepository();
            TvDB_ImageFanartRepository     repFanart      = new TvDB_ImageFanartRepository();
            TvDB_ImageWideBannerRepository repWideBanners = new TvDB_ImageWideBannerRepository();

            MovieDB_PosterRepository repMoviePosters = new MovieDB_PosterRepository();
            MovieDB_FanartRepository repMovieFanart  = new MovieDB_FanartRepository();

            Trakt_ImageFanartRepository repTraktFanart   = new Trakt_ImageFanartRepository();
            Trakt_ImagePosterRepository repTraktPosters  = new Trakt_ImagePosterRepository();
            Trakt_EpisodeRepository     repTraktEpisodes = new Trakt_EpisodeRepository();
            Trakt_FriendRepository      repTraktFriends  = new Trakt_FriendRepository();

            JMMImageType imageType = (JMMImageType)entityType;

            switch (imageType)
            {
            case JMMImageType.AniDB_Cover:

                AniDB_Anime anime = repAnime.GetByAnimeID(int.Parse(entityID));
                if (anime == null)
                {
                    return(null);
                }

                if (File.Exists(anime.PosterPath))
                {
                    return(File.ReadAllBytes(anime.PosterPath));
                }
                else
                {
                    logger.Trace("Could not find AniDB_Cover image: {0}", anime.PosterPath);
                    return(null);
                }

            case JMMImageType.AniDB_Character:

                AniDB_CharacterRepository repChar = new AniDB_CharacterRepository();
                AniDB_Character           chr     = repChar.GetByID(int.Parse(entityID));
                if (chr == null)
                {
                    return(null);
                }

                if (File.Exists(chr.PosterPath))
                {
                    return(File.ReadAllBytes(chr.PosterPath));
                }
                else
                {
                    logger.Trace("Could not find AniDB_Character image: {0}", chr.PosterPath);
                    return(null);
                }

            case JMMImageType.AniDB_Creator:

                AniDB_SeiyuuRepository repCreator = new AniDB_SeiyuuRepository();
                AniDB_Seiyuu           creator    = repCreator.GetByID(int.Parse(entityID));
                if (creator == null)
                {
                    return(null);
                }

                if (File.Exists(creator.PosterPath))
                {
                    return(File.ReadAllBytes(creator.PosterPath));
                }
                else
                {
                    logger.Trace("Could not find AniDB_Creator image: {0}", creator.PosterPath);
                    return(null);
                }

            case JMMImageType.TvDB_Cover:

                TvDB_ImagePoster poster = repPosters.GetByID(int.Parse(entityID));
                if (poster == null)
                {
                    return(null);
                }

                if (File.Exists(poster.FullImagePath))
                {
                    return(File.ReadAllBytes(poster.FullImagePath));
                }
                else
                {
                    logger.Trace("Could not find TvDB_Cover image: {0}", poster.FullImagePath);
                    return(null);
                }

            case JMMImageType.TvDB_Banner:

                TvDB_ImageWideBanner wideBanner = repWideBanners.GetByID(int.Parse(entityID));
                if (wideBanner == null)
                {
                    return(null);
                }

                if (File.Exists(wideBanner.FullImagePath))
                {
                    return(File.ReadAllBytes(wideBanner.FullImagePath));
                }
                else
                {
                    logger.Trace("Could not find TvDB_Banner image: {0}", wideBanner.FullImagePath);
                    return(null);
                }

            case JMMImageType.TvDB_Episode:

                TvDB_Episode ep = repEpisodes.GetByID(int.Parse(entityID));
                if (ep == null)
                {
                    return(null);
                }

                if (File.Exists(ep.FullImagePath))
                {
                    return(File.ReadAllBytes(ep.FullImagePath));
                }
                else
                {
                    logger.Trace("Could not find TvDB_Episode image: {0}", ep.FullImagePath);
                    return(null);
                }

            case JMMImageType.TvDB_FanArt:

                TvDB_ImageFanart fanart = repFanart.GetByID(int.Parse(entityID));
                if (fanart == null)
                {
                    return(null);
                }

                if (thumnbnailOnly)
                {
                    if (File.Exists(fanart.FullThumbnailPath))
                    {
                        return(File.ReadAllBytes(fanart.FullThumbnailPath));
                    }
                    else
                    {
                        logger.Trace("Could not find TvDB_FanArt image: {0}", fanart.FullThumbnailPath);
                        return(null);
                    }
                }
                else
                {
                    if (File.Exists(fanart.FullImagePath))
                    {
                        return(File.ReadAllBytes(fanart.FullImagePath));
                    }
                    else
                    {
                        logger.Trace("Could not find TvDB_FanArt image: {0}", fanart.FullImagePath);
                        return(null);
                    }
                }

            case JMMImageType.MovieDB_Poster:

                MovieDB_Poster mPoster = repMoviePosters.GetByID(int.Parse(entityID));
                if (mPoster == null)
                {
                    return(null);
                }

                // now find only the original size
                mPoster = repMoviePosters.GetByOnlineID(mPoster.URL);
                if (mPoster == null)
                {
                    return(null);
                }

                if (File.Exists(mPoster.FullImagePath))
                {
                    return(File.ReadAllBytes(mPoster.FullImagePath));
                }
                else
                {
                    logger.Trace("Could not find MovieDB_Poster image: {0}", mPoster.FullImagePath);
                    return(null);
                }

            case JMMImageType.MovieDB_FanArt:

                MovieDB_Fanart mFanart = repMovieFanart.GetByID(int.Parse(entityID));
                if (mFanart == null)
                {
                    return(null);
                }

                mFanart = repMovieFanart.GetByOnlineID(mFanart.URL);
                if (mFanart == null)
                {
                    return(null);
                }

                if (File.Exists(mFanart.FullImagePath))
                {
                    return(File.ReadAllBytes(mFanart.FullImagePath));
                }
                else
                {
                    logger.Trace("Could not find MovieDB_FanArt image: {0}", mFanart.FullImagePath);
                    return(null);
                }

            case JMMImageType.Trakt_Fanart:

                Trakt_ImageFanart tFanart = repTraktFanart.GetByID(int.Parse(entityID));
                if (tFanart == null)
                {
                    return(null);
                }

                if (File.Exists(tFanart.FullImagePath))
                {
                    return(File.ReadAllBytes(tFanart.FullImagePath));
                }
                else
                {
                    logger.Trace("Could not find Trakt_Fanart image: {0}", tFanart.FullImagePath);
                    return(null);
                }

            case JMMImageType.Trakt_Friend:


                Trakt_Friend tFriend = repTraktFriends.GetByID(int.Parse(entityID));
                if (tFriend == null)
                {
                    return(null);
                }

                if (File.Exists(tFriend.FullImagePath))
                {
                    return(File.ReadAllBytes(tFriend.FullImagePath));
                }
                else
                {
                    logger.Trace("Could not find Trakt_Friend image: {0}", tFriend.FullImagePath);
                    return(null);
                }

            case JMMImageType.Trakt_ActivityScrobble:
            case JMMImageType.Trakt_ShoutUser:


                Trakt_Friend tFriendScrobble = repTraktFriends.GetByID(int.Parse(entityID));
                if (tFriendScrobble == null)
                {
                    return(null);
                }

                if (File.Exists(tFriendScrobble.FullImagePath))
                {
                    return(File.ReadAllBytes(tFriendScrobble.FullImagePath));
                }
                else
                {
                    logger.Trace("Could not find Trakt_ActivityScrobble image: {0}", tFriendScrobble.FullImagePath);
                    return(null);
                }

            case JMMImageType.Trakt_Poster:

                Trakt_ImagePoster tPoster = repTraktPosters.GetByID(int.Parse(entityID));
                if (tPoster == null)
                {
                    return(null);
                }

                if (File.Exists(tPoster.FullImagePath))
                {
                    return(File.ReadAllBytes(tPoster.FullImagePath));
                }
                else
                {
                    logger.Trace("Could not find Trakt_Poster image: {0}", tPoster.FullImagePath);
                    return(null);
                }

            case JMMImageType.Trakt_Episode:
            case JMMImageType.Trakt_WatchedEpisode:

                Trakt_Episode tEpisode = repTraktEpisodes.GetByID(int.Parse(entityID));
                if (tEpisode == null)
                {
                    return(null);
                }

                if (File.Exists(tEpisode.FullImagePath))
                {
                    return(File.ReadAllBytes(tEpisode.FullImagePath));
                }
                else
                {
                    logger.Trace("Could not find Trakt_Episode image: {0}", tEpisode.FullImagePath);
                    return(null);
                }

            default:

                return(null);
            }
        }
Ejemplo n.º 4
0
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_DownloadImage: {0}", EntityID);
            string downloadURL = "";

            try
            {
                ImageDownloadRequest req = null;
                switch (EntityTypeEnum)
                {
                case JMMImageType.AniDB_Cover:
                    AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
                    AniDB_Anime           anime    = repAnime.GetByID(EntityID);
                    if (anime == null)
                    {
                        return;
                    }

                    req = new ImageDownloadRequest(EntityTypeEnum, anime, ForceDownload);
                    break;

                case JMMImageType.TvDB_Episode:

                    TvDB_EpisodeRepository repTvEp = new TvDB_EpisodeRepository();
                    TvDB_Episode           ep      = repTvEp.GetByID(EntityID);
                    if (ep == null)
                    {
                        return;
                    }
                    if (string.IsNullOrEmpty(ep.Filename))
                    {
                        return;
                    }

                    req = new ImageDownloadRequest(EntityTypeEnum, ep, ForceDownload);
                    break;

                case JMMImageType.TvDB_FanArt:

                    TvDB_ImageFanartRepository repFanart = new TvDB_ImageFanartRepository();
                    TvDB_ImageFanart           fanart    = repFanart.GetByID(EntityID);
                    if (fanart == null)
                    {
                        return;
                    }
                    if (string.IsNullOrEmpty(fanart.BannerPath))
                    {
                        return;
                    }

                    req = new ImageDownloadRequest(EntityTypeEnum, fanart, ForceDownload);
                    break;

                case JMMImageType.TvDB_Cover:

                    TvDB_ImagePosterRepository repPoster = new TvDB_ImagePosterRepository();
                    TvDB_ImagePoster           poster    = repPoster.GetByID(EntityID);
                    if (poster == null)
                    {
                        return;
                    }
                    if (string.IsNullOrEmpty(poster.BannerPath))
                    {
                        return;
                    }

                    req = new ImageDownloadRequest(EntityTypeEnum, poster, ForceDownload);
                    break;

                case JMMImageType.TvDB_Banner:

                    TvDB_ImageWideBannerRepository repBanners = new TvDB_ImageWideBannerRepository();
                    TvDB_ImageWideBanner           wideBanner = repBanners.GetByID(EntityID);
                    if (wideBanner == null)
                    {
                        return;
                    }
                    if (string.IsNullOrEmpty(wideBanner.BannerPath))
                    {
                        return;
                    }

                    req = new ImageDownloadRequest(EntityTypeEnum, wideBanner, ForceDownload);
                    break;

                case JMMImageType.MovieDB_Poster:

                    MovieDB_PosterRepository repMoviePosters = new MovieDB_PosterRepository();
                    MovieDB_Poster           moviePoster     = repMoviePosters.GetByID(EntityID);
                    if (moviePoster == null)
                    {
                        return;
                    }
                    if (string.IsNullOrEmpty(moviePoster.URL))
                    {
                        return;
                    }

                    req = new ImageDownloadRequest(EntityTypeEnum, moviePoster, ForceDownload);
                    break;

                case JMMImageType.MovieDB_FanArt:

                    MovieDB_FanartRepository repMovieFanart = new MovieDB_FanartRepository();
                    MovieDB_Fanart           movieFanart    = repMovieFanart.GetByID(EntityID);
                    if (movieFanart == null)
                    {
                        return;
                    }
                    if (string.IsNullOrEmpty(movieFanart.URL))
                    {
                        return;
                    }

                    req = new ImageDownloadRequest(EntityTypeEnum, movieFanart, ForceDownload);
                    break;

                case JMMImageType.Trakt_Poster:

                    Trakt_ImagePosterRepository repTraktPosters = new Trakt_ImagePosterRepository();
                    Trakt_ImagePoster           traktPoster     = repTraktPosters.GetByID(EntityID);
                    if (traktPoster == null)
                    {
                        return;
                    }
                    if (string.IsNullOrEmpty(traktPoster.ImageURL))
                    {
                        return;
                    }

                    req = new ImageDownloadRequest(EntityTypeEnum, traktPoster, ForceDownload);
                    break;

                case JMMImageType.Trakt_Fanart:

                    Trakt_ImageFanartRepository repTraktFanarts = new Trakt_ImageFanartRepository();
                    Trakt_ImageFanart           traktFanart     = repTraktFanarts.GetByID(EntityID);
                    if (traktFanart == null)
                    {
                        return;
                    }
                    if (string.IsNullOrEmpty(traktFanart.ImageURL))
                    {
                        return;
                    }

                    req = new ImageDownloadRequest(EntityTypeEnum, traktFanart, ForceDownload);
                    break;

                case JMMImageType.Trakt_Friend:

                    Trakt_FriendRepository repFriends = new Trakt_FriendRepository();
                    Trakt_Friend           friend     = repFriends.GetByID(EntityID);
                    if (friend == null)
                    {
                        return;
                    }
                    if (string.IsNullOrEmpty(friend.Avatar))
                    {
                        return;
                    }

                    req = new ImageDownloadRequest(EntityTypeEnum, friend, ForceDownload);
                    break;

                case JMMImageType.Trakt_Episode:

                    Trakt_EpisodeRepository repTraktEpisodes = new Trakt_EpisodeRepository();
                    Trakt_Episode           traktEp          = repTraktEpisodes.GetByID(EntityID);
                    if (traktEp == null)
                    {
                        return;
                    }
                    if (string.IsNullOrEmpty(traktEp.EpisodeImage))
                    {
                        return;
                    }

                    req = new ImageDownloadRequest(EntityTypeEnum, traktEp, ForceDownload);
                    break;

                case JMMImageType.AniDB_Character:
                    AniDB_CharacterRepository repChars = new AniDB_CharacterRepository();
                    AniDB_Character           chr      = repChars.GetByID(EntityID);
                    if (chr == null)
                    {
                        return;
                    }

                    req = new ImageDownloadRequest(EntityTypeEnum, chr, ForceDownload);
                    break;

                case JMMImageType.AniDB_Creator:
                    AniDB_SeiyuuRepository repCreator = new AniDB_SeiyuuRepository();
                    AniDB_Seiyuu           creator    = repCreator.GetByID(EntityID);
                    if (creator == null)
                    {
                        return;
                    }

                    req = new ImageDownloadRequest(EntityTypeEnum, creator, ForceDownload);
                    break;
                }

                if (req == null)
                {
                    return;
                }

                List <string> fileNames    = new List <string>();
                List <string> downloadURLs = new List <string>();

                string fileNameTemp    = GetFileName(req, false);
                string downloadURLTemp = GetFileURL(req, false);

                fileNames.Add(fileNameTemp);
                downloadURLs.Add(downloadURLTemp);

                if (req.ImageType == JMMImageType.TvDB_FanArt)
                {
                    fileNameTemp    = GetFileName(req, true);
                    downloadURLTemp = GetFileURL(req, true);

                    fileNames.Add(fileNameTemp);
                    downloadURLs.Add(downloadURLTemp);
                }

                for (int i = 0; i < fileNames.Count; i++)
                {
                    string fileName = fileNames[i];
                    downloadURL = downloadURLs[i];

                    bool downloadImage = true;
                    bool fileExists    = File.Exists(fileName);

                    if (fileExists)
                    {
                        if (!req.ForceDownload)
                        {
                            downloadImage = false;
                        }
                        else
                        {
                            downloadImage = true;
                        }
                    }
                    else
                    {
                        downloadImage = true;
                    }

                    if (downloadImage)
                    {
                        string tempName = Path.Combine(ImageUtils.GetImagesTempFolder(), Path.GetFileName(fileName));
                        if (File.Exists(tempName))
                        {
                            File.Delete(tempName);
                        }


                        try
                        {
                            if (fileExists)
                            {
                                File.Delete(fileName);
                            }
                        }
                        catch (Exception ex)
                        {
                            string msg = string.Format("Error deleting image: ({0}) - {1}", fileName, ex.Message);
                            logger.Warn(msg);
                            return;
                        }



                        // download image
                        using (WebClient client = new WebClient())
                        {
                            client.Headers.Add("user-agent", "JMM");
                            //OnImageDownloadEvent(new ImageDownloadEventArgs("", req, ImageDownloadEventType.Started));
                            //BaseConfig.MyAnimeLog.Write("ProcessImages: Download: {0}  *** to ***  {1}", req.URL, fullName);
                            if (downloadURL.Length > 0)
                            {
                                client.DownloadFile(downloadURL, tempName);

                                string extension   = "";
                                string contentType = client.ResponseHeaders["Content-type"].ToLower();
                                if (contentType.IndexOf("gif") >= 0)
                                {
                                    extension = ".gif";
                                }
                                if (contentType.IndexOf("jpg") >= 0)
                                {
                                    extension = ".jpg";
                                }
                                if (contentType.IndexOf("jpeg") >= 0)
                                {
                                    extension = ".jpg";
                                }
                                if (contentType.IndexOf("bmp") >= 0)
                                {
                                    extension = ".bmp";
                                }
                                if (contentType.IndexOf("png") >= 0)
                                {
                                    extension = ".png";
                                }
                                if (extension.Length > 0)
                                {
                                    string newFile = Path.ChangeExtension(tempName, extension);
                                    if (!newFile.ToLower().Equals(tempName.ToLower()))
                                    {
                                        try
                                        {
                                            System.IO.File.Delete(newFile);
                                        }
                                        catch
                                        {
                                            //BaseConfig.MyAnimeLog.Write("DownloadedImage:Download() Delete failed:{0}", newFile);
                                        }
                                        System.IO.File.Move(tempName, newFile);
                                        tempName = newFile;
                                    }
                                }
                            }
                        }

                        // move the file to it's final location
                        // check that the final folder exists
                        string fullPath = Path.GetDirectoryName(fileName);
                        if (!Directory.Exists(fullPath))
                        {
                            Directory.CreateDirectory(fullPath);
                        }


                        System.IO.File.Move(tempName, fileName);
                        logger.Info("Image downloaded: {0}", fileName);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Warn("Error processing CommandRequest_DownloadImage: {0} ({1}) - {2}", downloadURL, EntityID, ex.Message);
                return;
            }
        }
Ejemplo n.º 5
0
        public void UpdateStats(bool watchedStats, bool missingEpsStats, bool updateAllGroupsAbove)
        {
            DateTime start        = DateTime.Now;
            DateTime startOverall = DateTime.Now;

            logger.Info("Starting Updating STATS for SERIES {0} ({1} - {2} - {3})", this.ToString(), watchedStats, missingEpsStats, updateAllGroupsAbove);

            AnimeSeries_UserRepository      repSeriesUser  = new AnimeSeries_UserRepository();
            AnimeEpisode_UserRepository     repEpisodeUser = new AnimeEpisode_UserRepository();
            VideoLocalRepository            repVids        = new VideoLocalRepository();
            CrossRef_File_EpisodeRepository repXrefs       = new CrossRef_File_EpisodeRepository();

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

            DateTime            startEps = DateTime.Now;
            List <AnimeEpisode> eps      = GetAnimeEpisodes();
            TimeSpan            tsEps    = DateTime.Now - startEps;

            logger.Trace("Got episodes for SERIES {0} in {1}ms", this.ToString(), tsEps.TotalMilliseconds);

            DateTime                     startVids = DateTime.Now;
            List <VideoLocal>            vidsTemp  = repVids.GetByAniDBAnimeID(this.AniDB_ID);
            List <CrossRef_File_Episode> crossRefs = repXrefs.GetByAnimeID(this.AniDB_ID);

            Dictionary <int, List <CrossRef_File_Episode> > dictCrossRefs = new Dictionary <int, List <CrossRef_File_Episode> >();

            foreach (CrossRef_File_Episode xref in crossRefs)
            {
                if (!dictCrossRefs.ContainsKey(xref.EpisodeID))
                {
                    dictCrossRefs[xref.EpisodeID] = new List <CrossRef_File_Episode>();
                }
                dictCrossRefs[xref.EpisodeID].Add(xref);
            }

            Dictionary <string, VideoLocal> dictVids = new Dictionary <string, VideoLocal>();

            foreach (VideoLocal vid in vidsTemp)
            {
                dictVids[vid.Hash] = vid;
            }

            TimeSpan tsVids = DateTime.Now - startVids;

            logger.Trace("Got video locals for SERIES {0} in {1}ms", this.ToString(), tsVids.TotalMilliseconds);


            if (watchedStats)
            {
                foreach (JMMUser juser in allUsers)
                {
                    //this.WatchedCount = 0;
                    AnimeSeries_User userRecord = GetUserRecord(juser.JMMUserID);
                    if (userRecord == null)
                    {
                        userRecord = new AnimeSeries_User(juser.JMMUserID, this.AnimeSeriesID);
                    }

                    // reset stats
                    userRecord.UnwatchedEpisodeCount = 0;
                    userRecord.WatchedEpisodeCount   = 0;
                    userRecord.WatchedCount          = 0;
                    userRecord.WatchedDate           = null;

                    DateTime startUser = DateTime.Now;
                    List <AnimeEpisode_User>            epUserRecords   = repEpisodeUser.GetByUserID(juser.JMMUserID);
                    Dictionary <int, AnimeEpisode_User> dictUserRecords = new Dictionary <int, AnimeEpisode_User>();
                    foreach (AnimeEpisode_User usrec in epUserRecords)
                    {
                        dictUserRecords[usrec.AnimeEpisodeID] = usrec;
                    }
                    TimeSpan tsUser = DateTime.Now - startUser;
                    logger.Trace("Got user records for SERIES {0}/{1} in {2}ms", this.ToString(), juser.Username, tsUser.TotalMilliseconds);

                    foreach (AnimeEpisode ep in eps)
                    {
                        // if the episode doesn't have any files then it won't count towards watched/unwatched counts
                        List <VideoLocal> epVids = new List <VideoLocal>();

                        if (dictCrossRefs.ContainsKey(ep.AniDB_EpisodeID))
                        {
                            foreach (CrossRef_File_Episode xref in dictCrossRefs[ep.AniDB_EpisodeID])
                            {
                                if (xref.EpisodeID == ep.AniDB_EpisodeID)
                                {
                                    if (dictVids.ContainsKey(xref.Hash))
                                    {
                                        epVids.Add(dictVids[xref.Hash]);
                                    }
                                }
                            }
                        }
                        if (epVids.Count == 0)
                        {
                            continue;
                        }

                        if (ep.EpisodeTypeEnum == AniDBAPI.enEpisodeType.Episode || ep.EpisodeTypeEnum == AniDBAPI.enEpisodeType.Special)
                        {
                            AnimeEpisode_User epUserRecord = null;
                            if (dictUserRecords.ContainsKey(ep.AnimeEpisodeID))
                            {
                                epUserRecord = dictUserRecords[ep.AnimeEpisodeID];
                            }

                            if (epUserRecord != null && epUserRecord.WatchedDate.HasValue)
                            {
                                userRecord.WatchedEpisodeCount++;
                            }
                            else
                            {
                                userRecord.UnwatchedEpisodeCount++;
                            }

                            if (epUserRecord != null)
                            {
                                if (userRecord.WatchedDate.HasValue)
                                {
                                    if (epUserRecord.WatchedDate > userRecord.WatchedDate)
                                    {
                                        userRecord.WatchedDate = epUserRecord.WatchedDate;
                                    }
                                }
                                else
                                {
                                    userRecord.WatchedDate = epUserRecord.WatchedDate;
                                }

                                userRecord.WatchedCount += epUserRecord.WatchedCount;
                            }
                        }
                    }
                    repSeriesUser.Save(userRecord);
                }
            }

            TimeSpan ts = DateTime.Now - start;

            logger.Trace("Updated WATCHED stats for SERIES {0} in {1}ms", this.ToString(), ts.TotalMilliseconds);
            start = DateTime.Now;



            if (missingEpsStats)
            {
                enAnimeType animeType   = enAnimeType.TVSeries;
                AniDB_Anime aniDB_Anime = this.GetAnime();
                if (aniDB_Anime != null)
                {
                    animeType = aniDB_Anime.AnimeTypeEnum;
                }

                MissingEpisodeCount       = 0;
                MissingEpisodeCountGroups = 0;

                // get all the group status records
                AniDB_GroupStatusRepository repGrpStat  = new AniDB_GroupStatusRepository();
                List <AniDB_GroupStatus>    grpStatuses = repGrpStat.GetByAnimeID(this.AniDB_ID);

                // find all the episodes for which the user has a file
                // from this we can determine what their latest episode number is
                // find out which groups the user is collecting

                List <int> userReleaseGroups = new List <int>();
                foreach (AnimeEpisode ep in eps)
                {
                    List <VideoLocal> vids = new List <VideoLocal>();
                    if (dictCrossRefs.ContainsKey(ep.AniDB_EpisodeID))
                    {
                        foreach (CrossRef_File_Episode xref in dictCrossRefs[ep.AniDB_EpisodeID])
                        {
                            if (xref.EpisodeID == ep.AniDB_EpisodeID)
                            {
                                if (dictVids.ContainsKey(xref.Hash))
                                {
                                    vids.Add(dictVids[xref.Hash]);
                                }
                            }
                        }
                    }

                    //List<VideoLocal> vids = ep.VideoLocals;
                    foreach (VideoLocal vid in vids)
                    {
                        AniDB_File anifile = vid.GetAniDBFile();
                        if (anifile != null)
                        {
                            if (!userReleaseGroups.Contains(anifile.GroupID))
                            {
                                userReleaseGroups.Add(anifile.GroupID);
                            }
                        }
                    }
                }

                int         latestLocalEpNumber = 0;
                EpisodeList epReleasedList      = new EpisodeList(animeType);
                EpisodeList epGroupReleasedList = new EpisodeList(animeType);

                foreach (AnimeEpisode ep in eps)
                {
                    //List<VideoLocal> vids = ep.VideoLocals;
                    if (ep.EpisodeTypeEnum != AniDBAPI.enEpisodeType.Episode)
                    {
                        continue;
                    }

                    List <VideoLocal> vids = new List <VideoLocal>();
                    if (dictCrossRefs.ContainsKey(ep.AniDB_EpisodeID))
                    {
                        foreach (CrossRef_File_Episode xref in dictCrossRefs[ep.AniDB_EpisodeID])
                        {
                            if (xref.EpisodeID == ep.AniDB_EpisodeID)
                            {
                                if (dictVids.ContainsKey(xref.Hash))
                                {
                                    vids.Add(dictVids[xref.Hash]);
                                }
                            }
                        }
                    }



                    AniDB_Episode aniEp     = ep.AniDB_Episode;
                    int           thisEpNum = aniEp.EpisodeNumber;

                    if (thisEpNum > latestLocalEpNumber && vids.Count > 0)
                    {
                        latestLocalEpNumber = thisEpNum;
                    }

                    // does this episode have a file released
                    // does this episode have a file released by the group the user is collecting
                    bool epReleased      = false;
                    bool epReleasedGroup = false;
                    foreach (AniDB_GroupStatus gs in grpStatuses)
                    {
                        if (gs.LastEpisodeNumber >= thisEpNum)
                        {
                            epReleased = true;
                        }
                        if (userReleaseGroups.Contains(gs.GroupID) && gs.HasGroupReleasedEpisode(thisEpNum))
                        {
                            epReleasedGroup = true;
                        }
                    }


                    try
                    {
                        epReleasedList.Add(ep, (!epReleased || vids.Count != 0));
                        epGroupReleasedList.Add(ep, (!epReleasedGroup || vids.Count != 0));
                    }
                    catch (Exception e)
                    {
                        logger.Trace("Error {0}", e.ToString());
                        throw;
                    }
                }
                foreach (EpisodeList.StatEpisodes eplst in epReleasedList)
                {
                    if (!eplst.Available)
                    {
                        MissingEpisodeCount++;
                    }
                }
                foreach (EpisodeList.StatEpisodes eplst in epGroupReleasedList)
                {
                    if (!eplst.Available)
                    {
                        MissingEpisodeCountGroups++;
                    }
                }

                this.LatestLocalEpisodeNumber = latestLocalEpNumber;
            }

            ts = DateTime.Now - start;
            logger.Trace("Updated MISSING EPS stats for SERIES {0} in {1}ms", this.ToString(), ts.TotalMilliseconds);
            start = DateTime.Now;

            AnimeSeriesRepository rep = new AnimeSeriesRepository();

            rep.Save(this);

            if (updateAllGroupsAbove)
            {
                foreach (AnimeGroup grp in AllGroupsAbove)
                {
                    grp.UpdateStats(watchedStats, missingEpsStats);
                }
            }

            ts = DateTime.Now - start;
            logger.Trace("Updated GROUPS ABOVE stats for SERIES {0} in {1}ms", this.ToString(), ts.TotalMilliseconds);
            start = DateTime.Now;

            TimeSpan tsOverall = DateTime.Now - startOverall;

            logger.Info("Finished Updating STATS for SERIES {0} in {1}ms ({2} - {3} - {4})", this.ToString(), tsOverall.TotalMilliseconds,
                        watchedStats, missingEpsStats, updateAllGroupsAbove);
        }
Ejemplo n.º 6
0
        private AniDB_Anime SaveResultsForAnimeXML(ISession session, int animeID, bool downloadRelations,
                                                   AniDBHTTPCommand_GetFullAnime getAnimeCmd)
        {
            AniDB_Anime     anime          = null;
            ISessionWrapper sessionWrapper = session.Wrap();

            logger.Trace("cmdResult.Anime: {0}", getAnimeCmd.Anime);

            anime = RepoFactory.AniDB_Anime.GetByAnimeID(sessionWrapper, animeID);
            if (anime == null)
            {
                anime = new AniDB_Anime();
            }
            anime.PopulateAndSaveFromHTTP(session, getAnimeCmd.Anime, getAnimeCmd.Episodes, getAnimeCmd.Titles,
                                          getAnimeCmd.Categories, getAnimeCmd.Tags,
                                          getAnimeCmd.Characters, getAnimeCmd.Relations, getAnimeCmd.SimilarAnime, getAnimeCmd.Recommendations,
                                          downloadRelations);

            // Request an image download
            CommandRequest_DownloadImage cmd = new CommandRequest_DownloadImage(anime.AniDB_AnimeID,
                                                                                JMMImageType.AniDB_Cover,
                                                                                false);

            cmd.Save(session);
            // create AnimeEpisode records for all episodes in this anime
            // only if we have a series
            AnimeSeries ser = RepoFactory.AnimeSeries.GetByAnimeID(animeID);

            RepoFactory.AniDB_Anime.Save(anime);
            if (ser != null)
            {
                ser.CreateAnimeEpisodes(session);
                RepoFactory.AnimeSeries.Save(ser, true, false);
            }

            // update any files, that may have been linked

            /*CrossRef_File_EpisodeRepository repCrossRefs = new CrossRef_File_EpisodeRepository();
             * repCrossRefs.GetByAnimeID(*/

            // update cached stats

            //StatsCache.Instance.UpdateUsingAnime(session, anime.AnimeID);
            //StatsCache.Instance.UpdateAnimeContract(session, anime.AnimeID);

            // download character images
            foreach (AniDB_Anime_Character animeChar in anime.GetAnimeCharacters(session.Wrap()))
            {
                AniDB_Character chr = animeChar.GetCharacter(sessionWrapper);
                if (chr == null)
                {
                    continue;
                }

                if (ServerSettings.AniDB_DownloadCharacters)
                {
                    if (!string.IsNullOrEmpty(chr.PosterPath) && !File.Exists(chr.PosterPath))
                    {
                        logger.Debug("Downloading character image: {0} - {1}({2}) - {3}", anime.MainTitle, chr.CharName,
                                     chr.CharID,
                                     chr.PosterPath);
                        cmd = new CommandRequest_DownloadImage(chr.AniDB_CharacterID, JMMImageType.AniDB_Character,
                                                               false);
                        cmd.Save();
                    }
                }

                if (ServerSettings.AniDB_DownloadCreators)
                {
                    AniDB_Seiyuu seiyuu = chr.GetSeiyuu(session);
                    if (seiyuu == null || string.IsNullOrEmpty(seiyuu.PosterPath))
                    {
                        continue;
                    }

                    if (!File.Exists(seiyuu.PosterPath))
                    {
                        logger.Debug("Downloading seiyuu image: {0} - {1}({2}) - {3}", anime.MainTitle,
                                     seiyuu.SeiyuuName, seiyuu.SeiyuuID,
                                     seiyuu.PosterPath);
                        cmd = new CommandRequest_DownloadImage(seiyuu.AniDB_SeiyuuID, JMMImageType.AniDB_Creator, false);
                        cmd.Save();
                    }
                }
            }

            return(anime);
        }
Ejemplo n.º 7
0
        public static string GetFileURL(ImageDownloadRequest req, bool thumbNailOnly)
        {
            switch (req.ImageType)
            {
            case JMMImageType.AniDB_Cover:
                AniDB_Anime anime = req.ImageData as AniDB_Anime;
                return(string.Format(Constants.URLS.AniDB_Images, anime.Picname));

            case JMMImageType.TvDB_Episode:
                TvDB_Episode ep = req.ImageData as TvDB_Episode;
                return(string.Format(Constants.URLS.TvDB_Images, ep.Filename));

            case JMMImageType.TvDB_FanArt:
                TvDB_ImageFanart fanart = req.ImageData as TvDB_ImageFanart;

                if (thumbNailOnly)
                {
                    return(string.Format(Constants.URLS.TvDB_Images, fanart.ThumbnailPath));
                }
                else
                {
                    return(string.Format(Constants.URLS.TvDB_Images, fanart.BannerPath));
                }

            case JMMImageType.TvDB_Cover:
                TvDB_ImagePoster poster = req.ImageData as TvDB_ImagePoster;
                return(string.Format(Constants.URLS.TvDB_Images, poster.BannerPath));

            case JMMImageType.TvDB_Banner:
                TvDB_ImageWideBanner wideBanner = req.ImageData as TvDB_ImageWideBanner;
                return(string.Format(Constants.URLS.TvDB_Images, wideBanner.BannerPath));

            case JMMImageType.MovieDB_Poster:
                MovieDB_Poster moviePoster = req.ImageData as MovieDB_Poster;
                return(moviePoster.URL);

            case JMMImageType.MovieDB_FanArt:

                MovieDB_Fanart movieFanart = req.ImageData as MovieDB_Fanart;
                return(movieFanart.URL);

            case JMMImageType.Trakt_Poster:
                Trakt_ImagePoster traktPoster = req.ImageData as Trakt_ImagePoster;
                return(traktPoster.ImageURL);

            case JMMImageType.Trakt_Fanart:
                Trakt_ImageFanart traktFanart = req.ImageData as Trakt_ImageFanart;
                return(traktFanart.ImageURL);

            case JMMImageType.Trakt_Friend:
                Trakt_Friend traktFriend = req.ImageData as Trakt_Friend;
                return(traktFriend.Avatar);

            case JMMImageType.Trakt_Episode:
                Trakt_Episode traktEp = req.ImageData as Trakt_Episode;
                return(traktEp.EpisodeImage);

            case JMMImageType.AniDB_Character:
                AniDB_Character chr = req.ImageData as AniDB_Character;
                return(string.Format(Constants.URLS.AniDB_Images, chr.PicName));

            case JMMImageType.AniDB_Creator:
                AniDB_Seiyuu creator = req.ImageData as AniDB_Seiyuu;
                return(string.Format(Constants.URLS.AniDB_Images, creator.PicName));

            default:
                return("");
            }
        }
Ejemplo n.º 8
0
        private static bool PopulateVideoEpisodeFromAnime(Video v, AnimeEpisode ep, AnimeSeries ser, Contract_AnimeSeries cserie, AniDB_Anime ani, Video nv)
        {
            bool ret = false;

//            v.ParentTitle = "Season 1";
//            v.GrandparentTitle = ser.GetSeriesName();
            v.ParentIndex = "1";
            v.Art         = ani.GetDefaultFanartDetailsNoBlanks().GenArt();
            if (ep.EpisodeTypeEnum != enEpisodeType.Episode)
            {
                //v.ParentTitle = ep.ToString();
                v.ParentIndex = null;
            }
            else if (cserie.CrossRefAniDBTvDBV2 != null && cserie.CrossRefAniDBTvDBV2.Count > 0)
            {
                Contract_CrossRef_AniDB_TvDBV2 c2 =
                    cserie.CrossRefAniDBTvDBV2.FirstOrDefault(
                        a =>
                        a.AniDBStartEpisodeType == ep.AniDB_Episode.EpisodeType &&
                        a.AniDBStartEpisodeNumber <= ep.AniDB_Episode.EpisodeNumber);
                if (c2 != null)
                {
                    //  v.ParentTitle = "Season " + c2.TvDBSeasonNumber;
                    if (c2.TvDBSeasonNumber > 0)
                    {
                        v.ParentIndex = c2.TvDBSeasonNumber.ToString();
                    }
                }
            }
            //v.Title1 = v.GrandparentTitle;
            //v.Title2 = v.ParentTitle;
            if (ani != null)
            {
                if (ani.Restricted > 0)
                {
                    v.ContentRating = "R";
                }
                if (ani.AnimeTypeEnum == enAnimeType.Movie)
                {
                    v.Type = "movie";
                    if (v.Title.StartsWith("Complete Movie"))
                    {
                        v.Title   = nv.Title;
                        v.Summary = nv.Summary;
                        v.Index   = null;
                        ret       = true;
                    }
                    else if (v.Title.StartsWith("Part "))
                    {
                        v.Title   = nv.Title + " - " + v.Title;
                        v.Summary = nv.Summary;
                    }
                    v.Thumb = nv.Thumb;
                }
                else if (ani.AnimeTypeEnum == enAnimeType.OVA)
                {
                    if (v.Title == "OVA")
                    {
                        v.Title   = nv.Title;
                        v.Type    = "movie";
                        v.Thumb   = nv.Thumb;
                        v.Summary = nv.Summary;
                        v.Index   = null;
                        ret       = true;
                    }
                }
                // else
                //   v.ParentTitle = nv.Title;
            }
            if (string.IsNullOrEmpty(v.Art))
            {
                v.Art = nv.Art;
            }
            if (v.Tags == null)
            {
                v.Tags = nv.Tags;
            }
            if (v.Genres == null)
            {
                v.Genres = nv.Genres;
            }
            if (v.Roles == null)
            {
                v.Roles = nv.Roles;
            }
            if (string.IsNullOrEmpty(v.Rating))
            {
                v.Rating = nv.Rating;
            }
            v.Index = ep.AniDB_Episode.EpisodeNumber.ToString();
            return(ret);
        }
Ejemplo n.º 9
0
        public static Video MayReplaceVideo(Video v1, AnimeSeries ser, Contract_AnimeSeries cserie, AniDB_Anime anime, JMMType type, int userid, bool all = true)
        {
            int epcount = all ? ser.GetAnimeEpisodesCountWithVideoLocal() :  ser.GetAnimeEpisodesNormalCountWithVideoLocal();

            if ((epcount == 1) && (anime.AnimeTypeEnum == enAnimeType.OVA || anime.AnimeTypeEnum == enAnimeType.Movie))
            {
                List <AnimeEpisode> episodes = ser.GetAnimeEpisodes();
                List <VideoLocal>   l        = episodes[0].GetVideoLocals();
                if (l.Count > 0)
                {
                    Video v2 = new Video();
                    try
                    {
                        if (PopulateVideo(v2, l[0], episodes[0], ser, cserie, anime, v1, JMMType.File, userid))
                        {
                            v2.Thumb = anime.GetDefaultPosterDetailsNoBlanks().GenPoster();
                            return(v2);
                        }
                    }
                    catch (Exception e)
                    {
                        //Fast fix if file do not exist, and still is in db. (Xml Serialization of video info will fail on null)
                    }
                }
            }
            return(v1);
        }
Ejemplo n.º 10
0
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_GetUpdated");

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

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

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



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

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

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

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

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

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


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

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

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

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

                logger.Info("Updating {0} anime records, and {1} group status records", countAnime, countSeries);
            }
            catch (Exception ex)
            {
                logger.Error("Error processing CommandRequest_GetUpdated: {0}", ex.ToString());
                return;
            }
        }
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_GetCalendar");

            try
            {
                // we will always assume that an anime was downloaded via http first

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

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

                sched.LastUpdate = DateTime.Now;
                RepoFactory.ScheduledUpdate.Save(sched);

                CalendarCollection colCalendars = JMMService.AnidbProcessor.GetCalendarUDP();
                if (colCalendars == null || colCalendars.Calendars == null)
                {
                    logger.Error("Could not get calendar from AniDB");
                    return;
                }
                foreach (AniDBAPI.Calendar cal in colCalendars.Calendars)
                {
                    AniDB_Anime anime = RepoFactory.AniDB_Anime.GetByAnimeID(cal.AnimeID);
                    if (anime != null)
                    {
                        // don't update if the local data is less 2 days old
                        TimeSpan ts = DateTime.Now - anime.DateTimeUpdated;
                        if (ts.TotalDays >= 2)
                        {
                            CommandRequest_GetAnimeHTTP cmdAnime = new CommandRequest_GetAnimeHTTP(cal.AnimeID, true,
                                                                                                   false);
                            cmdAnime.Save();
                        }
                        else
                        {
                            // update the release date even if we don't update the anime record
                            if (anime.AirDate != cal.ReleaseDate)
                            {
                                anime.AirDate = cal.ReleaseDate;
                                RepoFactory.AniDB_Anime.Save(anime);
                                AnimeSeries ser = RepoFactory.AnimeSeries.GetByAnimeID(anime.AnimeID);
                                if (ser != null)
                                {
                                    RepoFactory.AnimeSeries.Save(ser, true, false);
                                }
                            }
                        }
                    }
                    else
                    {
                        CommandRequest_GetAnimeHTTP cmdAnime = new CommandRequest_GetAnimeHTTP(cal.AnimeID, true, false);
                        cmdAnime.Save();
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Error processing CommandRequest_GetCalendar: " + ex.ToString());
                return;
            }
        }
        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());
            }
        }
        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();
            }
        }
        public System.IO.Stream GetFilters(string uid)
        {
            int t = 0;

            int.TryParse(uid, out t);
            JMMUser user = t > 0 ? PlexHelper.GetJMMUser(uid) : PlexHelper.GetUser(uid);

            if (user == null)
            {
                return(new MemoryStream());
            }
            int         userid = user.JMMUserID;
            HistoryInfo info   = new HistoryInfo {
                Key = PlexHelper.ConstructFiltersUrl(userid), Title = "Anime"
            };
            PlexObject ret = new PlexObject(PlexHelper.NewMediaContainer(MediaContainerTypes.Show, info, false));

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

            try
            {
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    GroupFilterRepository            repGF  = new GroupFilterRepository();
                    List <GroupFilter>               allGfs = repGF.GetAll(session);
                    Dictionary <int, HashSet <int> > gstats = StatsCache.Instance.StatUserGroupFilter[userid];
                    foreach (GroupFilter gg in allGfs.ToArray())
                    {
                        if ((!StatsCache.Instance.StatUserGroupFilter.ContainsKey(userid)) ||
                            (!StatsCache.Instance.StatUserGroupFilter[userid].ContainsKey(gg.GroupFilterID)))
                        {
                            allGfs.Remove(gg);
                        }
                    }


                    AnimeGroupRepository repGroups = new AnimeGroupRepository();
                    allGfs.Insert(0, new GroupFilter()
                    {
                        GroupFilterName = "All", GroupFilterID = -999
                    });
                    foreach (GroupFilter gg in allGfs)
                    {
                        Random    rnd = new Random(123456789);
                        Directory pp  = new Directory {
                            Type = "show"
                        };
                        pp.Key   = PlexHelper.ConstructFilterIdUrl(userid, gg.GroupFilterID);
                        pp.Title = gg.GroupFilterName;
                        HashSet <int> groups;
                        groups = gg.GroupFilterID == -999 ? new HashSet <int>(repGroups.GetAllTopLevelGroups(session).Select(a => a.AnimeGroupID)) : gstats[gg.GroupFilterID];
                        if (groups.Count != 0)
                        {
                            bool repeat;
                            int  nn = 0;
                            pp.LeafCount       = groups.Count.ToString();
                            pp.ViewedLeafCount = "0";
                            do
                            {
                                repeat = true;
                                int                grp  = groups.ElementAt(rnd.Next(groups.Count));
                                AnimeGroup         ag   = repGroups.GetByID(grp);
                                List <AnimeSeries> sers = ag.GetSeries(session);
                                if (sers.Count > 0)
                                {
                                    AnimeSeries ser  = sers[rnd.Next(sers.Count)];
                                    AniDB_Anime anim = ser.GetAnime(session);
                                    if (anim != null)
                                    {
                                        ImageDetails poster = anim.GetDefaultPosterDetailsNoBlanks(session);
                                        ImageDetails fanart = anim.GetDefaultFanartDetailsNoBlanks(session);
                                        if (poster != null)
                                        {
                                            pp.Thumb = poster.GenPoster();
                                        }
                                        if (fanart != null)
                                        {
                                            pp.Art = fanart.GenArt();
                                        }
                                        if (poster != null)
                                        {
                                            repeat = false;
                                        }
                                    }
                                }
                                nn++;
                                if ((repeat) && (nn == 15))
                                {
                                    repeat = false;
                                }
                            } while (repeat);
                            dirs.Add(pp, info);
                        }
                    }
                    VideoLocalRepository repVids = new VideoLocalRepository();
                    List <VideoLocal>    vids    = repVids.GetVideosWithoutEpisode();
                    if (vids.Count > 0)
                    {
                        Directory pp = new Directory()
                        {
                            Type = "show"
                        };
                        pp.Key             = PlexHelper.ConstructUnsortUrl(userid);
                        pp.Title           = "Unsort";
                        pp.Thumb           = PlexHelper.ConstructSupportImageLink("plex_unsort.png");
                        pp.LeafCount       = vids.Count.ToString();
                        pp.ViewedLeafCount = "0";
                        dirs.Add(pp, info);
                    }
                    var repPlaylist = new PlaylistRepository();
                    var playlists   = repPlaylist.GetAll();
                    if (playlists.Count > 0)
                    {
                        Directory pp = new Directory()
                        {
                            Type = "show"
                        };
                        pp.Key             = PlexHelper.ConstructPlaylistUrl(userid);
                        pp.Title           = "Playlists";
                        pp.Thumb           = PlexHelper.ConstructSupportImageLink("plex_playlists.png");
                        pp.LeafCount       = playlists.Count.ToString();
                        pp.ViewedLeafCount = "0";
                        dirs.Add(pp, info);
                    }
                    dirs = dirs.OrderBy(a => a.Title).ToList();
                }
                ret.Childrens = dirs;
                return(ret.GetStream());
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return(new MemoryStream());
            }
        }
Ejemplo n.º 15
0
        private void ProcessFile_AniDB(VideoLocal vidLocal)
        {
            logger.Trace("Checking for AniDB_File record for: {0} --- {1}", vidLocal.Hash, vidLocal.FileName);
            // check if we already have this AniDB_File info in the database



            AniDB_File aniFile = null;

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

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

            int animeID = 0;

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

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

                    aniFile.Populate(fileInfo);

                    //overwrite with local file name
                    string localFileName = vidLocal.FileName;
                    aniFile.FileName = localFileName;

                    RepoFactory.AniDB_File.Save(aniFile, false);
                    aniFile.CreateLanguages();
                    aniFile.CreateCrossEpisodes(localFileName);

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

                    animeID = aniFile.AnimeID;
                }
            }

            bool missingEpisodes = false;

            // if we still haven't got the AniDB_File Info we try the web cache or local records
            if (aniFile == null)
            {
                // check if we have any records from previous imports
                List <CrossRef_File_Episode> crossRefs = RepoFactory.CrossRef_File_Episode.GetByHash(vidLocal.Hash);
                if (crossRefs == null || crossRefs.Count == 0)
                {
                    // lets see if we can find the episode/anime info from the web cache
                    if (ServerSettings.WebCache_XRefFileEpisode_Get)
                    {
                        List <JMMServer.Providers.Azure.CrossRef_File_Episode> xrefs =
                            JMMServer.Providers.Azure.AzureWebAPI.Get_CrossRefFileEpisode(vidLocal);

                        crossRefs = new List <CrossRef_File_Episode>();
                        if (xrefs == null || xrefs.Count == 0)
                        {
                            logger.Debug(
                                "Cannot find AniDB_File record or get cross ref from web cache record so exiting: {0}",
                                vidLocal.ED2KHash);
                            return;
                        }
                        else
                        {
                            foreach (JMMServer.Providers.Azure.CrossRef_File_Episode xref in xrefs)
                            {
                                CrossRef_File_Episode xrefEnt = new CrossRef_File_Episode();
                                xrefEnt.Hash           = vidLocal.ED2KHash;
                                xrefEnt.FileName       = vidLocal.FileName;
                                xrefEnt.FileSize       = vidLocal.FileSize;
                                xrefEnt.CrossRefSource = (int)JMMServer.CrossRefSource.WebCache;
                                xrefEnt.AnimeID        = xref.AnimeID;
                                xrefEnt.EpisodeID      = xref.EpisodeID;
                                xrefEnt.Percentage     = xref.Percentage;
                                xrefEnt.EpisodeOrder   = xref.EpisodeOrder;

                                bool duplicate = false;

                                foreach (CrossRef_File_Episode xrefcheck in crossRefs)
                                {
                                    if (xrefcheck.AnimeID == xrefEnt.AnimeID &&
                                        xrefcheck.EpisodeID == xrefEnt.EpisodeID &&
                                        xrefcheck.Hash == xrefEnt.Hash)
                                    {
                                        duplicate = true;
                                    }
                                }

                                if (!duplicate)
                                {
                                    crossRefs.Add(xrefEnt);
                                    // in this case we need to save the cross refs manually as AniDB did not provide them
                                    RepoFactory.CrossRef_File_Episode.Save(xrefEnt);
                                }
                            }
                        }
                    }
                    else
                    {
                        logger.Debug("Cannot get AniDB_File record so exiting: {0}", vidLocal.ED2KHash);
                        return;
                    }
                }

                // we assume that all episodes belong to the same anime
                foreach (CrossRef_File_Episode xref in crossRefs)
                {
                    animeID = xref.AnimeID;

                    AniDB_Episode ep = RepoFactory.AniDB_Episode.GetByEpisodeID(xref.EpisodeID);
                    if (ep == null)
                    {
                        missingEpisodes = true;
                    }
                }
            }
            else
            {
                // check if we have the episode info
                // if we don't, we will need to re-download the anime info (which also has episode info)

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

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

                        animeID = xref.AnimeID;
                    }
                }
            }

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

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

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

            // create the group/series/episode records if needed
            AnimeSeries ser = null;

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


                ser.CreateAnimeEpisodes();

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

                // update stats
                ser.EpisodeAddedDate = DateTime.Now;
                RepoFactory.AnimeSeries.Save(ser, false, false);

                foreach (AnimeGroup grp in ser.AllGroupsAbove)
                {
                    grp.EpisodeAddedDate = DateTime.Now;
                    RepoFactory.AnimeGroup.Save(grp, true, false);
                }
            }
            vidLocal.Places.ForEach(a =>
            {
                a.RenameIfRequired();
                a.MoveFileIfRequired();
            });


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


            // Add this file to the users list
            if (ServerSettings.AniDB_MyList_AddFiles)
            {
                CommandRequest_AddFileToMyList cmd = new CommandRequest_AddFileToMyList(vidLocal.ED2KHash);
                cmd.Save();
            }
        }
Ejemplo n.º 16
0
        public static Video FromSerieWithPossibleReplacement(Contract_AnimeSeries cserie, AnimeSeries ser, AniDB_Anime anidb, int userid)
        {
            Video v = new Directory();

            FillSerie(v, ser, anidb, cserie, userid);
            if (ser.GetAnimeNumberOfEpisodeTypes() > 1)
            {
                v.Type = "show";
            }
            else if ((cserie.AniDBAnime.AnimeType == (int)enAnimeType.Movie) || (cserie.AniDBAnime.AnimeType == (int)enAnimeType.OVA))
            {
                v = MayReplaceVideo(v, ser, cserie, ser.GetAnime(), JMMType.File, userid);
            }
            return(v);
        }
Ejemplo n.º 17
0
        public AniDB_Anime GetAnimeInfoUDP(int animeID, bool forceRefresh)
        {
            AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
            AniDB_Anime           anime    = null;

            bool skip = true;

            if (forceRefresh)
            {
                skip = false;
            }
            else
            {
                anime = repAnime.GetByAnimeID(animeID);
                if (anime == null)
                {
                    skip = false;
                }
            }

            if (skip)
            {
                if (anime == null)
                {
                    anime = repAnime.GetByAnimeID(animeID);
                }

                return(anime);
            }

            if (!Login())
            {
                return(null);
            }

            enHelperActivityType      ev          = enHelperActivityType.NoSuchAnime;
            AniDBCommand_GetAnimeInfo getAnimeCmd = null;

            lock (lockAniDBConnections)
            {
                Pause();

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

            if (ev == enHelperActivityType.GotAnimeInfo && getAnimeCmd.AnimeInfo != null)
            {
                // check for an existing record so we don't over write the description
                anime = repAnime.GetByAnimeID(getAnimeCmd.AnimeInfo.AnimeID);
                if (anime == null)
                {
                    anime = new AniDB_Anime();
                }

                anime.PopulateAndSaveFromUDP(getAnimeCmd.AnimeInfo);
            }

            return(anime);
        }
Ejemplo n.º 18
0
        public static void FillSerie(Video p, AnimeSeries aser, AniDB_Anime anidb, Contract_AnimeSeries ser, int userid)
        {
            using (ISession session = JMMService.SessionFactory.OpenSession())
            {
                Contract_AniDBAnime anime = ser.AniDBAnime;
                p.Key = ConstructSerieIdUrl(userid, ser.AnimeSeriesID.ToString());
                if (ser.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 (!string.IsNullOrEmpty(anime.AllTags))
                {
                    p.Genres = new List <Tag>();
                    anime.AllTags.Split('|').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 = anime.DefaultImagePoster.GenPoster();
                p.Art   = anime.DefaultImageFanart.GenArt();
                List <AniDB_Anime_Character> chars = anidb.GetAnimeCharacters(session);

                p.Roles = new List <Tag>();
                if (chars != null)
                {
                    foreach (AniDB_Anime_Character c in chars)
                    {
                        AniDB_Character cha    = c.GetCharacter(session);
                        AniDB_Seiyuu    seiyuu = cha?.GetSeiyuu(session);
                        if (seiyuu != null)
                        {
                            p.Roles.Add(new Tag
                            {
                                Value = seiyuu.SeiyuuName,
                                Role  = cha.CharName
                            });
                        }
                    }
                }
            }
        }
Ejemplo n.º 19
0
        public GroupStatusCollection GetReleaseGroupStatusUDP(int animeID)
        {
            if (!Login())
            {
                return(null);
            }

            enHelperActivityType        ev     = enHelperActivityType.NoSuchCreator;
            AniDBCommand_GetGroupStatus getCmd = null;

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

            if (ev == enHelperActivityType.GotGroupStatus && getCmd.GrpStatusCollection != null)
            {
                // delete existing records


                RepoFactory.AniDB_GroupStatus.DeleteForAnime(animeID);

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

                // updated cached stats
                // we don't do it in the save method as it would be too many unecessary updates
                logger.Trace("Updating group stats by anime from GetReleaseGroupStatusUDP: {0}", animeID);


                // StatsCache.Instance.UpdateUsingAnime(animeID);
                //Removed QueueUpdateStatus will Update Groups


                if (getCmd.GrpStatusCollection.LatestEpisodeNumber > 0)
                {
                    // update the anime with a record of the latest subbed episode
                    AniDB_Anime anime = RepoFactory.AniDB_Anime.GetByAnimeID(animeID);
                    if (anime != null)
                    {
                        anime.LatestEpisodeNumber = getCmd.GrpStatusCollection.LatestEpisodeNumber;
                        RepoFactory.AniDB_Anime.Save(anime);

                        // check if we have this episode in the database
                        // if not get it now by updating the anime record
                        List <AniDB_Episode> eps = RepoFactory.AniDB_Episode.GetByAnimeIDAndEpisodeNumber(animeID,
                                                                                                          getCmd.GrpStatusCollection.LatestEpisodeNumber);
                        if (eps.Count == 0)
                        {
                            CommandRequest_GetAnimeHTTP cr_anime = new CommandRequest_GetAnimeHTTP(animeID, true, false);
                            cr_anime.Save();
                        }
                        // update the missing episode stats on groups and children
                        AnimeSeries series = RepoFactory.AnimeSeries.GetByAnimeID(animeID);
                        if (series != null)
                        {
                            series.QueueUpdateStats();
                            //series.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true, true, true);
                        }
                    }
                }
            }

            return(getCmd.GrpStatusCollection);
        }
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_MovieDBSearchAnime: {0}", AnimeID);

            try
            {
                using (var session = DatabaseFactory.SessionFactory.OpenSession())
                {
                    ISessionWrapper sessionWrapper = session.Wrap();

                    // first check if the user wants to use the web cache
                    if (ServerSettings.WebCache_TvDB_Get)
                    {
                        try
                        {
                            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   = RepoFactory.MovieDb_Movie.GetByOnlineID(sessionWrapper, movieID);
                                if (movie == null)
                                {
                                    // update the info from online
                                    MovieDBHelper.UpdateMovieInfo(session, movieID, true);
                                    movie = RepoFactory.MovieDb_Movie.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_Anime anime          = RepoFactory.AniDB_Anime.GetByAnimeID(sessionWrapper, 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())
                        {
                            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;
            }
        }
Ejemplo n.º 21
0
        private string GetFileName(ImageDownloadRequest req, bool thumbNailOnly)
        {
            switch (req.ImageType)
            {
            case JMMImageType.AniDB_Cover:

                AniDB_Anime anime = req.ImageData as AniDB_Anime;
                return(anime.PosterPath);

            case JMMImageType.TvDB_Episode:

                TvDB_Episode ep = req.ImageData as TvDB_Episode;
                return(ep.FullImagePath);

            case JMMImageType.TvDB_FanArt:

                TvDB_ImageFanart fanart = req.ImageData as TvDB_ImageFanart;
                if (thumbNailOnly)
                {
                    return(fanart.FullThumbnailPath);
                }
                else
                {
                    return(fanart.FullImagePath);
                }

            case JMMImageType.TvDB_Cover:

                TvDB_ImagePoster poster = req.ImageData as TvDB_ImagePoster;
                return(poster.FullImagePath);

            case JMMImageType.TvDB_Banner:

                TvDB_ImageWideBanner wideBanner = req.ImageData as TvDB_ImageWideBanner;
                return(wideBanner.FullImagePath);

            case JMMImageType.MovieDB_Poster:

                MovieDB_Poster moviePoster = req.ImageData as MovieDB_Poster;
                return(moviePoster.FullImagePath);

            case JMMImageType.MovieDB_FanArt:

                MovieDB_Fanart movieFanart = req.ImageData as MovieDB_Fanart;
                return(movieFanart.FullImagePath);

            case JMMImageType.Trakt_Poster:
                Trakt_ImagePoster traktPoster = req.ImageData as Trakt_ImagePoster;
                return(traktPoster.FullImagePath);

            case JMMImageType.Trakt_Fanart:
                Trakt_ImageFanart traktFanart = req.ImageData as Trakt_ImageFanart;
                return(traktFanart.FullImagePath);

            case JMMImageType.Trakt_Friend:
                Trakt_Friend traktFriend = req.ImageData as Trakt_Friend;
                return(traktFriend.FullImagePath);

            case JMMImageType.Trakt_Episode:
                Trakt_Episode traktEp = req.ImageData as Trakt_Episode;
                return(traktEp.FullImagePath);

            case JMMImageType.AniDB_Character:
                AniDB_Character chr = req.ImageData as AniDB_Character;
                return(chr.PosterPath);

            case JMMImageType.AniDB_Creator:
                AniDB_Seiyuu creator = req.ImageData as AniDB_Seiyuu;
                return(creator.PosterPath);

            default:
                return("");
            }
        }
Ejemplo n.º 22
0
        public static void MigrateTraktLinks_V1_to_V2()
        {
            try
            {
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    List <CrossRef_AniDB_Trakt> xrefsTrakt = RepoFactory.CrossRef_AniDB_Trakt.GetAll();
                    foreach (CrossRef_AniDB_Trakt xrefTrakt in xrefsTrakt)
                    {
                        CrossRef_AniDB_TraktV2 xrefNew = new CrossRef_AniDB_TraktV2();
                        xrefNew.AnimeID           = xrefTrakt.AnimeID;
                        xrefNew.CrossRefSource    = xrefTrakt.CrossRefSource;
                        xrefNew.TraktID           = xrefTrakt.TraktID;
                        xrefNew.TraktSeasonNumber = xrefTrakt.TraktSeasonNumber;

                        Trakt_Show show = xrefTrakt.GetByTraktShow(session);
                        if (show != null)
                        {
                            xrefNew.TraktTitle = show.Title;
                        }

                        // determine start ep type
                        if (xrefTrakt.TraktSeasonNumber == 0)
                        {
                            xrefNew.AniDBStartEpisodeType = (int)enEpisodeType.Special;
                        }
                        else
                        {
                            xrefNew.AniDBStartEpisodeType = (int)enEpisodeType.Episode;
                        }

                        xrefNew.AniDBStartEpisodeNumber = 1;
                        xrefNew.TraktStartEpisodeNumber = 1;

                        RepoFactory.CrossRef_AniDB_TraktV2.Save(xrefNew);
                    }

                    // create cross ref's for specials
                    foreach (CrossRef_AniDB_Trakt xrefTrakt in xrefsTrakt)
                    {
                        AniDB_Anime anime = RepoFactory.AniDB_Anime.GetByAnimeID(xrefTrakt.AnimeID);
                        if (anime == null)
                        {
                            continue;
                        }

                        Trakt_Show show = xrefTrakt.GetByTraktShow(session);
                        if (show == null)
                        {
                            continue;
                        }

                        // this anime has specials
                        if (anime.EpisodeCountSpecial <= 0)
                        {
                            continue;
                        }

                        // this Trakt series has a season 0 (specials)
                        List <int> seasons = RepoFactory.Trakt_Episode.GetSeasonNumbersForSeries(show.Trakt_ShowID);
                        if (!seasons.Contains(0))
                        {
                            continue;
                        }

                        //make sure we are not doubling up
                        CrossRef_AniDB_TraktV2 temp = RepoFactory.CrossRef_AniDB_TraktV2.GetByTraktID(xrefTrakt.TraktID, 0, 1,
                                                                                                      xrefTrakt.AnimeID,
                                                                                                      (int)enEpisodeType.Special, 1);
                        if (temp != null)
                        {
                            continue;
                        }

                        CrossRef_AniDB_TraktV2 xrefNew = new CrossRef_AniDB_TraktV2();
                        xrefNew.AnimeID                 = xrefTrakt.AnimeID;
                        xrefNew.CrossRefSource          = xrefTrakt.CrossRefSource;
                        xrefNew.TraktID                 = xrefTrakt.TraktID;
                        xrefNew.TraktSeasonNumber       = 0;
                        xrefNew.TraktStartEpisodeNumber = 1;
                        xrefNew.AniDBStartEpisodeType   = (int)enEpisodeType.Special;
                        xrefNew.AniDBStartEpisodeNumber = 1;
                        xrefNew.TraktTitle              = show.Title;

                        RepoFactory.CrossRef_AniDB_TraktV2.Save(xrefNew);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Could not MigrateTraktLinks_V1_to_V2: " + ex.ToString());
            }
        }
Ejemplo n.º 23
0
        public Contract_AnimeSeries ToContract(AniDB_Anime animeRec, List <CrossRef_AniDB_TvDBV2> tvDBCrossRefs, CrossRef_AniDB_Other movieDBCrossRef,
                                               AnimeSeries_User userRecord, List <TvDB_Series> tvseries, List <CrossRef_AniDB_MAL> malDBCrossRef, bool passedDefaultImages, AniDB_Anime_DefaultImage defPoster,
                                               AniDB_Anime_DefaultImage defFanart, AniDB_Anime_DefaultImage defWideBanner, List <AniDB_Anime_Title> titles, bool forceimages = false)
        {
            Contract_AnimeSeries contract = new Contract_AnimeSeries();

            contract.AniDB_ID                  = this.AniDB_ID;
            contract.AnimeGroupID              = this.AnimeGroupID;
            contract.AnimeSeriesID             = this.AnimeSeriesID;
            contract.DateTimeUpdated           = this.DateTimeUpdated;
            contract.DateTimeCreated           = this.DateTimeCreated;
            contract.DefaultAudioLanguage      = this.DefaultAudioLanguage;
            contract.DefaultSubtitleLanguage   = this.DefaultSubtitleLanguage;
            contract.LatestLocalEpisodeNumber  = this.LatestLocalEpisodeNumber;
            contract.EpisodeAddedDate          = this.EpisodeAddedDate;
            contract.MissingEpisodeCount       = this.MissingEpisodeCount;
            contract.MissingEpisodeCountGroups = this.MissingEpisodeCountGroups;
            contract.SeriesNameOverride        = this.SeriesNameOverride;



            if (userRecord == null)
            {
                contract.PlayedCount           = 0;
                contract.StoppedCount          = 0;
                contract.UnwatchedEpisodeCount = 0;
                contract.WatchedCount          = 0;
                contract.WatchedDate           = null;
                contract.WatchedEpisodeCount   = 0;
            }
            else
            {
                contract.PlayedCount           = userRecord.PlayedCount;
                contract.StoppedCount          = userRecord.StoppedCount;
                contract.UnwatchedEpisodeCount = userRecord.UnwatchedEpisodeCount;
                contract.WatchedCount          = userRecord.WatchedCount;
                contract.WatchedDate           = userRecord.WatchedDate;
                contract.WatchedEpisodeCount   = userRecord.WatchedEpisodeCount;
            }

            // get AniDB data
            contract.AniDBAnime = null;
            if (animeRec != null)
            {
                Contract_AniDBAnime animecontract = animeRec.ToContract(false, titles);

                AniDB_Anime_DefaultImage defaultPoster = null;
                if (passedDefaultImages)
                {
                    defaultPoster = defPoster;
                }
                else
                {
                    defaultPoster = animeRec.GetDefaultPoster();
                }

                if (defaultPoster == null)
                {
                    animecontract.DefaultImagePoster = null;
                }
                else
                {
                    animecontract.DefaultImagePoster = defaultPoster.ToContract();
                }

                if ((animecontract.DefaultImagePoster == null) && (forceimages))
                {
                    ImageDetails im = animeRec.GetDefaultPosterDetailsNoBlanks();
                    if (im != null)
                    {
                        animecontract.DefaultImagePoster           = new Contract_AniDB_Anime_DefaultImage();
                        animecontract.DefaultImagePoster.AnimeID   = im.ImageID;
                        animecontract.DefaultImagePoster.ImageType = (int)im.ImageType;
                    }
                }
                AniDB_Anime_DefaultImage defaultFanart = null;
                if (passedDefaultImages)
                {
                    defaultFanart = defFanart;
                }
                else
                {
                    defaultFanart = animeRec.GetDefaultFanart();
                }

                if (defaultFanart == null)
                {
                    animecontract.DefaultImageFanart = null;
                }
                else
                {
                    animecontract.DefaultImageFanart = defaultFanart.ToContract();
                }

                if ((animecontract.DefaultImagePoster == null) && (forceimages))
                {
                    ImageDetails im = animeRec.GetDefaultFanartDetailsNoBlanks();
                    if (im != null)
                    {
                        animecontract.DefaultImageFanart           = new Contract_AniDB_Anime_DefaultImage();
                        animecontract.DefaultImageFanart.AnimeID   = im.ImageID;
                        animecontract.DefaultImageFanart.ImageType = (int)im.ImageType;
                    }
                }

                AniDB_Anime_DefaultImage defaultWideBanner = null;
                if (passedDefaultImages)
                {
                    defaultWideBanner = defWideBanner;
                }
                else
                {
                    defaultWideBanner = animeRec.GetDefaultWideBanner();
                }

                if (defaultWideBanner == null)
                {
                    animecontract.DefaultImageWideBanner = null;
                }
                else
                {
                    animecontract.DefaultImageWideBanner = defaultWideBanner.ToContract();
                }

                contract.AniDBAnime = animecontract;
            }

            contract.CrossRefAniDBTvDBV2 = new List <Contract_CrossRef_AniDB_TvDBV2>();
            foreach (CrossRef_AniDB_TvDBV2 tvXref in tvDBCrossRefs)
            {
                contract.CrossRefAniDBTvDBV2.Add(tvXref.ToContract());
            }


            contract.TvDB_Series = new List <Contract_TvDB_Series>();
            foreach (TvDB_Series ser in tvseries)
            {
                contract.TvDB_Series.Add(ser.ToContract());
            }

            contract.CrossRefAniDBMovieDB = null;
            if (movieDBCrossRef != null)
            {
                contract.CrossRefAniDBMovieDB = movieDBCrossRef.ToContract();
            }

            contract.CrossRefAniDBMAL = new List <Contract_CrossRef_AniDB_MAL>();
            if (malDBCrossRef != null)
            {
                foreach (CrossRef_AniDB_MAL xref in malDBCrossRef)
                {
                    contract.CrossRefAniDBMAL.Add(xref.ToContract());
                }
            }

            return(contract);
        }
Ejemplo n.º 24
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)
                                {
                                    TraktTVShow showInfo = TraktTVHelper.GetShowInfo(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)
                        {
                            TraktTVShow showInfo = TraktTVHelper.GetShowInfo(tvXRef.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, (AniDBAPI.enEpisodeType)tvXRef.AniDBStartEpisodeType,
                                                                     tvXRef.AniDBStartEpisodeNumber, showInfo.TraktID, 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 <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;
            }
        }
Ejemplo n.º 25
0
        public override void ProcessCommand()
        {
            logger.Info("Get AniDB file info: {0}", VideoLocalID);


            try
            {
                vlocal = RepoFactory.VideoLocal.GetByID(VideoLocalID);
                if (vlocal == null)
                {
                    return;
                }

                AniDB_File aniFile = RepoFactory.AniDB_File.GetByHashAndFileSize(vlocal.Hash, vlocal.FileSize);

                /*// get anidb file info from web cache
                 *              if (aniFile == null && ServerSettings.WebCache_AniDB_File_Get)
                 *              {
                 *                      AniDB_FileRequest fr = XMLService.Get_AniDB_File(vlocal.Hash, vlocal.FileSize);
                 *                      if (fr != null)
                 *                      {
                 *                              aniFile = new AniDB_File();
                 *                              aniFile.Populate(fr);
                 *
                 *                              //overwrite with local file name
                 *                              string localFileName = Path.GetFileName(vlocal.FilePath);
                 *                              aniFile.FileName = localFileName;
                 *
                 *                              repAniFile.Save(aniFile, false);
                 *                              aniFile.CreateLanguages();
                 *                              aniFile.CreateCrossEpisodes(localFileName);
                 *
                 *                              StatsCache.Instance.UpdateUsingAniDBFile(vlocal.Hash);
                 *                      }
                 *              }*/

                Raw_AniDB_File fileInfo = null;
                if (aniFile == null || ForceAniDB)
                {
                    fileInfo = JMMService.AnidbProcessor.GetFileInfo(vlocal);
                }

                if (fileInfo != null)
                {
                    // save to the database
                    if (aniFile == null)
                    {
                        aniFile = new AniDB_File();
                    }

                    aniFile.Populate(fileInfo);

                    //overwrite with local file name
                    string localFileName = vlocal.FileName;
                    aniFile.FileName = localFileName;

                    RepoFactory.AniDB_File.Save(aniFile, false);
                    aniFile.CreateLanguages();
                    aniFile.CreateCrossEpisodes(localFileName);

                    if (!string.IsNullOrEmpty(fileInfo.OtherEpisodesRAW))
                    {
                        string[] epIDs = fileInfo.OtherEpisodesRAW.Split(',');
                        foreach (string epid in epIDs)
                        {
                            int id = 0;
                            if (int.TryParse(epid, out id))
                            {
                                CommandRequest_GetEpisode cmdEp = new CommandRequest_GetEpisode(id);
                                cmdEp.Save();
                            }
                        }
                    }
                    AniDB_Anime anime = RepoFactory.AniDB_Anime.GetByAnimeID(aniFile.AnimeID);
                    if (anime != null)
                    {
                        using (var session = JMMService.SessionFactory.OpenSession())
                        {
                            anime.UpdateContractDetailed(session.Wrap());
                        }
                    }
                    AnimeSeries series = RepoFactory.AnimeSeries.GetByAnimeID(aniFile.AnimeID);
                    series.UpdateStats(false, true, true);
//					StatsCache.Instance.UpdateUsingAniDBFile(vlocal.Hash);
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error processing CommandRequest_GetFile: {0} - {1}", VideoLocalID, ex.ToString());
                return;
            }
        }
Ejemplo n.º 26
0
        private static bool PopulateVideoEpisodeFromAnime(Video v, AniDB_Anime ani, Video nv)
        {
            bool ret = false;

            if (ani != null)
            {
                if (ani.Restricted > 0)
                {
                    v.ContentRating = "R";
                }
                if (ani.AnimeTypeEnum == enAnimeType.Movie)
                {
                    v.Type = "movie";
                    if (v.Title.StartsWith("Complete Movie"))
                    {
                        v.Title   = nv.Title;
                        v.Summary = nv.Summary;
                        v.Index   = null;
                        ret       = true;
                    }
                    else if (v.Title.StartsWith("Part "))
                    {
                        v.Title   = nv.Title + " - " + v.Title;
                        v.Summary = nv.Summary;
                    }
                    v.Thumb = nv.Thumb;
                }
                else if (ani.AnimeTypeEnum == enAnimeType.OVA)
                {
                    if (v.Title == "OVA")
                    {
                        v.Title   = nv.Title;
                        v.Type    = "movie";
                        v.Thumb   = nv.Thumb;
                        v.Summary = nv.Summary;
                        v.Index   = null;
                        ret       = true;
                    }
                }
                else
                {
                    v.ParentTitle = nv.Title;
                }
            }
            if (string.IsNullOrEmpty(v.Art))
            {
                v.Art = nv.Art;
            }
            if (v.Tags == null)
            {
                v.Tags = nv.Tags;
            }
            if (v.Genres == null)
            {
                v.Genres = nv.Genres;
            }
            if (v.Season == null)
            {
                v.Season = nv.Season;
            }
            v.ParentThumb     = nv.Thumb;
            v.ParentRatingKey = v.ParentKey = nv.Key;
            if (string.IsNullOrEmpty(v.Rating))
            {
                v.Rating = nv.Rating;
                v.Votes  = nv.Votes;
            }
            return(ret);
        }
Ejemplo n.º 27
0
        public static void MigrateTvDBLinks_V1_to_V2()
        {
            try
            {
                AniDB_AnimeRepository  repAnime = new AniDB_AnimeRepository();
                TvDB_EpisodeRepository repEps   = new TvDB_EpisodeRepository();

                CrossRef_AniDB_TvDBRepository   repCrossRefTvDB    = new CrossRef_AniDB_TvDBRepository();
                CrossRef_AniDB_TvDBV2Repository repCrossRefTvDBNew = new CrossRef_AniDB_TvDBV2Repository();

                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    List <CrossRef_AniDB_TvDB> xrefsTvDB = repCrossRefTvDB.GetAll();
                    foreach (CrossRef_AniDB_TvDB xrefTvDB in xrefsTvDB)
                    {
                        CrossRef_AniDB_TvDBV2 xrefNew = new CrossRef_AniDB_TvDBV2();
                        xrefNew.AnimeID          = xrefTvDB.AnimeID;
                        xrefNew.CrossRefSource   = xrefTvDB.CrossRefSource;
                        xrefNew.TvDBID           = xrefTvDB.TvDBID;
                        xrefNew.TvDBSeasonNumber = xrefTvDB.TvDBSeasonNumber;

                        TvDB_Series ser = xrefTvDB.GetTvDBSeries(session);
                        if (ser != null)
                        {
                            xrefNew.TvDBTitle = ser.SeriesName;
                        }

                        // determine start ep type
                        if (xrefTvDB.TvDBSeasonNumber == 0)
                        {
                            xrefNew.AniDBStartEpisodeType = (int)AniDBAPI.enEpisodeType.Special;
                        }
                        else
                        {
                            xrefNew.AniDBStartEpisodeType = (int)AniDBAPI.enEpisodeType.Episode;
                        }

                        xrefNew.AniDBStartEpisodeNumber = 1;
                        xrefNew.TvDBStartEpisodeNumber  = 1;

                        repCrossRefTvDBNew.Save(xrefNew);
                    }

                    // create cross ref's for specials
                    foreach (CrossRef_AniDB_TvDB xrefTvDB in xrefsTvDB)
                    {
                        AniDB_Anime anime = repAnime.GetByAnimeID(xrefTvDB.AnimeID);
                        if (anime == null)
                        {
                            continue;
                        }

                        // this anime has specials
                        if (anime.EpisodeCountSpecial <= 0)
                        {
                            continue;
                        }

                        // this tvdb series has a season 0 (specials)
                        List <int> seasons = repEps.GetSeasonNumbersForSeries(xrefTvDB.TvDBID);
                        if (!seasons.Contains(0))
                        {
                            continue;
                        }

                        //make sure we are not doubling up
                        CrossRef_AniDB_TvDBV2 temp = repCrossRefTvDBNew.GetByTvDBID(xrefTvDB.TvDBID, 0, 1, xrefTvDB.AnimeID, (int)AniDBAPI.enEpisodeType.Special, 1);
                        if (temp != null)
                        {
                            continue;
                        }

                        CrossRef_AniDB_TvDBV2 xrefNew = new CrossRef_AniDB_TvDBV2();
                        xrefNew.AnimeID                 = xrefTvDB.AnimeID;
                        xrefNew.CrossRefSource          = xrefTvDB.CrossRefSource;
                        xrefNew.TvDBID                  = xrefTvDB.TvDBID;
                        xrefNew.TvDBSeasonNumber        = 0;
                        xrefNew.TvDBStartEpisodeNumber  = 1;
                        xrefNew.AniDBStartEpisodeType   = (int)AniDBAPI.enEpisodeType.Special;
                        xrefNew.AniDBStartEpisodeNumber = 1;

                        TvDB_Series ser = xrefTvDB.GetTvDBSeries(session);
                        if (ser != null)
                        {
                            xrefNew.TvDBTitle = ser.SeriesName;
                        }

                        repCrossRefTvDBNew.Save(xrefNew);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException("Could not MigrateTvDBLinks_V1_to_V2: " + ex.ToString(), ex);
            }
        }
Ejemplo n.º 28
0
 public static bool PopulateVideo(Video l, VideoLocal v, AnimeEpisode ep, AnimeSeries series, AniDB_Anime ani, Video nv, JMMType type, int userid)
 {
     PopulateVideoEpisodeFromVideoLocal(l, v, type);
     if (ep != null)
     {
         PopulateVideoEpisodeFromAnimeEpisode(l, ep, userid);
         if (series != null)
         {
             return(PopulateVideoEpisodeFromAnime(l, ani, nv));
         }
     }
     return(false);
 }
        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
                                CrossRef_AniDB_TvDBV2Repository repCrossRef = new CrossRef_AniDB_TvDBV2Repository();
                                List <CrossRef_AniDB_TvDBV2>    xrefTemp    = repCrossRef.GetByAnimeID(AnimeID);
                                if (xrefTemp != null && xrefTemp.Count > 0)
                                {
                                    return;
                                }

                                foreach (JMMServer.Providers.Azure.CrossRef_AniDB_TvDB xref in cacheResults)
                                {
                                    TvDB_Series tvser = TvDBHelper.GetSeriesInfoOnline(cacheResults[0].TvDBID);
                                    if (tvser != null)
                                    {
                                        logger.Trace("Found tvdb match on web cache for {0}", AnimeID);
                                        TvDBHelper.LinkAniDBTvDB(AnimeID, (AniDBAPI.enEpisodeType)cacheResults[0].AniDBStartEpisodeType, cacheResults[0].AniDBStartEpisodeNumber,
                                                                 cacheResults[0].TvDBID, cacheResults[0].TvDBSeasonNumber, cacheResults[0].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_AnimeRepository repAnime = new AniDB_AnimeRepository();
                    AniDB_Anime           anime    = repAnime.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;
            }
        }
        public System.IO.Stream GetImage(string ImageType, string ImageID, bool thumnbnailOnly, out string contentType)
        {
            contentType = null;

            JMMImageType imageType = (JMMImageType)int.Parse(ImageType);

            string path;

            switch (imageType)
            {
            case JMMImageType.AniDB_Cover:

                AniDB_Anime anime = RepoFactory.AniDB_Anime.GetByAnimeID(int.Parse(ImageID));
                if (anime == null)
                {
                    return(null);
                }

                path = anime.PosterPath;
                if (File.Exists(path))
                {
                    FileStream fs = File.OpenRead(path);
                    contentType = MimeTypes.GetMimeType(path);
                    return(fs);
                }
                else
                {
                    logger.Trace("Could not find AniDB_Cover image: {0}", anime.PosterPath);
                    return(BlankImage());
                }

            case JMMImageType.AniDB_Character:

                AniDB_Character chr = RepoFactory.AniDB_Character.GetByID(int.Parse(ImageID));
                if (chr == null)
                {
                    return(null);
                }

                path = chr.PosterPath;
                if (File.Exists(path))
                {
                    FileStream fs = File.OpenRead(path);
                    contentType = MimeTypes.GetMimeType(path);
                    return(fs);
                }
                else
                {
                    logger.Trace("Could not find AniDB_Character image: {0}", chr.PosterPath);
                    return(BlankImage());
                }

            case JMMImageType.AniDB_Creator:

                AniDB_Seiyuu creator = RepoFactory.AniDB_Seiyuu.GetByID(int.Parse(ImageID));
                if (creator == null)
                {
                    return(null);
                }

                path = creator.PosterPath;
                if (File.Exists(path))
                {
                    FileStream fs = File.OpenRead(path);
                    contentType = MimeTypes.GetMimeType(path);
                    return(fs);
                }
                else
                {
                    logger.Trace("Could not find AniDB_Creator image: {0}", creator.PosterPath);
                    return(BlankImage());
                }

            case JMMImageType.TvDB_Cover:

                TvDB_ImagePoster poster = RepoFactory.TvDB_ImagePoster.GetByID(int.Parse(ImageID));
                if (poster == null)
                {
                    return(null);
                }

                path = poster.FullImagePath;
                if (File.Exists(path))
                {
                    FileStream fs = File.OpenRead(path);
                    contentType = MimeTypes.GetMimeType(path);
                    return(fs);
                }
                else
                {
                    logger.Trace("Could not find TvDB_Cover image: {0}", poster.FullImagePath);
                    return(BlankImage());
                }

            case JMMImageType.TvDB_Banner:

                TvDB_ImageWideBanner wideBanner = RepoFactory.TvDB_ImageWideBanner.GetByID(int.Parse(ImageID));
                if (wideBanner == null)
                {
                    return(null);
                }

                path = wideBanner.FullImagePath;
                if (File.Exists(path))
                {
                    FileStream fs = File.OpenRead(path);
                    contentType = MimeTypes.GetMimeType(path);
                    return(fs);
                }
                else
                {
                    logger.Trace("Could not find TvDB_Banner image: {0}", wideBanner.FullImagePath);
                    return(BlankImage());
                }

            case JMMImageType.TvDB_Episode:

                TvDB_Episode ep = RepoFactory.TvDB_Episode.GetByID(int.Parse(ImageID));
                if (ep == null)
                {
                    return(null);
                }

                path = ep.FullImagePath;
                if (File.Exists(path))
                {
                    FileStream fs = File.OpenRead(path);
                    contentType = MimeTypes.GetMimeType(path);
                    return(fs);
                }
                else
                {
                    logger.Trace("Could not find TvDB_Episode image: {0}", ep.FullImagePath);
                    return(BlankImage());
                }

            case JMMImageType.TvDB_FanArt:

                TvDB_ImageFanart fanart = RepoFactory.TvDB_ImageFanart.GetByID(int.Parse(ImageID));
                if (fanart == null)
                {
                    return(null);
                }

                if (thumnbnailOnly)
                {
                    path = fanart.FullThumbnailPath;
                    if (File.Exists(path))
                    {
                        FileStream fs = File.OpenRead(path);
                        contentType = MimeTypes.GetMimeType(path);
                        return(fs);
                    }
                    else
                    {
                        logger.Trace("Could not find TvDB_FanArt image: {0}", fanart.FullThumbnailPath);
                        return(null);
                    }
                }
                else
                {
                    path = fanart.FullImagePath;
                    if (File.Exists(path))
                    {
                        FileStream fs = File.OpenRead(path);
                        contentType = MimeTypes.GetMimeType(path);
                        return(fs);
                    }
                    else
                    {
                        logger.Trace("Could not find TvDB_FanArt image: {0}", fanart.FullImagePath);
                        return(BlankImage());
                    }
                }

            case JMMImageType.MovieDB_Poster:

                MovieDB_Poster mPoster = RepoFactory.MovieDB_Poster.GetByID(int.Parse(ImageID));
                if (mPoster == null)
                {
                    return(null);
                }

                // now find only the original size
                mPoster = RepoFactory.MovieDB_Poster.GetByOnlineID(mPoster.URL);
                if (mPoster == null)
                {
                    return(null);
                }

                path = mPoster.FullImagePath;
                if (File.Exists(path))
                {
                    FileStream fs = File.OpenRead(path);
                    contentType = MimeTypes.GetMimeType(path);
                    return(fs);
                }
                else
                {
                    logger.Trace("Could not find MovieDB_Poster image: {0}", mPoster.FullImagePath);
                    return(BlankImage());
                }

            case JMMImageType.MovieDB_FanArt:

                MovieDB_Fanart mFanart = RepoFactory.MovieDB_Fanart.GetByID(int.Parse(ImageID));
                if (mFanart == null)
                {
                    return(null);
                }

                mFanart = RepoFactory.MovieDB_Fanart.GetByOnlineID(mFanart.URL);
                if (mFanart == null)
                {
                    return(null);
                }

                path = mFanart.FullImagePath;
                if (File.Exists(path))
                {
                    FileStream fs = File.OpenRead(path);
                    contentType = MimeTypes.GetMimeType(path);
                    return(fs);
                }
                else
                {
                    logger.Trace("Could not find MovieDB_FanArt image: {0}", mFanart.FullImagePath);
                    return(BlankImage());
                }

            case JMMImageType.Trakt_Fanart:

                Trakt_ImageFanart tFanart = RepoFactory.Trakt_ImageFanart.GetByID(int.Parse(ImageID));
                if (tFanart == null)
                {
                    return(null);
                }

                path = tFanart.FullImagePath;
                if (File.Exists(path))
                {
                    FileStream fs = File.OpenRead(path);
                    contentType = MimeTypes.GetMimeType(path);
                    return(fs);
                }
                else
                {
                    logger.Trace("Could not find Trakt_Fanart image: {0}", tFanart.FullImagePath);
                    return(BlankImage());
                }

            case JMMImageType.Trakt_Poster:

                Trakt_ImagePoster tPoster = RepoFactory.Trakt_ImagePoster.GetByID(int.Parse(ImageID));
                if (tPoster == null)
                {
                    return(null);
                }

                path = tPoster.FullImagePath;
                if (File.Exists(path))
                {
                    FileStream fs = File.OpenRead(path);
                    contentType = MimeTypes.GetMimeType(path);
                    return(fs);
                }
                else
                {
                    logger.Trace("Could not find Trakt_Poster image: {0}", tPoster.FullImagePath);
                    return(BlankImage());
                }

            case JMMImageType.Trakt_Episode:
            case JMMImageType.Trakt_WatchedEpisode:

                Trakt_Episode tEpisode = RepoFactory.Trakt_Episode.GetByID(int.Parse(ImageID));
                if (tEpisode == null)
                {
                    return(null);
                }

                path = tEpisode.FullImagePath;
                if (File.Exists(path))
                {
                    FileStream fs = File.OpenRead(path);
                    contentType = MimeTypes.GetMimeType(path);
                    return(fs);
                }
                else
                {
                    logger.Trace("Could not find Trakt_Episode image: {0}", tEpisode.FullImagePath);
                    return(BlankImage());
                }

            default:

                return(BlankImage());
            }
        }