Esempio n. 1
0
        /// <summary>
        /// Return if releases exist in repository for artist, if not fetch from MusicBrainz and populate then return
        /// </summary>
        /// <param name="artistMbId">Artist Music Brainz Id</param>
        /// <returns>Collection of Music Brainz Releases</returns>
        public async Task <IEnumerable <Release> > ReleasesForArtist(string artistMbId)
        {
            IEnumerable <Release> results = null;

            try
            {
                using (var db = new LiteDatabase(FileName))
                {
                    var col = db.GetCollection <RepositoryRelease>("releases");
                    col.EnsureIndex(x => x.ArtistMbId);
                    col.EnsureIndex(x => x.Release.id);
                    var releases = col.Find(x => x.ArtistMbId == artistMbId);
                    if (releases == null || !releases.Any())
                    {
                        // Query to get collection of Releases for Artist
                        var pageSize = 50;
                        var page     = 0;
                        var url      = MusicBrainzRequestHelper.CreateArtistBrowseTemplate(artistMbId, pageSize, 0);
                        var mbReleaseBrowseResult = await MusicBrainzRequestHelper.GetAsync <ReleaseBrowseResult>(url);

                        var totalReleases = mbReleaseBrowseResult != null ? mbReleaseBrowseResult.releasecount : 0;
                        var totalPages    = Math.Ceiling((decimal)totalReleases / pageSize);
                        var fetchResult   = new List <Release>();
                        do
                        {
                            if (mbReleaseBrowseResult != null)
                            {
                                fetchResult.AddRange(mbReleaseBrowseResult.releases.Where(x => !string.IsNullOrEmpty(x.date)));
                            }
                            page++;
                            mbReleaseBrowseResult = await MusicBrainzRequestHelper.GetAsync <ReleaseBrowseResult>(MusicBrainzRequestHelper.CreateArtistBrowseTemplate(artistMbId, pageSize, pageSize *page));
                        } while (page < totalPages);
                        col.InsertBulk(fetchResult.Select(x => new RepositoryRelease
                        {
                            ArtistMbId = artistMbId,
                            Release    = x
                        }));
                        results = fetchResult;
                    }
                    else
                    {
                        results = releases.Select(x => x.Release).ToArray();
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                Logger.LogTrace($"MusicBrainz:ReleasesForArtist, Artist [{ artistMbId }], Ex [{ ex.ToString() }]");
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
            return(results.OrderBy(x => x.date).ThenBy(x => x.title).ToArray());
        }
Esempio n. 2
0
        public async Task <IEnumerable <Release> > ReleasesForArtist(string artist, string artistMusicBrainzId = null)
        {
            try
            {
                var artistSearch = await this.PerformArtistSearch(artist, 1);

                if (artistSearch == null || !artistSearch.IsSuccess)
                {
                    return(null);
                }
                var mbArtist = artistSearch.Data.First();
                if (string.IsNullOrEmpty(artistMusicBrainzId))
                {
                    if (mbArtist == null)
                    {
                        return(null);
                    }
                    artistMusicBrainzId = mbArtist.MusicBrainzId;
                }
                var cacheKey = string.Format("uri:musicbrainz:ReleasesForArtist:{0}", artistMusicBrainzId);
                var result   = this.CacheManager.Get <List <Release> >(cacheKey);
                if (result == null)
                {
                    var pageSize = 50;
                    var page     = 0;
                    var url      = MusicBrainzRequestHelper.CreateArtistBrowseTemplate(artistMusicBrainzId, pageSize, 0);
                    var mbReleaseBrowseResult = await MusicBrainzRequestHelper.GetAsync <ReleaseBrowseResult>(url);

                    var totalReleases = mbReleaseBrowseResult != null ? mbReleaseBrowseResult.releasecount : 0;
                    var totalPages    = Math.Ceiling((decimal)totalReleases / (decimal)pageSize);
                    result = new List <Release>();
                    do
                    {
                        if (mbReleaseBrowseResult != null)
                        {
                            result.AddRange(mbReleaseBrowseResult.releases);
                        }
                        page++;
                        mbReleaseBrowseResult = await MusicBrainzRequestHelper.GetAsync <ReleaseBrowseResult>(MusicBrainzRequestHelper.CreateArtistBrowseTemplate(artistMusicBrainzId, pageSize, pageSize *page));
                    } while (page < totalPages);
                    result = result.OrderBy(x => x.date).ThenBy(x => x.title).ToList();
                    this.CacheManager.Add(cacheKey, result);
                }
                return(result);
            }
            catch (HttpRequestException)
            {
            }
            catch (Exception ex)
            {
                this.Logger.LogError(ex);
            }
            return(null);
        }
Esempio n. 3
0
        /// <summary>
        /// Return if artist exists in repository, if not fetch from MusicBrainz and populate then return
        /// </summary>
        /// <param name="name">Query name of Artist</param>
        /// <param name="resultsCount">Maximum Number of Results</param>
        public async Task <Artist> ArtistByName(string name, int?resultsCount = null)
        {
            Artist result = null;

            try
            {
                using (var db = new LiteDatabase(FileName))
                {
                    var col = db.GetCollection <RepositoryArtist>("artists");
                    col.EnsureIndex(x => x.ArtistName);
                    col.EnsureIndex(x => x.ArtistMbId);
                    var artist = col.Find(x => x.ArtistName.Equals(name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                    if (artist == null)
                    {
                        // Perform a query to get the MbId for the Name
                        var artistResult = await MusicBrainzRequestHelper.GetAsync <ArtistResult>(MusicBrainzRequestHelper.CreateSearchTemplate("artist", name, resultsCount ?? 1, 0));

                        if (artistResult == null || artistResult.artists == null || !artistResult.artists.Any() || artistResult.count < 1)
                        {
                            return(null);
                        }
                        var mbId = artistResult.artists.First().id;
                        // Now perform a detail request to get the details by the MbId
                        result = await MusicBrainzRequestHelper.GetAsync <Artist>(MusicBrainzRequestHelper.CreateLookupUrl("artist", mbId, "aliases+tags+genres+url-rels"));

                        if (result != null)
                        {
                            col.Insert(new RepositoryArtist
                            {
                                ArtistName = name,
                                ArtistMbId = result.id,
                                Artist     = result
                            });
                        }
                    }
                    else
                    {
                        result = artist.Artist;
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                Logger.LogTrace($"MusicBrainzArtist: ArtistName [{ name }], HttpRequestException: [{ ex.ToString() }] ");
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
            return(result);
        }
Esempio n. 4
0
        public async Task <Release> MusicBrainzReleaseById(string musicBrainzId)
        {
            if (string.IsNullOrEmpty(musicBrainzId))
            {
                return(null);
            }
            Release release = null;

            try
            {
                var artistCacheKey = string.Format("uri:musicbrainz:MusicBrainzReleaseById:{0}", musicBrainzId);
                release = this.CacheManager.Get <Release>(artistCacheKey);
                if (release == null)
                {
                    release = await MusicBrainzRequestHelper.GetAsync <Release>(MusicBrainzRequestHelper.CreateLookupUrl("release", musicBrainzId, "labels+aliases+recordings+release-groups+media+url-rels"));

                    if (release != null)
                    {
                        var coverUrls = await this.CoverArtForMusicBrainzReleaseById(musicBrainzId);

                        if (coverUrls != null)
                        {
                            var frontCover = coverUrls.images.FirstOrDefault(i => i.front);
                            release.imageUrls = coverUrls.images.Select(x => x.image).ToList();
                            if (frontCover != null)
                            {
                                release.coverThumbnailUrl = frontCover.image;
                                release.imageUrls         = release.imageUrls.Where(x => x != release.coverThumbnailUrl).ToList();
                            }
                        }
                        this.CacheManager.Add(artistCacheKey, release);
                    }
                }
            }
            catch (HttpRequestException)
            {
            }
            if (release == null)
            {
                this.Logger.LogWarning("MusicBrainzReleaseById: MusicBrainzId [{0}], No MusicBrainz Release Found", musicBrainzId);
            }
            return(release);
        }
Esempio n. 5
0
 private async Task <CoverArtArchivesResult> CoverArtForMusicBrainzReleaseById(string musicBrainzId)
 {
     return(await MusicBrainzRequestHelper.GetAsync <CoverArtArchivesResult>(MusicBrainzRequestHelper.CreateCoverArtReleaseUrl(musicBrainzId)));
 }
Esempio n. 6
0
        public async Task <IEnumerable <AudioMetaData> > MusicBrainzReleaseTracks(string artistName, string releaseTitle)
        {
            try
            {
                if (string.IsNullOrEmpty(artistName) && string.IsNullOrEmpty(releaseTitle))
                {
                    return(null);
                }
                // Find the Artist
                var artistCacheKey = string.Format("uri:musicbrainz:artist:{0}", artistName);
                var artistSearch   = await PerformArtistSearch(artistName, 1);

                if (!artistSearch.IsSuccess)
                {
                    return(null);
                }
                var artist = artistSearch.Data.First();

                if (artist == null)
                {
                    return(null);
                }
                var ReleaseCacheKey = string.Format("uri:musicbrainz:release:{0}", releaseTitle);
                var release         = CacheManager.Get <Release>(ReleaseCacheKey);
                if (release == null)
                {
                    // Now Get Artist Details including Releases
                    var ReleaseResult = artist.Releases.FirstOrDefault(x =>
                                                                       x.ReleaseTitle.Equals(releaseTitle, StringComparison.InvariantCultureIgnoreCase));
                    if (ReleaseResult == null)
                    {
                        ReleaseResult = artist.Releases.FirstOrDefault(x =>
                                                                       x.ReleaseTitle.EndsWith(releaseTitle, StringComparison.InvariantCultureIgnoreCase));

                        if (ReleaseResult == null)
                        {
                            ReleaseResult = artist.Releases.FirstOrDefault(x =>
                                                                           x.ReleaseTitle.StartsWith(releaseTitle, StringComparison.InvariantCultureIgnoreCase));
                            if (ReleaseResult == null)
                            {
                                return(null);
                            }
                        }
                    }

                    // Now get The Release Details
                    release = await MusicBrainzRequestHelper.GetAsync <Release>(
                        MusicBrainzRequestHelper.CreateLookupUrl("release", ReleaseResult.MusicBrainzId, "recordings"));

                    if (release == null)
                    {
                        return(null);
                    }
                    CacheManager.Add(ReleaseCacheKey, release);
                }

                var result = new List <AudioMetaData>();
                foreach (var media in release.media)
                {
                    foreach (var track in media.tracks)
                    {
                        var date = 0;
                        if (!string.IsNullOrEmpty(release.date))
                        {
                            if (release.date.Length > 4)
                            {
                                var ReleaseDate = DateTime.MinValue;
                                if (DateTime.TryParse(release.date, out ReleaseDate))
                                {
                                    date = ReleaseDate.Year;
                                }
                            }
                            else
                            {
                                int.TryParse(release.date, out date);
                            }
                        }

                        result.Add(new AudioMetaData
                        {
                            ReleaseMusicBrainzId = release.id,
                            MusicBrainzId        = track.id,
                            Artist            = artist.ArtistName,
                            Release           = release.title,
                            Title             = track.title,
                            Time              = track.length.HasValue ? (TimeSpan?)TimeSpan.FromMilliseconds(track.length.Value) : null,
                            TrackNumber       = SafeParser.ToNumber <short?>(track.position ?? track.number) ?? 0,
                            Disc              = media.position,
                            Year              = date > 0 ? (int?)date : null,
                            TotalTrackNumbers = media.trackcount
                                                //tagFile.Tag.Pictures.Select(x => new AudoMetaDataImage
                                                //{
                                                //    Data = x.Data.Data,
                                                //    Description = x.Description,
                                                //    MimeType = x.MimeType,
                                                //    Type = (AudioMetaDataImageType)x.Type
                                                //}).ToArray()
                        });
                    }
                }

                return(result);
            }
            catch (Exception)
            {
            }

            return(null);
        }
Esempio n. 7
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 }
            });
        }