Exemplo n.º 1
0
        public Task <OperationResult <IEnumerable <ArtistSearchResult> > > PerformArtistSearch(string query, int resultsCount)
        {
            if (string.IsNullOrEmpty(query) || resultsCount == 0)
            {
                return(Task.FromResult(new OperationResult <IEnumerable <ArtistSearchResult> >()));
            }
            var tcs     = new TaskCompletionSource <OperationResult <IEnumerable <ArtistSearchResult> > >();
            var client  = new RestClient("https://en.wikipedia.org/w/api.php?format=xml&action=query&redirects=1&prop=extracts&exintro=&explaintext=&titles=" + HttpEncoder.UrlEncode(query ?? string.Empty));
            var request = new RestRequest(Method.GET);

            client.ExecuteAsync <api>(request, response =>
            {
                ArtistSearchResult data = null;
                if (response?.Data?.query?.pages?.Any() ?? false)
                {
                    var bio = response?.Data?.query?.pages.FirstOrDefault()?.extract;
                    if (bio != null)
                    {
                        data = new ArtistSearchResult
                        {
                            Bio = response.Data.query.pages.First().extract
                        };
                    }
                }
                tcs.SetResult(new OperationResult <IEnumerable <ArtistSearchResult> >
                {
                    IsSuccess = data != null,
                    Data      = data != null ? new[] { data } : null
                });
            });
            return(tcs.Task);
        }
Exemplo n.º 2
0
        public async Task <OperationResult <IEnumerable <ArtistSearchResult> > > PerformArtistSearch(string query, int resultsCount)
        {
            ArtistSearchResult data = null;

            try
            {
                this.Logger.LogTrace("SpotifyHelper:PerformArtistSearch:{0}", query);
                var request = this.BuildSearchRequest(query, 1, "artist");

                var client = new RestClient("http://api.spotify.com/v1");
                client.UserAgent = WebHelper.UserAgent;

                var response = await client.ExecuteTaskAsync <SpotifyResult>(request);

                if (response.ResponseStatus == ResponseStatus.Error)
                {
                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        throw new AuthenticationException("Unauthorized");
                    }
                    throw new Exception(string.Format("Request Error Message: {0}. Content: {1}.", response.ErrorMessage, response.Content));
                }
                Item spotifyArtist = null;
                if (response.Data != null && response.Data.artists != null && response.Data.artists.items != null)
                {
                    spotifyArtist = response.Data.artists.items.FirstOrDefault(x => x.name.Equals(query, StringComparison.OrdinalIgnoreCase));
                }
                if (spotifyArtist == null)
                {
                    return(new OperationResult <IEnumerable <ArtistSearchResult> >());
                }
                data = new ArtistSearchResult
                {
                    ArtistName = spotifyArtist.name,
                    ArtistType = spotifyArtist.type,
                    SpotifyId  = spotifyArtist.id
                };
                if (spotifyArtist.images != null)
                {
                    data.ImageUrls = spotifyArtist.images.OrderByDescending(x => x.height).Take(1).Select(x => x.url).ToList();
                }
                if (spotifyArtist.genres != null)
                {
                    data.ArtistGenres = spotifyArtist.genres.Select(x => x).ToList();
                }
                if (spotifyArtist.external_urls != null)
                {
                    data.Urls = new string[] { spotifyArtist.external_urls.spotify };
                }
            }
            catch (Exception ex)
            {
                this.Logger.LogError(ex);
            }
            return(new OperationResult <IEnumerable <ArtistSearchResult> >
            {
                IsSuccess = data != null,
                Data = new ArtistSearchResult[] { data }
            });
        }
Exemplo n.º 3
0
        public async Task <OperationResult <IEnumerable <ArtistSearchResult> > > PerformArtistSearch(string query, int resultsCount)
        {
            ArtistSearchResult data = null;

            try
            {
                var request  = BuildRequest(query, 1, "musicArtist");
                var response = await _client.ExecuteAsync <ITunesSearchResult>(request);

                if (response.ResponseStatus == ResponseStatus.Error)
                {
                    if (response.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        throw new AuthenticationException("Unauthorized");
                    }
                    throw new Exception(string.Format("Request Error Message: {0}. Content: {1}.",
                                                      response.ErrorMessage, response.Content));
                }

                var responseData = response?.Data?.results?.FirstOrDefault();
                if (responseData != null)
                {
                    var urls = new List <string>();
                    if (!string.IsNullOrEmpty(responseData.artistLinkUrl))
                    {
                        urls.Add(responseData.artistLinkUrl);
                    }
                    if (!string.IsNullOrEmpty(responseData.artistViewUrl))
                    {
                        urls.Add(responseData.artistViewUrl);
                    }
                    if (!string.IsNullOrEmpty(responseData.collectionViewUrl))
                    {
                        urls.Add(responseData.collectionViewUrl);
                    }
                    data = new ArtistSearchResult
                    {
                        ArtistName         = responseData.artistName,
                        iTunesId           = responseData.artistId.ToString(),
                        AmgId              = responseData.amgArtistId.ToString(),
                        ArtistType         = responseData.artistType,
                        ArtistThumbnailUrl = responseData.artworkUrl100,
                        ArtistGenres       = new[] { responseData.primaryGenreName },
                        Urls = urls
                    };
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }

            return(new OperationResult <IEnumerable <ArtistSearchResult> >
            {
                IsSuccess = data != null,
                Data = new[] { data }
            });
        }
Exemplo n.º 4
0
        /// <summary>
        /// Searches for artists with the <see cref="SearchText"/>.
        /// </summary>
        /// <returns>Task.</returns>
        private async Task SearchArtists()
        {
            EnableControls = false;

            try
            {
                OnStatusUpdated(string.Format("Searching for artist '{0}'", SearchText));
                ArtistSearchResult asr = null;
                await Task.Run(() => asr = _setlistFMClient.FindArtists(new ArtistSearchOptions()
                {
                    Name = SearchText, Page = ArtistResultPage
                }));

                if (asr != null)
                {
                    ObservableCollection <FetchedArtistViewModel> vms = new ObservableCollection <FetchedArtistViewModel>();
                    foreach (var artist in asr.Artists)
                    {
                        Uri imgUri   = null;
                        var response = await MainViewModel.Client.Artist.GetInfoAsync(artist.Name);

                        if (response.Success)
                        {
                            imgUri = response.Content.MainImage.ExtraLarge;
                        }

                        FetchedArtistViewModel vm = new FetchedArtistViewModel(new Models.Artist(artist.Name, artist.MbId, imgUri));
                        vm.ArtistClicked += ArtistClicked;
                        vms.Add(vm);
                    }

                    if (vms.Count > 0)
                    {
                        FetchedArtists = new ObservableCollection <FetchedArtistViewModel>(vms);
                        CurrentView    = _artistResultView;
                        OnStatusUpdated("Successfully fetched artists");
                    }
                    else
                    {
                        OnStatusUpdated("Found no artists");
                    }
                }
                else
                {
                    OnStatusUpdated("Found no artists");
                }
            }
            catch (Exception ex)
            {
                OnStatusUpdated("Fatal error while searching for artist: " + ex.Message);
            }
            finally
            {
                EnableControls = true;
            }
        }
Exemplo n.º 5
0
        public async Task <OperationResult <IEnumerable <ArtistSearchResult> > > PerformArtistSearch(string query, int resultsCount)
        {
            ArtistSearchResult result = null;

            Logger.LogTrace("MusicBrainzProvider:PerformArtistSearch:{0}", query);
            var a = await Repository.ArtistByName(query, resultsCount);

            if (a != null)
            {
                var imageUrls       = a.relations?.Where(x => x.type.Equals("image", StringComparison.OrdinalIgnoreCase)).Select(x => x.url.resource).Distinct().ToArray();
                var notImageUrls    = a.relations?.Where(x => !x.type.Equals("image", StringComparison.OrdinalIgnoreCase)).Select(x => x.url.resource).Distinct().ToArray();
                var discogRelation  = a.relations?.FirstOrDefault(x => x.type.Equals("discogs", StringComparison.OrdinalIgnoreCase));
                var discogId        = discogRelation?.url?.resource?.LastSegmentInUrl();
                var amgRelation     = a.relations?.FirstOrDefault(x => x.type.Equals("allmusic", StringComparison.OrdinalIgnoreCase));
                var amgId           = amgRelation?.url?.resource?.LastSegmentInUrl();
                var lastFmRelation  = a.relations?.FirstOrDefault(x => x.type.Equals("last.fm", StringComparison.OrdinalIgnoreCase));
                var lastFmId        = lastFmRelation?.url?.resource?.LastSegmentInUrl();
                var iTunesRelation  = a.relations?.FirstOrDefault(x => x.url?.resource?.StartsWith("https://itunes.apple.com/") ?? false);
                var iTunesId        = iTunesRelation?.url?.resource?.LastSegmentInUrl();
                var spotifyRelation = a.relations?.FirstOrDefault(x => x.url?.resource?.StartsWith("https://open.spotify.com/artist/") ?? false);
                var spotifyId       = spotifyRelation?.url?.resource?.LastSegmentInUrl();
                result = new ArtistSearchResult
                {
                    ArtistName     = a.name,
                    ArtistSortName = a.sortname,
                    MusicBrainzId  = a.id,
                    ArtistType     = a.type,
                    ArtistGenres   = a.genres?.Select(x => x.name).ToArray(),
                    AlternateNames = a.aliases?.Select(x => x.name).Distinct().ToArray(),
                    ArtistRealName = a.aliases?.FirstOrDefault(x => x.type == "Legal name")?.name,
                    BeginDate      = (a.type ?? string.Empty) == "group" ? SafeParser.ToDateTime(a.lifespan?.begin) : null,
                    BirthDate      = (a.type ?? string.Empty) == "group" ? null : SafeParser.ToDateTime(a.lifespan?.begin),
                    ImageUrls      = imageUrls,
                    Urls           = notImageUrls,
                    LastFMId       = lastFmId,
                    AmgId          = amgId,
                    iTunesId       = iTunesId,
                    DiscogsId      = discogId,
                    SpotifyId      = spotifyId,
                    EndDate        = SafeParser.ToDateTime(a.lifespan?.end),
                    Tags           = a.tags?.Select(x => x.name).Distinct().ToArray(),
                    IPIs           = a.ipis,
                    ISNIs          = a.isnilist?.Select(x => x.isni).ToArray()
                };
                Logger.LogTrace($"MusicBrainzArtist: ArtistName [{ query }], MbId [{ result.MusicBrainzId }], DiscogId [{ result.DiscogsId }], LastFMId [{ result.LastFMId }], AmgId [{ result.AmgId }], Itunes [{ result.iTunesId }], Spotify [{ result.SpotifyId }]");
            }
            else
            {
                Logger.LogTrace("MusicBrainzArtist: ArtistName [{0}], No MusicBrainz Artist Found", query);
            }
            return(new OperationResult <IEnumerable <ArtistSearchResult> >
            {
                IsSuccess = result != null,
                Data = new[] { result }
            });
        }
Exemplo n.º 6
0
        /// <summary>
        /// 从云端API获取艺术家列表
        /// </summary>
        /// <param name="art">艺术家名</param>
        /// <returns>无</returns>
        private async Task GetArtistsAsync(string art)
        {
            ArtistSearchResult Result = await NetEaseMusic.SearchAsync <ArtistSearchResult>(art, 30, 0, NeteaseMusicAPI.SearchType.Artist);

            if (Result.result.artists == null)
            {
                return;
            }
            SingerList.Clear();
            foreach (var item in Result.result.artists)
            {
                SingerList.Add(new SearchSinger(item.name, new Uri(item.img1v1Url), item.id));
            }
        }
Exemplo n.º 7
0
        public async Task <OperationResult <IEnumerable <ArtistSearchResult> > > PerformArtistSearch(string query, int resultsCount)
        {
            try
            {
                var cacheKey = $"uri:lastfm:artistsearch:{ query.ToAlphanumericName() }";
                var data     = await CacheManager.GetAsync <ArtistSearchResult>(cacheKey, async() =>
                {
                    Logger.LogTrace("LastFmHelper:PerformArtistSearch:{0}", query);
                    var auth     = new LastAuth(ApiKey.Key, ApiKey.KeySecret);
                    var albumApi = new ArtistApi(auth);
                    var response = await albumApi.GetInfoAsync(query);
                    if (!response.Success)
                    {
                        return(null);
                    }
                    var lastFmArtist = response.Content;
                    var result       = new ArtistSearchResult
                    {
                        ArtistName    = lastFmArtist.Name,
                        LastFMId      = lastFmArtist.Id,
                        MusicBrainzId = lastFmArtist.Mbid,
                        Bio           = lastFmArtist.Bio != null ? lastFmArtist.Bio.Content : null
                    };
                    if (lastFmArtist.Tags != null)
                    {
                        result.Tags = lastFmArtist.Tags.Select(x => x.Name).ToList();
                    }
                    // No longer fetching/consuming images LastFm says is violation of ToS ; https://getsatisfaction.com/lastfm/topics/api-announcement-dac8oefw5vrxq
                    if (lastFmArtist.Url != null)
                    {
                        result.Urls = new[] { lastFmArtist.Url.ToString() };
                    }
                    return(result);
                }, "uri:metadata");

                return(new OperationResult <IEnumerable <ArtistSearchResult> >
                {
                    IsSuccess = data != null,
                    Data = new[] { data }
                });
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, ex.Serialize());
            }

            return(new OperationResult <IEnumerable <ArtistSearchResult> >());
        }
Exemplo n.º 8
0
        public async Task <OperationResult <IEnumerable <ArtistSearchResult> > > PerformArtistSearch(string query, int resultsCount)
        {
            try
            {
                this.Logger.LogTrace("LastFmHelper:PerformArtistSearch:{0}", query);
                var auth     = new LastAuth(this.ApiKey.Key, this.ApiKey.KeySecret);
                var albumApi = new ArtistApi(auth);
                var response = await albumApi.GetInfoAsync(query);

                if (!response.Success)
                {
                    return(new OperationResult <IEnumerable <ArtistSearchResult> >());
                }
                var lastFmArtist = response.Content;
                var result       = new ArtistSearchResult
                {
                    ArtistName    = lastFmArtist.Name,
                    LastFMId      = lastFmArtist.Id,
                    MusicBrainzId = lastFmArtist.Mbid,
                    Bio           = lastFmArtist.Bio != null ? lastFmArtist.Bio.Content : null
                };
                if (lastFmArtist.Tags != null)
                {
                    result.Tags = lastFmArtist.Tags.Select(x => x.Name).ToList();
                }
                if (lastFmArtist.MainImage != null && (lastFmArtist.MainImage.ExtraLarge != null || lastFmArtist.MainImage.Large != null))
                {
                    result.ArtistThumbnailUrl = (lastFmArtist.MainImage.ExtraLarge ?? lastFmArtist.MainImage.Large).ToString();
                }
                if (lastFmArtist.Url != null)
                {
                    result.Urls = new string[] { lastFmArtist.Url.ToString() };
                }
                return(new OperationResult <IEnumerable <ArtistSearchResult> >
                {
                    IsSuccess = response.Success,
                    Data = new List <ArtistSearchResult> {
                        result
                    }
                });
            }
            catch (Exception ex)
            {
                this.Logger.LogError(ex, ex.Serialize());
            }
            return(new OperationResult <IEnumerable <ArtistSearchResult> >());
        }
Exemplo n.º 9
0
        private ArtistSearchResult ReadArtistSearchResult(JObject source)
        {
            ArtistSearchResult artistResult = new ArtistSearchResult();

            foreach (var item in source)
            {
                switch (item.Key)
                {
                case "id":
                case "thumb":
                case "title":
                case "type":
                case "uri":
                case "resource_url":
                    break;

                default:
                    this.ThrowIfStrict("Unknown key: " + item.Key);
                    break;
                }
            }
            return(artistResult);
        }
Exemplo n.º 10
0
        public Task <OperationResult <IEnumerable <ArtistSearchResult> > > PerformArtistSearch(string query, int resultsCount)
        {
            var tcs     = new TaskCompletionSource <OperationResult <IEnumerable <ArtistSearchResult> > >();
            var client  = new RestClient("https://en.wikipedia.org/w/api.php?format=xml&action=query&redirects=1&prop=extracts&exintro=&explaintext=&titles=" + this.HttpEncoder.UrlEncode(query));
            var request = new RestRequest(Method.GET);

            client.ExecuteAsync <api>(request, (response) =>
            {
                ArtistSearchResult data = null;
                if (response != null && response.Data != null && response.Data.query != null && response.Data.query.pages != null)
                {
                    data = new ArtistSearchResult
                    {
                        Bio = response.Data.query.pages.First().extract
                    };
                }
                tcs.SetResult(new OperationResult <IEnumerable <ArtistSearchResult> >
                {
                    IsSuccess = data != null,
                    Data      = new ArtistSearchResult[] { data }
                });
            });
            return(tcs.Task);
        }
Exemplo n.º 11
0
        public async Task <OperationResult <IEnumerable <ReleaseSearchResult> > > PerformReleaseSearch(string artistName, string query, int resultsCount)
        {
            var artistResult = await this.PerformArtistSearch(artistName, resultsCount);

            if (!artistResult.IsSuccess)
            {
                return(new OperationResult <IEnumerable <ReleaseSearchResult> >());
            }
            try
            {
                var tcs     = new TaskCompletionSource <OperationResult <IEnumerable <ReleaseSearchResult> > >();
                var request = new RestRequest(Method.GET);

                ReleaseSearchResult result = null;

                var response = await this.AlbumsForArtist(artistResult.Data.First().SpotifyId);

                if (response != null && response.items != null)
                {
                    string foundByAlternateName = null;
                    var    spotifyAlbum         = response.items.FirstOrDefault(x => x.name.Trim().Equals(query.Trim(), StringComparison.OrdinalIgnoreCase));
                    if (spotifyAlbum == null)
                    {
                        // No Exact match see if one starts with and use the first one
                        spotifyAlbum = response.items.FirstOrDefault(x => x.name.Trim().StartsWith(query.Trim(), StringComparison.OrdinalIgnoreCase));
                        if (spotifyAlbum == null)
                        {
                            return(new OperationResult <IEnumerable <ReleaseSearchResult> >());
                        }
                        foundByAlternateName = spotifyAlbum.name;
                    }
                    var client      = new RestClient(string.Format("http://api.spotify.com/v1/albums/{0}", spotifyAlbum.id));
                    var albumResult = await client.ExecuteTaskAsync <AlbumResult>(request);

                    if (albumResult != null && albumResult.Data != null)
                    {
                        var sa         = albumResult.Data;
                        var resultTags = new List <string>();
                        var resultUrls = new List <string>();
                        if (sa.external_ids != null)
                        {
                            resultTags.Add("upc:" + sa.external_ids.upc);
                        }
                        result = new ReleaseSearchResult
                        {
                            ReleaseTitle   = !string.IsNullOrEmpty(foundByAlternateName) ? query.ToTitleCase(false) : sa.name,
                            ReleaseDate    = SafeParser.ToDateTime(sa.release_date),
                            ReleaseType    = sa.album_type,
                            SpotifyId      = sa.id,
                            Tags           = resultTags,
                            AlternateNames = !string.IsNullOrEmpty(foundByAlternateName) ? new string[] { foundByAlternateName } : null
                        };
                        if (sa.artists != null && sa.artists.FirstOrDefault() != null)
                        {
                            var saArtist = sa.artists.First();
                            result.Artist = new ArtistSearchResult
                            {
                                ArtistName = saArtist.name,
                                ArtistType = saArtist.type,
                                SpotifyId  = saArtist.id
                            };
                        }
                        if (sa.genres != null)
                        {
                            result.ReleaseGenres = sa.genres.ToList();
                        }
                        if (sa.external_urls != null)
                        {
                            resultUrls.Add(sa.external_urls.spotify);
                        }
                        if (sa.images != null)
                        {
                            result.ImageUrls = sa.images.OrderBy(x => x.width).Take(1).Select(x => x.url).ToList();
                        }
                        if (sa.tracks != null)
                        {
                            var releaseMediaCount = sa.tracks.items.Max(x => x.disc_number ?? 0);
                            var releaseMedias     = new List <ReleaseMediaSearchResult>();
                            for (short?i = 1; i <= releaseMediaCount; i++)
                            {
                                var releaseTracks = new List <TrackSearchResult>();
                                foreach (var saTrack in sa.tracks.items)
                                {
                                    ArtistSearchResult trackArtist = null;
                                    if (saTrack.artists != null && saTrack.artists.FirstOrDefault() != null)
                                    {
                                        var saTrackArtist = saTrack.artists.First();
                                        trackArtist = new ArtistSearchResult
                                        {
                                            ArtistName = saTrackArtist.name,
                                            SpotifyId  = saTrackArtist.id,
                                            ArtistType = saTrackArtist.type
                                        };
                                    }
                                    releaseTracks.Add(new TrackSearchResult
                                    {
                                        Artist      = !trackArtist.SpotifyId.Equals(trackArtist.SpotifyId) ? trackArtist : null,
                                        TrackNumber = saTrack.track_number,
                                        Title       = saTrack.name,
                                        SpotifyId   = saTrack.id,
                                        Urls        = new List <string> {
                                            saTrack.external_urls.spotify, saTrack.preview_url
                                        },
                                        Duration  = saTrack.duration_ms,
                                        TrackType = saTrack.type
                                    });
                                }
                                releaseMedias.Add(new ReleaseMediaSearchResult
                                {
                                    ReleaseMediaNumber = i,
                                    TrackCount         = (short)sa.tracks.items.Count(x => x.disc_number == i),
                                    Tracks             = releaseTracks
                                });
                            }
                            result.ReleaseMedia = releaseMedias;
                        }

                        result.Urls = resultUrls;
                    }
                }
                return(new OperationResult <IEnumerable <ReleaseSearchResult> >
                {
                    IsSuccess = result != null,
                    Data = new List <ReleaseSearchResult> {
                        result
                    }
                });
            }
            catch (Exception ex)
            {
                this.Logger.LogError(ex, ex.Serialize());
            }
            return(new OperationResult <IEnumerable <ReleaseSearchResult> >());
        }
Exemplo n.º 12
0
 private ArtistSearchResult ReadArtistSearchResult(JObject source)
 {
     ArtistSearchResult artistResult = new ArtistSearchResult();
     foreach (var item in source)
     {
         switch (item.Key)
         {
             case "id":
             case "thumb":
             case "title":
             case "type":
             case "uri":
             case "resource_url":
                 break;
             default:
                 this.ThrowIfStrict("Unknown key: " + item.Key);
                 break;
         }
     }
     return artistResult;
 }
Exemplo n.º 13
0
        public async Task <OperationResult <IEnumerable <ArtistSearchResult> > > PerformArtistSearch(string query, int resultsCount)
        {
            ArtistSearchResult data = null;

            try
            {
                var cacheKey = $"uri:discogs:artistsearch:{ query.ToAlphanumericName() }";
                data = await CacheManager.GetAsync <ArtistSearchResult>(cacheKey, async() =>
                {
                    Logger.LogTrace("DiscogsHelper:PerformArtistSearch:{0}", query);
                    var request = BuildSearchRequest(query, 1, "artist");

                    var client = new RestClient("https://api.discogs.com/database")
                    {
                        UserAgent = WebHelper.UserAgent
                    };

                    var response = await client.ExecuteAsync <DiscogsResult>(request);

                    if (response.ResponseStatus == ResponseStatus.Error)
                    {
                        if (response.StatusCode == HttpStatusCode.Unauthorized)
                        {
                            throw new AuthenticationException("Unauthorized");
                        }
                        throw new Exception(string.Format("Request Error Message: {0}. Content: {1}.", response.ErrorMessage, response.Content));
                    }

                    var responseData = response.Data.results != null && response.Data.results.Any()
                        ? response.Data.results.First()
                        : null;
                    if (responseData != null)
                    {
                        request = BuildArtistRequest(responseData.id);
                        var c2  = new RestClient("https://api.discogs.com/")
                        {
                            UserAgent = WebHelper.UserAgent
                        };
                        var artistResponse = await c2.ExecuteTaskAsync <DiscogArtistResponse>(request);
                        var artist         = artistResponse.Data;
                        if (artist != null)
                        {
                            var urls                  = new List <string>();
                            var images                = new List <string>();
                            var alternateNames        = new List <string>();
                            string artistThumbnailUrl = null;
                            urls.Add(artist.uri);
                            if (artist.urls != null)
                            {
                                urls.AddRange(artist.urls);
                            }
                            if (artist.images != null)
                            {
                                images.AddRange(artist.images.Where(x => x.type != "primary").Select(x => x.uri));
                                var primaryImage = artist.images.FirstOrDefault(x => x.type == "primary");
                                if (primaryImage != null)
                                {
                                    artistThumbnailUrl = primaryImage.uri;
                                }
                                if (string.IsNullOrEmpty(artistThumbnailUrl))
                                {
                                    artistThumbnailUrl = artist.images.First(x => !string.IsNullOrEmpty(x.uri)).uri;
                                }
                            }
                            if (artist.namevariations != null)
                            {
                                alternateNames.AddRange(artist.namevariations.Distinct());
                            }
                            return(new ArtistSearchResult
                            {
                                ArtistName = artist.name,
                                DiscogsId = artist.id.ToString(),
                                ArtistType = responseData.type,
                                Profile = artist.profile,
                                AlternateNames = alternateNames,
                                ArtistThumbnailUrl = artistThumbnailUrl,
                                Urls = urls,
                                ImageUrls = images
                            });
                        }
                    }
                    return(null);
                }, "uri:metadata");
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }

            return(new OperationResult <IEnumerable <ArtistSearchResult> >
            {
                IsSuccess = data != null,
                Data = new[] { data }
            });
        }
Exemplo n.º 14
0
        public async Task <OperationResult <IEnumerable <ArtistSearchResult> > > PerformArtistSearch(string query, int resultsCount)
        {
            ArtistSearchResult result = null;

            try
            {
                this.Logger.LogTrace("MusicBrainzProvider:PerformArtistSearch:{0}", query);
                // Find the Artist
                var artistCacheKey = string.Format("uri:musicbrainz:ArtistSearchResult:{0}", query);
                result = this.CacheManager.Get <ArtistSearchResult>(artistCacheKey);
                if (result == null)
                {
                    ArtistResult artistResult = null;
                    try
                    {
                        artistResult = await MusicBrainzRequestHelper.GetAsync <ArtistResult>(MusicBrainzRequestHelper.CreateSearchTemplate("artist", query, resultsCount, 0));
                    }
                    catch (Exception ex)
                    {
                        this.Logger.LogError(ex);
                    }
                    if (artistResult == null || artistResult.artists == null || artistResult.count < 1)
                    {
                        return(new OperationResult <IEnumerable <ArtistSearchResult> >());
                    }
                    var a        = artistResult.artists.First();
                    var mbArtist = await MusicBrainzRequestHelper.GetAsync <Artist>(MusicBrainzRequestHelper.CreateLookupUrl("artist", artistResult.artists.First().id, "releases"));

                    if (mbArtist == null)
                    {
                        return(new OperationResult <IEnumerable <ArtistSearchResult> >());
                    }
                    result = new ArtistSearchResult
                    {
                        ArtistName     = mbArtist.name,
                        ArtistSortName = mbArtist.sortname,
                        MusicBrainzId  = mbArtist.id,
                        ArtistType     = mbArtist.type,
                        IPIs           = mbArtist.ipis,
                        ISNIs          = mbArtist.isnis
                    };
                    if (mbArtist.lifespan != null)
                    {
                        result.BeginDate = SafeParser.ToDateTime(mbArtist.lifespan.begin);
                        result.EndDate   = SafeParser.ToDateTime(mbArtist.lifespan.end);
                    }
                    if (a.aliases != null)
                    {
                        result.AlternateNames = a.aliases.Select(x => x.name).Distinct().ToArray();
                    }
                    if (a.tags != null)
                    {
                        result.Tags = a.tags.Select(x => x.name).Distinct().ToArray();
                    }
                    var mbFilteredReleases = new List <Release>();
                    var filteredPlaces     = new List <string> {
                        "US", "WORLDWIDE", "XW", "GB"
                    };
                    foreach (var release in mbArtist.releases)
                    {
                        if (filteredPlaces.Contains((release.country ?? string.Empty).ToUpper()))
                        {
                            mbFilteredReleases.Add(release);
                        }
                    }
                    result.Releases = new List <ReleaseSearchResult>();
                    var bag = new ConcurrentBag <Release>();
                    var filteredReleaseDetails = mbFilteredReleases.Select(async release =>
                    {
                        bag.Add(await this.MusicBrainzReleaseById(release.id));
                    });
                    await Task.WhenAll(filteredReleaseDetails);

                    foreach (var mbRelease in bag.Where(x => x != null))
                    {
                        var release = new ReleaseSearchResult
                        {
                            MusicBrainzId       = mbRelease.id,
                            ReleaseTitle        = mbRelease.title,
                            ReleaseThumbnailUrl = mbRelease.coverThumbnailUrl
                        };
                        if (mbRelease.imageUrls != null)
                        {
                            release.ImageUrls = mbRelease.imageUrls;
                        }
                        if (mbRelease.releaseevents != null)
                        {
                            release.ReleaseDate = SafeParser.ToDateTime(mbRelease.releaseevents.First().date);
                        }
                        // Labels
                        if (mbRelease.media != null)
                        {
                            var releaseMedias = new List <ReleaseMediaSearchResult>();
                            foreach (var mbMedia in mbRelease.media)
                            {
                                var releaseMedia = new ReleaseMediaSearchResult
                                {
                                    ReleaseMediaNumber = SafeParser.ToNumber <short?>(mbMedia.position),
                                    TrackCount         = mbMedia.trackcount
                                };
                                if (mbMedia.tracks != null)
                                {
                                    var releaseTracks = new List <TrackSearchResult>();
                                    foreach (var mbTrack in mbMedia.tracks)
                                    {
                                        releaseTracks.Add(new TrackSearchResult
                                        {
                                            MusicBrainzId = mbTrack.id,
                                            TrackNumber   = SafeParser.ToNumber <short?>(mbTrack.number),
                                            Title         = mbTrack.title,
                                            Duration      = mbTrack.length
                                        });
                                    }
                                    releaseMedia.Tracks = releaseTracks;
                                }
                                releaseMedias.Add(releaseMedia);
                            }
                            release.ReleaseMedia = releaseMedias;
                        }

                        result.Releases.Add(release);
                    }
                    ;
                    this.CacheManager.Add(artistCacheKey, result);
                }
            }
            catch (HttpRequestException)
            {
            }
            catch (Exception ex)
            {
                this.Logger.LogError(ex);
            }
            if (result == null)
            {
                this.Logger.LogWarning("MusicBrainzArtist: ArtistName [{0}], No MusicBrainz Artist Found", query);
            }
            else
            {
                this.Logger.LogTrace("MusicBrainzArtist: Result [{0}]", query, result.ToString());
            }
            return(new OperationResult <IEnumerable <ArtistSearchResult> >
            {
                IsSuccess = result != null,
                Data = new ArtistSearchResult[] { result }
            });
        }