예제 #1
0
        public void Parse_Datetime_ShouldBe1988(string input)
        {
            var parsed = SafeParser.ToDateTime(input);

            Assert.NotNull(parsed);
            Assert.Equal(1988, parsed.Value.Year);
        }
예제 #2
0
        public void GenerateReleaseFolderNames(string input, string releaseDate, string artistFolder, string shouldBe)
        {
            var af            = new DirectoryInfo(Path.Combine(Configuration.LibraryFolder, artistFolder));
            var releaseFolder = FolderPathHelper.ReleasePath(af.FullName, input, SafeParser.ToDateTime(releaseDate).Value);
            var t             = new DirectoryInfo(Path.Combine(Configuration.LibraryFolder, shouldBe));

            Assert.Equal(t.FullName, releaseFolder);
        }
예제 #3
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 }
            });
        }
예제 #4
0
        public static short?ParseYear(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return(null);
            }
            var   date = SafeParser.ToDateTime(input);
            short?year = (short?)date?.Year ?? SafeParser.ToNumber <short?>(input);

            return(year > 2200 || year < 1900 ? null : year);
        }
예제 #5
0
        public async Task <IActionResult> Scrobble(Guid id, string startedPlaying, bool isRandom)
        {
            var result = await PlayActivityService.Scrobble(await CurrentUserModel().ConfigureAwait(false), new ScrobbleInfo
            {
                TrackId              = id,
                TimePlayed           = SafeParser.ToDateTime(startedPlaying) ?? DateTime.UtcNow,
                IsRandomizedScrobble = isRandom
            }).ConfigureAwait(false);

            if (result?.IsNotFoundResult != false)
            {
                return(NotFound());
            }
            if (!result.IsSuccess)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError));
            }
            return(Ok(result));
        }
예제 #6
0
        private async Task <string> DetermineReleaseFolder(string artistFolder, AudioMetaData metaData, bool doJustInfo, int?submissionId)
        {
            var artist = await this.ArtistLookupEngine.GetByName(metaData, !doJustInfo);

            if (!artist.IsSuccess)
            {
                return(null);
            }
            this._artistId = artist.Data.RoadieId;
            var release = await this.ReleaseLookupEngine.GetByName(artist.Data, metaData, !doJustInfo, submissionId : submissionId);

            if (!release.IsSuccess)
            {
                return(null);
            }
            this._releaseId          = release.Data.RoadieId;
            release.Data.ReleaseDate = SafeParser.ToDateTime(release.Data.ReleaseYear ?? metaData.Year);
            if (release.Data.ReleaseYear.HasValue && release.Data.ReleaseYear != metaData.Year)
            {
                this.Logger.LogWarning($"Found Release `{ release.Data }` has different Release Year than MetaData Year `{ metaData }`");
            }
            return(release.Data.ReleaseFileFolder(artistFolder));
        }
예제 #7
0
        public async Task <Data.Release> ReleaseForMusicBrainzReleaseById(string musicBrainzId)
        {
            var release = await MusicBrainzReleaseById(musicBrainzId);

            if (release == null)
            {
                return(null);
            }
            var media = release.media.First();

            if (media == null)
            {
                return(null);
            }

            var result = new Data.Release
            {
                Title         = release.title.ToTitleCase(false),
                ReleaseDate   = SafeParser.ToDateTime(release.date),
                MusicBrainzId = release.id
            };

            var releaseMedia = new Data.ReleaseMedia
            {
                Tracks = media.tracks.Select(m => new Data.Track
                {
                    TrackNumber   = SafeParser.ToNumber <short>(m.position ?? m.number),
                    Title         = m.title.ToTitleCase(false),
                    MusicBrainzId = m.id,
                }).ToList()
            };

            result.Medias = new List <ReleaseMedia> {
                releaseMedia
            };
            return(result);
        }
예제 #8
0
        public async Task <OperationResult <Data.Release> > PerformMetaDataProvidersReleaseSearch(AudioMetaData metaData, string artistFolder = null, int?submissionId = null)
        {
            SimpleContract.Requires <ArgumentNullException>(metaData != null, "Invalid MetaData");

            var sw = new Stopwatch();

            sw.Start();

            var result = new Data.Release
            {
                Title        = metaData.Release.ToTitleCase(false),
                TrackCount   = (short)(metaData.TotalTrackNumbers ?? 0),
                ReleaseDate  = SafeParser.ToDateTime(metaData.Year),
                SubmissionId = submissionId
            };
            var resultsExceptions = new List <Exception>();
            var releaseGenres     = new List <string>();

            // Add any Genre found in the given MetaData
            if (metaData.Genres != null)
            {
                releaseGenres.AddRange(metaData.Genres);
            }
            var releaseLabels    = new List <ReleaseLabelSearchResult>();
            var releaseMedias    = new List <ReleaseMediaSearchResult>();
            var releaseImageUrls = new List <string>();

            var dontDoMetaDataProvidersSearchArtists = this.Configuration.DontDoMetaDataProvidersSearchArtists;

            if (!dontDoMetaDataProvidersSearchArtists.Any(x => x.Equals(metaData.Artist, StringComparison.OrdinalIgnoreCase)))
            {
                try
                {
                    #region ITunes

                    if (this.ITunesReleaseSearchEngine.IsEnabled)
                    {
                        this.Logger.LogTrace("ITunesReleaseSearchEngine Release Search for ArtistName [{0}], ReleaseTitle [{1}]", metaData.Artist, result.Title);
                        var iTunesResult = await this.ITunesReleaseSearchEngine.PerformReleaseSearch(metaData.Artist, result.Title, 1);

                        if (iTunesResult.IsSuccess)
                        {
                            var i = iTunesResult.Data.First();
                            if (i.AlternateNames != null)
                            {
                                result.AlternateNames = result.AlternateNames.AddToDelimitedList(i.AlternateNames);
                            }
                            if (i.Tags != null)
                            {
                                result.Tags = result.Tags.AddToDelimitedList(i.Tags);
                            }
                            if (i.Urls != null)
                            {
                                result.URLs = result.URLs.AddToDelimitedList(i.Urls);
                            }
                            if (i.ImageUrls != null)
                            {
                                releaseImageUrls.AddRange(i.ImageUrls);
                            }
                            if (i.ReleaseGenres != null)
                            {
                                releaseGenres.AddRange(i.ReleaseGenres);
                            }
                            result.CopyTo(new Data.Release
                            {
                                ReleaseDate = result.ReleaseDate ?? i.ReleaseDate,
                                AmgId       = i.AmgId,
                                Profile     = i.Profile,
                                ITunesId    = i.iTunesId,
                                Title       = result.Title ?? i.ReleaseTitle,
                                Thumbnail   = i.ReleaseThumbnailUrl != null ? WebHelper.BytesForImageUrl(i.ReleaseThumbnailUrl) : null,
                                ReleaseType = result.ReleaseType == ReleaseType.Unknown ? SafeParser.ToEnum <ReleaseType>(i.ReleaseType) : result.ReleaseType
                            });
                            if (i.ReleaseLabel != null)
                            {
                                releaseLabels.AddRange(i.ReleaseLabel);
                            }
                            if (i.ReleaseMedia != null)
                            {
                                releaseMedias.AddRange(i.ReleaseMedia);
                            }
                        }
                        if (iTunesResult.Errors != null)
                        {
                            resultsExceptions.AddRange(iTunesResult.Errors);
                        }
                    }

                    #endregion ITunes

                    #region MusicBrainz

                    if (this.MusicBrainzReleaseSearchEngine.IsEnabled)
                    {
                        this.Logger.LogTrace("MusicBrainzReleaseSearchEngine Release Search for ArtistName [{0}], ReleaseTitle [{1}]", metaData.Artist, result.Title);
                        var mbResult = await this.MusicBrainzReleaseSearchEngine.PerformReleaseSearch(metaData.Artist, result.Title, 1);

                        if (mbResult.IsSuccess)
                        {
                            var mb = mbResult.Data.First();
                            if (mb.AlternateNames != null)
                            {
                                result.AlternateNames = result.AlternateNames.AddToDelimitedList(mb.AlternateNames);
                            }
                            if (mb.Tags != null)
                            {
                                result.Tags = result.Tags.AddToDelimitedList(mb.Tags);
                            }
                            if (mb.Urls != null)
                            {
                                result.URLs = result.URLs.AddToDelimitedList(mb.Urls);
                            }
                            if (mb.ImageUrls != null)
                            {
                                releaseImageUrls.AddRange(mb.ImageUrls);
                            }
                            if (mb.ReleaseGenres != null)
                            {
                                releaseGenres.AddRange(mb.ReleaseGenres);
                            }
                            if (!string.IsNullOrEmpty(mb.ReleaseTitle) && !mb.ReleaseTitle.Equals(result.Title, StringComparison.OrdinalIgnoreCase))
                            {
                                result.AlternateNames.AddToDelimitedList(new string[] { mb.ReleaseTitle });
                            }
                            result.CopyTo(new Data.Release
                            {
                                ReleaseDate   = result.ReleaseDate ?? mb.ReleaseDate,
                                AmgId         = mb.AmgId,
                                Profile       = mb.Profile,
                                TrackCount    = mb.ReleaseMedia != null ? (short)mb.ReleaseMedia.Sum(x => x.TrackCount) : (short)0,
                                MusicBrainzId = mb.MusicBrainzId,
                                ITunesId      = mb.iTunesId,
                                Title         = result.Title ?? mb.ReleaseTitle,
                                Thumbnail     = mb.ReleaseThumbnailUrl != null ? WebHelper.BytesForImageUrl(mb.ReleaseThumbnailUrl) : null,
                                ReleaseType   = result.ReleaseType == ReleaseType.Unknown ? SafeParser.ToEnum <ReleaseType>(mb.ReleaseType) : result.ReleaseType
                            });
                            if (mb.ReleaseLabel != null)
                            {
                                releaseLabels.AddRange(mb.ReleaseLabel);
                            }
                            if (mb.ReleaseMedia != null)
                            {
                                releaseMedias.AddRange(mb.ReleaseMedia);
                            }
                        }
                        if (mbResult.Errors != null)
                        {
                            resultsExceptions.AddRange(mbResult.Errors);
                        }
                    }

                    #endregion MusicBrainz

                    #region LastFm

                    if (this.LastFmReleaseSearchEngine.IsEnabled)
                    {
                        this.Logger.LogTrace("LastFmReleaseSearchEngine Release Search for ArtistName [{0}], ReleaseTitle [{1}]", metaData.Artist, result.Title);
                        var lastFmResult = await this.LastFmReleaseSearchEngine.PerformReleaseSearch(metaData.Artist, result.Title, 1);

                        if (lastFmResult.IsSuccess)
                        {
                            var l = lastFmResult.Data.First();
                            if (l.AlternateNames != null)
                            {
                                result.AlternateNames = result.AlternateNames.AddToDelimitedList(l.AlternateNames);
                            }
                            if (l.Tags != null)
                            {
                                result.Tags = result.Tags.AddToDelimitedList(l.Tags);
                            }
                            if (l.Urls != null)
                            {
                                result.URLs = result.URLs.AddToDelimitedList(l.Urls);
                            }
                            if (l.ImageUrls != null)
                            {
                                releaseImageUrls.AddRange(l.ImageUrls);
                            }
                            if (l.ReleaseGenres != null)
                            {
                                releaseGenres.AddRange(l.ReleaseGenres);
                            }
                            if (!string.IsNullOrEmpty(l.ReleaseTitle) && !l.ReleaseTitle.Equals(result.Title, StringComparison.OrdinalIgnoreCase))
                            {
                                result.AlternateNames.AddToDelimitedList(new string[] { l.ReleaseTitle });
                            }
                            result.CopyTo(new Data.Release
                            {
                                ReleaseDate   = result.ReleaseDate ?? l.ReleaseDate,
                                AmgId         = l.AmgId,
                                Profile       = l.Profile,
                                LastFMId      = l.LastFMId,
                                LastFMSummary = l.LastFMSummary,
                                MusicBrainzId = l.MusicBrainzId,
                                ITunesId      = l.iTunesId,
                                Title         = result.Title ?? l.ReleaseTitle,
                                Thumbnail     = l.ReleaseThumbnailUrl != null ? WebHelper.BytesForImageUrl(l.ReleaseThumbnailUrl) : null,
                                ReleaseType   = result.ReleaseType == ReleaseType.Unknown ? SafeParser.ToEnum <ReleaseType>(l.ReleaseType) : result.ReleaseType
                            });
                            if (l.ReleaseLabel != null)
                            {
                                releaseLabels.AddRange(l.ReleaseLabel);
                            }
                            if (l.ReleaseMedia != null)
                            {
                                releaseMedias.AddRange(l.ReleaseMedia);
                            }
                        }
                        if (lastFmResult.Errors != null)
                        {
                            resultsExceptions.AddRange(lastFmResult.Errors);
                        }
                    }

                    #endregion LastFm

                    #region Spotify

                    if (this.SpotifyReleaseSearchEngine.IsEnabled)
                    {
                        this.Logger.LogTrace("SpotifyReleaseSearchEngine Release Search for ArtistName [{0}], ReleaseTitle [{1}]", metaData.Artist, result.Title);
                        var spotifyResult = await this.SpotifyReleaseSearchEngine.PerformReleaseSearch(metaData.Artist, result.Title, 1);

                        if (spotifyResult.IsSuccess)
                        {
                            var s = spotifyResult.Data.First();
                            if (s.Tags != null)
                            {
                                result.Tags = result.Tags.AddToDelimitedList(s.Tags);
                            }
                            if (s.Urls != null)
                            {
                                result.URLs = result.URLs.AddToDelimitedList(s.Urls);
                            }
                            if (s.ImageUrls != null)
                            {
                                releaseImageUrls.AddRange(s.ImageUrls);
                            }
                            if (s.ReleaseGenres != null)
                            {
                                releaseGenres.AddRange(s.ReleaseGenres);
                            }
                            if (!string.IsNullOrEmpty(s.ReleaseTitle) && !s.ReleaseTitle.Equals(result.Title, StringComparison.OrdinalIgnoreCase))
                            {
                                result.AlternateNames.AddToDelimitedList(new string[] { s.ReleaseTitle });
                            }
                            result.CopyTo(new Data.Release
                            {
                                ReleaseDate   = result.ReleaseDate ?? s.ReleaseDate,
                                AmgId         = s.AmgId,
                                Profile       = this.HttpEncoder.HtmlEncode(s.Profile),
                                SpotifyId     = s.SpotifyId,
                                MusicBrainzId = s.MusicBrainzId,
                                ITunesId      = s.iTunesId,
                                Title         = result.Title ?? s.ReleaseTitle,
                                Thumbnail     = s.ReleaseThumbnailUrl != null ? WebHelper.BytesForImageUrl(s.ReleaseThumbnailUrl) : null,
                                ReleaseType   = result.ReleaseType == ReleaseType.Unknown ? SafeParser.ToEnum <ReleaseType>(s.ReleaseType) : result.ReleaseType
                            });
                            if (s.ReleaseLabel != null)
                            {
                                releaseLabels.AddRange(s.ReleaseLabel);
                            }
                            if (s.ReleaseMedia != null)
                            {
                                releaseMedias.AddRange(s.ReleaseMedia);
                            }
                        }
                        if (spotifyResult.Errors != null)
                        {
                            resultsExceptions.AddRange(spotifyResult.Errors);
                        }
                    }

                    #endregion Spotify

                    #region Discogs

                    if (this.DiscogsReleaseSearchEngine.IsEnabled)
                    {
                        this.Logger.LogTrace("DiscogsReleaseSearchEngine Release Search for ArtistName [{0}], ReleaseTitle [{1}]", metaData.Artist, result.Title);
                        var discogsResult = await this.DiscogsReleaseSearchEngine.PerformReleaseSearch(metaData.Artist, result.Title, 1);

                        if (discogsResult.IsSuccess)
                        {
                            var d = discogsResult.Data.First();
                            if (d.Urls != null)
                            {
                                result.URLs = result.URLs.AddToDelimitedList(d.Urls);
                            }
                            if (d.ImageUrls != null)
                            {
                                releaseImageUrls.AddRange(d.ImageUrls);
                            }
                            if (d.AlternateNames != null)
                            {
                                result.AlternateNames = result.AlternateNames.AddToDelimitedList(d.AlternateNames);
                            }
                            if (!string.IsNullOrEmpty(d.ReleaseTitle) && !d.ReleaseTitle.Equals(result.Title, StringComparison.OrdinalIgnoreCase))
                            {
                                result.AlternateNames.AddToDelimitedList(new string[] { d.ReleaseTitle });
                            }
                            result.CopyTo(new Data.Release
                            {
                                Profile     = this.HttpEncoder.HtmlEncode(d.Profile),
                                DiscogsId   = d.DiscogsId,
                                Title       = result.Title ?? d.ReleaseTitle,
                                Thumbnail   = d.ReleaseThumbnailUrl != null ? WebHelper.BytesForImageUrl(d.ReleaseThumbnailUrl) : null,
                                ReleaseType = result.ReleaseType == ReleaseType.Unknown ? SafeParser.ToEnum <ReleaseType>(d.ReleaseType) : result.ReleaseType
                            });
                            if (d.ReleaseLabel != null)
                            {
                                releaseLabels.AddRange(d.ReleaseLabel);
                            }
                            if (d.ReleaseMedia != null)
                            {
                                releaseMedias.AddRange(d.ReleaseMedia);
                            }
                        }
                        if (discogsResult.Errors != null)
                        {
                            resultsExceptions.AddRange(discogsResult.Errors);
                        }
                    }

                    #endregion Discogs
                }
                catch (Exception ex)
                {
                    this.Logger.LogError(ex);
                }

                this.Logger.LogTrace("Metadata Providers Search Complete. [{0}]", sw.ElapsedMilliseconds);
            }
            else
            {
                this.Logger.LogTrace("Skipped Metadata Providers Search, DontDoMetaDataProvidersSearchArtists set for Artist [{0}].", metaData.Artist);
            }

            if (result.AlternateNames != null)
            {
                result.AlternateNames = string.Join("|", result.AlternateNames.ToListFromDelimited().Distinct().OrderBy(x => x));
            }
            if (result.URLs != null)
            {
                result.URLs = string.Join("|", result.URLs.ToListFromDelimited().Distinct().OrderBy(x => x));
            }
            if (result.Tags != null)
            {
                result.Tags = string.Join("|", result.Tags.ToListFromDelimited().Distinct().OrderBy(x => x));
            }
            if (releaseGenres.Any())
            {
                result.Genres = new List <ReleaseGenre>();
                foreach (var releaseGenre in releaseGenres.Where(x => !string.IsNullOrEmpty(x)).GroupBy(x => x).Select(x => x.First()))
                {
                    var rg = releaseGenre.Trim();
                    if (!string.IsNullOrEmpty(rg))
                    {
                        result.Genres.Add(new Data.ReleaseGenre
                        {
                            Genre = (this.DbContext.Genres.Where(x => x.Name.ToLower() == rg.ToLower()).FirstOrDefault() ?? new Data.Genre {
                                Name = rg
                            })
                        });
                    }
                }
                ;
            }
            if (releaseImageUrls.Any())
            {
                var imageBag = new ConcurrentBag <Data.Image>();
                var i        = releaseImageUrls.Select(async url =>
                {
                    imageBag.Add(await WebHelper.GetImageFromUrlAsync(url));
                });
                await Task.WhenAll(i);

                // If the release has images merge any fetched images
                var existingImages = result.Images != null?result.Images.ToList() : new List <Data.Image>();

                existingImages.AddRange(imageBag.ToList());
                // Now set release images to be unique image based on image hash
                result.Images = existingImages.Where(x => x != null && x.Bytes != null).GroupBy(x => x.Signature).Select(x => x.First()).Take(this.Configuration.Processing.MaximumReleaseImagesToAdd).ToList();
                if (result.Thumbnail == null && result.Images != null)
                {
                    result.Thumbnail = result.Images.First().Bytes;
                }
            }

            if (releaseLabels.Any())
            {
                result.Labels = releaseLabels.GroupBy(x => x.CatalogNumber).Select(x => x.First()).Select(x => new Data.ReleaseLabel
                {
                    CatalogNumber = x.CatalogNumber,
                    BeginDate     = x.BeginDate,
                    EndDate       = x.EndDate,
                    Status        = Statuses.New,
                    Label         = new Data.Label
                    {
                        Name           = x.Label.LabelName,
                        SortName       = x.Label.LabelSortName,
                        MusicBrainzId  = x.Label.MusicBrainzId,
                        BeginDate      = x.Label.StartDate,
                        EndDate        = x.Label.EndDate,
                        ImageUrl       = x.Label.LabelImageUrl,
                        AlternateNames = x.Label.AlternateNames.ToDelimitedList(),
                        URLs           = x.Label.Urls.ToDelimitedList(),
                        Status         = Statuses.New
                    }
                }).ToList();
            }

            if (releaseMedias.Any())
            {
                var resultReleaseMedias = new List <Data.ReleaseMedia>();
                foreach (var releaseMedia in releaseMedias.GroupBy(x => x.ReleaseMediaNumber).Select(x => x.First()))
                {
                    var rm = new Data.ReleaseMedia
                    {
                        MediaNumber = releaseMedia.ReleaseMediaNumber ?? 0,
                        SubTitle    = releaseMedia.ReleaseMediaSubTitle,
                        TrackCount  = releaseMedia.TrackCount ?? 0,
                        Status      = Statuses.New
                    };
                    var rmTracks = new List <Data.Track>();
                    foreach (var releaseTrack in releaseMedias.Where(x => x.ReleaseMediaNumber == releaseMedia.ReleaseMediaNumber)
                             .SelectMany(x => x.Tracks)
                             .Where(x => x.TrackNumber.HasValue)
                             .OrderBy(x => x.TrackNumber))
                    {
                        var foundTrack = true;
                        var rmTrack    = rmTracks.FirstOrDefault(x => x.TrackNumber == releaseTrack.TrackNumber.Value);
                        if (rmTrack == null)
                        {
                            Data.Artist trackArtist = null;
                            if (releaseTrack.Artist != null)
                            {
                                trackArtist = new Data.Artist
                                {
                                    Name       = releaseTrack.Artist.ArtistName,
                                    SpotifyId  = releaseTrack.Artist.SpotifyId,
                                    ArtistType = releaseTrack.Artist.ArtistType
                                };
                            }
                            rmTrack = new Data.Track
                            {
                                TrackArtist    = trackArtist,
                                TrackArtists   = releaseTrack.Artists,
                                TrackNumber    = releaseTrack.TrackNumber.Value,
                                MusicBrainzId  = releaseTrack.MusicBrainzId,
                                SpotifyId      = releaseTrack.SpotifyId,
                                AmgId          = releaseTrack.AmgId,
                                Title          = releaseTrack.Title,
                                AlternateNames = releaseTrack.AlternateNames.ToDelimitedList(),
                                Duration       = releaseTrack.Duration,
                                Tags           = releaseTrack.Tags.ToDelimitedList(),
                                ISRC           = releaseTrack.ISRC,
                                LastFMId       = releaseTrack.LastFMId,
                                Status         = Statuses.New
                            };
                            foundTrack = false;
                        }
                        rmTrack.Duration      = rmTrack.Duration ?? releaseTrack.Duration;
                        rmTrack.MusicBrainzId = rmTrack.MusicBrainzId ?? releaseTrack.MusicBrainzId;
                        rmTrack.SpotifyId     = rmTrack.SpotifyId ?? releaseTrack.SpotifyId;
                        rmTrack.AmgId         = rmTrack.AmgId ?? releaseTrack.AmgId;
                        rmTrack.Title         = rmTrack.Title ?? releaseTrack.Title;
                        rmTrack.Duration      = releaseTrack.Duration;
                        rmTrack.Tags          = rmTrack.Tags == null?releaseTrack.Tags.ToDelimitedList() : rmTrack.Tags.AddToDelimitedList(releaseTrack.Tags);

                        rmTrack.AlternateNames = rmTrack.AlternateNames == null?releaseTrack.AlternateNames.ToDelimitedList() : rmTrack.AlternateNames.AddToDelimitedList(releaseTrack.AlternateNames);

                        rmTrack.ISRC     = rmTrack.ISRC ?? releaseTrack.ISRC;
                        rmTrack.LastFMId = rmTrack.LastFMId ?? releaseTrack.LastFMId;
                        if (!foundTrack)
                        {
                            rmTracks.Add(rmTrack);
                        }
                    }
                    rm.Tracks     = rmTracks;
                    rm.TrackCount = (short)rmTracks.Count();
                    resultReleaseMedias.Add(rm);
                }
                result.Medias     = resultReleaseMedias;
                result.TrackCount = (short)releaseMedias.SelectMany(x => x.Tracks).Count();
            }

            if (metaData.Images != null && metaData.Images.Any())
            {
                var image = metaData.Images.FirstOrDefault(x => x.Type == AudioMetaDataImageType.FrontCover);
                if (image == null)
                {
                    image = metaData.Images.FirstOrDefault();
                }
                // If there is an image on the metadata file itself then that over-rides metadata providers.
                if (image != null)
                {
                    result.Thumbnail = image.Data;
                }
            }
            if (!string.IsNullOrEmpty(artistFolder))
            {
                // If any file exist for cover that over-rides whatever if found in metadata providers.
                var releaseFolder = new DirectoryInfo(result.ReleaseFileFolder(artistFolder));
                if (releaseFolder.Exists)
                {
                    var cover = ImageHelper.FindImageTypeInDirectory(releaseFolder, ImageType.Release);
                    if (cover.Any())
                    {
                        // Read image and convert to jpeg
                        var coverFileName = cover.First().FullName;
                        result.Thumbnail = File.ReadAllBytes(coverFileName);
                        this.Logger.LogDebug("Using Release Cover File [{0}]", coverFileName);
                    }
                }
            }

            if (result.Thumbnail != null)
            {
                result.Thumbnail = ImageHelper.ResizeImage(result.Thumbnail, this.Configuration.ThumbnailImageSize.Width, this.Configuration.ThumbnailImageSize.Height);
                result.Thumbnail = ImageHelper.ConvertToJpegFormat(result.Thumbnail);
            }
            sw.Stop();
            return(new OperationResult <Data.Release>
            {
                Data = result,
                IsSuccess = result != null,
                Errors = resultsExceptions,
                OperationTime = sw.ElapsedMilliseconds
            });
        }
예제 #9
0
        private OperationResult <AudioMetaData> MetaDataForFileFromIdSharp(string fileName)
        {
            var sw = new Stopwatch();

            sw.Start();
            AudioMetaData result    = new AudioMetaData();
            var           isSuccess = false;

            try
            {
                result.Filename = fileName;
                IAudioFile audioFile = AudioFile.Create(fileName, true);
                if (ID3v2Tag.DoesTagExist(fileName))
                {
                    IID3v2Tag id3v2 = new ID3v2Tag(fileName);
                    result.Release         = id3v2.Album;
                    result.Artist          = id3v2.AlbumArtist ?? id3v2.Artist;
                    result.ArtistRaw       = id3v2.AlbumArtist ?? id3v2.Artist;
                    result.Genres          = id3v2.Genre?.Split(new char[] { ',', '\\' });
                    result.TrackArtist     = id3v2.OriginalArtist ?? id3v2.Artist ?? id3v2.AlbumArtist;
                    result.TrackArtistRaw  = id3v2.OriginalArtist;
                    result.AudioBitrate    = (int?)audioFile.Bitrate;
                    result.AudioChannels   = audioFile.Channels;
                    result.AudioSampleRate = (int)audioFile.Bitrate;
                    result.Disk            = ID3TagsHelper.ParseDiscNumber(id3v2.DiscNumber);
                    result.DiskSubTitle    = id3v2.SetSubtitle;
                    result.Images          = id3v2.PictureList?.Select(x => new AudioMetaDataImage
                    {
                        Data        = x.PictureData,
                        Description = x.Description,
                        MimeType    = x.MimeType,
                        Type        = (AudioMetaDataImageType)x.PictureType
                    }).ToArray();
                    result.Time              = audioFile.TotalSeconds > 0 ? ((decimal?)audioFile.TotalSeconds).ToTimeSpan() : null;
                    result.Title             = id3v2.Title.ToTitleCase(false);
                    result.TrackNumber       = ID3TagsHelper.ParseTrackNumber(id3v2.TrackNumber);
                    result.TotalTrackNumbers = ID3TagsHelper.ParseTotalTrackNumber(id3v2.TrackNumber);
                    var year = id3v2.Year ?? id3v2.RecordingTimestamp ?? id3v2.ReleaseTimestamp ?? id3v2.OriginalReleaseTimestamp;
                    result.Year = ID3TagsHelper.ParseYear(year);
                    isSuccess   = result.IsValid;
                }

                if (!isSuccess)
                {
                    if (ID3v1Tag.DoesTagExist(fileName))
                    {
                        IID3v1Tag id3v1 = new ID3v1Tag(fileName);
                        result.Release         = id3v1.Album;
                        result.Artist          = id3v1.Artist;
                        result.ArtistRaw       = id3v1.Artist;
                        result.AudioBitrate    = (int?)audioFile.Bitrate;
                        result.AudioChannels   = audioFile.Channels;
                        result.AudioSampleRate = (int)audioFile.Bitrate;
                        result.Time            = audioFile.TotalSeconds > 0 ? ((decimal?)audioFile.TotalSeconds).ToTimeSpan() : null;
                        result.Title           = id3v1.Title.ToTitleCase(false);
                        result.TrackNumber     = SafeParser.ToNumber <short?>(id3v1.TrackNumber);
                        var date = SafeParser.ToDateTime(id3v1.Year);
                        result.Year = date?.Year ?? SafeParser.ToNumber <int?>(id3v1.Year);
                        isSuccess   = result.IsValid;
                    }
                }
            }
            catch (Exception ex)
            {
                this.Logger.LogError(ex, "MetaDataForFileFromTagLib Filename [" + fileName + "] Error [" + ex.Serialize() + "]");
            }
            sw.Stop();
            return(new OperationResult <AudioMetaData>
            {
                IsSuccess = isSuccess,
                OperationTime = sw.ElapsedMilliseconds,
                Data = result
            });
        }
예제 #10
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 }
            });
        }
예제 #11
0
        public void Parse_Datetime_ShouldBe2004(string input)
        {
            var parsed = SafeParser.ToDateTime(input);

            Assert.NotNull(parsed);
        }
예제 #12
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> >());
        }
예제 #13
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 }
            });
        }
예제 #14
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 }
            });
        }
예제 #15
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 }
            });
        }
예제 #16
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 }
            });
        }