Exemplo n.º 1
0
        public static bool IsSubscribing(TvShow show)
        {
            if (show == null)
                return false;

            return Repository.GetTvShow(show.ID) != null;
        }
Exemplo n.º 2
0
        public void AddUnmatchedShow()
        {
            // Create new show and episodes
            var delta = new TvShow { Name = "Delta", FolderName = "Delta", TvdbId = "4" };
            var episode1 = new Episode { EpisodeNumber = 1, SeasonNumber = 1, Name = "Episode 1", TvdbId = "41" };

            // Create a file for the search to return.
            this.CreateTestFile(this.Root, "Delta.S01E01.avi");

            // When the data provider searches for Delta return the delta show.
            this.dataProvider.SearchShow("Delta").Returns(new List<TvShow> { delta });

            // When the show is saved, get the new show. A new one will be created by
            // TvShow.FromSearchResult
            this.StorageProvider.When(x => x.SaveShow(Arg.Any<TvShow>())).Do(x => { delta = x.Arg<TvShow>(); });

            // Delta should be updated.When it is, add the episode.
            this.dataProvider.When(x => x.UpdateShow(delta)).Do(
                x => { delta.Episodes = new List<Episode> { episode1 }; });

            // Search the folder.
            List<FileResult> results = this.scanManager.Refresh(this.Root);

            // There should be one result matching Delta Episode 1.
            Assert.AreEqual(1, results.Count, "There should be one result.");
            Assert.AreEqual(results[0].Show, delta, "The show shuld be Delta");
            Assert.AreEqual(results[0].Episode, episode1, "The episode should be Episode 1");
        }
Exemplo n.º 3
0
        private async Task UpdateTvShowInfo(TvShow tvShow)
        {
            await Novaroma.Helper.RunTask(() => _engine.UpdateTvShow(tvShow), _exceptionHandler);

            if (SelectedTvShow == tvShow)
            {
                SelectedTvShow = null;
                SelectedTvShow = tvShow;
            }
        }
Exemplo n.º 4
0
 public ActionResult Edit([Bind(Include = "Id,Title,Season,Date,Rating,UserId")] TvShow tvShow)
 {
     if (ModelState.IsValid)
     {
         db.Entry(tvShow).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(tvShow));
 }
Exemplo n.º 5
0
        public EntryInformation(int entryId)
        {
            this.entryId = entryId;

            //Media Api
            apiKey = "24db2192e9447969b597b0a6823f7e8e";
            client = new TMDbClient(apiKey);
            movie  = client.GetMovieAsync(entryId, MovieMethods.Credits).Result;
            tvshow = client.GetTvShowAsync(entryId, TvShowMethods.Credits).Result;
        }
Exemplo n.º 6
0
        public IActionResult Episodes(int id)
        {
            TvShow     tvShow     = ApiHandler.GetTvShowAndEpisodeDetails(id);
            EpisodesVM episodesVM = new EpisodesVM
            {
                Episodes = tvShow.EmbeddedItems.Episodes
            };

            return(PartialView("Episodes", episodesVM));
        }
Exemplo n.º 7
0
        public async Task <ActionResponse <UserTVShowMapping> > ManageAdditionAsync(TvShow tvShow)
        {
            var userId  = _userContextManager.GetUserIdFromContext();
            var mapping = new UserTVShowMapping {
                UserId = userId, TvShow = tvShow
            };
            var response = await _addUserTVShowMapping.Add(mapping);

            return(response);
        }
        public async Task <IActionResult> Create([Bind("Id,Title,Genre,Rating,ImdbUrl,ImageUrl")] TvShow tvShow)
        {
            if (ModelState.IsValid)
            {
                await _services.CreateEntry(tvShow);

                return(RedirectToAction(nameof(Index)));
            }
            return(View(tvShow));
        }
Exemplo n.º 9
0
        public static void InitTvShow(TvShow tvShow, INovaromaEngine engine)
        {
            var episodes = tvShow.Seasons.SelectMany(s => s.Episodes).ToList();

            episodes.ForEach(e => {
                if (!string.IsNullOrEmpty(e.FilePath) && !File.Exists(e.FilePath))
                {
                    e.FilePath           = string.Empty;
                    e.SubtitleDownloaded = false;
                }
                if (e.IsWatched)
                {
                    return;
                }

                e.BackgroundDownload         = true;
                e.BackgroundSubtitleDownload = engine.SubtitlesNeeded(tvShow.Language);
                e.SubtitleDownloaded         = false;
            });

            if (string.IsNullOrWhiteSpace(tvShow.Directory) || !Directory.Exists(tvShow.Directory))
            {
                return;
            }

            var files      = new DirectoryInfo(tvShow.Directory).GetFiles("*", SearchOption.AllDirectories).ToList();
            var videoFiles = files.Where(IsVideoFile).ToList();

            foreach (var videoFile in videoFiles)
            {
                int?season, episode;
                DetectEpisodeInfo(videoFile.NameWithoutExtension(), tvShow.Title, out season, out episode, videoFile, tvShow.Seasons.Max(s => s.Season));
                if (!season.HasValue || !episode.HasValue)
                {
                    continue;
                }

                var tvEpisode = episodes.FirstOrDefault(e => e.TvShowSeason.Season == season && e.Episode == episode.Value);
                if (tvEpisode == null)
                {
                    continue;
                }

                tvEpisode.BackgroundDownload = false;
                tvEpisode.NotFound           = false;
                tvEpisode.FilePath           = videoFile.FullName;
                var subtitleFilePath = GetSubtitleFilePath(videoFile);
                if (!string.IsNullOrEmpty(subtitleFilePath))
                {
                    tvEpisode.BackgroundSubtitleDownload = false;
                    tvEpisode.SubtitleNotFound           = false;
                    tvEpisode.SubtitleDownloaded         = true;
                }
            }
        }
Exemplo n.º 10
0
        public ContentResult OnGet()
        {
            TvShow = Config.GetSection("tvshow").Get <TvShow>();

            return(Content(
                       $"Series:   {TvShow.Metadata.Series}   \n" +
                       $"Title:    {TvShow.Metadata.Title}    \n" +
                       $"AirDate:  {TvShow.Metadata.AirDate}  \n" +
                       $"Episodes: {TvShow.Metadata.Episodes} \n" +
                       $"Actors:   {TvShow.Actors.Names}"));
        }
Exemplo n.º 11
0
 public async Task HandleSelectionAsync(TvShowRequest request, TvShow tvShow, NormalTvSeason selectedSeason)
 {
     if (selectedSeason.IsRequested == RequestedState.Full)
     {
         await RequestNotificationsForSeasonAsync(request, tvShow, selectedSeason);
     }
     else
     {
         await _userInterface.DisplayTvShowDetailsForSeasonAsync(request, tvShow, selectedSeason);
     }
 }
Exemplo n.º 12
0
 public async Task HandleSelectionAsync(TvShowRequest request, TvShow tvShow, FutureTvSeasons selectedSeason)
 {
     if (tvShow.IsRequested)
     {
         await _tvShowNotificationWorkflow.NotifyForExistingRequestAsync(request.User.UserId, tvShow, selectedSeason);
     }
     else
     {
         await _userInterface.DisplayTvShowDetailsForSeasonAsync(request, tvShow, selectedSeason);
     }
 }
 public ActionResult Edit([Bind(Include = "ShowID,NetworkID,ShowName,Seasons,StartYear,ImdbRating,TvShow_Image_Link")] TvShow tvShow)
 {
     if (ModelState.IsValid)
     {
         db.Entry(tvShow).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.NetworkID = new SelectList(db.Networks, "NetworkID", "NetName", tvShow.NetworkID);
     return(View(tvShow));
 }
Exemplo n.º 14
0
        public static DiscordEmbed GenerateTvShowDetailsAsync(TvShow tvShow)
        {
            var title = tvShow.Title;

            if (!string.IsNullOrWhiteSpace(tvShow.FirstAired))
            {
                if (tvShow.FirstAired.Length >= 4 && !title.Contains(tvShow.FirstAired.Split("T")[0].Substring(0, 4), StringComparison.InvariantCultureIgnoreCase))
                {
                    title = $"{title} ({tvShow.FirstAired.Split("T")[0].Substring(0, 4)})";
                }
            }

            var embedBuilder = new DiscordEmbedBuilder()
                               .WithTitle(title)
                               .WithTimestamp(DateTime.Now)
                               .WithThumbnail("https://thetvdb.com/images/logo.png")
                               .WithFooter("Powered by Requestrr");

            if (!string.IsNullOrWhiteSpace(tvShow.Overview))
            {
                embedBuilder.WithDescription(tvShow.Overview.Substring(0, Math.Min(tvShow.Overview.Length, 255)) + "(...)");
            }

            if (!string.IsNullOrEmpty(tvShow.Banner) && tvShow.Banner.StartsWith("http", StringComparison.InvariantCultureIgnoreCase))
            {
                embedBuilder.WithImageUrl(tvShow.Banner);
            }
            if (!string.IsNullOrWhiteSpace(tvShow.WebsiteUrl))
            {
                embedBuilder.WithUrl(tvShow.WebsiteUrl);
            }
            if (!string.IsNullOrWhiteSpace(tvShow.Network))
            {
                embedBuilder.AddField($"__{Language.Current.DiscordEmbedTvNetwork}__", tvShow.Network, true);
            }
            if (!string.IsNullOrWhiteSpace(tvShow.Status))
            {
                embedBuilder.AddField($"__{Language.Current.DiscordEmbedTvStatus}__", tvShow.Status, true);
            }
            if (!string.IsNullOrWhiteSpace(tvShow.Quality))
            {
                embedBuilder.AddField($"__{Language.Current.DiscordEmbedTvQuality}__", $"{tvShow.Quality}p", true);
            }
            if (!string.IsNullOrWhiteSpace(tvShow.PlexUrl))
            {
                embedBuilder.AddField($"__Plex__", $"[{Language.Current.DiscordEmbedTvWatchNow}]({tvShow.PlexUrl})", true);
            }
            if (!string.IsNullOrWhiteSpace(tvShow.EmbyUrl))
            {
                embedBuilder.AddField($"__Emby__", $"[{Language.Current.DiscordEmbedTvWatchNow}]({tvShow.EmbyUrl})", true);
            }

            return(embedBuilder.Build());
        }
Exemplo n.º 15
0
        public async Task <TvShow> CreateEntry(TvShow model)
        {
            try
            {
                var order = new TvShow();

                if (model.Id == 0)
                {
                    order = new TvShow
                    {
                        Title    = model.Title,
                        Rating   = model.Rating,
                        ImageUrl = model.ImageUrl,
                        ImdbUrl  = model.ImdbUrl,
                        Genre    = model.Genre,
                        Id       = model.Id
                    };
                    await _repo.TvShow.AddAsync(order);

                    await _repo.SaveAsync();
                }
                else if (model.Id > 0)
                {
                    order = new TvShow
                    {
                        Title    = model.Title,
                        Rating   = model.Rating,
                        ImageUrl = model.ImageUrl,
                        ImdbUrl  = model.ImdbUrl,
                        Genre    = model.Genre,
                        Id       = model.Id
                    };
                    await _repo.TvShow.UpdateAsync(order);

                    await _repo.SaveAsync();
                }
                return(new TvShow
                {
                    Title = order.Title,
                    Rating = order.Rating,
                    ImageUrl = order.ImageUrl,
                    ImdbUrl = order.ImdbUrl,
                    Genre = order.Genre,
                    Id = order.Id
                });
            }

            catch (Exception ex)
            {
                return(new TvShow
                {
                });
            }
        }
Exemplo n.º 16
0
        public async Task <EpisodeDto> GetNextEpisode(TvShow tvShow)
        {
            var episode = await this.context.Episodes
                          .Include(e => e.Season)
                          .Include(e => e.Season.TvShow)
                          .Where(e => e.Season.TvShow.TmdbId == tvShow.TmdbId)
                          .OrderBy(e => e.AirDate)
                          .FirstOrDefaultAsync(e => DateTime.Today <= e.AirDate);

            return(episode?.ToDto());
        }
Exemplo n.º 17
0
        private void TvShowArchiveChanged(TvShow show)
        {
            if (show == null)
            {
                return;
            }

            showDetails.TvShow    = show;
            shows.TvShows         = TvShowService.GetActiveTvShows().ToObservableCollection();
            archivedShows.TvShows = TvShowService.GetArchivedTvShows().ToObservableCollection();
        }
Exemplo n.º 18
0
        public async Task <TvShow> getShow(TvShow show)
        {
            Response resp = await getResponse("http://followshows.com/show/" + show.showUrl, null, false);

            HtmlDocument doc = new HtmlDocument();

            if (resp.page == null)
            {
                return(show);
            }

            doc.LoadHtml(resp.page);

            HtmlNode summaryid = doc.GetElementbyId("summary");

            string extendedPart = getChild(summaryid.DescendantNodes(), "class", "details").InnerText;

            show.SummaryExtended = getChild(summaryid.DescendantNodes(), "class", "summary-text").InnerText.Replace("...&nbsp;(more)", "");

            show.Summary = show.SummaryExtended.Replace(extendedPart, "") + "...";



            HtmlNode showSummary = doc.GetElementbyId("content-about");

            show.Genre = getChild(showSummary.ChildNodes, "class", "genres").InnerText.Replace("GENRES:", "");
            show.Airs  = getChild(showSummary.DescendantNodes(), "class", "infos col-xs-12 col-sm-6").InnerText.Replace("AIRS:", "");

            HtmlNode forFollowandName = getChild(showSummary.ChildNodes, "class", "summary");

            show.Followers = getChild(forFollowandName.ChildNodes, "class", "followers").InnerText.Replace(" followers)", "").Replace("( ", "");
            show.Name      = getChild(forFollowandName, 0).InnerText;

            HtmlNode season = doc.GetElementbyId("season-filter");

            if (season != null)
            {
                show.numberOfSeasons = season.ChildNodes.ToArray <HtmlNode>().Length;
            }

            HtmlNode actors = doc.GetElementbyId("actors");

            if (actors != null)
            {
                show.Actors = actors.InnerText;
            }
            else
            {
                show.Actors = "None";
            }


            return(show);
        }
Exemplo n.º 19
0
        public void TestTvShowGetTvShowWithImageLanguage()
        {
            IgnoreMissingJson(" / account_states", " / alternative_titles", " / changes", " / credits", " / content_ratings", " / genre_ids", " / keywords", " / lists", " / release_dates", " / releases", " / reviews", " / similar", " / translations", " / videos", " / recommendations", " / external_ids");

            TvShow resp = Config.Client.GetTvShowAsync(IdHelper.BreakingBad, language: "en-US", includeImageLanguage: "en", extraMethods: TvShowMethods.Images).Result;

            Assert.True(resp.Images.Backdrops.Count > 0);
            Assert.True(resp.Images.Backdrops.All(b => b.Iso_639_1.Equals("en", StringComparison.OrdinalIgnoreCase)));
            Assert.True(resp.Images.Posters.Count > 0);
            Assert.True(resp.Images.Posters.All(p => p.Iso_639_1.Equals("en", StringComparison.OrdinalIgnoreCase)));
        }
Exemplo n.º 20
0
        public async Task <IActionResult> Create([Bind("Id,Title,Genre,Rating,ImdbUrl,ImageUrl")] TvShow tvShow)
        {
            if (ModelState.IsValid)
            {
                _context.Add(tvShow);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(tvShow));
        }
Exemplo n.º 21
0
 private async Task RequestNotificationsForSeasonAsync(TvShow tvShow, TvSeason selectedSeason)
 {
     if (selectedSeason.IsAvailable)
     {
         await _userInterface.WarnSeasonAlreadyAvailableAsync(selectedSeason);
     }
     else
     {
         await _tvShowNotificationWorkflow.NotifyForExistingRequestAsync(_user.UserId, tvShow, selectedSeason);
     }
 }
Exemplo n.º 22
0
 public async Task HandleSelectionAsync(TvShowRequest request, TvShow tvShow, AllTvSeasons selectedSeason)
 {
     if (tvShow.AllSeasonsFullyRequested())
     {
         await _userInterface.WarnAlreadySeasonAlreadyRequestedAsync(tvShow, new FutureTvSeasons());
     }
     else
     {
         await _userInterface.DisplayTvShowDetailsForSeasonAsync(request, tvShow, selectedSeason);
     }
 }
Exemplo n.º 23
0
        public async Task TestTvShowExtrasNoneAsync()
        {
            TvShow tvShow = await TMDbClient.GetTvShowAsync(IdHelper.BreakingBad);

            await Verify(tvShow);

            // Test all extras, ensure none of them are populated
            foreach (Func <TvShow, object> selector in Methods.Values)
            {
                Assert.Null(selector(tvShow));
            }
        }
Exemplo n.º 24
0
 public void InsertOrUpdate(TvShow entity)
 {
     if (this.context.TvShows.Any(e => e.TmdbId == entity.TmdbId))
     {
         this.context.TvShows.Attach(entity);
         this.context.Entry(entity).State = EntityState.Modified;
     }
     else
     {
         this.context.TvShows.Add(entity);
     }
 }
        /// <summary>
        /// Starts playing in shuffle mode.
        /// </summary>
        private void Shuffle()
        {
            TvShow retrievedTvShow = (TvShow)SelectedMediaElement;

            TvShowEpisode[] randomOrderedEpisodes = retrievedTvShow.AllEpisodes.OrderBy(q => Guid.NewGuid()).ToArray();

            NavigationService.Navigate(typeof(PlaybackConfirmationView), new PlaybackViewParameterModel
            {
                SelectedMediaElement = randomOrderedEpisodes[0],
                Playlist             = randomOrderedEpisodes.Skip(1).ToArray()
            });
        }
Exemplo n.º 26
0
        /// <summary>
        ///     Returns a new TVShow from a search result.
        /// </summary>
        /// <param name="searchResult">
        ///     The search result.
        /// </param>
        /// <returns>
        ///     The new TVShow.
        /// </returns>
        public TvShow FromSearchResult(TvShow searchResult)
        {
            var show = new TvShow
            {
                Name       = searchResult.Name,
                FolderName = searchResult.FolderName,
                TvdbId     = searchResult.TvdbId
            };

            show.InitialiseDefaultData();
            return(show);
        }
Exemplo n.º 27
0
        private IEnumerable <PersonInfo> GetPersons(TvShow seriesResult)
        {
            if (seriesResult.Credits?.Cast != null)
            {
                foreach (var actor in seriesResult.Credits.Cast.OrderBy(a => a.Order).Take(Plugin.Instance.Configuration.MaxCastMembers))
                {
                    var personInfo = new PersonInfo
                    {
                        Name      = actor.Name.Trim(),
                        Role      = actor.Character,
                        Type      = PersonType.Actor,
                        SortOrder = actor.Order,
                        ImageUrl  = _tmdbClientManager.GetPosterUrl(actor.ProfilePath)
                    };

                    if (actor.Id > 0)
                    {
                        personInfo.SetProviderId(MetadataProvider.Tmdb, actor.Id.ToString(CultureInfo.InvariantCulture));
                    }

                    yield return(personInfo);
                }
            }

            if (seriesResult.Credits?.Crew != null)
            {
                var keepTypes = new[]
                {
                    PersonType.Director,
                    PersonType.Writer,
                    PersonType.Producer
                };

                foreach (var person in seriesResult.Credits.Crew)
                {
                    // Normalize this
                    var type = TmdbUtils.MapCrewToPersonType(person);

                    if (!keepTypes.Contains(type, StringComparison.OrdinalIgnoreCase) &&
                        !keepTypes.Contains(person.Job ?? string.Empty, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    yield return(new PersonInfo
                    {
                        Name = person.Name.Trim(),
                        Role = person.Job,
                        Type = type
                    });
                }
            }
        }
Exemplo n.º 28
0
        private static async Task NotifyUsersInChannel(TvShow tvShow, int seasonNumber, HashSet <ulong> discordUserIds, HashSet <string> userNotified, SocketTextChannel channel)
        {
            var usersToMention = channel.Users.Where(x => discordUserIds.Contains(x.Id));
            await channel.SendMessageAsync($"The first episode of **season {seasonNumber}** of **{tvShow.Title}** has finished downloading!", false, DiscordTvShowsRequestingWorkFlow.GenerateTvShowDetailsAsync(tvShow));

            await SendUserMentionMessageAsync(channel, usersToMention);

            foreach (var user in usersToMention)
            {
                userNotified.Add(user.Id.ToString());
            }
        }
Exemplo n.º 29
0
        public async Task InsertOrUpdateItemAsync(TvShow tvShow, CancellationToken cancellationToken)
        {
            if (tvShow == null)
            {
                throw new ArgumentException(nameof(tvShow));
            }

            await TvShowsCollection.ReplaceOneAsync(t => t.Id == tvShow.Id, tvShow, new UpdateOptions
            {
                IsUpsert = true
            }, cancellationToken);
        }
Exemplo n.º 30
0
        public void TestTvShowExtrasNone()
        {
            TvShow tvShow = _config.Client.GetTvShow(BreakingBad).Result;

            TestBreakingBadBaseProperties(tvShow);

            // Test all extras, ensure none of them are populated
            foreach (Func <TvShow, object> selector in _methods.Values)
            {
                Assert.IsNull(selector(tvShow));
            }
        }
Exemplo n.º 31
0
        /// <summary>The mod entry point, called after the mod is first loaded.</summary>
        /// <param name="helper">Provides simplified APIs for writing mods.</param>
        public override void Entry(IModHelper helper)
        {
            ModHelper  = helper;
            ModMonitor = Monitor;

            helper.Events.Player.Warped       += Player_Warped;
            helper.Events.GameLoop.SaveLoaded += GameLoop_SaveLoaded;

            TvShow.LoadShows();

            MusicManager = new MusicManager();
        }
Exemplo n.º 32
0
 /// <summary>
 /// Updates the specified show.
 /// </summary>
 /// <param name="show">
 /// The show to update. 
 /// </param>
 public void UpdateShow(TvShow show)
 {
     DateTime serverTime = TvdbDownload.GetServerTime();
     string xmlFile = TvdbDownload.DownloadShowEpisodes(show);
     try
     {
         this.tvdbProcess.ProcessShow(show, xmlFile, serverTime);
     }
     catch (Exception e)
     {
         Logger.OnLogMessage(this, "Error parsing XML for {0}. {1}", LogType.Error, show.Name, e.Message);
     }
 }
Exemplo n.º 33
0
        private void searchItem_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Grid   grid = sender as Grid;
            TvShow show = grid.DataContext as TvShow;

            api.passed = show;
            Frame rootFrame = Window.Current.Content as Frame;

            if (!rootFrame.Navigate(typeof(ShowPage), api))
            {
                throw new Exception("Failed to create initial page");
            }
        }
Exemplo n.º 34
0
        public OperationResult<TvShow> AddShow(TvShow show)
        {
            var tvShow = _tvShowRepository.FindBy(t => t.ShowName == show.ShowName);
            if(tvShow.Any())
            {
                return new OperationResult<TvShow>(false);
            }

            show.Key = Guid.NewGuid();
            _tvShowRepository.Add(show);
            _tvShowRepository.Save();

            return new OperationResult<TvShow>(true) { Entity = show };
        }
Exemplo n.º 35
0
 public TvEpisodesInfo FindEpisodes(TvShow show)
 {
     if(show == null) throw new InvalidDataException("Show cannot be null");
     const string additional = @"[""summary"",""collection"",""poster_mtime"",""watched_ratio""]";
     var tvEpisodesResult = CallMethod<TvEpisodesResult>("SYNO.VideoStation.TVShowEpisode", "list", new ReqParams
     {
         {"additional", additional},
         {"tvshow_id", show.Id.ToString()},
         {"library_id", 0.ToString()}
     });
     if (!tvEpisodesResult.Success)
         throw new TvEpisodeRequestException(@"Synology error code " + tvEpisodesResult.Error);
     return tvEpisodesResult.Data;
 }
Exemplo n.º 36
0
        public async Task<List<TvShow>> searchTvShow(string searchTerm)
        {
            List<TvShow> res = new List<TvShow>();
            List<TvShow> res2 = new List<TvShow>();

            if (searchTerm == null || searchTerm == "")
            {
                passed = res2;
                return res;
            }

            Response resp = await getResponse("http://followshows.com/ajax/header/search?term=" + searchTerm, null, false);
            if (resp.page == null)
                return res;
            List<SearchResult> response = JsonConvert.DeserializeObject<List<SearchResult>>(resp.page);
            foreach (SearchResult result in response)
            {
                if (result.type == "show")
                {
                    TvShow show = new TvShow(result.followed);
                    if (result.poster)
                    {
                        show.Image = new BitmapImage(new Uri(result.image.Replace("30x42", "357x500")));
                    }
                    show.Name = result.value;
                    show.showUrl = result.id;
                    res.Add(show);
                }
                else
                {
                    TvShow show = new TvShow(false);
                    if (result.poster)
                    {
                        show.Image = new BitmapImage(new Uri(result.image.Replace("30x42", "357x500")));
                    }
                    show.Name = result.value;
                    show.showUrl = result.id;
                    res2.Add(show);
                }
            }
            passed = res2;
            return res;
        }
Exemplo n.º 37
0
        /// <summary>
        /// Downloads the banner for the specified show.
        /// </summary>
        /// <param name="tvShow">
        /// The show to download the banner for. 
        /// </param>
        public static void DownloadBanner(TvShow tvShow)
        {
            var webClient = new WebClient();
            string bannerAddress = Mirror + "/banners/" + tvShow.Banner;
            string saveAddress = Tvdb.ImageDirectory + tvShow.TvdbId + ".jpg";

            if (!Directory.Exists(Tvdb.ImageDirectory))
            {
                Directory.CreateDirectory(Tvdb.ImageDirectory);
            }

            if (File.Exists(saveAddress))
            {
                File.Delete(saveAddress);
            }

            webClient.DownloadFile(new Uri(bannerAddress), saveAddress);
        }
Exemplo n.º 38
0
 /// <summary>
 /// Gets a new TVShow from the specified element.
 /// </summary>
 /// <param name="element">
 /// The element to load.
 /// </param>
 /// <returns>
 /// The new TV Show.
 /// </returns>
 private static TvShow NewTvShow(XElement element)
 {
     var show = new TvShow();
     show.FromXml(element);
     return show;
 }
Exemplo n.º 39
0
        public void SearchShowTest()
        {
            var gamma = new TvShow { Name = "Gamma", TvdbId = "3", FolderName = "Gamma Folder" };
            var delta = new TvShow { Name = "Delta", TvdbId = "4", FolderName = "Delta Folder" };
            var delta2 = new TvShow { Name = "Delta2", TvdbId = "5", FolderName = "Delta2 Folder" };

            this.dataProvider.SearchShow("Gamma Folder").Returns(new List<TvShow> { gamma });
            this.dataProvider.SearchShow("Delta Folder").Returns(new List<TvShow> { delta, delta2 });

            // Create the directories that will be searched.
            this.CreateTestDirectory(this.Root, "Alpha Folder", "Beta Folder", "Gamma Folder", "Delta Folder");

            Dictionary<string, List<TvShow>> results = ScanManager.SearchNewShows(
                this.StorageProvider, this.dataProvider, new[] { this.Root });

            // Assert that dataProvider.SearchShow was not called for Alpha and Beta since they already exist in storage.
            this.dataProvider.DidNotReceive().SearchShow("Alpha Folder");
            this.dataProvider.DidNotReceive().SearchShow("Beta Folder");

            // Assert that other shows where only searched once.
            this.dataProvider.Received(1).SearchShow("Gamma Folder");
            this.dataProvider.Received(1).SearchShow("Delta Folder");

            // Ensure that there were only 2 calls in total.
            this.dataProvider.ReceivedWithAnyArgs(2).SearchShow(Arg.Any<string>());

            // Ensure that the Gamma show was saved as there was only one result.
            this.StorageProvider.Received(1).SaveShow(gamma);

            // Should only have the Delta show in the results.
            Assert.AreEqual(1, results.Count);
            Assert.AreEqual(2, results["Delta Folder"].Count);

            // Check that the results are the shows that the data provider returned.
            Assert.AreEqual(delta, results["Delta Folder"][0]);
            Assert.AreEqual(delta2, results["Delta Folder"][1]);
        }
Exemplo n.º 40
0
        /// <summary>
        /// Processes a TVShow result
        /// </summary>
        /// <param name="showName">
        /// The name of the show.
        /// </param>
        /// <param name="result">
        /// The matched result.
        /// </param>
        /// <returns>
        /// The matched TV Show.
        /// </returns>
        private TvShow ProcessResult(string showName, TvShow result)
        {
            // See if we already have the show under the same TVDB.
            TvShow show = this.tvShows.FirstOrDefault(x => x.Equals(result));
            if (show != null)
            {
                Logger.OnLogMessage(this, "{0} matched as {1}. Adding alternate name.", LogType.Info, showName, show.Name);
                show.AlternateNames.Add(showName);
                show.Save(this.storageProvider);
                return show;
            }

            Logger.OnLogMessage(this, "Matched {0} as a new show. Adding and updating...", LogType.Info, showName);

            // Doesn't exist with the same TVDB. Add a new show and update.
            show = TvShow.FromSearchResult(result);
            show.Save(this.storageProvider);
            show.Update(this.dataProvider, this.storageProvider);
            this.tvShows.Add(show);
            return show;
        }
Exemplo n.º 41
0
 public async void markSeasonAsWatched(string seasonnr, TvShow show)
 {
     if (seasonnr == null || show.showUrl == null) return;
     Response resp = await getResponse("http://followshows.com/api/markSeasonAsWatched?show=" + show.showUrl + "&season=" + seasonnr, null);
     if (resp.hasInternet)
     {
         lastPage = resp.page;
     }
     if (resp.page == null || resp.page.Contains("DMCA Policy"))
     {
         Helper.message("Uhm... Something went wrong.", "Sorry");
     }
 }
Exemplo n.º 42
0
 /// <summary>
 /// Handles the Select button being clicked.
 /// </summary>
 /// <param name="sender">
 /// The sender of the event. 
 /// </param>
 /// <param name="e">
 /// The arguments of the event. 
 /// </param>
 private void SelectButtonClick(object sender, EventArgs e)
 {
     this.SelectedShow = (TvShow)this.showList.SelectedItem;
     this.DialogResult = DialogResult.OK;
     this.Close();
 }
Exemplo n.º 43
0
        public TvShow UpdateTvShow(TvShow show)
        {
            _tvShowRepository.Edit(show);
            _tvShowRepository.Save();

            return show;
        }
Exemplo n.º 44
0
 /// <summary>
 /// Sets the show of the checked results.
 /// </summary>
 /// <param name="show">
 /// The show to set them to.
 /// </param>
 public void SetShow(TvShow show)
 {
     var scanManager = new ScanManager(Factory.StorageProvider, Factory.DataProvider);
     foreach (FileResult result in this.Results.Where(x => x.Checked))
     {
         scanManager.ResetShow(result, show);
     }
 }
 /// <summary>
 /// Sets the show of the specified indices.
 /// </summary>
 /// <param name="show">
 /// The show to set them to. 
 /// </param>
 public void SetShow(TvShow show)
 {
     this.fileSearch.SetShow(show);
 }
Exemplo n.º 46
0
        /// <summary>
        /// Gets the necessary info from the file name and return the episode object
        /// </summary>
        /// <param name="match">
        /// The regexp match 
        /// </param>
        /// <param name="show">
        /// The show. 
        /// </param>
        /// <returns>
        /// The episode objects that have been matched.
        /// </returns>
        private IEnumerable<Episode> ProcessEpisode(Match match, TvShow show)
        {
            Group season = match.Groups["S"];
            Group episode = match.Groups["E"];
            Group year = match.Groups["Y"];
            Group month = match.Groups["M"];
            Group day = match.Groups["D"];

            if (show == null)
            {
                yield break;
            }

            // Determine if the match was a season/episode or a date.
            if (season.Success && episode.Success)
            {
                int seasonNum = int.Parse(season.ToString());

                // There is the possibility of multiple episodes being matches
                foreach (Capture episodeGroup in match.Groups["E"].Captures)
                {
                    int episodeNum = int.Parse(episodeGroup.ToString());
                    yield return
                        show.Episodes.FirstOrDefault(x => x.EpisodeNumber == episodeNum && x.SeasonNumber == seasonNum);
                }
            }
            else if (year.Success && month.Success && day.Success)
            {
                DateTime date = DateTime.Parse(string.Concat(year, "-", month, "-", day));
                yield return show.Episodes.FirstOrDefault(x => x.FirstAir.Equals(date));
            }
            else
            {
                throw new Exception("Invalid regular expression.");
            }
        }
Exemplo n.º 47
0
 public static void CreateMusicBtn(TvShow show)
 {
     GameObject newMusicBtnPrefab = Instantiate(Instance.musicBtnPrefab);
     newMusicBtnPrefab.transform.SetParent(Instance.musicScreen.transform);
     newMusicBtnPrefab.GetComponentInChildren<Text>().text = show.audioClip.name;
     newMusicBtnPrefab.GetComponent<MusicBtn>().music = show.audioClip;
 }
Exemplo n.º 48
0
        //parse page(s) containing relations
        /// <summary>
        /// Parses page containing the relation data
        /// </summary>
        /// <param name="url">URL of the page to parse</param>
        /// <param name="Showname">Showname</param>
        public static void GetRelations(string url, string Showname, TvShowInfoProvider provider, BackgroundWorker worker, DoWorkEventArgs dwea)
        {
            if (provider == null) {
                log.Error("GetRelations: No relation provider found/selected");
                return;
            }
            if (String.IsNullOrEmpty(url)) {
                log.Error("GetRelations: URL is null or empty");
                return;
            }
            if (String.IsNullOrEmpty(Showname)) {
                log.Error("GetRelations: Showname is null or empty");
                return;
            }
            log.Debug("Trying to get relations from " + url);
            //if episode infos are stored on a new page for each season, this should be marked with %S in url, so we can iterate through all those pages
            int season = 1;
            string url2 = url;
            //Create new RelationCollection
            TvShow rc = new TvShow(Showname);
            while (true) {
                if (url2.Contains("%S")) {
                    url = url2.Replace("%S", season.ToString());
                }

                if (url == null || url == "")
                    return;
                // request
                url = System.Web.HttpUtility.UrlPathEncode(url);
                log.Debug("Trying to get relations for season " + season + " from " + url);
                HttpWebRequest requestHtml = null;
                try {
                    requestHtml = (HttpWebRequest)(HttpWebRequest.Create(url));
                } catch (Exception ex) {
                    log.Error(ex.Message);
                    requestHtml.Abort();
                    return;
                }
                requestHtml.Timeout = Helper.ReadInt(AppProperties.CONNECTION_TIMEOUT_KEY);
                // get response
                HttpWebResponse responseHtml = null;
                try {
                    responseHtml = (HttpWebResponse)(requestHtml.GetResponse());
                } catch (WebException ex) {
                    //Serienjunkies returns "(300) Mehrdeutige Umleitung" when an inexistant season is requested
                    if (ex.Message.Contains("(300)"))
                        break;
                    log.Error(ex.Message);
                    if (responseHtml != null) {
                        responseHtml.Close();
                    }
                    return;
                }
                log.Debug("Response URL: " + responseHtml.ResponseUri.AbsoluteUri);
                //if we get redirected, lets assume this page does not exist
                if (responseHtml.ResponseUri.AbsoluteUri != url) {
                    log.Debug("Response URL doesn't match request URL, page doesn't seem to exist");
                    responseHtml.Close();
                    requestHtml.Abort();
                    break;
                }
                // and download
                //Logger.Instance.LogMessage("charset=" + responseHtml.CharacterSet, LogLevel.INFO);
                Encoding enc;
                if (provider.Encoding != null && provider.Encoding != "") {
                    try {
                        enc = Encoding.GetEncoding(provider.Encoding);
                    } catch (Exception ex) {
                        log.Error("Invalid encoding in config file: " + ex.Message);
                        enc = Encoding.GetEncoding(responseHtml.CharacterSet);
                    }
                } else {
                    enc = Encoding.GetEncoding(responseHtml.CharacterSet);
                }
                StreamReader r = new StreamReader(responseHtml.GetResponseStream(), enc);
                string source = r.ReadToEnd();
                r.Close();
                responseHtml.Close();

                //Source cropping
                source = source.Substring(Math.Max(source.IndexOf(provider.RelationsStart), 0));
                source = source.Substring(0, Math.Max(source.LastIndexOf(provider.RelationsEnd), 0));

                string pattern = provider.RelationsRegExp;

                //for some reason, responseHtml.ResponseUri is null for some providers when running on mono
                if (!Settings.Instance.isMonoCompatibilityMode) {
                    log.Debug("Trying to match source from " + responseHtml.ResponseUri.AbsoluteUri + " with " + pattern);
                }
                RegexOptions ro = RegexOptions.IgnoreCase | RegexOptions.Singleline;
                if (provider.RelationsRightToLeft)
                    ro |= RegexOptions.RightToLeft;
                MatchCollection mc = Regex.Matches(source, pattern, ro);

                string CleanupRegex = provider.RelationsRemove;
                for (int i = 0; i < mc.Count; i++) {
                    Match m = mc[i];
                    string result = Regex.Replace(System.Web.HttpUtility.HtmlDecode(m.Groups["Title"].Value), CleanupRegex, "");
                    //RELATIONS_REMOVE_KEY may be used to filter out results completely, for example if they are a html tag
                    if (result != "") {
                        //parse season and episode numbers
                        int s, e;

                        Int32.TryParse(m.Groups["Season"].Value, out s);
                        Int32.TryParse(m.Groups["Episode"].Value, out e);
                        //if we are iterating through season pages, take season from page url directly
                        if (url != url2) {
                            rc.AddEpisode(new ShowEpisode(season, e, result));
                            log.Debug("Found Relation: " + "S" + s.ToString() + "E" + e.ToString() + " - " + result);
                        } else {
                            rc.AddEpisode(new ShowEpisode(s, e, result));
                            log.Debug("Found Relation: " + "S" + s.ToString() + "E" + e.ToString() + " - " + result);
                        }
                    }
                }
                TvShowManager.Instance.addTvShow(rc);

                // THOU SHALL NOT FORGET THE BREAK
                if (!url2.Contains("%S"))
                    break;
                season++;
            }
            log.Debug("" + (season - 1) + " Seasons, " + rc.CountEpisodes + " relations found");
        }
Exemplo n.º 49
0
        /// <summary>
        /// Downloads the data for the specified show and returns the path to the file.
        /// </summary>
        /// <param name="show">
        /// The show to download data for. 
        /// </param>
        /// <returns>
        /// The path to the downloaded file. 
        /// </returns>
        public static string DownloadShowEpisodes(TvShow show)
        {
            for (int i = 0; i < RetryCount; i++)
            {
                try
                {
                    var webClient = new WebClient();
                    string showAddress = Mirror + ApiLoc + "/series/" + show.TvdbId + "/all/en.zip";
                    string savePath = Tvdb.CacheDirectory + show.TvdbId + ".xml";

                    if (!Directory.Exists(Tvdb.CacheDirectory))
                    {
                        Directory.CreateDirectory(Tvdb.CacheDirectory);
                    }

                    if (File.Exists(savePath))
                    {
                        File.Delete(savePath);
                    }

                    webClient.DownloadFile(showAddress, savePath + ".zip");

                    // Download the zip file to a zip stream
                    using (var stream = new ZipInputStream(savePath + ".zip"))
                    {
                        ZipEntry e;
                        var buffer = new byte[2048];

                        // Loop through all the entries looking for en.xml.
                        while ((e = stream.GetNextEntry()) != null)
                        {
                            if (!e.FileName.Equals("en.xml"))
                            {
                                while (stream.Read(buffer, 0, buffer.Length) > 0)
                                {
                                }
                            }

                            // Write the file to savePath.
                            using (var output = File.Open(savePath, FileMode.Create, FileAccess.ReadWrite))
                            {
                                int n;
                                while ((n = stream.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    output.Write(buffer, 0, n);
                                }
                            }

                            break;
                        }
                    }

                    return savePath;
                }
                catch (WebException)
                {
                    // Suppress any exceptions so the download can be retried.
                }
            }

            throw new Exception("Unable to download show data for " + show.Name);
        }
Exemplo n.º 50
0
        public async Task<List<Episode>> getSeason(TvShow show, int seasonNr)
        {
            List<Episode> season = new List<Episode>();

            Response resp = await getResponse("http://followshows.com/api/show/" + show.showUrl + "/season/" + seasonNr, null, false);
            HtmlDocument doc = new HtmlDocument();
            if (resp.page == null)
                return season;
            doc.LoadHtml(resp.page);



            foreach (HtmlNode episode in getChild(doc.DocumentNode.ChildNodes, "class", "clearfix").ChildNodes)
            {
                Episode ep = new Episode(false, false);
                ep.ShowName = show.Name;

                HtmlNode name = getChild(episode.DescendantNodes(), "class", "episode-link");
                if (name != null)
                {
                    ep.Aired = true;
                    ep.EpisodeName = name.InnerText;
                    ep.Image = new BitmapImage(new Uri(getAttribute(getChild(episode.DescendantNodes(), "class", "poster").DescendantNodes(), "src").Replace("130x75", "360x207")));

                    string[] build = getChild(episode.DescendantNodes(), "class", "episode-label").InnerText.Split(new char[] { ' ' });
                    ep.ISeason = int.Parse(build[1]);
                    ep.IEpisode = int.Parse(build[3].Split(new char[] { ',' })[0]);
                    ep.EpisodePos = "S" + ep.ISeason + "E" + ep.IEpisode;
                    ep.id = getAttribute(episode.ChildNodes, "episodeid");
                    if (!episode.InnerText.Contains("Mark as watched"))
                    {
                        ep.Seen = true;
                    }

                }
                else
                {
                    ep.Aired = false;
                    ep.Image = new BitmapImage(new Uri("ms-appx:Assets/basicQueueItem.png"));
                    string[] build = episode.InnerText.Split(new char[] { ',' });
                    ep.EpisodeName = build[0];
                    string[] seasonThing = build[1].Split(new char[] { ' ' });
                    ep.ISeason = int.Parse(seasonThing[1]);
                    ep.IEpisode = int.Parse(seasonThing[3]);
                    ep.EpisodePos = "S" + ep.ISeason + "E" + ep.IEpisode;
                }


                season.Add(ep);
            }

            //season.Reverse();
            return season;
        }
Exemplo n.º 51
0
 /// <summary>
 /// Raises a banner download required event.
 /// </summary>
 /// <param name="show">
 /// The show that requires a banner. 
 /// </param>
 /// <param name="newBanner">
 /// The new banner to download. 
 /// </param>
 private void OnBannerDownloadRequired(TvShow show, string newBanner)
 {
     if (this.BannerDownloadRequired != null)
     {
         this.BannerDownloadRequired(this, new BannerDownloadRequiredEventArgs(show, newBanner));
     }
 }
Exemplo n.º 52
0
        /// <summary>
        /// Processes a cached XML file to extract all the episodes and save them.
        /// </summary>
        /// <param name="show">
        /// The show to process. 
        /// </param>
        /// <param name="filePath">
        /// The path to its XML file. 
        /// </param>
        /// <param name="serverTime">
        /// The time of the server. 
        /// </param>
        public void ProcessShow(TvShow show, string filePath, DateTime serverTime)
        {
            if (show == null)
            {
                throw new ArgumentNullException("show");
            }

            if (filePath == null)
            {
                throw new ArgumentNullException("filePath");
            }

            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException("No file can be found at the specified file path.");
            }

            XDocument doc = XDocument.Load(filePath);
            XElement data = doc.Root;
            if (data == null)
            {
                throw new Exception("XML is invalid");
            }

            XElement series = data.Element("Series");
            if (series == null)
            {
                throw new Exception("XML is invalid");
            }

            XElement banner = series.Element("banner");

            // Check that the banner exists in the file, and that the file doesn't exist or the banner is different to the downloaded one.
            if (banner != null
                && (!File.Exists(Tvdb.ImageDirectory + show.TvdbId + ".jpg") || banner.Value != show.Banner))
            {
                this.OnBannerDownloadRequired(show, banner.Value);
            }

            string episodeElement = "EpisodeNumber";
            string seasonElement = "SeasonNumber";

            if (show.UseDvdOrder)
            {
                episodeElement = "DVD_episodenumber";
                seasonElement = "DVD_season";
            }

            List<Episode> newEpisodes = (from episode in data.Descendants("Episode")
                                         let episodeNum = this.GetElementValue(episode, episodeElement, "-1")
                                         let seasonNum = this.GetElementValue(episode, seasonElement, "-1")
                                         select
                                             new Episode
                                                 {
                                                     TvdbId = this.GetElementValue(episode, "id", string.Empty),
                                                     EpisodeNumber = this.ParseInt(episodeNum),
                                                     SeasonNumber = this.ParseInt(seasonNum),
                                                     FirstAir =
                                                         DateTime.Parse(
                                                             this.GetElementValue(episode, "FirstAired", "1970-01-01")),
                                                     Name = this.GetElementValue(episode, "EpisodeName", string.Empty),
                                                     Show = show,
                                                 }).ToList();

            // Copy the episodes filecount across
            if (show.Episodes != null)
            {
                foreach (Episode episode in newEpisodes)
                {
                    Episode currentEpisode = show.Episodes.FirstOrDefault(x => x.Equals(episode));
                    if (currentEpisode != null)
                    {
                        episode.FileCount = currentEpisode.FileCount;
                    }
                }
            }

            show.Episodes = newEpisodes;
            show.LastUpdated = serverTime;

            Logger.OnLogMessage(this, "Updated show {0}. Has {1} episodes.", LogType.Info, show.Name, newEpisodes.Count);
        }
Exemplo n.º 53
0
        /// <summary>
        /// Saves the specified show. Updates if it already exists and adds if it doesn't
        /// </summary>
        /// <param name="show">
        /// The show to save. 
        /// </param>
        public void SaveShow(TvShow show)
        {
            XElement showElement =
                this.document.Descendants(GetName("Show")).FirstOrDefault(x => x.GetAttribute("tvdbid") == show.TvdbId);

            if (showElement != null)
            {
                showElement.ReplaceWith(show.ToXml());
                this.OnTvShowChanged(show);
            }
            else
            {
                XElement shows = this.document.Descendants(GetName("Shows")).FirstOrDefault();
                if (shows == null)
                {
                    throw new XmlException("XML is invalid.");
                }

                shows.Add(show.ToXml());
                this.OnTvShowAdded(show);
            }

            this.document.Save(XmlFile);
        }
Exemplo n.º 54
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TvShowEventArgs"/> class. 
 /// </summary>
 /// <param name="tvShow">
 /// The TV Show for the event.
 /// </param>
 public TvShowEventArgs(TvShow tvShow)
 {
     this.TvShow = tvShow;
 }
Exemplo n.º 55
0
        /// <summary>
        /// Resets the show of the specified result.
        /// </summary>
        /// <param name="result">
        /// The result to modify.
        /// </param>
        /// <param name="show">
        /// The show to set the result to.
        /// </param>
        public void ResetShow(FileResult result, TvShow show)
        {
            result.Show = show;
            List<Match> match = this.GetFirstMatch(result.InputFile);
            if (match == null)
            {
                result.Episode = null;
            }

            //Resolve Result
            foreach (Match m in match)
            {
                //result.Episodes = this.ProcessEpisode(match, show).ToList();
                //result.Episode = result.Episodes.FirstOrDefault();
            }
        }
Exemplo n.º 56
0
        public void findEpisodeName(TvShow rc)
        {
            resetName();
            if (rc == null)
                return;

            for (int i = 0; i < rc.CountEpisodes; i++) {
                if (isValidRelation(rc[i])) {
                    EpisodeTitle = rc[i].Title;
                    break;
                }
                if (isInValidSeason(rc[i]) || isInValidEpisode(rc[i]))
                    EpisodeTitle = rc[i].Title;
            }
        }
Exemplo n.º 57
0
        public HttpResponseMessage PostTv(TvShowImportRequestModel requestModel)
        {
            string username = User.Identity.Name;
            var user = _membershipService.GetUser(username);

            Guid tvShowKey = Guid.Empty;
            if (!string.IsNullOrEmpty(requestModel.SeriesName))
            {
                Guid showId = Guid.Empty;
                var tvShow = _tvService.GetTvShow(requestModel.SeriesName);
                if (tvShow == null)
                {
                    TvShow show = new TvShow { ShowName = requestModel.SeriesName };
                    var showResult = _tvService.AddShow(show);
                    showId = showResult.Entity.Key;
                }
                else
                {
                    showId = tvShow.Key;
                }
                tvShowKey = showId;
            }

            TvEpisode dbEp = _tvService.GetTvEpisode(requestModel.FileHash, requestModel.Season, requestModel.Episode);
            if (dbEp == null)
            {
                var tvEpisode = Mapper.Map<TvEpisode>(requestModel);
                tvEpisode.TvShowKey = tvShowKey;
                var createdEp = _tvService.AddTvEpisode(tvEpisode);
                dbEp = createdEp.Entity;
                if (!createdEp.IsSuccess)
                {
                    Log.ErrorFormat("Could not create episode {0} [{1}].  Hashcode was {2}.", string.Format("{0}.S{1}E{2}", requestModel.SeriesName, requestModel.Season, requestModel.Episode), requestModel.FullPath, requestModel.FileHash);
                    return new HttpResponseMessage(HttpStatusCode.Conflict);
                }
            }

            var existingUserEpisode = _tvService.GetUserTvEpisode(dbEp.Key, user.User.Key);

            if (existingUserEpisode == null)
            {
                var userEpisode = Mapper.Map<UserTvEpisode>(requestModel);
                userEpisode.TvEpisodeKey = dbEp.Key;
                userEpisode.OwnerKey = user.User.Key;

                var createdUserEpisode = _tvService.AddUserTvEpisode(userEpisode);
                if (!createdUserEpisode.IsSuccess)
                {
                    Log.ErrorFormat("Could not add episode {0} to user {1}.  Episode ID: {2}",
                                    string.Format("{0}.S{1}E{2}", requestModel.SeriesName, requestModel.Season,
                                                  requestModel.Episode), user.User.Key, userEpisode.TvEpisodeKey);

                    Log.ErrorFormat("Imported File Path: {0}", requestModel.FullPath);
                    Log.ErrorFormat("Imported File Hash: {0}", requestModel.FileHash);

                    var existingUserMovie = dbEp.UserTvEpisodes.FirstOrDefault(x => x.OwnerKey == user.User.Key);
                    if (existingUserMovie != null)
                    {
                        Log.ErrorFormat("Existing File Path: {0}", existingUserMovie.FullPath);
                        Log.ErrorFormat("Existing File Hash: {0}", dbEp.FileHash);
                    }
                    else
                    {
                        Log.Error("No existing episode. BOGUS ERROR!!!!");
                    }

                    return new HttpResponseMessage(HttpStatusCode.Conflict);
                }

                existingUserEpisode = createdUserEpisode.Entity;
            }
            else if(requestModel.UpdateExisting)
            {
                existingUserEpisode.Filename = requestModel.Filename;
                existingUserEpisode.FullPath = requestModel.FullPath;

                _tvService.UpdateUserTvEpisode(existingUserEpisode);
            }

            var response = Request.CreateResponse(HttpStatusCode.Created, Mapper.Map<TvEpisodeDto>(existingUserEpisode));

            return response;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="BannerDownloadRequiredEventArgs"/> class.
 /// </summary>
 /// <param name="show">
 /// The show. 
 /// </param>
 /// <param name="newBanner">
 /// The new banner. 
 /// </param>
 public BannerDownloadRequiredEventArgs(TvShow show, string newBanner)
 {
     this.Show = show;
     this.NewBanner = newBanner;
 }
Exemplo n.º 59
0
 /// <summary>
 /// Fires a TvShowRemoved event.
 /// </summary>
 /// <param name="show">
 /// The show that was removed.
 /// </param>
 private void OnTvShowRemoved(TvShow show)
 {
     if (this.TvShowRemoved != null)
     {
         this.TvShowRemoved(this, new TvShowEventArgs(show));
     }
 }
Exemplo n.º 60
0
        /// <summary>
        /// Removes the specified show from the storage.
        /// </summary>
        /// <param name="show">
        /// The show to remove. 
        /// </param>
        public void RemoveShow(TvShow show)
        {
            XElement showElement = this.document.Descendants(GetName("Show")).Where(
                x =>
                    {
                        XAttribute tvdbId = x.Attribute("tvdbid");
                        return tvdbId != null && tvdbId.Value.Equals(show.TvdbId);
                    }).FirstOrDefault();

            if (showElement != null)
            {
                showElement.Remove();
                this.OnTvShowRemoved(show);
            }

            this.document.Save(XmlFile);
        }