public static BitmapImage ComposerToThumbnail(Composer composer)
        {
            var thumbnail = (BitmapImage)null;

            if (_thumbnailCache.TryGetValue(composer.ComposerId, out thumbnail))
            {
                return _thumbnailCache[composer.ComposerId];
            }

            var directoryPath = $@"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.Create)}\Music Timeline\Resources\Thumbnails\";

            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            var thumbnailPath = $@"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.Create)}\Music Timeline\Resources\Thumbnails\{composer.ComposerId}.jpg";
            var thumbnailUri = new Uri(thumbnailPath, UriKind.Absolute);

            if (File.Exists(thumbnailPath))
            {
                thumbnail = new BitmapImage();
                thumbnail.BeginInit();
                thumbnail.DecodePixelHeight = 50;
                thumbnail.StreamSource = new MemoryStream(File.ReadAllBytes(thumbnailPath));
                thumbnail.EndInit();
                thumbnail.Freeze();

                _thumbnailCache[composer.ComposerId] = thumbnail;

                return thumbnail;
            }

            return CreateThumbnail(composer);
        }
 public ComposerEventViewModel(string label, ExtendedDateTimeInterval dates, Composer composer, Brush background, Brush foreground, IEnumerable<ComposerEraViewModel> eras, ICommand clickCommand)
 {
     _dates = dates;
     _composer = composer;
     _background = background;
     _foreground = foreground;
     _label = label;
     _eras = eras;
     _clickCommand = clickCommand;
 }
        private static BitmapImage CreateThumbnail(Composer composer)
        {
            BitmapImage thumbnail = null;
            var thumbnailPath = $@"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.Create)}\Music Timeline\Resources\Thumbnails\{composer.ComposerId}.jpg";
            var context = new ClassicalMusicContext(new Uri("http://www.harrenstein.com/ClassicalMusic/ClassicalMusic.svc"));
            var image = context.Execute<ComposerImage>(new Uri($"http://www.harrenstein.com/ClassicalMusic/ClassicalMusic.svc/Composers({composer.ComposerId})/ComposerImages")).Select(c => c.Bytes).FirstOrDefault();

            if (image != null)
            {
                thumbnail = new BitmapImage();
                thumbnail.CacheOption = BitmapCacheOption.None;
                thumbnail.BeginInit();
                thumbnail.DecodePixelHeight = 40;
                thumbnail.StreamSource = new MemoryStream(image);
                thumbnail.EndInit();
                thumbnail.Freeze();

                var encoder = new JpegBitmapEncoder();
                encoder.QualityLevel = 60;
                encoder.Frames.Add(BitmapFrame.Create(thumbnail));

                using (var stream = new FileStream(thumbnailPath, FileMode.Create))
                {
                    encoder.Save(stream);
                }

                _thumbnailCache[composer.ComposerId] = thumbnail;

                return thumbnail;
            }
            else if (!_thumbnailCache.TryGetValue(0, out thumbnail))
            {
                thumbnailPath = $@"pack://application:,,,/Resources/Composers/Unknown.jpg";
                var thumbnailUri = new Uri(thumbnailPath, UriKind.Absolute);

                thumbnail = new BitmapImage(thumbnailUri);

                _thumbnailCache[0] = thumbnail;

                return thumbnail;
            }
            else
            {
                return thumbnail;
            }
        }
        private async Task LoadComposerAsync()
        {
            _loadingCancellationTokenSource = new CancellationTokenSource();

            if (ProgressBar.Visibility == Visibility.Collapsed)
            {
                ProgressBar.Visibility = Visibility.Visible;
            }

            var composerId = (int)Application.Current.Properties["SelectedComposer"];

            var composerUri = new Uri($"http://www.harrenstein.com/ClassicalMusic/ClassicalMusic.svc/Composers?$filter=ComposerId eq {composerId}&$expand=Details,Details/BirthLocation,Details/DeathLocation,Nationalities,Influences,Influenced,Links");
            var composerQuery = await _classicalMusicContext.ExecuteAsync<Composer>(composerUri, null);

            _composer = composerQuery.First();

            ComposerNameTextBlock.Text = NameUtility.ToFirstLast(_composer.Name);

            if (_composer.Details != null)
            {
                if (_composer.Details.BirthLocation != null)
                {
                    BornTextBlock.Text = $"{ExtendedDateTimeInterval.Parse(_composer.Dates).Start}; {_composer.Details.BirthLocation.Name}";
                }
                else
                {
                    BornTextBlock.Text = ExtendedDateTimeInterval.Parse(_composer.Dates).Start.ToString();
                }

                var deathLocation = _composer.Details.DeathLocation;

                if (deathLocation != null)
                {
                    DiedTextBlock.Text = $"{ExtendedDateTimeInterval.Parse(_composer.Dates).End}; {deathLocation.Name}";
                }
                else
                {
                    DiedTextBlock.Text = ExtendedDateTimeInterval.Parse(_composer.Dates).End.ToString();
                }

                if (!string.IsNullOrEmpty(_composer.Details.Biography))
                {
                    var parserContext = new ParserContext();
                    parserContext.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
                    parserContext.XmlSpace = "preserve";

                    var flowDocument = (FlowDocument)XamlReader.Load(new MemoryStream(Encoding.UTF8.GetBytes(_composer.Details.Biography)), parserContext);

                    if (flowDocument != null)
                    {
                        flowDocument.FontFamily = new FontFamily("Cambria");
                        flowDocument.PagePadding = new Thickness(0, 5, 0, 0);
                        flowDocument.TextAlignment = TextAlignment.Left;

                        FlowDocumentScrollViewer.Document = flowDocument;
                    }
                }
            }

            ComposerFlagsItemsControl.ItemsSource = _composer.Nationalities;

            InfluencesItemsControl.ItemsSource = _composer.Influences;

            var influencesVisibility = _composer.Influences.Count > 0 ? Visibility.Visible : Visibility.Collapsed;

            InfluencesItemsControl.Visibility = influencesVisibility;
            InfluencesTextBlock.Visibility = influencesVisibility;
            InfluencesUnderline.Visibility = influencesVisibility;

            InfluencedItemsControl.ItemsSource = _composer.Influenced;

            var influencedVisibility = _composer.Influenced.Count > 0 ? Visibility.Visible : Visibility.Collapsed;

            InfluencedItemsControl.Visibility = influencedVisibility;
            InfluencedTextBlock.Visibility = influencedVisibility;
            InfluencedUnderline.Visibility = influencedVisibility;

            LinksItemControl.ItemsSource = _composer.Links;

            var linksVisibility = _composer.Links.Count > 0 ? Visibility.Visible : Visibility.Collapsed;

            LinksItemControl.Visibility = linksVisibility;
            LinksTextBlock.Visibility = linksVisibility;
            LinksUnderline.Visibility = linksVisibility;

            var composerImagesQuery = await _classicalMusicContext.LoadPropertyAsync(_composer, "ComposerImages");
            var composerImages = composerImagesQuery.Cast<ComposerImage>().ToList();

            if (composerImages.Count == 0)
            {
                ComposerImagesListBox.ItemsSource = new ComposerImage[] { GetDefaultComposerImage() };
            }
            else
            {
                ComposerImagesListBox.ItemsSource = composerImages;
            }

            ComposerImagesListBox.SelectedIndex = 0;

            var compositionsUri = new Uri($"http://www.harrenstein.com/ClassicalMusic/ClassicalMusic.svc/Compositions?$filter=Composers/any(d:d/Name eq '{_composer.Name}')&$expand=Genre,Key,Movements");

            var genresQuery = await _classicalMusicContext.ExecuteAsync<Composition>(compositionsUri, null);
            var genres = genresQuery.GroupBy(c => c.Genre == null ? "Unknown" : c.Genre.Name)
                .OrderBy(s => s.Key);

            TreeView.SetBinding(ItemsControl.ItemsSourceProperty, BindingBuilder.Build(genres));

            var samplesQuery = await _classicalMusicContext.LoadPropertyAsync(_composer, "Samples");
            var samples = samplesQuery.Cast<Sample>();

            foreach (var sample in samples)
            {
                var mp3FileReader = new Mp3FileReader(new MemoryStream(sample.Bytes));

                _sampleDictionary[mp3FileReader] = sample;
                _mp3Player.AddToPlaylist(mp3FileReader);

                if (_sampleDictionary.Count == 1)
                {
                    _mp3Player.Play();
                }
            }

            ProgressBar.Visibility = Visibility.Collapsed;
        }
示例#5
0
        public async static Task ScrapeCompositionsPageAsync(string url, Composer composer, ClassicalMusicContext classicalMusicContext, IProgress<double> progress = null, CancellationToken? cancellationToken = null)
        {
            var webClient = new WebClient();
            var htmlSource = await webClient.DownloadStringTaskAsync(new Uri(url));

            var htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(htmlSource);

            var tables = htmlDocument.DocumentNode.Descendants("table");
            var table = tables.FirstOrDefault(n =>
            {
                var classAttribute = n.Attributes["class"];

                if (classAttribute == null || classAttribute.Value != "wv")
                {
                    return false;
                }

                return true;
            });

            if (table == null)
            {
                return;
            }

            var tableRows = table.Elements("tr").ToArray();
            var increment = 1d;

            foreach (var tableRow in tableRows)
            {
                if (cancellationToken != null && cancellationToken.Value.IsCancellationRequested)
                {
                    return;
                }

                var tableDatas = tableRow.Elements("td").ToArray();

                var nameTableData = tableDatas[1];
                var compositionName = HtmlEntity.DeEntitize(nameTableData.InnerText);

                var compositionAnchor = nameTableData.Element("a");
                var hypertextReference = (HtmlAttribute)null;

                var composition = (Composition)null;

                if (compositionAnchor != null)
                {
                    hypertextReference = compositionAnchor.Attributes["href"];

                    if (hypertextReference != null)
                    {
                        composition = composer.Compositions.FirstOrDefault(c => c.Links.Any(l => l.Url == $"http://www.klassika.info/{hypertextReference.Value}"));
                    }
                }

                var catalogTableData = tableDatas[2];
                var catalogString = HtmlEntity.DeEntitize(catalogTableData.InnerText);

                var dateTableData = tableDatas[4];
                var compositionDate = HtmlEntity.DeEntitize(dateTableData.InnerText);

                var genreTableData = tableDatas[6];
                var genreName = TranslateGenre(HtmlEntity.DeEntitize(genreTableData.InnerText).Replace("(", "").Replace(")", ""));

                if (composition == null)
                {
                    composition = new Composition();
                    composition.Name = compositionName;
                    composition.Composers = new DataServiceCollection<Composer> { composer };
                    composition.Dates = compositionDate == "?" ? null : compositionDate;

                    composer.Compositions.Add(composition);
                }

                var catalogNumberString = (string)null;
                var compositionCatalogString = (string)null;

                if (!string.IsNullOrWhiteSpace(genreName))
                {
                    var genre = classicalMusicContext.Genres.FirstOrDefault(ct => ct.Name == genreName);

                    if (genre == null)
                    {
                        genre = new Genre();
                        genre.Name = genreName;
                        genre.Compositions.Add(composition);

                        classicalMusicContext.Genres.Add(genre);
                    }

                    if (composition.Genre == null)
                    {
                        composition.Genre = genre;
                    }
                }

                if (!string.IsNullOrWhiteSpace(catalogString))
                {
                    var catalogParts = catalogString.Split(new char[] { ' ' }, 2);

                    if (catalogParts.Length == 2)
                    {
                        compositionCatalogString = catalogParts[0];
                        catalogNumberString = catalogParts[1];

                        var catalog = composer.Catalogs.FirstOrDefault(cc => cc.Prefix == compositionCatalogString);

                        if (catalog == null)
                        {
                            catalog = new Catalog();
                            catalog.Prefix = compositionCatalogString;
                            catalog.Composer = composer;

                            composer.Catalogs.Add(catalog);
                        }

                        var catalogNumber = catalog.CatalogNumbers.FirstOrDefault(cn => cn.Value == catalogNumberString);

                        if (catalogNumber == null)
                        {
                            catalogNumber = new CatalogNumber();
                            catalogNumber.Catalog = catalog;
                            catalogNumber.Compositions.Add(composition);
                            catalogNumber.Value = catalogNumberString;

                            catalog.CatalogNumbers.Add(catalogNumber);
                        }
                    }
                }

                if (hypertextReference != null)
                {
                    await ScrapeCompositionDetailPageAsync($"http://www.klassika.info/{hypertextReference.Value}", composition, classicalMusicContext);
                }

                if (progress != null)
                {
                    progress.Report(increment++ / (double)tableRows.Length);
                }

#if DEBUG
                Debug.WriteLine(composition.Name);
#endif
            }
        }
示例#6
0
        public async static Task ScrapeComposerDetailPageAsync(string url, Composer composer, ClassicalMusicContext classicalMusicContext, IProgress<double> progress = null, CancellationToken? cancellationToken = null)
        {
            var composerLink = composer.Links.FirstOrDefault(l => l.Url.Contains("klassika.info"));

            if (composerLink == null)
            {
                composerLink = new Link();
                composerLink.Composers.Add(composer);
                composerLink.Url = url;

                composer.Links.Add(composerLink);
            }

            var urlParts = url.Split('/');

            if (urlParts.Length < 2)
            {
                return;
            }

            var composerKey = urlParts.ElementAt(urlParts.Length - 2);

            await ScrapeCompositionsPageAsync($"http://www.klassika.info/Komponisten/{composerKey}/wv_abc.html", composer, classicalMusicContext, progress, cancellationToken);
        }
示例#7
0
        public async static Task ScrapeComposersPageAsync(ClassicalMusicContext classicalMusicContext)
        {
            for (char c = 'A'; c <= 'Z'; c++)
            {
                var webClient = new WebClient();
                var htmlSource = await webClient.DownloadStringTaskAsync(new Uri($"http://www.klassika.info/Komponisten/lindex_{c}.html"));

                var htmlDocument = new HtmlDocument();
                htmlDocument.LoadHtml(htmlSource);

                var column1 = htmlDocument.GetElementbyId("personen_s1v3");
                var column2 = htmlDocument.GetElementbyId("personen_s2v3");

                var column1Anchors = column1.Elements("a");
                var column2Anchors = column2.Elements("a");

                var anchors = column1Anchors.Concat(column2Anchors);

                foreach (var anchor in anchors)
                {
                    var hypertextReference = anchor.Attributes["href"];

                    if (hypertextReference == null)
                    {
                        continue;
                    }

                    var composerNameAndDate = HtmlEntity.DeEntitize(anchor.InnerText);
                    var composerNameAndDateParts = composerNameAndDate.Split(new string[] { " (" }, 2, StringSplitOptions.None);
                    var composerName = composerNameAndDateParts.Length == 2 ? composerNameAndDateParts[0] : composerNameAndDate;
                    var composer = classicalMusicContext.Composers.FirstOrDefault(co => co.Name == composerName);

                    if (composer == null)
                    {
                        composer = new Composer();
                        composer.Name = composerName;

                        classicalMusicContext.Composers.Add(composer);
                    }

                    await ScrapeComposerDetailPageAsync($"http://www.klassika.info/{hypertextReference.Value}", composer, classicalMusicContext);
                }
            }

            classicalMusicContext.SaveChanges();
        }
        public static void ScrapeComposer(string url, Composer composer, ClassicalMusicContext dbContext)
        {
            if (url == null)
            {
                return;
            }

            var urlParts = url.Split('#');

            if (urlParts.Length != 2)
            {
                return;
            }

            string source = null;

            using (var webClient = new WebClient())
            {
                webClient.Proxy = null;

                try
                {
                    source = webClient.DownloadString(url);
                }
                catch (WebException e)
                {
                    MessageBox.Show(e.Message);

                    return;
                }
            }

            var htmlSegments = source.Split(new string[] { "<p>" }, StringSplitOptions.RemoveEmptyEntries);

            var composerHtmlSegment = htmlSegments.FirstOrDefault(s => s.Contains($"name=\"{urlParts[1]}\""));

            if (composerHtmlSegment == null)
            {
                return;
            }

            var hasInfluencedSplit = composerHtmlSegment.Split(new string[] { "instruc1.htm#e9" }, StringSplitOptions.RemoveEmptyEntries);

            if (hasInfluencedSplit.Length > 1)
            {
                var influencedComposerUrls = Regex.Matches(hasInfluencedSplit[1], "(?<=href=\").*?(?=\")").OfType<Match>().Select(m => "http://people.wku.edu/charles.smith/music/" + m.Value);

                foreach (var influencedComposerUrl in influencedComposerUrls)
                {
                    var influencedComposerLink = dbContext.Links.Where(l => l.Url == influencedComposerUrl).FirstOrDefault();

                    if (influencedComposerLink == null)
                    {
                        continue;
                    }

                    var influencedComposer = influencedComposerLink.Composers.FirstOrDefault();

                    if (!composer.Influenced.Contains(influencedComposer))
                    {
                        composer.Influenced.Add(influencedComposer);
                        influencedComposer.Influences.Add(composer);
                    }
                }
            }

            var influencesSplit = hasInfluencedSplit[0].Split(new string[] { "instruc1.htm#e8" }, StringSplitOptions.RemoveEmptyEntries);

            if (influencesSplit.Length > 1)
            {
                var influenceComposerUrls = Regex.Matches(influencesSplit[1], "(?<=href=\").*?(?=\")").OfType<Match>().Select(m => "http://people.wku.edu/charles.smith/music/" + m.Value);

                foreach (var influenceComposerUrl in influenceComposerUrls)
                {
                    var influenceComposerLink = dbContext.Links.Where(l => l.Url == influenceComposerUrl).FirstOrDefault();

                    if (influenceComposerLink == null)
                    {
                        continue;
                    }

                    var influenceComposer = influenceComposerLink.Composers.FirstOrDefault();

                    if (!composer.Influences.Contains(influenceComposer))
                    {
                        composer.Influences.Add(influenceComposer);
                        influenceComposer.Influenced.Add(composer);
                    }
                }
            }
        }