コード例 #1
0
        public void GenerateArtistFolderNames(string input, int artistId, string shouldBe)
        {
            var artistFolder = FolderPathHelper.ArtistPath(Configuration, artistId, input);
            var t            = new DirectoryInfo(Path.Combine(Configuration.LibraryFolder, shouldBe));

            Assert.Equal(t.FullName, artistFolder);
        }
コード例 #2
0
        public void GenerateGenreFolderNames(string input, string shouldBe)
        {
            var artistFolder = FolderPathHelper.GenrePath(Configuration, input);
            var t            = new DirectoryInfo(Path.Combine(Configuration.GenreImageFolder, shouldBe));

            Assert.Equal(t.FullName, artistFolder);
        }
コード例 #3
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);
        }
コード例 #4
0
        ///// <summary>
        /////     Returns a full file path to the Genre Image
        ///// </summary>
        //public string PathToImage(IRoadieSettings configuration)
        //{
        //    return Path.Combine(configuration.GenreImageFolder, $"{ Name.ToFileNameFriendly() } [{ Id }].jpg");
        //}

        /// <summary>
        ///     Returns a full file path to the Genre Image
        /// </summary>
        public string PathToImage(IRoadieSettings configuration, bool makeFolderIfNotExist = false)
        {
            var folder = FolderPathHelper.GenrePath(configuration, SortNameValue);

            if (!Directory.Exists(folder) && makeFolderIfNotExist)
            {
                Directory.CreateDirectory(folder);
            }
            return(Path.Combine(folder, $"{ SortNameValue.ToFileNameFriendly() } [{ Id }].jpg"));
        }
コード例 #5
0
        public static OperationResult <bool> DeleteEmptyFolders(DirectoryInfo processingFolder, ILogger logger)
        {
            var result = new OperationResult <bool>();

            try
            {
                result.IsSuccess = FolderPathHelper.DeleteEmptyFolders(processingFolder);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, string.Format("Error Deleting Empty Folder [{0}] Error [{1}]", processingFolder.FullName, ex.Serialize()));
            }
            return(result);
        }
コード例 #6
0
        public void Inspect(bool doCopy, bool isReadOnly, string directoryToInspect, string destination, bool dontAppendSubFolder, bool dontDeleteEmptyFolders, bool dontRunPreScripts)
        {
            Configuration.Inspector.IsInReadOnlyMode = isReadOnly;
            Configuration.Inspector.DoCopyFiles      = doCopy;

            var artistsFound       = new List <string>();
            var releasesFound      = new List <string>();
            var mp3FilesFoundCount = 0;

            Trace.Listeners.Add(new LoggingTraceListener());

            Console.BackgroundColor = ConsoleColor.White;
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine($"✨ Inspector Start, UTC [{DateTime.UtcNow.ToString("s")}]");
            Console.ResetColor();

            string scriptResult = null;

            // Run PreInspect script
            if (dontRunPreScripts)
            {
                Console.BackgroundColor = ConsoleColor.Blue;
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine($"Skipping PreInspectScript.");
                Console.ResetColor();
            }
            else
            {
                scriptResult = RunScript(Configuration.Processing.PreInspectScript, doCopy, isReadOnly, directoryToInspect, destination);
                if (!string.IsNullOrEmpty(scriptResult))
                {
                    Console.BackgroundColor = ConsoleColor.Blue;
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine($"PreInspectScript Results: {Environment.NewLine + scriptResult + Environment.NewLine}");
                    Console.ResetColor();
                }
            }
            // Create a new destination subfolder for each Inspector run by Current timestamp
            var dest = Path.Combine(destination, DateTime.UtcNow.ToString("yyyyMMddHHmm"));

            if (isReadOnly || dontAppendSubFolder)
            {
                dest = destination;
            }
            // Get all the directorys in the directory
            var directoryDirectories = Directory.GetDirectories(directoryToInspect, "*.*", SearchOption.AllDirectories);
            var directories          = new List <string>
            {
                directoryToInspect
            };

            directories.AddRange(directoryDirectories);
            directories.Remove(dest);
            var inspectedImagesInDirectories = new List <string>();

            try
            {
                var createdDestinationFolder = false;
                var sw = Stopwatch.StartNew();

                foreach (var directory in directories.OrderBy(x => x))
                {
                    var directoryInfo = new DirectoryInfo(directory);

                    Console.ForegroundColor = ConsoleColor.Blue;
                    Console.WriteLine($"╔ 📂 Inspecting [{directory}]");
                    Console.ResetColor();
                    Console.WriteLine("╠╦════════════════════════╣");

                    // Get all the MP3 files in 'directory'
                    var files = Directory.GetFiles(directory, "*.mp3", SearchOption.TopDirectoryOnly);
                    if (files != null && files.Any())
                    {
                        if (!isReadOnly && !createdDestinationFolder && !Directory.Exists(dest))
                        {
                            Directory.CreateDirectory(dest);
                            createdDestinationFolder = true;
                        }

                        // Run directory plugins against current directory
                        foreach (var plugin in DirectoryPlugins.Where(x => !x.IsPostProcessingPlugin)
                                 .OrderBy(x => x.Order))
                        {
                            Console.WriteLine($"╠╬═ Running Directory Plugin {plugin.Description}");
                            var pluginResult = plugin.Process(directoryInfo);
                            if (!pluginResult.IsSuccess)
                            {
                                Console.WriteLine(
                                    $"📛 Plugin Failed: Error [{JsonConvert.SerializeObject(pluginResult)}]");
                                return;
                            }

                            if (!string.IsNullOrEmpty(pluginResult.Data))
                            {
                                Console.WriteLine($"╠╣ Directory Plugin Message: {pluginResult.Data}");
                            }
                        }

                        Console.WriteLine("╠╝");
                        Console.WriteLine($"╟─ Found [{files.Length}] mp3 Files");
                        var fileMetaDatas = new List <AudioMetaData>();
                        var fileInfos     = new List <FileInfo>();
                        // Inspect the found MP3 files in 'directory'
                        foreach (var file in files)
                        {
                            mp3FilesFoundCount++;
                            var fileInfo = new FileInfo(file);
                            Console.ForegroundColor = ConsoleColor.DarkGreen;
                            Console.WriteLine($"╟─ 🎵 Inspecting [{fileInfo.FullName}]");
                            var tagLib = TagsHelper.MetaDataForFile(fileInfo.FullName, true);
                            Console.ForegroundColor = ConsoleColor.Cyan;
                            if (!tagLib?.IsSuccess ?? false)
                            {
                                Console.ForegroundColor = ConsoleColor.DarkYellow;
                            }
                            Console.WriteLine($"╟ (Pre ) : {tagLib.Data}");
                            Console.ResetColor();
                            tagLib.Data.Filename = fileInfo.FullName;
                            var originalMetaData = tagLib.Data.Adapt <AudioMetaData>();
                            if (!originalMetaData.IsValid)
                            {
                                Console.ForegroundColor = ConsoleColor.DarkYellow;
                                Console.WriteLine(
                                    $"╟ ❗ INVALID: Missing: {ID3TagsHelper.DetermineMissingRequiredMetaData(originalMetaData)}");
                                Console.WriteLine($"╟ [{JsonConvert.SerializeObject(tagLib, Newtonsoft.Json.Formatting.Indented)}]");
                                Console.ResetColor();
                            }

                            var pluginMetaData = tagLib.Data;
                            // Run all file plugins against the MP3 file modifying the MetaData
                            foreach (var plugin in FilePlugins.OrderBy(x => x.Order))
                            {
                                Console.WriteLine($"╟┤ Running File Plugin {plugin.Description}");
                                OperationResult <AudioMetaData> pluginResult = null;
                                pluginResult = plugin.Process(pluginMetaData);
                                if (!pluginResult.IsSuccess)
                                {
                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine(
                                        $"📛 Plugin Failed: Error [{JsonConvert.SerializeObject(pluginResult)}]");
                                    Console.ResetColor();
                                    return;
                                }

                                pluginMetaData = pluginResult.Data;
                            }

                            if (!pluginMetaData.IsValid)
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine(
                                    $"╟ ❗ INVALID: Missing: {ID3TagsHelper.DetermineMissingRequiredMetaData(pluginMetaData)}");
                                Console.ResetColor();
                                return;
                            }

                            // See if the MetaData from the Plugins is different from the original
                            if (originalMetaData != null && pluginMetaData != null)
                            {
                                var differences = Comparer.Compare(originalMetaData, pluginMetaData);
                                if (differences.Any())
                                {
                                    var skipDifferences = new List <string>
                                    {
                                        "AudioMetaDataWeights", "FileInfo", "Images", "TrackArtists"
                                    };
                                    var differencesDescription = $"{Environment.NewLine}";
                                    foreach (var difference in differences)
                                    {
                                        if (skipDifferences.Contains(difference.Name))
                                        {
                                            continue;
                                        }
                                        differencesDescription +=
                                            $"╟ || {difference.Name} : Was [{difference.OldValue}] Now [{difference.NewValue}]{Environment.NewLine}";
                                    }

                                    Console.Write($"╟ ≡ != ID3 Tag Modified: {differencesDescription}");

                                    if (!isReadOnly)
                                    {
                                        if (!TagsHelper.WriteTags(pluginMetaData, pluginMetaData.Filename))
                                        {
                                            Console.ForegroundColor = ConsoleColor.Red;
                                            Console.WriteLine("📛 WriteTags Failed");
                                            Console.ResetColor();
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("╟ 🔒 Read Only Mode: Not Modifying File ID3 Tags.");
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("╟ ≡ == ID3 Tag NOT Modified");
                                }
                            }
                            else
                            {
                                var oBad = originalMetaData == null;
                                var pBad = pluginMetaData == null;
                                Console.WriteLine(
                                    $"╟ !! MetaData comparison skipped. {(oBad ? "Pre MetaData is Invalid" : "")} {(pBad ? "Post MetaData is Invalid" : "")}");
                            }

                            if (!pluginMetaData.IsValid)
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine(
                                    $"╟ ❗ INVALID: Missing: {ID3TagsHelper.DetermineMissingRequiredMetaData(pluginMetaData)}");
                                Console.ResetColor();
                            }
                            else
                            {
                                Console.ForegroundColor = ConsoleColor.Cyan;
                                Console.WriteLine($"╟ (Post) : {pluginMetaData}");
                                Console.ResetColor();

                                var artistToken = ArtistInspectorToken(tagLib.Data);
                                if (!artistsFound.Contains(artistToken))
                                {
                                    artistsFound.Add(artistToken);
                                }
                                var releaseToken = ReleaseInspectorToken(tagLib.Data);
                                if (!releasesFound.Contains(releaseToken))
                                {
                                    releasesFound.Add(releaseToken);
                                }
                                var newFileName =
                                    $"CD{(tagLib.Data.Disc ?? ID3TagsHelper.DetermineDiscNumber(tagLib.Data)).ToString("000")}_{tagLib.Data.TrackNumber.Value.ToString("0000")}.mp3";
                                // Artist sub folder is created to hold Releases for Artist and Artist Images
                                var artistSubDirectory = directory == dest
                                    ? fileInfo.DirectoryName
                                    : Path.Combine(dest, artistToken);
                                // Each release is put into a subfolder into the current run Inspector folder to hold MP3 Files and Release Images
                                var subDirectory = directory == dest
                                    ? fileInfo.DirectoryName
                                    : Path.Combine(dest, artistToken, releaseToken);
                                if (!isReadOnly && !Directory.Exists(subDirectory))
                                {
                                    Directory.CreateDirectory(subDirectory);
                                }
                                // Inspect images
                                if (!inspectedImagesInDirectories.Contains(directoryInfo.FullName))
                                {
                                    // Get all artist images and move to artist folder
                                    var foundArtistImages = new List <FileInfo>();
                                    foundArtistImages.AddRange(ImageHelper.FindImagesByName(directoryInfo,
                                                                                            tagLib.Data.Artist, SearchOption.TopDirectoryOnly));
                                    foundArtistImages.AddRange(ImageHelper.FindImagesByName(directoryInfo.Parent,
                                                                                            tagLib.Data.Artist, SearchOption.TopDirectoryOnly));
                                    foundArtistImages.AddRange(ImageHelper.FindImageTypeInDirectory(
                                                                   directoryInfo.Parent, ImageType.Artist, SearchOption.TopDirectoryOnly));
                                    foundArtistImages.AddRange(ImageHelper.FindImageTypeInDirectory(
                                                                   directoryInfo.Parent, ImageType.ArtistSecondary,
                                                                   SearchOption.TopDirectoryOnly));
                                    foundArtistImages.AddRange(ImageHelper.FindImageTypeInDirectory(directoryInfo,
                                                                                                    ImageType.Artist, SearchOption.TopDirectoryOnly));
                                    foundArtistImages.AddRange(ImageHelper.FindImageTypeInDirectory(directoryInfo,
                                                                                                    ImageType.ArtistSecondary, SearchOption.TopDirectoryOnly));

                                    foreach (var artistImage in foundArtistImages)
                                    {
                                        InspectImage(isReadOnly, doCopy, dest, artistSubDirectory, artistImage);
                                    }

                                    // Get all release images and move to release folder
                                    var foundReleaseImages = new List <FileInfo>();
                                    foundReleaseImages.AddRange(
                                        ImageHelper.FindImagesByName(directoryInfo, tagLib.Data.Release));
                                    foundReleaseImages.AddRange(
                                        ImageHelper.FindImageTypeInDirectory(directoryInfo, ImageType.Release));
                                    foundReleaseImages.AddRange(
                                        ImageHelper.FindImageTypeInDirectory(directoryInfo,
                                                                             ImageType.ReleaseSecondary));
                                    foreach (var foundReleaseImage in foundReleaseImages)
                                    {
                                        InspectImage(isReadOnly, doCopy, dest, subDirectory, foundReleaseImage);
                                    }
                                    inspectedImagesInDirectories.Add(directoryInfo.FullName);
                                }

                                // If enabled move MP3 to new folder
                                var newPath = Path.Combine(dest, subDirectory, newFileName.ToFileNameFriendly());
                                if (isReadOnly)
                                {
                                    Console.WriteLine(
                                        $"╟ 🔒 Read Only Mode: File would be [{(doCopy ? "Copied" : "Moved")}] to [{newPath}]");
                                }
                                else
                                {
                                    if (!doCopy)
                                    {
                                        if (fileInfo.FullName != newPath)
                                        {
                                            if (File.Exists(newPath))
                                            {
                                                File.Delete(newPath);
                                            }
                                            fileInfo.MoveTo(newPath);
                                        }
                                    }
                                    else
                                    {
                                        fileInfo.CopyTo(newPath, true);
                                    }

                                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                                    Console.WriteLine($"╠═ 🚛 {(doCopy ? "Copied" : "Moved")} MP3 File to [{newPath}]");
                                    Console.ResetColor();
                                }

                                Console.WriteLine("╠════════════════════════╣");
                            }
                        }
                    }
                }

                foreach (var directory in directories.OrderBy(x => x))
                {
                    var directoryInfo = new DirectoryInfo(directory);
                    Console.WriteLine($"╠╬═ Post-Processing Directory [{directoryInfo.FullName}] ");

                    // Run post-processing directory plugins against current directory
                    foreach (var plugin in DirectoryPlugins.Where(x => x.IsPostProcessingPlugin).OrderBy(x => x.Order))
                    {
                        Console.WriteLine($"╠╬═ Running Post-Processing Directory Plugin {plugin.Description}");
                        var pluginResult = plugin.Process(directoryInfo);
                        if (!pluginResult.IsSuccess)
                        {
                            Console.WriteLine($"📛 Plugin Failed: Error [{JsonConvert.SerializeObject(pluginResult)}]");
                            return;
                        }

                        if (!string.IsNullOrEmpty(pluginResult.Data))
                        {
                            Console.WriteLine($"╠╣ Directory Plugin Message: {pluginResult.Data}");
                        }
                    }
                }

                Console.WriteLine("╠╝");
                sw.Stop();
                Console.WriteLine(
                    $"╚═ Elapsed Time {sw.ElapsedMilliseconds.ToString("0000000")}, Artists {artistsFound.Count()}, Releases {releasesFound.Count()}, MP3s {mp3FilesFoundCount} ═╝");
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                Console.WriteLine("📛 Exception: " + ex);
            }

            if (!dontDeleteEmptyFolders)
            {
                var delEmptyFolderIn = new DirectoryInfo(directoryToInspect);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine($"❌ Deleting Empty folders in [{delEmptyFolderIn.FullName}]");
                Console.ResetColor();
                FolderPathHelper.DeleteEmptyFolders(delEmptyFolderIn);
            }
            else
            {
                Console.WriteLine("🔒 Read Only Mode: Not deleting empty folders.");
            }

            // Run PreInspect script
            scriptResult = RunScript(Configuration.Processing.PostInspectScript, doCopy, isReadOnly, directoryToInspect, destination);
            if (!string.IsNullOrEmpty(scriptResult))
            {
                Console.BackgroundColor = ConsoleColor.Blue;
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine(
                    $"PostInspectScript Results: {Environment.NewLine + scriptResult + Environment.NewLine}");
                Console.ResetColor();
            }
        }
コード例 #7
0
ファイル: ArtistPartial.cs プロジェクト: jindal1979/roadie
 public string ArtistFileFolder(IRoadieSettings configuration, bool createIfNotFound = false)
 {
     return(FolderPathHelper.ArtistPath(configuration, Id, SortNameValue, createIfNotFound));
 }
コード例 #8
0
 /// <summary>
 /// Returns a full file path to the current track thumbnail (if any)
 /// </summary>
 public string PathToTrackThumbnail(IRoadieSettings configuration, string libraryFolder)
 {
     return(FolderPathHelper.PathForTrackThumbnail(configuration, this, libraryFolder));
 }
コード例 #9
0
        public override async Task <OperationResult <bool> > Process(FileInfo fileInfo, bool doJustInfo, int?submissionId)
        {
            Logger.LogTrace($">> Audio: Process FileInfo [{fileInfo}], doJustInfo [{doJustInfo}], submissionId [{submissionId}]", fileInfo, doJustInfo, submissionId);
            var sw     = Stopwatch.StartNew();
            var result = new OperationResult <bool>();

            try
            {
                string destinationName = null;

                var metaData = await AudioMetaDataHelper.GetInfo(fileInfo, doJustInfo).ConfigureAwait(false);

                if (!metaData.IsValid)
                {
                    var minWeight = MinWeightToDelete;
                    if (metaData.ValidWeight < minWeight && minWeight > 0)
                    {
                        Logger.LogTrace(
                            "Invalid File{3}: ValidWeight [{0}], Under MinWeightToDelete [{1}]. Deleting File [{2}]",
                            metaData.ValidWeight, minWeight, fileInfo.FullName,
                            doJustInfo ? " [Read Only Mode] " : string.Empty);
                        if (!doJustInfo)
                        {
                            fileInfo.Delete();
                        }
                    }

                    return(result);
                }

                var artist      = metaData.Artist.CleanString(Configuration);
                var album       = metaData.Release.CleanString(Configuration);
                var title       = metaData.Title.CleanString(Configuration).ToTitleCase(false);
                var year        = metaData.Year;
                var trackNumber = metaData.TrackNumber ?? 0;
                var discNumber  = metaData.Disc ?? 0;

                SimpleContract.Requires(metaData.IsValid, "Track MetaData Invalid");
                SimpleContract.Requires <ArgumentException>(!string.IsNullOrEmpty(artist), "Missing Track Artist");
                SimpleContract.Requires <ArgumentException>(!string.IsNullOrEmpty(album), "Missing Track Album");
                SimpleContract.Requires <ArgumentException>(!string.IsNullOrEmpty(title), "Missing Track Title");
                SimpleContract.Requires <ArgumentException>(year > 0, string.Format("Invalid Track Year [{0}]", year));
                SimpleContract.Requires <ArgumentException>(trackNumber > 0, "Missing Track Number");

                var artistFolder = await DetermineArtistFolder(metaData, doJustInfo).ConfigureAwait(false);

                if (string.IsNullOrEmpty(artistFolder))
                {
                    Logger.LogWarning("Unable To Find ArtistFolder [{0}] For MetaData [{1}]", artistFolder,
                                      metaData.ToString());
                    return(new OperationResult <bool>("Unable To Find Artist Folder"));
                }

                var releaseFolder = await DetermineReleaseFolder(artistFolder, metaData, doJustInfo, submissionId).ConfigureAwait(false);

                if (string.IsNullOrEmpty(releaseFolder))
                {
                    Logger.LogWarning("Unable To Find ReleaseFolder For MetaData [{0}]", metaData.ToString());
                    return(new OperationResult <bool>("Unable To Find Release Folder"));
                }

                destinationName = FolderPathHelper.TrackFullPath(Configuration, metaData, artistFolder, releaseFolder);
                Logger.LogTrace("Info: FileInfo [{0}], Artist Folder [{1}], Release Folder [{1}], Destination Name [{3}]", fileInfo.FullName, artistFolder, releaseFolder, destinationName);
                if (doJustInfo)
                {
                    result.IsSuccess = metaData.IsValid;
                    return(result);
                }

                if (CheckMakeFolder(artistFolder))
                {
                    Logger.LogTrace("Created ArtistFolder [{0}]", artistFolder);
                }
                if (CheckMakeFolder(releaseFolder))
                {
                    Logger.LogTrace("Created ReleaseFolder [{0}]", releaseFolder);
                }

                try
                {
                    // See if file folder parent folder (likely file is in release folder) has primary artist image if so then move to artist folder
                    var artistImages = new List <FileInfo>();
                    artistImages.AddRange(ImageHelper.FindImageTypeInDirectory(fileInfo.Directory, ImageType.Artist));
                    artistImages.AddRange(ImageHelper.FindImageTypeInDirectory(fileInfo.Directory.Parent, ImageType.Artist));
                    if (artistImages.Count > 0)
                    {
                        var artistImage         = artistImages[0];
                        var artistImageFilename = Path.Combine(artistFolder, ImageHelper.ArtistImageFilename);
                        if (artistImageFilename != artistImage.FullName)
                        {
                            // Read image and convert to jpeg
                            var imageBytes = File.ReadAllBytes(artistImage.FullName);
                            imageBytes = ImageHelper.ConvertToJpegFormat(imageBytes);

                            // Move artist image to artist folder
                            if (!doJustInfo)
                            {
                                File.WriteAllBytes(artistImageFilename, imageBytes);
                                artistImage.Delete();
                            }

                            Logger.LogDebug("Found Artist Image File [{0}], Moved to artist folder.", artistImage.Name);
                        }
                    }

                    // See if any secondary artist images if so then move to artist folder
                    artistImages.Clear();
                    artistImages.AddRange(ImageHelper.FindImageTypeInDirectory(fileInfo.Directory, ImageType.ArtistSecondary));
                    artistImages.AddRange(ImageHelper.FindImageTypeInDirectory(fileInfo.Directory.Parent, ImageType.Artist));
                    if (artistImages.Count > 0)
                    {
                        var looper = 0;
                        foreach (var artistImage in artistImages)
                        {
                            looper++;
                            var artistImageFilename = Path.Combine(artistFolder,
                                                                   string.Format(ImageHelper.ArtistSecondaryImageFilename, looper.ToString("00")));
                            if (artistImageFilename != artistImage.FullName)
                            {
                                // Read image and convert to jpeg
                                var imageBytes = File.ReadAllBytes(artistImage.FullName);
                                imageBytes = ImageHelper.ConvertToJpegFormat(imageBytes);

                                // Move artist image to artist folder
                                if (!doJustInfo)
                                {
                                    while (File.Exists(artistImageFilename))
                                    {
                                        looper++;
                                        artistImageFilename = Path.Combine(artistFolder,
                                                                           string.Format(ImageHelper.ArtistSecondaryImageFilename,
                                                                                         looper.ToString("00")));
                                    }

                                    File.WriteAllBytes(artistImageFilename, imageBytes);
                                    artistImage.Delete();
                                }

                                Logger.LogDebug(
                                    "Found Artist Secondary Image File [{0}], Moved to artist folder [{1}].",
                                    artistImage.Name, artistImageFilename);
                            }
                        }
                    }

                    // See if file folder has release image if so then move to release folder
                    var releaseImages = ImageHelper.FindImageTypeInDirectory(fileInfo.Directory, ImageType.Release);
                    if (releaseImages.Any())
                    {
                        var releaseImage  = releaseImages.First();
                        var coverFileName = Path.Combine(releaseFolder, ImageHelper.ReleaseCoverFilename);
                        if (coverFileName != releaseImage.FullName)
                        {
                            // Read image and convert to jpeg
                            var imageBytes = File.ReadAllBytes(releaseImage.FullName);
                            imageBytes = ImageHelper.ConvertToJpegFormat(imageBytes);

                            // Move cover to release folder
                            if (!doJustInfo)
                            {
                                File.WriteAllBytes(coverFileName, imageBytes);
                                releaseImage.Delete();
                            }

                            Logger.LogTrace("Found Release Image File [{0}], Moved to release folder", releaseImage.Name);
                        }
                    }

                    // See if folder has secondary release image if so then move to release folder
                    releaseImages = ImageHelper.FindImageTypeInDirectory(fileInfo.Directory, ImageType.ReleaseSecondary);
                    if (releaseImages.Any())
                    {
                        var looper = 0;
                        foreach (var releaseImage in releaseImages)
                        {
                            looper++;
                            var releaseImageFilename = Path.Combine(releaseFolder,
                                                                    string.Format(ImageHelper.ReleaseSecondaryImageFilename, looper.ToString("00")));
                            if (releaseImageFilename != releaseImage.FullName)
                            {
                                // Read image and convert to jpeg
                                var imageBytes = File.ReadAllBytes(releaseImage.FullName);
                                imageBytes = ImageHelper.ConvertToJpegFormat(imageBytes);

                                // Move cover to release folder
                                if (!doJustInfo)
                                {
                                    File.WriteAllBytes(releaseImageFilename, imageBytes);
                                    releaseImage.Delete();
                                }

                                Logger.LogTrace("Found Release Image File [{0}], Moved to release folder [{1}]", releaseImage.Name, releaseImageFilename);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, "Error with Managing Images For [{0}]", fileInfo.FullName);
                }

                var doesFileExistsForTrack = File.Exists(destinationName);
                if (doesFileExistsForTrack)
                {
                    var existing = new FileInfo(destinationName);

                    // If Exists determine which is better - if same do nothing
                    var existingMetaData = await AudioMetaDataHelper.GetInfo(existing, doJustInfo).ConfigureAwait(false);

                    var areSameFile = existing.FullName.Replace("\\", "").Replace("/", "")
                                      .Equals(fileInfo.FullName.Replace("\\", "").Replace("/", ""),
                                              StringComparison.OrdinalIgnoreCase);
                    var currentBitRate  = metaData.AudioBitrate;
                    var existingBitRate = existingMetaData.AudioBitrate;

                    if (!areSameFile)
                    {
                        if (!existingMetaData.IsValid || currentBitRate > existingBitRate)
                        {
                            Logger.LogTrace("Newer Is Better: Deleting Existing File [{0}]", existing);
                            if (!doJustInfo)
                            {
                                existing.Delete();
                                fileInfo.MoveTo(destinationName);
                            }
                        }
                        else
                        {
                            Logger.LogTrace("Existing [{0}] Is Better or Equal: Deleting Found File [{1}]", existing,
                                            fileInfo.FullName);
                            if (!doJustInfo)
                            {
                                fileInfo.Delete();
                            }
                        }
                    }
                }
                else
                {
                    Logger.LogTrace("Moving File To [{0}]", destinationName);
                    if (!doJustInfo)
                    {
                        try
                        {
                            fileInfo.MoveTo(destinationName);
                        }
                        catch (Exception ex)
                        {
                            Logger.LogError(ex, "Error Moving File [{0}}", destinationName);
                        }
                    }
                }

                result.AdditionalData.Add(PluginResultInfo.AdditionalDataKeyPluginResultInfo, new PluginResultInfo
                {
                    ArtistFolder  = artistFolder,
                    ArtistId      = _artistId,
                    ReleaseFolder = releaseFolder,
                    ReleaseId     = _releaseId,
                    Filename      = fileInfo.FullName,
                    TrackNumber   = metaData.TrackNumber,
                    TrackTitle    = metaData.Title
                });
                result.IsSuccess = true;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error Processing File [{0}}", fileInfo);
            }

            sw.Stop();
            Logger.LogTrace("<< Audio: Process Complete. Result `{0}`, ElapsedTime [{1}]",
                            JsonConvert.SerializeObject(result), sw.ElapsedMilliseconds);
            return(result);
        }
コード例 #10
0
 public string ArtistFileFolder(IRoadieSettings configuration, string destinationRoot)
 {
     return(FolderPathHelper.ArtistPath(configuration, this.SortNameValue, destinationRoot));
 }
コード例 #11
0
ファイル: ReleasePartial.cs プロジェクト: jindal1979/roadie
 /// <summary>
 ///     Return this releases file folder for the given artist folder
 /// </summary>
 /// <param name="artistFolder"></param>
 /// <returns></returns>
 public string ReleaseFileFolder(string artistFolder, bool createIfNotFound = false) => FolderPathHelper.ReleasePath(artistFolder, SortTitleValue, ReleaseDate.Value, createIfNotFound);
コード例 #12
0
ファイル: TrackPartial.cs プロジェクト: jindal1979/roadie
 /// <summary>
 ///     Returns a full file path to the current track
 /// </summary>
 public string PathToTrack(IRoadieSettings configuration)
 {
     return(FolderPathHelper.PathForTrack(configuration, this));
 }
コード例 #13
0
 /// <summary>
 /// Return this releases file folder for the given artist folder
 /// </summary>
 /// <param name="artistFolder"></param>
 /// <returns></returns>
 public string ReleaseFileFolder(string artistFolder)
 {
     return(FolderPathHelper.ReleasePath(artistFolder, this.Title, this.ReleaseDate.Value));
 }