Example #1
0
        public bool WriteTags(AudioMetaData metaData, string filename, bool force = false)
        {
            try
            {
                if (!metaData.IsValid)
                {
                    this.Logger.LogWarning($"Invalid MetaData `{ metaData }` to save to file [{ filename }]");
                    return(false);
                }
                ID3v1Tag.RemoveTag(filename);

                var trackNumber      = metaData.TrackNumber ?? 1;
                var totalTrackNumber = metaData.TotalTrackNumbers ?? trackNumber;

                var disc      = metaData.Disk ?? 1;
                var discCount = metaData.TotalDiscCount ?? disc;

                IID3v2Tag id3v2 = new ID3v2Tag(filename)
                {
                    Artist      = metaData.Artist,
                    Album       = metaData.Release,
                    Title       = metaData.Title,
                    Year        = metaData.Year.Value.ToString(),
                    TrackNumber = totalTrackNumber < 99 ? $"{trackNumber.ToString("00")}/{totalTrackNumber.ToString("00")}" : $"{trackNumber.ToString()}/{totalTrackNumber.ToString()}",
                    DiscNumber  = discCount < 99 ? $"{disc.ToString("00")}/{discCount.ToString("00")}" : $"{disc.ToString()}/{discCount.ToString()}"
                };
                if (metaData.TrackArtists.Any())
                {
                    id3v2.OriginalArtist = string.Join("/", metaData.TrackArtists);
                }
                if (this.Configuration.Processing.DoClearComments)
                {
                    if (id3v2.CommentsList.Any())
                    {
                        for (var i = 0; i < id3v2.CommentsList.Count; i++)
                        {
                            id3v2.CommentsList[i].Description = null;
                            id3v2.CommentsList[i].Value       = null;
                        }
                    }
                }
                id3v2.Save(filename);

                //// Delete first embedded picture (let's say it exists)
                //theTrack.EmbeddedPictures.RemoveAt(0);

                //// Add 'CD' embedded picture
                //PictureInfo newPicture = new PictureInfo(Commons.ImageFormat.Gif, PictureInfo.PIC_TYPE.CD);
                //newPicture.PictureData = System.IO.File.ReadAllBytes("E:/temp/_Images/pic1.gif");
                //theTrack.EmbeddedPictures.Add(newPicture);

                //// Save modifications on the disc
                //theTrack.Save();


                //tagFile.Tag.Pictures = metaData.Images == null ? null : metaData.Images.Select(x => new TagLib.Picture
                //{
                //    Data = new TagLib.ByteVector(x.Data),
                //    Description = x.Description,
                //    MimeType = x.MimeType,
                //    Type = (TagLib.PictureType)x.Type
                //}).ToArray();
                //tagFile.Save();
                return(true);
            }
            catch (Exception ex)
            {
                this.Logger.LogError(ex, string.Format("MetaData [{0}], Filename [{1}]", metaData.ToString(), filename));
            }
            return(false);
        }
Example #2
0
        public async Task <OperationResult <Data.Release> > GetByName(Data.Artist artist, AudioMetaData metaData, bool doFindIfNotInDatabase = false, bool doAddTracksInDatabase = false, int?submissionId = null)
        {
            SimpleContract.Requires <ArgumentNullException>(artist != null, "Invalid Artist");
            SimpleContract.Requires <ArgumentOutOfRangeException>(artist.Id > 0, "Invalid Artist Id");
            try
            {
                var sw = new Stopwatch();
                sw.Start();
                var cacheRegion   = (new Data.Release {
                    Artist = artist, Title = metaData.Release
                }).CacheRegion;
                var cacheKey      = string.Format("urn:release_by_artist_id_and_name:{0}:{1}", artist.Id, metaData.Release);
                var resultInCache = this.CacheManager.Get <Data.Release>(cacheKey, cacheRegion);
                if (resultInCache != null)
                {
                    sw.Stop();
                    return(new OperationResult <Data.Release>
                    {
                        IsSuccess = true,
                        OperationTime = sw.ElapsedMilliseconds,
                        Data = resultInCache
                    });
                }

                var searchName        = metaData.Release.NormalizeName().ToLower();
                var specialSearchName = metaData.Release.ToAlphanumericName();

                var altStart = $"{ searchName }|";
                var altIn    = $"|{ searchName }|";
                var altEnds  = $"|{ searchName }";

                var altStartSpecial = $"{ specialSearchName }|";
                var altInSpecial    = $"|{ specialSearchName }|";
                var altEndsSpecial  = $"|{ specialSearchName }";

                var release = (from r in this.DbContext.Releases
                               where (r.ArtistId == artist.Id)
                               where (r.Title.ToLower() == searchName ||
                                      r.AlternateNames.ToLower() == searchName ||
                                      r.AlternateNames.ToLower() == specialSearchName ||
                                      r.AlternateNames.ToLower().Contains(altStart) ||
                                      r.AlternateNames.ToLower().Contains(altIn) ||
                                      r.AlternateNames.ToLower().Contains(altEnds) ||
                                      r.AlternateNames.ToLower().Contains(altStartSpecial) ||
                                      r.AlternateNames.ToLower().Contains(altInSpecial) ||
                                      r.AlternateNames.ToLower().Contains(altEndsSpecial))
                               select r
                               ).FirstOrDefault();

                sw.Stop();
                if (release == null || !release.IsValid)
                {
                    this.Logger.LogInformation("ReleaseFactory: Release Not Found For Artist `{0}` MetaData [{1}]", artist.ToString(), metaData.ToString());
                    if (doFindIfNotInDatabase)
                    {
                        OperationResult <Data.Release> releaseSearch = new OperationResult <Data.Release>();
                        try
                        {
                            releaseSearch = await this.PerformMetaDataProvidersReleaseSearch(metaData, artist.ArtistFileFolder(this.Configuration, this.Configuration.LibraryFolder), submissionId);
                        }
                        catch (Exception ex)
                        {
                            sw.Stop();
                            this.Logger.LogError(ex);
                            return(new OperationResult <Data.Release>
                            {
                                OperationTime = sw.ElapsedMilliseconds,
                                Errors = new Exception[1] {
                                    ex
                                }
                            });
                        }
                        if (releaseSearch.IsSuccess)
                        {
                            release          = releaseSearch.Data;
                            release.ArtistId = artist.Id;
                            var addResult = await this.Add(release, doAddTracksInDatabase);

                            if (!addResult.IsSuccess)
                            {
                                sw.Stop();
                                return(new OperationResult <Data.Release>
                                {
                                    OperationTime = sw.ElapsedMilliseconds,
                                    Errors = addResult.Errors
                                });
                            }
                        }
                    }
                }
                if (release != null)
                {
                    this.CacheManager.Add(cacheKey, release);
                }
                return(new OperationResult <Data.Release>
                {
                    IsSuccess = release != null,
                    OperationTime = sw.ElapsedMilliseconds,
                    Data = release
                });
            }
            catch (Exception ex)
            {
                this.Logger.LogError(ex);
            }
            return(new OperationResult <Data.Release>());
        }
Example #3
0
        public async Task <OperationResult <Artist> > GetByName(AudioMetaData metaData, bool doFindIfNotInDatabase = false)
        {
            try
            {
                var sw = new Stopwatch();
                sw.Start();
                var artistName = metaData.Artist ?? metaData.TrackArtist;
                var cacheRegion = new Artist {
                    Name = artistName
                }.CacheRegion;
                var cacheKey      = string.Format("urn:artist_by_name:{0}", artistName);
                var resultInCache = CacheManager.Get <Artist>(cacheKey, cacheRegion);
                if (resultInCache != null)
                {
                    sw.Stop();
                    return(new OperationResult <Artist>
                    {
                        IsSuccess = true,
                        OperationTime = sw.ElapsedMilliseconds,
                        Data = resultInCache
                    });
                }

                var artist = (await DatabaseQueryForArtistName(artistName).ConfigureAwait(false)).FirstOrDefault();
                sw.Stop();
                if (artist?.IsValid != true)
                {
                    Logger.LogTrace("ArtistLookupEngine: Artist Not Found By Name [{0}]", artistName);
                    if (doFindIfNotInDatabase)
                    {
                        OperationResult <Artist> artistSearch = null;

                        // See if roadie.json file exists in the metadata files folder, if so then use artist data from that
                        string releaseRoadieDataFilename = null;
                        try
                        {
                            releaseRoadieDataFilename = Path.Combine(Path.GetDirectoryName(metaData.Filename), "roadie.artist.json");
                        }
                        catch (Exception)
                        {
                        }
                        if (!string.IsNullOrEmpty(releaseRoadieDataFilename) && File.Exists(releaseRoadieDataFilename))
                        {
                            artist = JsonConvert.DeserializeObject <Artist>(File.ReadAllText(releaseRoadieDataFilename));
                            var addResult = await Add(artist).ConfigureAwait(false);

                            if (!addResult.IsSuccess)
                            {
                                sw.Stop();
                                Logger.LogWarning("Unable To Add Artist For Roadie Data File [{0}]", releaseRoadieDataFilename);
                                return(new OperationResult <Artist>
                                {
                                    OperationTime = sw.ElapsedMilliseconds,
                                    Errors = addResult.Errors
                                });
                            }
                            else
                            {
                                File.Delete(releaseRoadieDataFilename);
                            }
                            artist = addResult.Data;
                        }
                        else
                        {
                            try
                            {
                                artistSearch = await PerformMetaDataProvidersArtistSearch(metaData).ConfigureAwait(false);

                                if (artistSearch.IsSuccess)
                                {
                                    artist = artistSearch.Data;
                                    // See if Artist already exist with either Name or Sort Name
                                    var alreadyExists = (await DatabaseQueryForArtistName(artistSearch.Data.Name, artistSearch.Data.SortNameValue).ConfigureAwait(false)).FirstOrDefault();
                                    if (alreadyExists?.IsValid != true)
                                    {
                                        var addResult = await Add(artist).ConfigureAwait(false);

                                        if (!addResult.IsSuccess)
                                        {
                                            sw.Stop();
                                            Logger.LogWarning("Unable To Add Artist For MetaData [{0}]", metaData.ToString());
                                            return(new OperationResult <Artist>
                                            {
                                                OperationTime = sw.ElapsedMilliseconds,
                                                Errors = addResult.Errors
                                            });
                                        }

                                        artist = addResult.Data;
                                    }
                                    else
                                    {
                                        artist = alreadyExists;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.LogError(ex, ex.Serialize());
                            }
                        }
                    }
                }

                if (artist?.IsValid == true)
                {
                    CacheManager.Add(cacheKey, artist);
                }
                return(new OperationResult <Artist>
                {
                    IsSuccess = artist != null,
                    OperationTime = sw.ElapsedMilliseconds,
                    Data = artist
                });
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, ex.Serialize());
            }

            return(new OperationResult <Artist>());
        }