예제 #1
0
        public Task <OperationResult <IEnumerable <ReleaseSearchResult> > > PerformReleaseSearch(string artistName, string query, int resultsCount)
        {
            var tcs = new TaskCompletionSource <OperationResult <IEnumerable <ReleaseSearchResult> > >();

            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) + " (album)");
            var request = new RestRequest(Method.GET);

            client.ExecuteAsync <api>(request, (response) =>
            {
                ReleaseSearchResult data = null;
                if (response.Data != null)
                {
                    data = new ReleaseSearchResult
                    {
                        Bio = response.Data.query.pages.First().extract
                    };
                }
                tcs.SetResult(new OperationResult <IEnumerable <ReleaseSearchResult> >
                {
                    IsSuccess = data != null,
                    Data      = new ReleaseSearchResult[] { data }
                });
            });
            return(tcs.Task);
        }
예제 #2
0
        public async Task <OperationResult <IEnumerable <ReleaseSearchResult> > > PerformReleaseSearch(string artistName, string query, int resultsCount)
        {
            var cacheKey = $"uri:lastfm:releasesearch:{ artistName.ToAlphanumericName() }:{ query.ToAlphanumericName() }";
            var data     = await CacheManager.GetAsync <ReleaseSearchResult>(cacheKey, async() =>
            {
                var request      = new RestRequest(Method.GET);
                var client       = new RestClient(string.Format("http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key={0}&artist={1}&album={2}&format=xml", ApiKey.Key, artistName, query));
                var responseData = await client.ExecuteAsync <lfm>(request);

                ReleaseSearchResult result = null;

                var response = responseData != null && responseData.Data != null ? responseData.Data : null;
                if (response != null && response.album != null)
                {
                    var lastFmAlbum = response.album;
                    result          = new ReleaseSearchResult
                    {
                        ReleaseTitle  = lastFmAlbum.name,
                        MusicBrainzId = lastFmAlbum.mbid
                    };

                    // No longer fetching/consuming images LastFm says is violation of ToS ; https://getsatisfaction.com/lastfm/topics/api-announcement-dac8oefw5vrxq

                    if (lastFmAlbum.tags != null)
                    {
                        result.Tags = lastFmAlbum.tags.Select(x => x.name).ToList();
                    }
                    if (lastFmAlbum.tracks != null)
                    {
                        var tracks = new List <TrackSearchResult>();
                        foreach (var lastFmTrack in lastFmAlbum.tracks)
                        {
                            tracks.Add(new TrackSearchResult
                            {
                                TrackNumber = SafeParser.ToNumber <short?>(lastFmTrack.rank),
                                Title       = lastFmTrack.name,
                                Duration    = SafeParser.ToNumber <int?>(lastFmTrack.duration),
                                Urls        = string.IsNullOrEmpty(lastFmTrack.url) ? new[] { lastFmTrack.url } : null
                            });
                        }
                        result.ReleaseMedia = new List <ReleaseMediaSearchResult>
                        {
                            new ReleaseMediaSearchResult
                            {
                                ReleaseMediaNumber = 1,
                                Tracks             = tracks
                            }
                        };
                    }
                }
                return(result);
            }, "uri:metadata");

            return(new OperationResult <IEnumerable <ReleaseSearchResult> >
            {
                IsSuccess = data != null,
                Data = new[] { data }
            });
        }
예제 #3
0
        public async Task <OperationResult <IEnumerable <ReleaseSearchResult> > > PerformReleaseSearch(string artistName, string query, int resultsCount)
        {
            var request      = new RestRequest(Method.GET);
            var client       = new RestClient(string.Format("http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key={0}&artist={1}&album={2}&format=xml", this.ApiKey.Key, artistName, query));
            var responseData = await client.ExecuteTaskAsync <lfm>(request);

            ReleaseSearchResult result = null;

            var response = responseData != null && responseData.Data != null ? responseData.Data : null;

            if (response != null && response.album != null)
            {
                var lastFmAlbum = response.album;
                result = new ReleaseSearchResult
                {
                    ReleaseTitle  = lastFmAlbum.name,
                    MusicBrainzId = lastFmAlbum.mbid
                };

                if (lastFmAlbum.image != null)
                {
                    result.ImageUrls = lastFmAlbum.image.Where(x => x.size == "extralarge").Select(x => x.Value).ToList();
                }
                if (lastFmAlbum.tags != null)
                {
                    result.Tags = lastFmAlbum.tags.Select(x => x.name).ToList();
                }
                if (lastFmAlbum.tracks != null)
                {
                    var tracks = new List <TrackSearchResult>();
                    foreach (var lastFmTrack in lastFmAlbum.tracks)
                    {
                        tracks.Add(new TrackSearchResult
                        {
                            TrackNumber = SafeParser.ToNumber <short?>(lastFmTrack.rank),
                            Title       = lastFmTrack.name,
                            Duration    = SafeParser.ToNumber <int?>(lastFmTrack.duration),
                            Urls        = string.IsNullOrEmpty(lastFmTrack.url) ? new string[] { lastFmTrack.url } : null,
                        });
                    }
                    result.ReleaseMedia = new List <ReleaseMediaSearchResult>
                    {
                        new ReleaseMediaSearchResult
                        {
                            ReleaseMediaNumber = 1,
                            Tracks             = tracks
                        }
                    };
                }
            }
            return(new OperationResult <IEnumerable <ReleaseSearchResult> >
            {
                IsSuccess = result != null,
                Data = new List <ReleaseSearchResult> {
                    result
                }
            });
        }
예제 #4
0
        public async Task <OperationResult <IEnumerable <ReleaseSearchResult> > > PerformReleaseSearch(string artistName, string query, int resultsCount)
        {
            var request  = BuildRequest(query, 1, "album");
            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));
            }

            ReleaseSearchResult data = null;

            try
            {
                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 ReleaseSearchResult
                    {
                        ReleaseTitle        = responseData.collectionName,
                        iTunesId            = responseData.artistId.ToString(),
                        AmgId               = responseData.amgArtistId.ToString(),
                        ReleaseType         = responseData.collectionType,
                        ReleaseThumbnailUrl = responseData.artworkUrl100,
                        ReleaseGenres       = new[] { responseData.primaryGenreName },
                        Urls = urls
                    };
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }

            return(new OperationResult <IEnumerable <ReleaseSearchResult> >
            {
                IsSuccess = data != null,
                Data = new[] { data }
            });
        }
예제 #5
0
        private ReleaseSearchResult ReadReleaseSearchResult(JObject source)
        {
            ReleaseSearchResult releaseResult = new ReleaseSearchResult();

            this.ReadReleaseBaseSearchResultData(releaseResult, source);
            foreach (var item in source)
            {
                var v = item.Value;

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

                case "style":
                case "year":
                case "genre":
                    break;

                case "format":
                    releaseResult.Formats = v.ValueAsStringArray();
                    break;

                case "country":
                    releaseResult.Country = v.Value <string>();
                    break;

                case "label":
                    releaseResult.Label = v.ValueAsStringArray();
                    break;

                case "catno":
                    releaseResult.CatalogNumber = v.Value <string>();
                    break;

                default:
                    this.ThrowIfStrict("Unknown key: " + item.Key);
                    break;
                }
            }
            return(releaseResult);
        }
예제 #6
0
        public async Task <OperationResult <IEnumerable <ReleaseSearchResult> > > PerformReleaseSearch(string artistName, string query, int resultsCount)
        {
            ReleaseSearchResult result = null;

            try
            {
                var releaseInfosForArtist = await ReleasesForArtist(artistName);

                if (releaseInfosForArtist != null)
                {
                    var r = releaseInfosForArtist.FirstOrDefault(x => x.title.Equals(query, StringComparison.OrdinalIgnoreCase));
                    if (r != null)
                    {
                        var imageUrls       = r.relations?.Where(x => x.type.Equals("image", StringComparison.OrdinalIgnoreCase)).Select(x => x.url.resource).Distinct().ToArray();
                        var notImageUrls    = r.relations?.Where(x => !x.type.Equals("image", StringComparison.OrdinalIgnoreCase)).Select(x => x.url.resource).Distinct().ToArray();
                        var discogRelation  = r.relations?.FirstOrDefault(x => x.type.Equals("discogs", StringComparison.OrdinalIgnoreCase));
                        var discogId        = discogRelation?.url?.resource?.LastSegmentInUrl();
                        var amgRelation     = r.relations?.FirstOrDefault(x => x.type.Equals("allmusic", StringComparison.OrdinalIgnoreCase));
                        var amgId           = amgRelation?.url?.resource?.LastSegmentInUrl();
                        var lastFmRelation  = r.relations?.FirstOrDefault(x => x.type.Equals("last.fm", StringComparison.OrdinalIgnoreCase));
                        var lastFmId        = lastFmRelation?.url?.resource?.LastSegmentInUrl();
                        var iTunesRelation  = r.relations?.FirstOrDefault(x => x.url?.resource?.StartsWith("https://itunes.apple.com/") ?? false);
                        var iTunesId        = iTunesRelation?.url?.resource?.LastSegmentInUrl();
                        var spotifyRelation = r.relations?.FirstOrDefault(x => x.url?.resource?.StartsWith("https://open.spotify.com/artist/") ?? false);
                        var spotifyId       = spotifyRelation?.url?.resource?.LastSegmentInUrl();
                        result = new ReleaseSearchResult
                        {
                            ReleaseDate = r.releasegroup != null?SafeParser.ToDateTime(r.releasegroup.firstreleasedate) : null,
                                              ReleaseTitle  = r.title,
                                              ImageUrls     = imageUrls,
                                              Urls          = notImageUrls,
                                              LastFMId      = lastFmId,
                                              AmgId         = amgId,
                                              iTunesId      = iTunesId,
                                              DiscogsId     = discogId,
                                              SpotifyId     = spotifyId,
                                              MusicBrainzId = r.id,
                                              Tags          = r.releasegroup?.tags?.Select(x => x.name).Distinct().ToArray(),
                                              ReleaseGenres = r.releasegroup?.genres?.Select(x => x.name).Distinct().ToArray(),
                                              ReleaseType   = r.releasegroup?.primarytype
                        };
                        var coverUrls = await CoverArtForMusicBrainzReleaseById(r.id);

                        if (coverUrls != null)
                        {
                            var frontCover = coverUrls.images.FirstOrDefault(i => i.front);
                            result.ImageUrls = coverUrls.images.Select(x => x.image).ToList();
                            if (frontCover != null)
                            {
                                result.ReleaseThumbnailUrl = frontCover.image;
                                result.ImageUrls           = result.ImageUrls.Where(x => x != result.ReleaseThumbnailUrl).ToList();
                            }
                        }
                        if (r.labelinfo != null)
                        {
                            var releaseLabels = new List <ReleaseLabelSearchResult>();
                            foreach (var mbLabel in r.labelinfo)
                            {
                                if (mbLabel.label != null)
                                {
                                    releaseLabels.Add(new ReleaseLabelSearchResult
                                    {
                                        CatalogNumber = mbLabel.catalognumber,
                                        Label         = new LabelSearchResult
                                        {
                                            LabelName      = mbLabel.label.name,
                                            MusicBrainzId  = mbLabel.label.id,
                                            LabelSortName  = mbLabel.label.sortname,
                                            AlternateNames = mbLabel.label.aliases?.Select(x => x.name).ToList()
                                        }
                                    });
                                }
                            }
                            result.ReleaseLabel = releaseLabels;
                        }

                        if (r.media != null)
                        {
                            var releaseMedia = new List <ReleaseMediaSearchResult>();
                            foreach (var mbMedia in r.media.OrderBy(x => x.position))
                            {
                                var   mediaTracks = new List <TrackSearchResult>();
                                short trackLooper = 0;
                                foreach (var mbTrack in mbMedia.tracks.OrderBy(x => x.position))
                                {
                                    trackLooper++;
                                    mediaTracks.Add(new TrackSearchResult
                                    {
                                        Title          = mbTrack.title,
                                        TrackNumber    = trackLooper,
                                        Duration       = mbTrack.length,
                                        MusicBrainzId  = mbTrack.id,
                                        AlternateNames = mbTrack.recording != null && mbTrack.recording.aliases != null ? mbTrack.recording.aliases.Select(x => x.name).ToList() : null
                                    });
                                }

                                releaseMedia.Add(new ReleaseMediaSearchResult
                                {
                                    ReleaseMediaNumber   = SafeParser.ToNumber <short?>(mbMedia.position),
                                    ReleaseMediaSubTitle = mbMedia.title,
                                    TrackCount           = SafeParser.ToNumber <short?>(mbMedia.trackcount),
                                    Tracks = mediaTracks
                                });
                            }

                            result.ReleaseMedia = releaseMedia;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, ex.Serialize());
            }

            if (result == null)
            {
                Logger.LogTrace("MusicBrainzArtist: ArtistName [{0}], ReleaseTitle [{0}], No MusicBrainz Release Found", artistName, query);
            }
            else
            {
                Logger.LogTrace("MusicBrainzArtist: Result [{0}]", query, result.ToString());
            }
            return(new OperationResult <IEnumerable <ReleaseSearchResult> >
            {
                IsSuccess = result != null,
                Data = new[] { result }
            });
        }
예제 #7
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> >());
        }
예제 #8
0
        public async Task <OperationResult <IEnumerable <ReleaseSearchResult> > > PerformReleaseSearch(string artistName, string query, int resultsCount)
        {
            ReleaseSearchResult data = null;

            try
            {
                var cacheKey = $"uri:discogs:releasesearch:{ artistName.ToAlphanumericName() }:{ query.ToAlphanumericName() }";
                data = await CacheManager.GetAsync <ReleaseSearchResult>(cacheKey, async() =>
                {
                    var request = BuildSearchRequest(query, 10, "release", artistName);

                    var client = new RestClient("https://api.discogs.com/database")
                    {
                        UserAgent        = WebHelper.UserAgent,
                        ReadWriteTimeout = SafeParser.ToNumber <int>(Configuration.Integrations.DiscogsReadWriteTimeout),
                        Timeout          = SafeParser.ToNumber <int>(Configuration.Integrations.DiscogsTimeout)
                    };

                    var response = await client.ExecuteAsync <DiscogsReleaseSearchResult>(request);
                    if (response?.ResponseStatus == null || response.ResponseStatus == ResponseStatus.Error)
                    {
                        if (response.StatusCode == HttpStatusCode.Unauthorized)
                        {
                            throw new AuthenticationException("Unauthorized");
                        }
                        throw new Exception($"Request Error Message: {response?.ErrorMessage}. Content: {response?.Content}.");
                    }

                    var responseData = response?.Data?.results?.OrderBy(x => x.year).FirstOrDefault();
                    if (responseData?.id != null)
                    {
                        request = BuildReleaseRequest(responseData.id);
                        var c2  = new RestClient("https://api.discogs.com/")
                        {
                            UserAgent = WebHelper.UserAgent
                        };
                        var releaseResult = await c2.ExecuteTaskAsync <DiscogReleaseDetail>(request);
                        var release       = releaseResult?.Data;
                        if (release != null)
                        {
                            var urls   = new List <string>();
                            var images = new List <string>();
                            string releaseThumbnailUrl = null;
                            urls.Add(release.uri);
                            if (release.images != null)
                            {
                                images.AddRange(release.images.Where(x => x.type != "primary").Select(x => x.uri));
                                var primaryImage = release.images.FirstOrDefault(x => x.type == "primary");
                                if (primaryImage != null)
                                {
                                    releaseThumbnailUrl = primaryImage.uri;
                                }
                                if (string.IsNullOrEmpty(releaseThumbnailUrl))
                                {
                                    releaseThumbnailUrl = release.images.First(x => !string.IsNullOrEmpty(x.uri)).uri;
                                }
                            }

                            data = new ReleaseSearchResult
                            {
                                DiscogsId           = release.id.ToString(),
                                ReleaseType         = responseData.type,
                                ReleaseDate         = SafeParser.ToDateTime(release.released),
                                Profile             = release.notes,
                                ReleaseThumbnailUrl = releaseThumbnailUrl,
                                Urls      = urls,
                                ImageUrls = images
                            };
                            if (release.genres != null)
                            {
                                data.ReleaseGenres = release.genres.ToList();
                            }
                            if (release.labels != null)
                            {
                                data.ReleaseLabel = release.labels.Select(x => new ReleaseLabelSearchResult
                                {
                                    CatalogNumber = x.catno,
                                    Label         = new LabelSearchResult
                                    {
                                        LabelName = x.name,
                                        DiscogsId = x.id.ToString()
                                    }
                                }).ToList();
                            }
                            if (release.tracklist != null)
                            {
                                var releaseMediaCount = 1;
                                var releaseMedias     = new List <ReleaseMediaSearchResult>();
                                for (short?i = 1; i <= releaseMediaCount; i++)
                                {
                                    var releaseTracks = new List <TrackSearchResult>();
                                    short?looper      = 0;
                                    foreach (var dTrack in release.tracklist.OrderBy(x => x.position))
                                    {
                                        looper++;
                                        releaseTracks.Add(new TrackSearchResult
                                        {
                                            TrackNumber = looper,
                                            Title       = dTrack.title,
                                            Duration    = dTrack.duration.ToTrackDuration(),
                                            TrackType   = dTrack.type_
                                        });
                                    }

                                    releaseMedias.Add(new ReleaseMediaSearchResult
                                    {
                                        ReleaseMediaNumber = i,
                                        TrackCount         = (short)releaseTracks.Count(),
                                        Tracks             = releaseTracks
                                    });
                                }

                                data.ReleaseMedia = releaseMedias;
                            }

                            if (release.identifiers != null)
                            {
                                var barcode = release.identifiers.FirstOrDefault(x => (x.type ?? string.Empty) == "Barcode");
                                if (barcode?.value != null)
                                {
                                    data.Tags = new[] { "barcode:" + barcode.value };
                                }
                            }
                        }
                    }
                    return(null);
                }, "uri:metadata");
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, $"DiscogsHelper: Error in PerformReleaseSearch artistname [{ artistName }], query [{ query }], resultsCount [{ resultsCount }]");
            }

            return(new OperationResult <IEnumerable <ReleaseSearchResult> >
            {
                IsSuccess = data != null,
                Data = new[] { data }
            });
        }
예제 #9
0
        public async Task <OperationResult <IEnumerable <ReleaseSearchResult> > > PerformReleaseSearch(string artistName, string query, int resultsCount)
        {
            ReleaseSearchResult result = null;

            try
            {
                var releaseInfosForArtist = await this.ReleasesForArtist(artistName);

                if (releaseInfosForArtist != null)
                {
                    var releaseInfo = releaseInfosForArtist.FirstOrDefault(x => x.title.Equals(query, StringComparison.OrdinalIgnoreCase));
                    if (releaseInfo != null)
                    {
                        var mbRelease = await this.MusicBrainzReleaseById(releaseInfo.id);

                        if (mbRelease != null)
                        {
                            result = new ReleaseSearchResult
                            {
                                ReleaseDate = mbRelease.releasegroup != null?SafeParser.ToDateTime(mbRelease.releasegroup.firstreleasedate) : null,
                                                  ReleaseTitle  = mbRelease.title,
                                                  MusicBrainzId = mbRelease.id,
                                                  ReleaseType   = mbRelease.releasegroup != null ? mbRelease.releasegroup.primarytype : null,
                            };
                            if (mbRelease.labelinfo != null)
                            {
                                var releaseLabels = new List <ReleaseLabelSearchResult>();
                                foreach (var mbLabel in mbRelease.labelinfo)
                                {
                                    releaseLabels.Add(new ReleaseLabelSearchResult
                                    {
                                        CatalogNumber = mbLabel.catalognumber,
                                        Label         = new LabelSearchResult
                                        {
                                            LabelName      = mbLabel.label.name,
                                            MusicBrainzId  = mbLabel.label.id,
                                            LabelSortName  = mbLabel.label.sortname,
                                            AlternateNames = mbLabel.label.aliases.Select(x => x.name).ToList()
                                        }
                                    });
                                }
                                result.ReleaseLabel = releaseLabels;
                            }
                            if (mbRelease.media != null)
                            {
                                var releaseMedia = new List <ReleaseMediaSearchResult>();
                                foreach (var mbMedia in mbRelease.media.OrderBy(x => x.position))
                                {
                                    var   mediaTracks = new List <TrackSearchResult>();
                                    short trackLooper = 0;
                                    foreach (var mbTrack in mbMedia.tracks.OrderBy(x => x.position))
                                    {
                                        trackLooper++;
                                        mediaTracks.Add(new TrackSearchResult
                                        {
                                            Title          = mbTrack.title,
                                            TrackNumber    = trackLooper,
                                            Duration       = mbTrack.length,
                                            MusicBrainzId  = mbTrack.id,
                                            AlternateNames = mbTrack.recording != null && mbTrack.recording.aliases != null ? mbTrack.recording.aliases.Select(x => x.name).ToList() : null
                                        });
                                    }
                                    releaseMedia.Add(new ReleaseMediaSearchResult
                                    {
                                        ReleaseMediaNumber   = SafeParser.ToNumber <short?>(mbMedia.position),
                                        ReleaseMediaSubTitle = mbMedia.title,
                                        TrackCount           = SafeParser.ToNumber <short?>(mbMedia.trackcount),
                                        Tracks = mediaTracks
                                    });
                                }
                                result.ReleaseMedia = releaseMedia;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.Logger.LogError(ex, ex.Serialize());
            }
            if (result == null)
            {
                this.Logger.LogWarning("MusicBrainzArtist: ArtistName [{0}], ReleaseTitle [{0}], No MusicBrainz Release Found", artistName, query);
            }
            else
            {
                this.Logger.LogTrace("MusicBrainzArtist: Result [{0}]", query, result.ToString());
            }
            return(new OperationResult <IEnumerable <ReleaseSearchResult> >
            {
                IsSuccess = result != null,
                Data = new ReleaseSearchResult[] { result }
            });
        }
예제 #10
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 }
            });
        }
예제 #11
0
        public async Task <OperationResult <IEnumerable <ReleaseSearchResult> > > PerformReleaseSearch(string artistName, string query, int resultsCount)
        {
            ReleaseSearchResult data = null;

            try
            {
                var request = this.BuildSearchRequest(query, 10, "release", artistName);

                var client = new RestClient("https://api.discogs.com/database")
                {
                    UserAgent        = WebHelper.UserAgent,
                    ReadWriteTimeout = (int)this.Configuration.Integrations.DiscogsReadWriteTimeout,
                    Timeout          = (int)this.Configuration.Integrations.DiscogsTimeout
                };

                var response = await client.ExecuteTaskAsync <DiscogsReleaseSearchResult>(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 != null && response.Data.results.Any() ? response.Data.results.OrderBy(x => x.year).First() : null;
                if (responseData != null)
                {
                    request = this.BuildReleaseRequest(responseData.id);
                    var c2 = new RestClient("https://api.discogs.com/");
                    c2.UserAgent = WebHelper.UserAgent;
                    var releaseResult = await c2.ExecuteTaskAsync <DiscogReleaseDetail>(request);

                    var release = releaseResult != null && releaseResult.Data != null ? releaseResult.Data : null;
                    if (release != null)
                    {
                        var    urls   = new List <string>();
                        var    images = new List <string>();
                        string releaseThumbnailUrl = null;
                        urls.Add(release.uri);
                        if (release.images != null)
                        {
                            images.AddRange(release.images.Where(x => x.type != "primary").Select(x => x.uri));
                            var primaryImage = release.images.FirstOrDefault(x => x.type == "primary");
                            if (primaryImage != null)
                            {
                                releaseThumbnailUrl = primaryImage.uri;
                            }
                            if (string.IsNullOrEmpty(releaseThumbnailUrl))
                            {
                                releaseThumbnailUrl = release.images.First(x => !string.IsNullOrEmpty(x.uri)).uri;
                            }
                        }
                        data = new ReleaseSearchResult
                        {
                            DiscogsId           = release.id.ToString(),
                            ReleaseType         = responseData.type,
                            ReleaseDate         = SafeParser.ToDateTime(release.released),
                            Profile             = release.notes,
                            ReleaseThumbnailUrl = releaseThumbnailUrl,
                            Urls      = urls,
                            ImageUrls = images
                        };
                        if (release.genres != null)
                        {
                            data.ReleaseGenres = release.genres.ToList();
                        }
                        if (release.labels != null)
                        {
                            data.ReleaseLabel = release.labels.Select(x => new ReleaseLabelSearchResult
                            {
                                CatalogNumber = x.catno,
                                Label         = new LabelSearchResult
                                {
                                    LabelName = x.name,
                                    DiscogsId = x.id.ToString()
                                }
                            }).ToList();
                        }
                        if (release.tracklist != null)
                        {
                            var releaseMediaCount = 1;
                            var releaseMedias     = new List <ReleaseMediaSearchResult>();
                            for (short?i = 1; i <= releaseMediaCount; i++)
                            {
                                var   releaseTracks = new List <TrackSearchResult>();
                                short?looper        = 0;
                                foreach (var dTrack in release.tracklist.OrderBy(x => x.position))
                                {
                                    looper++;
                                    releaseTracks.Add(new TrackSearchResult
                                    {
                                        TrackNumber = looper,
                                        Title       = dTrack.title,
                                        Duration    = dTrack.duration.ToTrackDuration(),
                                        TrackType   = dTrack.type_
                                    });
                                }
                                releaseMedias.Add(new ReleaseMediaSearchResult
                                {
                                    ReleaseMediaNumber = i,
                                    TrackCount         = (short)releaseTracks.Count(),
                                    Tracks             = releaseTracks
                                });
                            }
                            data.ReleaseMedia = releaseMedias;
                        }
                        if (release.identifiers != null)
                        {
                            var barcode = release.identifiers.FirstOrDefault(x => x.type == "Barcode");
                            if (barcode != null && !string.IsNullOrEmpty(barcode.value))
                            {
                                data.Tags = new string[] { "barcode:" + barcode.value };
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.Logger.LogError(ex);
            }
            return(new OperationResult <IEnumerable <ReleaseSearchResult> >
            {
                IsSuccess = data != null,
                Data = new ReleaseSearchResult[] { data }
            });
        }