Inheritance: MonoBehaviour
Beispiel #1
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");
        }
Beispiel #2
0
        public void CompareEpisode()
        {
            ArrayList episodes = new ArrayList();
            Episode ep1 = new Episode(6, "bla");
            Episode ep2 = new Episode(4, "blub");
            Episode ep3 = new Episode(5, "bla");
            Episode ep4 = new Episode(1, "blub");

            episodes.Add(ep1);
            episodes.Add(ep2);
            episodes.Add(ep3);
            episodes.Add(ep4);

            episodes.Sort();

            Episode first = (Episode)episodes[0];
            Episode second = (Episode)episodes[1];
            Episode third = (Episode)episodes[2];
            Episode fourth = (Episode)episodes[3];

            Assert.That(first.Number, Is.EqualTo(1));
            Assert.That(second.Number, Is.EqualTo(4));
            Assert.That(third.Number, Is.EqualTo(5));
            Assert.That(fourth.Number, Is.EqualTo(6));
        }
        private static List<Episode> ScanForEpisodes(string html, string siteLinkNameExtension)
        {
            List<Episode> episodes = new List<Episode>();
            html = html.GetSubstringBetween(0, "<div style=\"font-size:14px;\">", "</div>");
                
            List<string> linkList = new List<string>(html.Split('"'));
            for (int i = 0; i < linkList.Count; i++)
            {
                if (!linkList[i].Contains("http")) linkList.RemoveAt(i--);
            }
            for (int i = (linkList.Count - 1); i >= 0; i--)
            {
                Episode e = new Episode();
                string link = linkList[i];

                e.AddLink(DubbedanimehdTvStreamingSite.NAME, link);
                e.Number = episodes.Count + 1;
                e.Name = "Episode " + e.Number.ToString();
                e.Season = 0;

                episodes.Add(e);
                FormMain.SeriesOpenCallback(e);
            }
            
            return episodes;
        }
Beispiel #4
0
        public PlayerForm(Episode episode)
        {
            InitializeComponent();

            this.MouseCoordinateSystem = CoordinateSystem.Relative;
            this.Size = new Size(Settings.ModuleSettings.Instance.PlayerWidth, Settings.ModuleSettings.Instance.PlayerHeight); // set the window size based on last saved values.
            this.SwitchTopMostMode(GlobalSettings.Instance.PlayerWindowsAlwaysOnTop); // set the form's top-most mode.

            this._episode = episode;

            this.gradientPanel.DoubleClick += SwitchMode;
            this.gradientPanel.MouseDown += FormDragStart;
            this.gradientPanel.MouseUp += FormDragEnd;
            this.gradientPanel.MouseMove += FormDrag;

            this.MediaPlayer.DoubleClick += SwitchMode;

            this.labelPosition.DoubleClick += SwitchMode;
            this.labelPosition.MouseDown += FormDragStart;
            this.labelPosition.MouseUp += FormDragEnd;
            this.labelPosition.MouseMove += FormDrag;
            this.labelPosition.DoubleBuffer();

            this.LabelSlider.DoubleClick += SwitchMode;
            this.LabelSlider.MouseDown += FormDragStart;
            this.LabelSlider.MouseUp += FormDragEnd;
            this.LabelSlider.MouseMove += FormDrag;
            this.LabelSlider.DoubleBuffer();

            this.SwitchNormalMode();
        }
        /// <summary>
        /// Searches for the specified show and its episode.
        /// </summary>
        /// <param name="ep">The episode.</param>
        public void Search(Episode ep)
        {
            _td = new TaskDialog
                {
                    Title           = "Searching...",
                    Instruction     = "{0} S{1:00}E{2:00}".FormatWith(ep.Show.Name, ep.Season, ep.Number),
                    Content         = "Searching for the episode...",
                    CommonButtons   = TaskDialogButton.Cancel,
                    ShowProgressBar = true
                };

            _td.SetMarqueeProgressBar(true);
            _td.Destroyed   += TaskDialogDestroyed;
            _td.ButtonClick += TaskDialogDestroyed;

            _active = true;
            new Thread(() =>
                {
                    Thread.Sleep(500);

                    if (_active)
                    {
                        _res = _td.Show().CommonButton;
                    }
                }).Start();

            _os.SearchAsync(ep);

            Utils.Win7Taskbar(state: TaskbarProgressBarState.Indeterminate);
        }
        public async Task DownloadEpisodeAsync(Episode episode)
        {
            var file = await fileDownloadManager.DownloadFileAsync(
                appFolderName: AppName,
                folderName: episode.Podcast.Title,
                fileName: string.Format("{0:dd.MM.yyyy} - {1} - {2}", episode.Published, episode.Author, episode.Title),
                fileUrl: episode.Path,
                callback: c =>
                {
                    var bytesReceived = c.Progress.BytesReceived;
                    var bytesToReceive = c.Progress.TotalBytesToReceive;
                    double percent = (bytesReceived * 100) / bytesToReceive;

                    Debug.WriteLine(string.Format("Received: {0}/{1} ({2:P1})", bytesReceived, bytesToReceive, percent / 100.0));
                },
                errorCallback: ex =>
                {
                    Debug.WriteLine(string.Format(ex.Message));
                }
                );

            if (file != null)
            {
                var podcast = episode.Podcast;
                var episodeToUpdate = podcast.Episodes.Where(e => e.Guid == episode.Guid).SingleOrDefault();

                episodeToUpdate.Path = file.Path;
                await storageService.SaveAsync(episode.Podcast);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="FileSearch"/> class.
        /// </summary>
        /// <param name="paths">The paths where to start the search.</param>
        /// <param name="episode">The episode to search for.</param>
        public FileSearch(IEnumerable<string> paths, Episode episode)
        {
            _episodes     = new[] { episode };
            _titleRegex   = new[] { episode.Show.GenerateRegex() };
            _episodeRegex = new[] { episode.GenerateRegex() };

            InitStartPaths(paths);
        }
Beispiel #8
0
 public void UpdateEpisode()
 {
     Episode ep = new Episode(1, "Pilot");
     ep.Number = 2;
     ep.Name = "Bla";
     Assert.That(ep.Name, Is.EqualTo("Bla"));
     Assert.That(ep.Number, Is.EqualTo(2));
 }
Beispiel #9
0
		protected override async Task FillGuide(DateTime date) {
			// Nolasīto bloku saturs. Viens [bloka] raidījums var būt vairākas reizes dienā, bet tam atbilst viena bloka lappuse.
			var episodes=new Dictionary<int, Episode>(12);
			bool previousIsPast=true; // Vai iepriekšējais bloks ir pagātnē. Lieto pašreizējā bloka noteikšanai (jo tas nekā neizceļās).
			string episodeCaption=null; // Pašreizējā bloka nosaukums.
			var sb=new StringBuilder(200);

			foreach (var xEpisode in await GetFragments("http://radiomayak.ru/schedule/index/date/"+date.ToString("dd-MM-yyyy"))) {
				string className=xEpisode.Attribute("class").Value;
				if (className == "b-schedule__list-sub-list") {
					// Dienas programmā pašreizējais bloks ir izvērsts, paņem no tā visus raidījumus.
					foreach (var fragment in xEpisode.Elements("div")) {
						var data=fragment.Element("div").Elements("div");
						AddBroadcast(date.Add(TimeSpan.Parse(data.ElementAt(0).Value.Substring(0, 5))), // hh:mm
							GetCaption(data, episodeCaption), GetDescription(data, sb));
					}
				} else {
					var data=xEpisode.Element("div").Elements("div");
					var link=data.ElementAt(1).Element("h5").Element("a");
					if (previousIsPast && !className.EndsWith("past-show")) {
						// Tā kā pirmais bloka raidījums sākas kopā ar bloku, iegaumē tikai tā nosaukumu.
						episodeCaption=link.Value;
					} else {
						if (episodeCaption == null) {
							// Raidījumiem pirms pašreizējā paņem tikai bloka laiku un nosaukumu.
							AddBroadcast(date.Add(TimeSpan.Parse(data.ElementAt(0).Value)), // hh:mm
								link.Value, null);
						} else {
							episodeCaption=link.Value;
							string episodeTime=data.ElementAt(0).Value; // hh:mm

							int id=int.Parse(idRx.Match(link.Attribute("href").Value).Groups[1].Value);
							Episode episode;
							if (!episodes.TryGetValue(id, out episode)) {
								// Nākošajiem raidījumiem bloka saturu izgūst no atsevišķas lappuses.
								episode=new Episode(await GetFragments("http://radiomayak.ru"+link.Attribute("href").Value));
								episodes.Add(id, episode);
							}

							bool inBlock=false; // Vai pašreizējie bloka raidījumi atbilst atlasāmajam laikam.
							for (int n=episode.StartIdx; n < episode.FragmentsCount; n++) {
								var fragment=episode.Fragments.ElementAt(n);
								data=fragment.Element("div").Elements("div");
								if (data.Count() == 2) { // Starp blokiem ir atdalītāji, kurus veido mazāk div elementu.
									if (inBlock) { episode.StartIdx=n+1; break; }
									continue;
								}
								string fragmentTime=data.ElementAt(0).Value.Substring(0, 5); // hh:mm (Substring nogriež atdalītāju un beigu laiku)
								if (episodeTime == fragmentTime) inBlock=true;
								if (inBlock)
									AddBroadcast(date.Add(TimeSpan.Parse(fragmentTime)), GetCaption(data, episodeCaption), GetDescription(data, sb));
							}
						}
					}
					previousIsPast=className.EndsWith("past-show");
				}
			}
		}
        public EpisodeViewModel(Episode episode)
        {
            this.fileDownloadService = ServiceLocator.Current.GetInstance<IFileDownloadService>();
            this.messageDialogService = ServiceLocator.Current.GetInstance<IMessageDialogService>();
            this.DownloadCommand = new RelayCommand(() => DownloadEpisodeAsync(), CanDownloadEpisode);

            this.PlayCommand = new RelayCommand(PlayEpisode, CanPlayEpisode);
            this.Episode = episode;
        }
Beispiel #11
0
        public void ContainsTest()
        {
            Season s01 = new Season(1);

            s01.Add(new Episode(1, "Pilot"));

            Episode ep1 = new Episode(1,"Pilot");

            Assert.That(s01.Contains(ep1));
        }
Beispiel #12
0
 public void AddEpisodeToSeason( string showName, int seasonNumber, Episode episode )
 {
     Show show = GetShowByName( showName );
     Season seasonObj = show.Seasons.FirstOrDefault( cena => cena.Number == seasonNumber );
     //if ( seasonObj == null )
     //{
     //    throw new ArgumentException( String.Format( "Season {0} does not exist in show {1}", seasonNumber, showName ) );
     //}
     seasonObj.Episodes.Add( episode );
 }
 public void Verify_Add_Should_AddTheEntityToTheContext()
 {
     // Arrange
     Mock<IDbSet<Episode>> mockSetEpisodes;
     var mockContext = EpisodesMockingSetup.DoMockingSetupForContext(false, out mockSetEpisodes);
     var repository = new EpisodesRepository(mockContext.Object);
     var episodes = new Episode { Active = true, CustomKey = "SALVATORE-RAA", };
     // Act
     repository.Add(episodes);
     // Assert
     mockSetEpisodes.Verify(x => x.Add(episodes), Times.Once);
 }
        private async Task PlayEpisodeAsync(Episode episode)
        {
            if (episode.Path.StartsWith("https://") ||
                episode.Path.StartsWith("http://"))
                BackgroundMediaPlayer.Current.SetUriSource(new Uri(episode.Path));
            else
            {
                var file = await StorageFile.GetFileFromPathAsync(episode.Path);
                BackgroundMediaPlayer.Current.SetFileSource(file);
            }

            BackgroundMediaPlayer.Current.Play();
        }
Beispiel #15
0
        public void AddDoubleEpisodeTest()
        {
            Episode ep1 = new Episode(1, "Pilot");
            Episode ep2 = new Episode(2, "ZweiteFolge");

            Dictionary<int, Episode> episoden = new Dictionary<int, Episode>();
            episoden.Add(ep1.Number, ep1);
            episoden.Add(ep2.Number, ep2);

            Season se = new Season(1, episoden);

            se.Add(new Episode(2, "Dritte Folge"));
        }
Beispiel #16
0
 /// <summary>
 /// Loads description page for specific episode
 /// </summary>
 /// <param name="episode">Episode url</param>
 /// <returns>Description page for specific episode</returns>
 public async Task<string> FetchEpisodePageAsync(Episode episode)
 {
     try
     {
         logger.LogMessage("Loader: Fetching episode page.");
         return await httpClient.GetStringAsync(mainUrl + episode.Url);
     }
     catch (Exception ex)
     {
         logger.LogMessage($"Loader: Error loading episode page. {ex.Message}", LoggingLevel.Error);
         return string.Empty;
     }
 }
        /// <summary>
        /// Searches for the specified show and its episode.
        /// </summary>
        /// <param name="episode">The episode to search for.</param>
        public void Search(Episode episode)
        {
            _ep = episode;

            var paths = Settings.Get<List<string>>("Download Paths");

            if (paths.Count == 0)
            {
                new TaskDialog
                    {
                        CommonIcon  = TaskDialogIcon.Stop,
                        Title       = "Search path not configured",
                        Instruction = "Search path not configured",
                        Content     = "To use this feature you must set your download path." + Environment.NewLine + Environment.NewLine + "To do so, click on the logo on the upper left corner of the application, then select 'Configure Software'. On the new window click the 'Browse' button under 'Download Path'."
                    }.Show();
                return;
            }

            _td = new TaskDialog
                {
                    Title           = "Searching...",
                    Instruction     = string.Format("{0} S{1:00}E{2:00}", _ep.Show.Name, _ep.Season, _ep.Number),
                    Content         = "Searching for the episode...",
                    CommonButtons   = TaskDialogButton.Cancel,
                    ShowProgressBar = true
                };

            _td.SetMarqueeProgressBar(true);
            _td.Destroyed   += TaskDialogDestroyed;
            _td.ButtonClick += TaskDialogDestroyed;

            _active = true;
            new Thread(() =>
                {
                    Thread.Sleep(500);

                    if (_active)
                    {
                        _res = _td.Show().CommonButton;
                    }
                }).Start();

            _fs = new FileSearch(paths, _ep);

            _fs.FileSearchDone += FileSearchDone;
            _fs.FileSearchProgressChanged += FileSearchProgressChanged;
            _fs.BeginSearch();

            Utils.Win7Taskbar(state: TaskbarProgressBarState.Indeterminate);
        }
		public async Task PlayEpisodeAsync(Episode episode)
		{
			if (episode.IsLocal)
			{
				var file = await StorageFile.GetFileFromPathAsync(episode.Path);
				mediaPlayer.Source = MediaSource.CreateFromStorageFile(file);
			}
			else
			{
				mediaPlayer.Source = MediaSource.CreateFromUri(new Uri(episode.Path));
			}

			mediaPlayer.Play();
		}
Beispiel #19
0
        public void ShouldReplaceIllegalCharactersInEpisodeName()
        {
            var episode = new Episode
            {
                Show = new Show { Name = new FuzzyString("Lost") },
                SeasonNumber = 3,
                EpisodeNumber = 17,
                Title = @"1\2/3:4*5?6'7""8<9>0|",
            };

            var pattern = new Pattern("{title}");
            var newName = pattern.GetName(episode);

            Assert.AreEqual("1234567890", newName);
        }
Beispiel #20
0
        public void AddGoodEpisodeTest()
        {
            Episode ep1 = new Episode(1, "Pilot");
            Episode ep2 = new Episode(2, "ZweiteFolge");

            Dictionary<int, Episode> episoden = new Dictionary<int, Episode>();
            episoden.Add(ep1.Number,ep1);
            episoden.Add(ep2.Number,ep2);

            Season se = new Season(1, episoden);

            se.Add(new Episode(3,"Dritte Folge"));
            Assert.That(se.GetEpisodeByNumber(3).Number, Is.EqualTo(3));
            Assert.That(se.GetEpisodeByNumber(3).Name, Is.EqualTo("Dritte Folge"));
        }
Beispiel #21
0
        public void ShouldReplaceAllTokens()
        {
            var episode = new Episode
              	{
                Show = new Show { Name = new FuzzyString("Lost") },
                SeasonNumber = 3,
                EpisodeNumber = 17,
                Title = "The hatch",
              	};

            var pattern = new Pattern("{show} - {season}{episode} - {title}");
            var newName = pattern.GetName(episode);

            Assert.AreEqual("Lost - 317 - The Hatch", newName);
        }
Beispiel #22
0
        public void IsInHistory_NotInHistory_ReturnsFalse()
        {
            var sabRequest = new MockSabRequest { InputXml = XDocument.Load("SabHistory.xml") };
            ISabService sabService = new SabService(new Config(), sabRequest);
            var episode = new Episode
            {
                ShowName = "Stargate Universe",
                SeasonNumber = 2,
                EpisodeNumber = 1
            };

            bool actual = sabService.IsInHistory(episode);

            Expect(actual, Is.False);
        }
Beispiel #23
0
        public void CopyToTest()
        {
            Season s01 = new Season(1);

            s01.Add(new Episode(1, "Pilot"));
            s01.Add(new Episode(2, "Second"));
            s01.Add(new Episode(3, "Third"));

            Episode[] liste = new Episode[s01.Count];

            s01.CopyTo(liste, 0);

            Assert.That(liste[0].Name, Is.EqualTo("Pilot"));
            Assert.That(liste[1].Name, Is.EqualTo("Second"));
            Assert.That(liste[2].Name, Is.EqualTo("Third"));
        }
Beispiel #24
0
        public void CheckTvDb()
        {
            //http://thetvdb.com/api/GetSeries.php?seriesname=The+Daily+Show
            //http://thetvdb.com/api/5D2D188E86E07F4F/series/71256/default/15/64
            // "The Daily Show 2010 05 06 Mario Batali";
            var episode = new Episode
            {
                ShowName = "The Daily Show",
                AirDate = DateTime.Parse("2010-05-06"),
            };
            var service = new TvDbService();

            service.GetEpisodeName(episode);

            Expect(episode.EpisodeName, Is.EqualTo("Mario Batali"));
        }
        public async Task<Podcast> GetPodcastAsync(string feedUrl)
        {
            var xml = await client.GetStringAsync(feedUrl);

            var xmlDocument = XDocument.Parse(xml);

            var title = xmlDocument.Element("rss").Element("channel").Element("title").Value;
            XNamespace itunes = "http://www.itunes.com/dtds/podcast-1.0.dtd";
            var items = xmlDocument.Element("rss").Element("channel").Elements("item");
            var description = xmlDocument.Element("rss").Element("channel").Element("description").Value;
            var summary = xmlDocument.Element("rss").Element("channel").Element(itunes + "summary").Value;
            var imageLink = xmlDocument.Element("rss").Element("channel").Element(itunes + "image").Attribute("href").Value;
            var author = xmlDocument.Element("rss").Element("channel").Element(itunes + "author").Value;
            string podcastDescription = string.Empty;

            if (description == null)
                podcastDescription = summary;
            else if (summary == null)
                podcastDescription = description;
            else
                podcastDescription = description;

            podcastDescription = podcastDescription.RemoveCData();

            var podcast = new Podcast(title, podcastDescription, author, feedUrl, imageLink, DateTime.Now);

            var episodes = new List<Episode>();

            foreach (var item in items)
            {
                title = item.Element("title").Value;
                var subtitle = item.Element(itunes + "subtitle").Value;
                var path = item.Element("enclosure").Attribute("url").Value;
                author = item.Element(itunes + "author").Value;
                summary = item.Element(itunes + "summary").Value;
                var pubDate = item.Element("pubDate").Value;
                var imageUrl = item.Element(itunes + "image") != null ? item.Element(itunes + "image").Attribute("href").Value : imageLink;
                var guid = item.Element("guid").Value;

                var episode = new Episode(title, subtitle, path, author, summary, pubDate, imageUrl, guid);
                episode.SetPodcast(podcast);
                episodes.Add(episode);
            }

            podcast.SetEpisodes(episodes);
            return podcast;
        }
        public void ExecuteFile(Episode episode)
        {
            if (episode == null || episode.File == null || !episode.File.Exists)
                return;

            episode.IsPlaying = true;

            try
            {
                Process.Start(episode.File.ToString());
            }
            catch (Win32Exception e)
            {
                if (!e.IsCancelled())
                    throw;
            }
        }
        public async Task<Podcast> GetPodcastAsync(string feedUrl)
        {
            var json = await GetChannelNodeAsync(feedUrl);

            string link = feedUrl;
            string title = json.title.ToString();
            string author = json["itunes:author"]?.ToString();
            string summary = json["itunes:summary"]?.ToString();
            string description = json.description?.ToString();
            string imageLink = json.image.url ?? json["itunes:image"]["@href"].ToString();
            string podcastDescription = string.Empty;

            if (description == null)
                podcastDescription = summary;
            else if (summary == null)
                podcastDescription = description;
            else
                podcastDescription = description;

            podcastDescription = podcastDescription.RemoveCData();

            var podcast = new Podcast(title, podcastDescription, author, link, imageLink, DateTime.Now);

            var episodes = new List<Episode>();

            var items = json.item;

            foreach (var item in items)
            {
                title = item.title.ToString();
                string subtitle = item["itunes:subtitle"].ToString();
                string path = item.enclosure["@url"].ToString();
                author = item["itunes:author"].ToString();
                summary = item["itunes:summary"].ToString();
                string pubDate = item.pubDate.ToString();
                string imageUrl = item["itunes:image"] != null ? item["itunes:image"]["@href"] : imageLink;
                string guid = item.guid.ToString();

                var episode = new Episode(title, subtitle, path, author, summary, pubDate, imageUrl, guid);
                episode.SetPodcast(podcast);
                episodes.Add(episode);
            }

            podcast.SetEpisodes(episodes.OrderByDescending(e=>e.Published));
            return podcast;
        }
		public Serie loadSerie(string name)
		{
			Serie eineSerie = new  Serie(name);
			try
			{
				string path = string.Format (@"{0}Data/{1}.xml", _Ordnerpfad, name);
                
                XDocument doc = XDocument.Load(path);
                foreach (var element in doc.Descendants("Staffel"))
                {
                    Staffel eineStaffel = new Staffel(element.Attribute("Name").ToString().Trim());
                    foreach (var elementEpisode in element.Descendants("Episode"))
                    {
                        Episode eineEpisode = new Episode();
                        eineEpisode.NummerInSerie = elementEpisode.Element("NummerInSerie").Value;
                        eineEpisode.NummerInStaffel = elementEpisode.Element("NummerInStaffel").Value;
                        eineEpisode.Name_de = elementEpisode.Element("Name_de").Value;
                        eineEpisode.Erstausstrahlung_de = Convert.ToDateTime(elementEpisode.Element("Erstausstrahulung_de").Value.ToString());
                        eineEpisode.Name_eng = elementEpisode.Element("Name_eng").Value;
                        eineEpisode.Erstausstrahlung_eng = Convert.ToDateTime(elementEpisode.Element("Erstausstrahulung_eng").Value.ToString());
                        eineEpisode.IstVorhanden = (bool)elementEpisode.Element("istVorhanden");

                        foreach (var elementSendetermin in elementEpisode.Descendants("Sendetermin"))
                        {
                            Sendetermin einSendetermin = new Sendetermin();
                            einSendetermin.Datum = Convert.ToDateTime(elementSendetermin.Element("Datum").Value.ToString());
                            einSendetermin.Wochentag = elementSendetermin.Element("Wochentag").Value;
							einSendetermin.Sendezeit = elementSendetermin.Element("Sendezeit").Value;
                            einSendetermin.Sender = elementSendetermin.Element("Sender").Value;

                            eineEpisode.AddSendetermin(Convert.ToInt32( elementSendetermin.Attribute("Key").Value), einSendetermin);
                        }
                        eineStaffel.AddEpisode(eineEpisode.NummerInSerie, eineEpisode);
                    }
                    eineSerie.AddStaffel(eineStaffel.Name, eineStaffel);  
                }
           	}
			catch (Exception ex)
			{
				//LogWindow.log (LogLevel.Error, ex.Message);
				//LogWindow.log (LogLevel.Error, ex.StackTrace);
			}
			return eineSerie;
		}
        /// <summary>
        /// Gets from an episode.
        /// </summary>
        /// <param name="episode">The episode.</param>
        /// <returns>The download index view model.</returns>
        public static DownloadIndexViewModel FromEpisode(
            Episode episode)
        {
            if (episode == null
                || episode.PodCast == null
                || !episode.PodCast.Id.HasValue)
            {
                return null;
            }

            return new DownloadIndexViewModel
                {
                    EpisodeDate = episode.Date,
                    EpisodeId = episode.Id,
                    EpisodeTitle = episode.Title,
                    PodCastId = episode.PodCast.Id.Value,
                    PodCastName = episode.PodCast.Name
                };
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="series"></param>
        /// <param name="episode"></param>
        /// <param name="quality"></param>
        /// <returns></returns>
        public override SearchResult FindTorrent(Series series, 
                                                 Episode episode, 
                                                 Global.EpisodeQuality quality)
        {
            string tempQuality = string.Empty;
            switch (quality)
            {
                case Global.EpisodeQuality.FullBluRay:
                    tempQuality = "1024";
                    break;
                case Global.EpisodeQuality.HdTv:
                    tempQuality = "HD";
                    break;
                case Global.EpisodeQuality.HdBluRay:
                case Global.EpisodeQuality.HdWebDl:
                case Global.EpisodeQuality.SdDvd:
                case Global.EpisodeQuality.SdTv:
                    tempQuality = "720";
                    break;
            }

            DailyTvTorrents api = new DailyTvTorrents();
            Torrent torrent = api.TorrentGetInfo(series.Name.Replace(" ", "-").ToLower(),
                                                 string.Format("S{0}E{1}", ((int)episode.SeasonNumber).ToString("D2"), ((int)episode.EpisodeNumber).ToString("D2")),
                                                 tempQuality);
            if (torrent.torrentFile == null)
            {
                return null;
            }

            FileNameParser fileNameParser = new FileNameParser();
            fileNameParser.Parse(torrent.torrentFile);
            if (fileNameParser.Matched() == false)
            {
                return null;
            }

            SearchResult searchResult = new SearchResult();
            searchResult.Url = torrent.torrentFile;

            return searchResult;
        }
Beispiel #31
0
        public void Setup()
        {
            _series = Builder <Series> .CreateNew()
                      .Build();

            _episode = Builder <Episode> .CreateNew()
                       .Build();

            _profile = new Profile
            {
                Name   = "Test",
                Cutoff = Quality.HDTV720p,
                Items  = new List <ProfileQualityItem>
                {
                    new ProfileQualityItem {
                        Allowed = true, Quality = Quality.HDTV720p
                    },
                    new ProfileQualityItem {
                        Allowed = true, Quality = Quality.WEBDL720p
                    },
                    new ProfileQualityItem {
                        Allowed = true, Quality = Quality.Bluray720p
                    }
                },
            };

            _series.Profile = new LazyLoaded <Profile>(_profile);

            _release = Builder <ReleaseInfo> .CreateNew().Build();

            _parsedEpisodeInfo = Builder <ParsedEpisodeInfo> .CreateNew().Build();

            _parsedEpisodeInfo.Quality = new QualityModel(Quality.HDTV720p);

            _remoteEpisode          = new RemoteEpisode();
            _remoteEpisode.Episodes = new List <Episode> {
                _episode
            };
            _remoteEpisode.Series            = _series;
            _remoteEpisode.ParsedEpisodeInfo = _parsedEpisodeInfo;
            _remoteEpisode.Release           = _release;

            _temporarilyRejected = new DownloadDecision(_remoteEpisode, new Rejection("Temp Rejected", RejectionType.Temporary));

            _heldReleases = new List <PendingRelease>();

            Mocker.GetMock <IPendingReleaseRepository>()
            .Setup(s => s.All())
            .Returns(_heldReleases);

            Mocker.GetMock <IPendingReleaseRepository>()
            .Setup(s => s.AllBySeriesId(It.IsAny <int>()))
            .Returns <int>(i => _heldReleases.Where(v => v.SeriesId == i).ToList());

            Mocker.GetMock <ISeriesService>()
            .Setup(s => s.GetSeries(It.IsAny <int>()))
            .Returns(_series);

            Mocker.GetMock <ISeriesService>()
            .Setup(s => s.GetSeries(It.IsAny <IEnumerable <int> >()))
            .Returns(new List <Series> {
                _series
            });

            Mocker.GetMock <IParsingService>()
            .Setup(s => s.GetEpisodes(It.IsAny <ParsedEpisodeInfo>(), _series, true, null))
            .Returns(new List <Episode> {
                _episode
            });

            Mocker.GetMock <IPrioritizeDownloadDecision>()
            .Setup(s => s.PrioritizeDecisions(It.IsAny <List <DownloadDecision> >()))
            .Returns((List <DownloadDecision> d) => d);
        }
 public void CreateEpisode(Episode episode)
 {
     _episodeRepository.CreateEpisode(episode);
 }
Beispiel #33
0
 private int CompareSpecials(Episode x, Episode y)
 {
     return(GetSpecialCompareValue(x).CompareTo(GetSpecialCompareValue(y)));
 }
Beispiel #34
0
 public ICharacter GetHero(Episode episode)
 {
     return(_repository.GetHero(episode));
 }
 public Task NavigateToEpisodeAsync(Episode episode) => _navigationService.NavigateToPlayerAsync(episode);
        private async Task <Episode> GetEpisodeUpdate(CrunchySession s, Episode placeholder, string datetime)
        {
            try
            {
                WebStream ws = await WebStream.Get(placeholder.PluginMetadata["Url"], null, LibSet[UserAgentS], null, s.cookies.ToCookieCollection(), SocketTimeout, true, null, _info.ProxyFromGlobalRequirements(_global));

                if (ws != null && ws.StatusCode == HttpStatusCode.OK)
                {
                    if (!VerifyLogin(ws.Cookies))
                    {
                        ws?.Dispose();
                        return(null);
                    }
                    StreamReader rd  = new StreamReader(ws);
                    string       dta = rd.ReadToEnd();
                    rd.Dispose();
                    Episodes eps = new Episodes();
                    eps.Items = new List <Episode>();
                    Show show = new Show();
                    show.PluginName = placeholder.PluginName;
                    show.Id         = placeholder.ShowId;

                    MatchCollection scol      = seasonregex.Matches(dta);
                    int             seasonnum = scol.Count;
                    if (scol.Count == 0)
                    {
                        AddEpisodes(eps, show, dta, String.Empty, 1, true);
                    }
                    else
                    {
                        Match sma = scol[0];
                        if (sma.Success)
                        {
                            string data      = sma.Value;
                            string seasoname = sma.Groups["season"].Value;
                            AddEpisodes(eps, show, data, seasoname, seasonnum, true);
                        }
                    }
                    if (eps.Items.Count == 0)
                    {
                        ws?.Dispose();
                        return(null);
                    }
                    Episode ep = eps.Items[0];
                    placeholder.PluginMetadata["Url"] = ep.PluginMetadata["Url"];
                    placeholder.ImageUri       = ep.ImageUri;
                    placeholder.Description    = ep.Description;
                    placeholder.EpisodeAlpha   = ep.EpisodeAlpha;
                    placeholder.EpisodeNumeric = ep.EpisodeNumeric;
                    placeholder.Id             = ep.Id;
                    placeholder.SeasonAlpha    = ep.SeasonAlpha;
                    placeholder.SeasonNumeric  = ep.SeasonNumeric;
                    placeholder.Name           = ep.Name;
                    placeholder.DateTime       = datetime;
                    UpdateHistory.Add(placeholder.UniqueTag, JsonConvert.SerializeObject(placeholder));
                    ws?.Dispose();
                    return(placeholder);
                }
            }
            catch (Exception)
            {
                return(null);
            }
            return(null);
        }
Beispiel #37
0
 void IDataService.Update(Episode character)
 {
     throw new NotImplementedException();
 }
Beispiel #38
0
    private async Task UpdateEpisode(ISearchRepository searchRepository, Episode episode)
    {
        foreach (EpisodeMetadata metadata in episode.EpisodeMetadata)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(metadata.Title))
                {
                    _logger.LogWarning(
                        "Unable to index episode without title {Show} s{Season}e{Episode}",
                        metadata.Episode.Season?.Show?.ShowMetadata.Head().Title,
                        metadata.Episode.Season?.SeasonNumber,
                        metadata.EpisodeNumber);

                    continue;
                }

                var doc = new Document
                {
                    new StringField(IdField, episode.Id.ToString(), Field.Store.YES),
                    new StringField(TypeField, EpisodeType, Field.Store.YES),
                    new TextField(TitleField, metadata.Title, Field.Store.NO),
                    new StringField(SortTitleField, metadata.SortTitle.ToLowerInvariant(), Field.Store.NO),
                    new TextField(LibraryNameField, episode.LibraryPath.Library.Name, Field.Store.NO),
                    new StringField(LibraryIdField, episode.LibraryPath.Library.Id.ToString(), Field.Store.NO),
                    new StringField(TitleAndYearField, GetTitleAndYear(metadata), Field.Store.NO),
                    new StringField(JumpLetterField, GetJumpLetter(metadata), Field.Store.YES),
                    new StringField(StateField, episode.State.ToString(), Field.Store.NO)
                };

                await AddLanguages(searchRepository, doc, episode.MediaVersions);

                foreach (MediaVersion version in episode.MediaVersions.HeadOrNone())
                {
                    doc.Add(
                        new Int32Field(MinutesField, (int)Math.Ceiling(version.Duration.TotalMinutes), Field.Store.NO));
                }

                if (metadata.ReleaseDate.HasValue)
                {
                    doc.Add(
                        new StringField(
                            ReleaseDateField,
                            metadata.ReleaseDate.Value.ToString("yyyyMMdd"),
                            Field.Store.NO));
                }

                doc.Add(new StringField(AddedDateField, metadata.DateAdded.ToString("yyyyMMdd"), Field.Store.NO));

                if (!string.IsNullOrWhiteSpace(metadata.Plot))
                {
                    doc.Add(new TextField(PlotField, metadata.Plot ?? string.Empty, Field.Store.NO));
                }

                foreach (Genre genre in metadata.Genres)
                {
                    doc.Add(new TextField(GenreField, genre.Name, Field.Store.NO));
                }

                foreach (Tag tag in metadata.Tags)
                {
                    doc.Add(new TextField(TagField, tag.Name, Field.Store.NO));
                }

                foreach (Studio studio in metadata.Studios)
                {
                    doc.Add(new TextField(StudioField, studio.Name, Field.Store.NO));
                }

                foreach (Actor actor in metadata.Actors)
                {
                    doc.Add(new TextField(ActorField, actor.Name, Field.Store.NO));
                }

                foreach (Director director in metadata.Directors)
                {
                    doc.Add(new TextField(DirectorField, director.Name, Field.Store.NO));
                }

                foreach (Writer writer in metadata.Writers)
                {
                    doc.Add(new TextField(WriterField, writer.Name, Field.Store.NO));
                }

                foreach (TraktListItem item in episode.TraktListItems)
                {
                    doc.Add(new StringField(TraktListField, item.TraktList.TraktId.ToString(), Field.Store.NO));
                }

                _writer.UpdateDocument(new Term(IdField, episode.Id.ToString()), doc);
            }
            catch (Exception ex)
            {
                metadata.Episode = null;
                _logger.LogWarning(ex, "Error indexing episode with metadata {@Metadata}", metadata);
            }
        }
    }
        private async Task <UpdateResponse> Updates(CrunchySession s, ShowType t)
        {
            int            startpage = 0;
            UpdateResponse ret       = new UpdateResponse();
            bool           end       = false;

            do
            {
                string    url = string.Format(LibSet[UpdateUrlS], ShowFromType(t), startpage);
                WebStream ws  = await WebStream.Get(url, null, LibSet[UserAgentS], null, s.cookies.ToCookieCollection(), SocketTimeout, true, null, _info.ProxyFromGlobalRequirements(_global));

                if (ws != null && ws.StatusCode == HttpStatusCode.OK)
                {
                    if (!VerifyLogin(ws.Cookies))
                    {
                        ws.Dispose();
                        SetLoginError(ret);
                        return(ret);
                    }
                    StreamReader rd  = new StreamReader(ws);
                    string       dta = rd.ReadToEnd();
                    rd.Dispose();
                    MatchCollection scol = updregex.Matches(dta);
                    if (scol.Count == 0)
                    {
                        end = true;
                    }
                    foreach (Match m in scol)
                    {
                        string show  = m.Groups["show"].Value;
                        string image = m.Groups["image"].Value;
                        string title = WebUtility.HtmlDecode(m.Groups["title"].Value);
                        string ep    = m.Groups["ep"].Value;
                        Uri    ur    = new Uri("http://www.crunchyroll.com" + m.Groups["url"].Value);
                        int    a     = ep.IndexOf("&ndash;", StringComparison.InvariantCulture);
                        if (a >= 0)
                        {
                            ep = ep.Substring(0, a).Trim();
                            string tag = CrunchyPluginInfo.PluginName + "|" + show + "|" + ep;
                            if (UpdateHistory.Exists(tag))
                            {
                                Episode c = JsonConvert.DeserializeObject <Episode>(UpdateHistory.Get(tag));
                                ret.Found.Add(c);
                            }
                            else
                            {
                                Episode p = new Episode();
                                p.PluginMetadata.Add("Url", ur.ToString());
                                p.ShowName   = title;
                                p.ShowId     = show;
                                p.PluginName = CrunchyPluginInfo.PluginName;
                                p.UniqueTag  = tag;
                                p.ImageUri   = new Uri(image);
                                p.Type       = t;
                                ret.NotFound.Add(p);
                            }
                        }
                    }
                }
                else
                {
                    ws?.Dispose();
                    SetWebError(ret);
                    return(ret);
                }
                ws?.Dispose();
                startpage++;
            } while (!end);
            return(ret);
        }
    public static List <DataPoint> parseJson(string fileName, Decoration decoration)
    {
        List <DataPoint> dataset = new List <DataPoint> ();

        List <String> validDecorationString = new List <String> ();

        if (decoration == Decoration.Logos)
        {
            validDecorationString.Add("logo");
        }
        else if (decoration == Decoration.Digits)
        {
            validDecorationString.Add("digit");
        }
        else if (decoration == Decoration.Both)
        {
            validDecorationString.Add("logo");
            validDecorationString.Add("digit");
        }

        var    json = System.IO.File.ReadAllText("Assets/" + fileName);
        JArray arr  = JArray.Parse(json);        // parse as array

        foreach (JObject root in arr)
        {
            // Check the decoration type
            string     decorationType  = root ["decoration"].ToString();
            bool       success         = false;
            Decoration pointDecoration = Decoration.Blank;

            foreach (string decorationString in validDecorationString)
            {
                if (decorationType.CompareTo(decorationString) == 0)
                {
                    if (decorationString.CompareTo("digit") == 0)
                    {
                        pointDecoration = Decoration.Digits;
                    }
                    else if (decorationString.CompareTo("logo") == 0)
                    {
                        pointDecoration = Decoration.Logos;
                    }

                    success = true;
                    break;
                }
            }

            if (!success)
            {
                continue;
            }

            // extract the block size
            float blockSize = float.Parse(root["side_length"].ToString());
            Debug.Log("Block size " + blockSize);

            // Parse the list of environment
            List <ObjectSystem> systems = new List <ObjectSystem> ();
            JToken v     = root ["states"];
            JToken envIt = v.First;
            while (envIt != null)
            {
                JToken         it             = envIt.First;
                List <Point3D> objectLocation = new List <Point3D> ();

                while (it != null)                   //iterates over objects in the environment
                {
                    JToken u = it;
                    JToken w = u.First;
                    double x = -double.Parse(w.ToString());
                    double y = double.Parse(w.Next.ToString());
                    double z = -double.Parse(w.Next.Next.ToString());
                    Debug.Log("(" + x + ", " + y + ", " + z + ")\n");

                    Point3D p = new Point3D(x, y, z);
                    objectLocation.Add(p);

                    it = it.Next;
                }

                Debug.Log("Number of objects " + objectLocation.Count);
                ObjectSystem system = new ObjectSystem(blockSize, objectLocation);
                systems.Add(system);

                envIt = envIt.Next;
            }

            Debug.Log("======= Done reading the first image  ======\n");
            Episode episode = new Episode(systems, blockSize);

            // Extract the sentences
            JToken frameIt = root ["notes"].First;
            while (frameIt != null)
            {
                int    start    = int.Parse(frameIt ["start"].ToString());
                int    finish   = int.Parse(frameIt ["finish"].ToString());
                string type     = frameIt ["type"].ToString();
                Type   enumType = (Type)Enum.Parse(typeof(Type), type, false);

                Debug.Log("Start is " + start + " finish: " + finish + " type: " + type);

                if (enumType != Type.A0)
                {
                    frameIt = frameIt.Next;
                    continue;
                }

                JToken instructionIt = frameIt ["notes"].First;
                JToken userIt        = frameIt ["users"].First;

                while (instructionIt != null)
                {
                    if (userIt == null)
                    {
                        throw new ApplicationException("Less user IDs than instructions");
                    }

                    Debug.Log("Instruction: " + instructionIt);

                    // Create a new datapoint
                    String    instruction = instructionIt.ToString();
                    String    userID      = userIt.ToString();
                    DataPoint datapoint   = new DataPoint(instruction, enumType, start, finish, userID, episode, pointDecoration);
                    dataset.Add(datapoint);

                    instructionIt = instructionIt.Next;
                    userIt        = userIt.Next;
                }

                if (userIt != null)
                {
                    throw new ApplicationException("More user IDs than instructions");
                }

                frameIt = frameIt.Next;
            }
        }

        Debug.Log("Dataset size " + dataset.Count);

        return(dataset);
    }
Beispiel #41
0
        /// <summary>
        /// Reports to trakt.tv that an episode is being watched. Or that Episode(s) have been watched.
        /// </summary>
        /// <param name="episode">The episode being watched</param>
        /// <param name="status">Enum indicating whether an episode is being watched or scrobbled</param>
        /// <param name="traktUser">The user that's watching the episode</param>
        /// <param name="progressPercent"></param>
        /// <returns>A List of standard TraktResponse Data Contracts</returns>
        public async Task <List <TraktScrobbleResponse> > SendEpisodeStatusUpdateAsync(Episode episode, MediaStatus status, TraktUser traktUser, float progressPercent)
        {
            var episodeDatas = new List <TraktScrobbleEpisode>();
            var tvDbId       = episode.GetProviderId(MetadataProviders.Tvdb);

            if (!string.IsNullOrEmpty(tvDbId) && (!episode.IndexNumber.HasValue || !episode.IndexNumberEnd.HasValue || episode.IndexNumberEnd <= episode.IndexNumber))
            {
                episodeDatas.Add(new TraktScrobbleEpisode
                {
                    app_date    = DateTime.Today.ToString("yyyy-MM-dd"),
                    app_version = _appHost.ApplicationVersion.ToString(),
                    progress    = progressPercent,
                    episode     = new TraktEpisode
                    {
                        ids = new TraktEpisodeId
                        {
                            tvdb = tvDbId.ConvertToInt()
                        },
                    }
                });
            }
            else if (episode.IndexNumber.HasValue)
            {
                var indexNumber = episode.IndexNumber.Value;
                var finalNumber = (episode.IndexNumberEnd ?? episode.IndexNumber).Value;

                for (var number = indexNumber; number <= finalNumber; number++)
                {
                    episodeDatas.Add(new TraktScrobbleEpisode
                    {
                        app_date    = DateTime.Today.ToString("yyyy-MM-dd"),
                        app_version = _appHost.ApplicationVersion.ToString(),
                        progress    = progressPercent,
                        episode     = new TraktEpisode
                        {
                            season = episode.GetSeasonNumber(),
                            number = number
                        },
                        show = new TraktShow
                        {
                            title = episode.Series.Name,
                            year  = episode.Series.ProductionYear,
                            ids   = new TraktShowId
                            {
                                tvdb   = episode.Series.GetProviderId(MetadataProviders.Tvdb).ConvertToInt(),
                                imdb   = episode.Series.GetProviderId(MetadataProviders.Imdb),
                                tvrage = episode.Series.GetProviderId(MetadataProviders.TvRage).ConvertToInt()
                            }
                        }
                    });
                }
            }

            string url;

            switch (status)
            {
            case MediaStatus.Watching:
                url = TraktUris.ScrobbleStart;
                break;

            case MediaStatus.Paused:
                url = TraktUris.ScrobblePause;
                break;

            default:
                url = TraktUris.ScrobbleStop;
                break;
            }
            var responses = new List <TraktScrobbleResponse>();

            foreach (var traktScrobbleEpisode in episodeDatas)
            {
                using (var response = await PostToTrakt(url, traktScrobbleEpisode, CancellationToken.None, traktUser))
                {
                    responses.Add(_jsonSerializer.DeserializeFromStream <TraktScrobbleResponse>(response));
                }
            }
            return(responses);
        }
Beispiel #42
0
 public PlayEpisodeMessage(Episode episode)
 {
     this.Episode = episode;
 }
Beispiel #43
0
 public async Task RemoveAsync(Episode model)
 {
     await _episodeRepository.RemoveAsync(model);
 }
Beispiel #44
0
 private string GetUniqueSeriesKey(Episode episode)
 {
     return(episode.SeriesPresentationUniqueKey);
 }
Beispiel #45
0
 public async Task <Episode> AddAsync(Episode model)
 {
     return(await _episodeRepository.AddAsync(model));
 }
Beispiel #46
0
 public Review OnReview(
     [Topic] Episode episode,
     [EventMessage] Review message) => message;
Beispiel #47
0
 /// <summary>
 /// add a new widget
 /// </summary>
 /// <param name="widget">widget to add</param>
 public void Add(Episode episode)
 {
     episode.Id = NextIdNumber();
     _collection.InsertOne(episode);
 }
Beispiel #48
0
        private async Task OrganizeEpisode(string sourcePath,
                                           Series series,
                                           Episode episode,
                                           TvFileOrganizationOptions options,
                                           bool rememberCorrection,
                                           FileOrganizationResult result,
                                           CancellationToken cancellationToken)
        {
            _logger.Info("Sorting file {0} into series {1}", sourcePath, series.Path);

            var originalExtractedSeriesString = result.ExtractedName;

            bool isNew = string.IsNullOrWhiteSpace(result.Id);

            if (isNew)
            {
                _organizationService.SaveResult(result, cancellationToken);
            }

            if (!_organizationService.AddToInProgressList(result, isNew))
            {
                throw new OrganizationException("File is currently processed otherwise. Please try again later.");
            }

            try
            {
                // Proceed to sort the file
                var newPath = episode.Path;

                if (string.IsNullOrEmpty(newPath))
                {
                    var msg = string.Format("Unable to sort {0} because target path could not be determined.", sourcePath);
                    throw new OrganizationException(msg);
                }

                _logger.Info("Sorting file {0} to new path {1}", sourcePath, newPath);
                result.TargetPath = newPath;

                var fileExists          = _fileSystem.FileExists(result.TargetPath);
                var otherDuplicatePaths = GetOtherDuplicatePaths(result.TargetPath, series, episode);

                if (!options.OverwriteExistingEpisodes)
                {
                    if (options.CopyOriginalFile && fileExists && IsSameEpisode(sourcePath, newPath))
                    {
                        var msg = string.Format("File '{0}' already copied to new path '{1}', stopping organization", sourcePath, newPath);
                        _logger.Info(msg);
                        result.Status        = FileSortingStatus.SkippedExisting;
                        result.StatusMessage = msg;
                        return;
                    }

                    if (fileExists)
                    {
                        var msg = string.Format("File '{0}' already exists as '{1}', stopping organization", sourcePath, newPath);
                        _logger.Info(msg);
                        result.Status        = FileSortingStatus.SkippedExisting;
                        result.StatusMessage = msg;
                        result.TargetPath    = newPath;
                        return;
                    }

                    if (otherDuplicatePaths.Count > 0)
                    {
                        var msg = string.Format("File '{0}' already exists as these:'{1}'. Stopping organization", sourcePath, string.Join("', '", otherDuplicatePaths));
                        _logger.Info(msg);
                        result.Status         = FileSortingStatus.SkippedExisting;
                        result.StatusMessage  = msg;
                        result.DuplicatePaths = otherDuplicatePaths;
                        return;
                    }
                }

                PerformFileSorting(options, result);

                if (options.OverwriteExistingEpisodes)
                {
                    var hasRenamedFiles = false;

                    foreach (var path in otherDuplicatePaths)
                    {
                        _logger.Debug("Removing duplicate episode {0}", path);

                        _libraryMonitor.ReportFileSystemChangeBeginning(path);

                        var renameRelatedFiles = !hasRenamedFiles &&
                                                 string.Equals(_fileSystem.GetDirectoryName(path), _fileSystem.GetDirectoryName(result.TargetPath), StringComparison.OrdinalIgnoreCase);

                        if (renameRelatedFiles)
                        {
                            hasRenamedFiles = true;
                        }

                        try
                        {
                            DeleteLibraryFile(path, renameRelatedFiles, result.TargetPath);
                        }
                        catch (IOException ex)
                        {
                            _logger.ErrorException("Error removing duplicate episode", ex, path);
                        }
                        finally
                        {
                            _libraryMonitor.ReportFileSystemChangeComplete(path, true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.Status        = FileSortingStatus.Failure;
                result.StatusMessage = ex.Message;
                _logger.Warn(ex.Message);
                return;
            }
            finally
            {
                _organizationService.RemoveFromInprogressList(result);
            }

            if (rememberCorrection)
            {
                SaveSmartMatchString(originalExtractedSeriesString, series, cancellationToken);
            }
        }
Beispiel #49
0
        private Series ReadSeriesXML(string xmlSource)
        {
            Series series = new Series();
            Dictionary <int, Episode> episodes = new Dictionary <int, Episode>();
            Episode episode    = null;
            bool    newSeries  = false;
            bool    newEpisode = false;

            string[] formats = new string[4] {
                "hh:mm tt", "h:mm tt", "HH:mm", "H:mm"
            };
            bool connection = false;

            while (!connection)
            {
                try
                {
                    WebRequest webRequest = WebRequest.Create(xmlSource);
                    webRequest.Timeout = 15000;
                    using (WebResponse response = webRequest.GetResponse())
                    {
                        using (XmlTextReader xmlTextReader = new XmlTextReader(response.GetResponseStream()))
                        {
                            while (xmlTextReader.Read())
                            {
                                if (xmlTextReader.Name == "Series")
                                {
                                    newSeries = xmlTextReader.NodeType == XmlNodeType.Element;
                                }
                                int      num;
                                DateTime date;
                                double   dub;
                                if (newSeries)
                                {
                                    switch (xmlTextReader.Name.ToLower())
                                    {
                                    case "id":
                                        if (int.TryParse(xmlTextReader.ReadInnerXml(), out num))
                                        {
                                            series.SeriesID = num;
                                        }
                                        break;

                                    case "actors":
                                        List <string> actors = new List <string>(xmlTextReader.ReadInnerXml().Split(new char[1] {
                                            '|'
                                        }, StringSplitOptions.RemoveEmptyEntries));
                                        series.Actors = actors;
                                        break;

                                    case "airs_dayofweek":
                                        series.DayOfWeekAirs = xmlTextReader.ReadInnerXml();
                                        break;

                                    case "airs_time":
                                        if (DateTime.TryParseExact(xmlTextReader.ReadInnerXml(), formats, (IFormatProvider)CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
                                        {
                                            series.TimeAirs = date;
                                        }
                                        break;

                                    case "contentrating":
                                        series.ContentRating = xmlTextReader.ReadInnerXml();
                                        break;

                                    case "firstaired":
                                        if (DateTime.TryParse(xmlTextReader.ReadInnerXml(), out date))
                                        {
                                            series.FirstAired = date;
                                        }
                                        break;

                                    case "genre":
                                        List <string> genres = new List <string>(xmlTextReader.ReadInnerXml().Split(new char[1] {
                                            '|'
                                        }, StringSplitOptions.RemoveEmptyEntries));
                                        series.Genre = genres;
                                        break;

                                    case "imdb_id":
                                        series.IMDB_ID = xmlTextReader.ReadInnerXml();
                                        break;

                                    case "language":
                                        series.Language = xmlTextReader.ReadInnerXml();
                                        break;

                                    case "network":
                                        series.Network = xmlTextReader.ReadInnerXml().Replace("&amp;", "&").Replace("amp;", "&");
                                        break;

                                    case "overview":
                                        series.Overview = xmlTextReader.ReadInnerXml().Replace("&amp;", "&").Replace("amp;", "&");
                                        break;

                                    case "rating":
                                        if (double.TryParse(xmlTextReader.ReadInnerXml(), out dub))
                                        {
                                            series.Rating = dub;
                                        }
                                        break;

                                    case "ratingcount":
                                        if (int.TryParse(xmlTextReader.ReadInnerXml(), out num))
                                        {
                                            series.RatingCount = num;
                                        }
                                        break;

                                    case "runtime":
                                        if (int.TryParse(xmlTextReader.ReadInnerXml(), out num))
                                        {
                                            series.Runtime = num;
                                        }
                                        break;

                                    case "seriesname":
                                        series.SeriesName = xmlTextReader.ReadInnerXml().Replace("&amp;", "&").Replace("amp;", "&");
                                        break;

                                    case "status":
                                        series.Status = xmlTextReader.ReadInnerXml();
                                        break;

                                    case "banner":
                                        series.Banner = xmlTextReader.ReadInnerXml();
                                        break;

                                    case "fanart":
                                        series.Fanart = xmlTextReader.ReadInnerXml();
                                        break;

                                    case "poster":
                                        series.Poster = xmlTextReader.ReadInnerXml();
                                        break;
                                    }
                                }
                                if (xmlTextReader.Name == "Episode")
                                {
                                    if (xmlTextReader.NodeType == XmlNodeType.Element)
                                    {
                                        episode    = new Episode();
                                        newEpisode = true;
                                    }
                                    else
                                    {
                                        episodes.Add(episode.EpisodeID, episode);
                                        newEpisode = false;
                                    }
                                }
                                if (newEpisode)
                                {
                                    switch (xmlTextReader.Name.ToLower())
                                    {
                                    case "seriesid":
                                        if (int.TryParse(xmlTextReader.ReadInnerXml(), out num))
                                        {
                                            episode.SeriesID = num;
                                        }
                                        break;

                                    case "id":
                                        if (int.TryParse(xmlTextReader.ReadInnerXml(), out num))
                                        {
                                            episode.EpisodeID = num;
                                        }
                                        break;

                                    case "director":
                                        episode.Director = xmlTextReader.ReadInnerXml();
                                        break;

                                    case "episodename":
                                        episode.Name = xmlTextReader.ReadInnerXml().Replace("&amp;", "&").Replace("amp;", "&");
                                        break;

                                    case "episodenumber":
                                        if (int.TryParse(xmlTextReader.ReadInnerXml(), out num))
                                        {
                                            episode.EpisodeNumber = num;
                                        }
                                        break;

                                    case "firstaired":
                                        if (DateTime.TryParse(xmlTextReader.ReadInnerXml(), out date))
                                        {
                                            episode.FirstAired = date;
                                        }
                                        break;

                                    case "gueststars":
                                        List <string> guestStars = new List <string>(xmlTextReader.ReadInnerXml().Split(new char[1] {
                                            '|'
                                        }, StringSplitOptions.RemoveEmptyEntries));
                                        episode.GuestStars = guestStars;
                                        break;

                                    case "language":
                                        episode.Language = xmlTextReader.ReadInnerXml();
                                        break;

                                    case "overview":
                                        episode.Overview = xmlTextReader.ReadInnerXml().Replace("&amp;", "&").Replace("amp;", "&");
                                        break;

                                    case "rating":
                                        if (double.TryParse(xmlTextReader.ReadInnerXml(), out dub))
                                        {
                                            episode.Rating = dub;
                                        }
                                        break;

                                    case "ratingcount":
                                        if (int.TryParse(xmlTextReader.ReadInnerXml(), out num))
                                        {
                                            episode.RatingCount = num;
                                        }
                                        break;

                                    case "seasonnumber":
                                        if (int.TryParse(xmlTextReader.ReadInnerXml(), out num))
                                        {
                                            episode.Season = num;
                                        }
                                        break;

                                    case "writer":
                                        List <string> writers = new List <string>(xmlTextReader.ReadInnerXml().Split(new char[1] {
                                            '|'
                                        }, StringSplitOptions.RemoveEmptyEntries));
                                        episode.Writer = writers;
                                        break;

                                    case "absolute_number":
                                        if (int.TryParse(xmlTextReader.ReadInnerXml(), out num))
                                        {
                                            episode.AbsoluteNumber = num;
                                        }
                                        break;

                                    default:
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    series.Episodes = episodes;
                    connection      = true;
                }
                catch (WebException ex)
                {
                }
            }
            return(series);
        }
Beispiel #50
0
        private void SetEpisodeFileName(string sourcePath, Series series, Season season, Episode episode, TvFileOrganizationOptions options)
        {
            var seriesName = series.Name.Trim();

            var episodeTitle = episode.Name.Trim();

            if (!episode.IndexNumber.HasValue || !season.IndexNumber.HasValue)
            {
                throw new OrganizationException("GetEpisodeFileName: Mandatory param as missing!");
            }

            var endingEpisodeNumber = episode.IndexNumberEnd;
            var episodeNumber       = episode.IndexNumber.Value;
            var seasonNumber        = season.IndexNumber.Value;

            var sourceExtension = (Path.GetExtension(sourcePath) ?? string.Empty).TrimStart('.');

            var pattern = endingEpisodeNumber.HasValue ? options.MultiEpisodeNamePattern : options.EpisodeNamePattern;

            if (string.IsNullOrWhiteSpace(pattern))
            {
                throw new OrganizationException("GetEpisodeFileName: Configured episode name pattern is empty!");
            }

            var result = pattern.Replace("%sn", seriesName)
                         .Replace("%s.n", seriesName.Replace(" ", "."))
                         .Replace("%s_n", seriesName.Replace(" ", "_"))
                         .Replace("%s", seasonNumber.ToString(_usCulture))
                         .Replace("%0s", seasonNumber.ToString("00", _usCulture))
                         .Replace("%00s", seasonNumber.ToString("000", _usCulture))
                         .Replace("%ext", sourceExtension)
                         .Replace("%en", "%#1")
                         .Replace("%e.n", "%#2")
                         .Replace("%e_n", "%#3")
                         .Replace("%fn", Path.GetFileNameWithoutExtension(sourcePath));

            if (endingEpisodeNumber.HasValue)
            {
                result = result.Replace("%ed", endingEpisodeNumber.Value.ToString(_usCulture))
                         .Replace("%0ed", endingEpisodeNumber.Value.ToString("00", _usCulture))
                         .Replace("%00ed", endingEpisodeNumber.Value.ToString("000", _usCulture));
            }

            result = result.Replace("%e", episodeNumber.ToString(_usCulture))
                     .Replace("%0e", episodeNumber.ToString("00", _usCulture))
                     .Replace("%00e", episodeNumber.ToString("000", _usCulture));

            if (result.Contains("%#"))
            {
                result = result.Replace("%#1", episodeTitle)
                         .Replace("%#2", episodeTitle.Replace(" ", "."))
                         .Replace("%#3", episodeTitle.Replace(" ", "_"));
            }

            // Finally, call GetValidFilename again in case user customized the episode expression with any invalid filename characters
            episode.Path = Path.Combine(season.Path, _fileSystem.GetValidFilename(result).Trim());
        }
 public void DownloadEpisode(Episode episode)
 {
     var task = BackgroundDownloadHelper.Download(new System.Uri(episode.Key));
 }
        public void ShouldHavePlayerDetailsMyDefault()
        {
            Episode e = new Episode();

            e.PlayedDetails.Should().NotBeNull();
        }
Beispiel #53
0
 public string GetFormatedSeasonEpisodeString()
 {
     return(String.Concat(Season.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0'), "x", Episode.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0')));
 }
Beispiel #54
0
 /// <summary>
 /// Delete specified episode.
 /// </summary>
 /// <param name="episode"></param>
 public void DeleteEpisode(Episode episode) =>
 context.Episodes
 .Remove(episode);
Beispiel #55
0
        public FileNameSampleService(IBuildFileNames buildFileNames)
        {
            _buildFileNames = buildFileNames;

            _standardSeries = new Series
            {
                SeriesType = SeriesTypes.Standard,
                Title      = "Series Title (2010)"
            };

            _dailySeries = new Series
            {
                SeriesType = SeriesTypes.Daily,
                Title      = "Series Title (2010)"
            };

            _animeSeries = new Series
            {
                SeriesType = SeriesTypes.Anime,
                Title      = "Series Title (2010)"
            };

            _episode1 = new Episode
            {
                SeasonNumber          = 1,
                EpisodeNumber         = 1,
                Title                 = "Episode Title (1)",
                AirDate               = "2013-10-30",
                AbsoluteEpisodeNumber = 1
            };

            _episode2 = new Episode
            {
                SeasonNumber          = 1,
                EpisodeNumber         = 2,
                Title                 = "Episode Title (2)",
                AbsoluteEpisodeNumber = 2
            };

            _singleEpisode = new List <Episode> {
                _episode1
            };
            _multiEpisodes = new List <Episode> {
                _episode1, _episode2
            };

            var mediaInfo = new MediaInfoModel()
            {
                VideoCodec     = "AVC",
                AudioFormat    = "DTS",
                AudioLanguages = "English",
                Subtitles      = "English/German"
            };

            var mediaInfoAnime = new MediaInfoModel()
            {
                VideoCodec     = "AVC",
                AudioFormat    = "DTS",
                AudioLanguages = "Japanese",
                Subtitles      = "Japanese/English"
            };

            _singleEpisodeFile = new EpisodeFile
            {
                Quality      = new QualityModel(Quality.HDTV720p),
                RelativePath = "Series.Title.S01E01.720p.HDTV.x264-EVOLVE.mkv",
                ReleaseGroup = "RlsGrp",
                MediaInfo    = mediaInfo
            };

            _multiEpisodeFile = new EpisodeFile
            {
                Quality      = new QualityModel(Quality.HDTV720p),
                RelativePath = "Series.Title.S01E01-E02.720p.HDTV.x264-EVOLVE.mkv",
                ReleaseGroup = "RlsGrp",
                MediaInfo    = mediaInfo
            };

            _dailyEpisodeFile = new EpisodeFile
            {
                Quality      = new QualityModel(Quality.HDTV720p),
                RelativePath = "Series.Title.2013.10.30.HDTV.x264-EVOLVE.mkv",
                ReleaseGroup = "RlsGrp",
                MediaInfo    = mediaInfo
            };

            _animeEpisodeFile = new EpisodeFile
            {
                Quality      = new QualityModel(Quality.HDTV720p),
                RelativePath = "Series.Title.001.HDTV.x264-EVOLVE.mkv",
                ReleaseGroup = "RlsGrp",
                MediaInfo    = mediaInfoAnime
            };
        }
Beispiel #56
0
 /// <summary>
 /// Update specified episode for specified character. No implmentation needed.
 /// </summary>
 /// <param name="characterId"></param>
 /// <param name="episode"></param>
 public void UpdateEpisodeForCharacter(Guid characterId, Episode episode)
 {
 }
        public async Task <Response> Download(ISession session, Episode episode, string template, string downloadpath, Quality quality, Format formats, CancellationToken token, IProgress <DownloadInfo> progress)
        {
            try
            {
                KeyValuePair <string, string> defl = AudioLanguageFromEpisode(episode);
                CrunchySession sess = session as CrunchySession;

                if (sess == null)
                {
                    return new Response {
                               ErrorMessage = "Invalid Session", Status = ResponseStatus.InvalidArgument
                    }
                }
                ;
                if (!episode.PluginMetadata.ContainsKey("Url"))
                {
                    return new Response {
                               ErrorMessage = "Invalid Episode", Status = ResponseStatus.InvalidArgument
                    }
                }
                ;
                DownloadInfo dp = new DownloadInfo {
                    FileName = TemplateParser.FilenameFromEpisode(episode, quality, template), Format = formats, Percent = 0, Quality = quality
                };

                token.ThrowIfCancellationRequested();
                dp.Languages = new List <string>();
                dp.Percent   = 1;
                dp.Status    = "Getting Metadata";
                progress.Report(dp);
                Config c = await GetStandardConfig(sess, episode.Id, quality);

                if (c == null)
                {
                    return new Response {
                               ErrorMessage = "Unable to retrieve metadata", Status = ResponseStatus.WebError
                    }
                }
                ;
                if (!string.IsNullOrEmpty(c.Stream_info.Error))
                {
                    return new Response {
                               ErrorMessage = "Login Required", Status = ResponseStatus.LoginRequired
                    }
                }
                ;
                List <Task <CrunchySubtitleInfo> > subTasks = new List <Task <CrunchySubtitleInfo> >();
                token.ThrowIfCancellationRequested();
                if ((c.Subtitles != null && c.Subtitles.Subtitle != null && c.Subtitles.Subtitle.Count > 0))
                {
                    foreach (Subtitle s in c.Subtitles.Subtitle)
                    {
                        subTasks.Add(GetSubtitle(sess, int.Parse(s.Id)));
                    }
                    dp.Percent = 2;

                    dp.Status = "Gettings subtitles";
                    progress.Report(dp);
                    await Task.WhenAll(subTasks);

                    foreach (CrunchySubtitleInfo s in subTasks.Select(a => a.Result))
                    {
                        dp.Languages.Add(s.Title);
                    }
                }
                else
                {
                    dp.Languages.Add("Hardcoded");
                }
                dp.Quality  = c.Stream_info.Metadata.Height.ToQuality();
                dp.FileName = TemplateParser.FilenameFromEpisode(episode, dp.Quality, template);
                dp.FullPath = Path.Combine(downloadpath, dp.FileName);
                string intermediatefile          = Path.Combine(downloadpath, dp.FileName + ".tm1");
                KeyValuePair <string, string> hh = ParseHost(c.Stream_info.Host);
                string        args          = string.Format(LibSet[RTMPDumpArgsS], hh.Key, hh.Value, c.Stream_info.File, intermediatefile);
                List <string> todeleteFiles = new List <string>();
                todeleteFiles.Add(intermediatefile);
                dp.Percent = 3;
                dp.Status  = "Downloading video";
                progress.Report(dp);
                RTMPDumpParser rtmp  = new RTMPDumpParser();
                double         dbl   = 92;
                double         final = 0;
                rtmp.OnProgress += (val) =>
                {
                    final      = val;
                    dp.Percent = (val * dbl / 100) + 3;
                    progress.Report(dp);
                };
                await rtmp.Start(LibSet[RTMPDumpEXES], args, token);

                if (final < 100)
                {
                    return new Response {
                               ErrorMessage = "Error downloading video", Status = ResponseStatus.TransferError
                    }
                }
                ;
                List <CrunchySubtitleInfo> sis = subTasks.Select(a => a.Result).ToList();
                string inputs = string.Empty;
                string maps   = String.Empty;
                int    pp     = 0;
                foreach (CrunchySubtitleInfo k in sis)
                {
                    string pth = Path.GetTempFileName() + ".ass";

                    todeleteFiles.Add(pth);
                    File.WriteAllText(pth, k.Ass);
                    inputs += "-i \"" + pth + "\" ";
                    maps   += GetFFMPEGSubtitleArguments(pp + 1, pp, k.Language, k.Title);
                    pp++;
                }
                dp.Size = await ReMux(intermediatefile, inputs, maps, formats, defl.Key, defl.Value, 96, 4, dp, progress, token);

                dp.Percent = 100;
                dp.Status  = "Finished";
                progress.Report(dp);
                foreach (string s in todeleteFiles)
                {
                    try
                    {
                        File.Delete(s);
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                }
                return(new Response {
                    Status = ResponseStatus.Ok, ErrorMessage = "OK"
                });
            }
            catch (Exception e)
            {
                if (e is OperationCanceledException)
                {
                    return new Response {
                               ErrorMessage = "Canceled", Status = ResponseStatus.Canceled
                    }
                }
                ;
                return(new Response {
                    ErrorMessage = e.ToString(), Status = ResponseStatus.SystemError
                });
            }
        }
Beispiel #58
0
        private void OnStartDownloadEpisodes(object sender, List <object> e)
        {
            try
            {
                foreach (Episode episode in e)
                {
                    if (episode != null)
                    {
                        //Download Torrent
                        _fileHandler.OpenStandardProgram(episode.Link, false);

                        // Wait for successful download
                        // Thread.Sleep(1000);
                        //Change into magnet link and start downloading
                        // _fileHandler.OpenStandardProgram(GetMagnetLink(LocalConfig.DownloadFolder + FileNameParser.TorrentNameParser(episode.Link)), false);

                        episode.DownloadDate = DateTime.Now;
                        if (LocalTvShows.Any(tvShow => tvShow.Name.Equals(episode.Name)))
                        {
                            TvShow localTvShow = LocalTvShows.SingleOrDefault(tvShow => tvShow.Name.Equals(episode.Name));
                            if (localTvShow != null &&
                                localTvShow.Episodes.Any(ep => ep.EpisodeNumber.Equals(episode.EpisodeNumber)))
                            {
                                Episode localEpisode =
                                    localTvShow.Episodes.SingleOrDefault(ep =>
                                                                         ep.EpisodeNumber.Equals(episode.EpisodeNumber));
                                if (localEpisode != null)
                                {
                                    localTvShow.LatestDownload = episode.DownloadDate;
                                    localEpisode.DownloadDate  = episode.DownloadDate;
                                    _dbHandler.UpdateEpisode(null, localEpisode);
                                }
                            }
                            else if (localTvShow != null)
                            {
                                localTvShow.LatestDownload = episode.DownloadDate;
                                localTvShow.Episodes.Add(episode);
                                _dbHandler.UpdateTvShow(null, localTvShow);
                            }
                        }
                        else
                        {
                            TvShow newTvShow = new TvShow()
                            {
                                Name     = episode.Name,
                                Episodes = new List <Episode>()
                                {
                                    episode
                                }
                            };
                            newTvShow.LatestDownload = episode.DownloadDate;
                            _dbHandler.AddTvShow(newTvShow, true);
                        }
                    }
                    Thread.Sleep(10);
                }
                _controller.RefreshData();
            }
            catch (Exception ex)
            {
                LogHandler.WriteSystemLog("OnStartDownloadEpisodes: " + ex, LogLevel.Error);
            }
        }
        /// <summary>
        /// Создать общий список эпизодов в каждом сезоне фильма (Южный Парк)
        /// </summary>
        /// <param name="film">Фильм</param>
        /// <param name="wvm">Индикатор прогресса загрузки</param>
        /// <param name="stopwatch">Таймер</param>
        private static async Task CreateSPEpisodes(Film film, WaitViewModel wvm, Stopwatch stopwatch)
        {
            var episodes = new List <Episode>();

            wvm.CurrentLoadingStatus = LoadingStatus.CreatingEpisodes;
            if (await GetCancelCreateEpisodesResult(episodes))
            {
                return;
            }
            var seasons = await GetSeasonsByFilm(film, wvm, stopwatch);

            var seasonEpisodes = await Task.Run(() => seasons.SelectMany(s => s.Episodes).ToList());

            var totalEpisodesCount = await Task.Run(() => seasons.Sum(season => GetSPEpisodesCount(season.Number)));

            wvm.MaxPercentValue += totalEpisodesCount;
            UpdateOperationTime(wvm, stopwatch);

            foreach (var season in seasons)
            {
                if (await GetCancelCreateEpisodesResult(episodes))
                {
                    return;
                }

                wvm.CurrentSeasonValue++;
                wvm.CurrentPercentValue++;

                var episodesCount = GetSPEpisodesCount(season.Number);
                wvm.ResetCurrentLoadingData(true);
                wvm.MaxEpisodeValue = episodesCount;

                for (var j = 0; j < episodesCount; j++)
                {
                    if (await GetCancelCreateEpisodesResult(episodes))
                    {
                        return;
                    }

                    wvm.CurrentEpisodeValue++;
                    wvm.CurrentPercentValue++;
                    var epNum     = j + 1;
                    var epFullNum = season.Number * 100 + epNum;

                    if (seasonEpisodes.Any(e => e.FullNumber == epFullNum))
                    {
                        continue;
                    }

                    var newEpisode = new Episode
                    {
                        Name        = $"Episode {epNum} of {season.Number} season",
                        Description = $"Description of {epNum} episode of {season.Number} season",
                        Number      = epNum,
                        Season      = season,
                        Film        = film
                    };

                    episodes.Add(newEpisode);
                    UpdateOperationTime(wvm, stopwatch);
                }
            }

            if (episodes.Count > 0)
            {
                await Task.Run(() => InsertEntityListToDb(episodes));
            }
        }
Beispiel #60
0
 /// <summary>
 /// Retrieve a hero by a particular Star Wars episode.
 /// </summary>
 /// <param name="episode">The episode to look up by.</param>
 /// <param name="repository"></param>
 /// <returns>The character.</returns>
 public ICharacter GetHero(
     Episode episode,
     [Service] ICharacterRepository repository) =>
 repository.GetHero(episode);