Skip to content

Commit

Permalink
Improved code to get rid of warnings, prepared release of 0.2.4
Browse files Browse the repository at this point in the history
  • Loading branch information
sandreas committed Dec 29, 2024
1 parent 311b885 commit 421506f
Show file tree
Hide file tree
Showing 24 changed files with 90 additions and 74 deletions.
2 changes: 1 addition & 1 deletion tone.Tests/tone.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<PackageReference Include="Sandreas.Files" Version="1.1.2" />
<PackageReference Include="Spectre.Console.Cli" Version="0.49.1" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
Expand Down
2 changes: 1 addition & 1 deletion tone/Commands/MergeCommand.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace tone.Commands;
// namespace tone.Commands;

// [Command("merge")]
// public class MergeCommand : ICommand
Expand Down
2 changes: 0 additions & 2 deletions tone/Commands/Settings/SplitCommandSettings.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System;
using Spectre.Console.Cli;
using tone.Interceptors;

namespace tone.Commands.Settings;

Expand Down
2 changes: 1 addition & 1 deletion tone/Commands/Settings/TagSettingsBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ public class TagSettingsBase : CommandSettingsBase,
IMetadata,
ICoverTaggerSettings,
IToneJsonTaggerSettings,
IIdTaggerSettings,
IPathPatternSettings,
IChptFmtNativeTaggerSettings,
IFfmetadataTaggerSettings,
IRemoveTaggerSettings,
ITaggerOrderSettings,
// IIdTaggerSettings, // IScriptSettings already implements IIdTaggerSettings
IScriptSettings,
IPrependMovementToDescriptionTaggerSettings
{
Expand Down
1 change: 0 additions & 1 deletion tone/Common/StringParser/Token.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Text;

namespace tone.Common.StringParser;

Expand Down
2 changes: 0 additions & 2 deletions tone/Directives/LinqExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace tone.Directives;

Expand Down
2 changes: 0 additions & 2 deletions tone/Interceptors/CommandSettingsProvider.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Spectre.Console.Cli;
using tone.Metadata.Taggers;

namespace tone.Interceptors;

Expand Down
2 changes: 1 addition & 1 deletion tone/Metadata/Taggers/ChptFmtNativeTagger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public ChptFmtNativeTagger(IFileSystem? fileSystem, ChptFmtNativeMetadataFormat
{
}

protected override string? BuildPreferredFileName(IFileInfo audioFile) => ConcatPreferredFileName(audioFile, DefaultFileSuffix);
protected override string BuildPreferredFileName(IFileInfo audioFile) => ConcatPreferredFileName(audioFile, DefaultFileSuffix);

protected override bool FilterCallback(IFileInfo f) => f.Name.EndsWith(DefaultFileSuffix);

Expand Down
2 changes: 1 addition & 1 deletion tone/Metadata/Taggers/CoverTagger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class CoverTagger: INamedTagger
public CoverTagger(IFileSystem fs, IEnumerable<string> covers, bool autoload=false)
{
_fs = fs;
_covers = covers.Select(f => fs.FileInfo.FromFileName(f)).ToList();
_covers = covers.Select(f => fs.FileInfo.New(f)).ToList();
_autoload = autoload;
}

Expand Down
2 changes: 1 addition & 1 deletion tone/Metadata/Taggers/FfmetadataTagger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public FfmetadataTagger(IFileSystem? fileSystem, FfmetadataFormat parser, string
{
}

protected override string? BuildPreferredFileName(IFileInfo audioFile) => ConcatPreferredFileName(audioFile, DefaultFileSuffix);
protected override string BuildPreferredFileName(IFileInfo audioFile) => ConcatPreferredFileName(audioFile, DefaultFileSuffix);

protected override bool FilterCallback(IFileInfo f) => f.Name.EndsWith(DefaultFileSuffix) || f.Name.EndsWith(".ffmetadata");

Expand Down
10 changes: 5 additions & 5 deletions tone/Metadata/Taggers/IFileSystemExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ public static class FileSystemExtensions
public static IDirectoryInfo GetContainingDirectory(this IFileSystem fs, string path) {
var attr = fs.File.GetAttributes(path);
if ((attr & FileAttributes.Directory) != FileAttributes.Directory) {
path = fs.Path.GetDirectoryName(path);
path = fs.Path.GetDirectoryName(path) ?? path;
}

return fs.DirectoryInfo.FromDirectoryName(path);
return fs.DirectoryInfo.New(path);
}

public static IEnumerable<IFileInfo> FindMatchingFiles(this IFileSystem fs, string path, string fileNameSuffix, string fileNamePrefix="")
Expand All @@ -29,14 +29,14 @@ public static IEnumerable<IFileInfo> FindMatchingFiles(this IFileSystem fs, stri
{
newFileNamePrefix = fs.Path.GetFileNameWithoutExtension(path) + ".";
}
path = fs.Path.GetDirectoryName(path);
result.AddRange(fs.Directory.EnumerateFiles(path).Where(f => f.StartsWith(newFileNamePrefix) && f.EndsWith(fileNameSuffix)).Select(f => fs.FileInfo.FromFileName(f)));
path = fs.Path.GetDirectoryName(path) ?? path;
result.AddRange(fs.Directory.EnumerateFiles(path).Where(f => f.StartsWith(newFileNamePrefix) && f.EndsWith(fileNameSuffix)).Select(f => fs.FileInfo.New(f)));
if (result.Count > 0)
{
return result;
}
}

return fs.Directory.EnumerateFiles(path).Where(f => (fileNamePrefix == "" || f.StartsWith(fileNamePrefix)) && f.EndsWith(fileNameSuffix)).Select(f => fs.FileInfo.FromFileName(f));
return fs.Directory.EnumerateFiles(path).Where(f => (fileNamePrefix == "" || f.StartsWith(fileNamePrefix)) && f.EndsWith(fileNameSuffix)).Select(f => fs.FileInfo.New(f));
}
}
4 changes: 2 additions & 2 deletions tone/Metadata/Taggers/IdTaggerComposite.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public async Task<Status<string>> UpdateAsync(IMetadata metadata, IMetadata? ori
if (tagger.SupportsId(Id))
{
tagger.Id = Id;
var result = await tagger.UpdateAsync(metadata);
_ = await tagger.UpdateAsync(metadata);
}
}

Expand All @@ -70,7 +70,7 @@ private Result<string, string> ResolveScriptedId(IMetadata metadata)
_jint.SetValue("metadata", metadata);
return Ok(_jint.Evaluate("return " + Id).AsString());
}
catch (Exception e)
catch (Exception)
{
return Error("Id could not be resolved: " + Id);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ namespace tone.Metadata.Taggers.IdTaggers.Audible;

public class AudibleMetadataResponse
{
public Product Product { get; set; }
public Product Product { get; set; } = new();

}
1 change: 0 additions & 1 deletion tone/Metadata/Taggers/IdTaggers/ScriptIdTagger.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Collections.Generic;
using System.Linq;
using Jint;

namespace tone.Metadata.Taggers.IdTaggers;
Expand Down
4 changes: 2 additions & 2 deletions tone/Metadata/Taggers/ToneJsonTagger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@ public class ToneJsonTagger : INamedTagger
public ToneJsonTagger(IFileSystem fs, IEnumerable<string> toneJsonFiles, bool autoload = false)
{
_fs = fs;
_toneJsonFiles = toneJsonFiles.Select(f => fs.FileInfo.FromFileName(f)).ToList();
_toneJsonFiles = toneJsonFiles.Select(f => fs.FileInfo.New(f)).ToList();
_autoload = autoload;
}

public ToneJsonTagger(IFileSystem fs, IToneJsonTaggerSettings settings)
{
_fs = fs;
_toneJsonFiles = settings.ToneJsonFiles.Select(f => fs.FileInfo.FromFileName(f)).ToList();
_toneJsonFiles = settings.ToneJsonFiles.Select(f => fs.FileInfo.New(f)).ToList();
_autoload = settings.AutoImportToneJson;
}

Expand Down
7 changes: 3 additions & 4 deletions tone/Metadata/ToneJsonAudio.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
using ATL;
using Sandreas.AudioMetadata;

namespace tone.Metadata;

public class ToneJsonAudio
{
public int Bitrate { get; set; }
public string Format { get; set; }
public string FormatShort { get; set; }
public string Format { get; set; } = "";
public string FormatShort { get; set; } = "";

public double SampleRate { get; set; }
public double Duration { get; set; }
public bool Vbr { get; set; }
public object? Channels { get; set; }
public object? Frames { get; set; }
public MetadataSpecification[] MetaFormat { get; set; }
public MetadataSpecification[] MetaFormat { get; set; } = System.Array.Empty<MetadataSpecification>();
}
2 changes: 0 additions & 2 deletions tone/Metadata/ToneJsonContractResolver.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using ATL;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Sandreas.AudioMetadata;
Expand Down
5 changes: 2 additions & 3 deletions tone/Metadata/ToneJsonFile.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using ATL;

namespace tone.Metadata;

Expand All @@ -9,6 +8,6 @@ public class ToneJsonFile
public DateTime Created { get; set; }
public DateTime Modified { get; set; }
public DateTime Accessed { get; set; }
public string Path { get; set; }
public string Name { get; set; }
public string Path { get; set; } = "";
public string Name { get; set; } = "";
}
45 changes: 23 additions & 22 deletions tone/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@
{
new StringEnumConverter { NamingStrategy = new CamelCaseNamingStrategy() }
},
Formatting = Formatting.Indented,
Formatting = Formatting.Indented
});
services.AddSingleton<ChptFmtNativeSerializer>();
services.AddSingleton<FfmetadataSerializer>();
Expand All @@ -116,24 +116,26 @@
var startupErrorsService = s.GetRequiredService<StartupErrorService>();
var settings = settingsProvider.Get<IPathPatternSettings>();
var pathPatterns = new List<(string, Grok)>();
if (settings != null)
if (settings == null)
{
var customPatterns = settings.PathPatternExtension.Concat(new[]
{
"NOTDIRSEP [^/\\\\]*",
"PARTNUMBER \\b[0-9-.,IVXLCDM]+\\b"
});
return new PathPatternMatcher(pathPatterns);
}

var grokDefinitions = patternService.Build(settings.PathPattern, customPatterns);
if (grokDefinitions)
{
pathPatterns = grokDefinitions.Value.ToList();
}
else
{
startupErrorsService.Errors.Add((ReturnCode.GeneralError,
"Could not parse `--path-pattern`: " + grokDefinitions.Error));
}
string[] predefinedPatterns = {
@"NOTDIRSEP [^/\\]*",
@"PARTNUMBER \b[0-9-.,IVXLCDM]+\b"
};
var customPatterns = settings.PathPatternExtension.Concat(predefinedPatterns);

var grokDefinitions = patternService.Build(settings.PathPattern, customPatterns);
if (grokDefinitions)
{
pathPatterns = grokDefinitions.Value.ToList();
}
else
{
startupErrorsService.Errors.Add((ReturnCode.GeneralError,
"Could not parse `--path-pattern`: " + grokDefinitions.Error));
}

return new PathPatternMatcher(pathPatterns);
Expand All @@ -151,10 +153,9 @@
});
});

services.AddSingleton<AudibleIdTaggerSettings>(_ => new AudibleIdTaggerSettings(){
services.AddSingleton<AudibleIdTaggerSettings>(_ => new AudibleIdTaggerSettings {
MetadataUrlTemplate = Environment.GetEnvironmentVariable("PILABOR_AUDIBLE_METADATA_URL_TEMPLATE") ?? "",
ChaptersUrlTemplate = Environment.GetEnvironmentVariable("PILABOR_AUDIBLE_CHAPTERS_URL_TEMPLATE") ?? "",

ChaptersUrlTemplate = Environment.GetEnvironmentVariable("PILABOR_AUDIBLE_CHAPTERS_URL_TEMPLATE") ?? ""
});
services.AddHttpClient<AudibleIdTagger>();

Expand Down Expand Up @@ -230,7 +231,7 @@
config.UseStrictParsing();
config.CaseSensitivity(CaseSensitivity.None);
config.SetApplicationName("tone");
config.SetApplicationVersion("0.2.3");
config.SetApplicationVersion("0.2.4");
config.ValidateExamples();
config.AddCommand<DumpCommand>("dump")
.WithDescription("dump metadata for files and directories (directories are traversed recursively)")
Expand Down Expand Up @@ -266,7 +267,7 @@
}
catch (Exception e)
{
if (e is CommandParseException { Pretty: { } } ce)
if (e is CommandParseException { Pretty: not null } ce)
{
AnsiConsole.Write(ce.Pretty);
}
Expand Down
10 changes: 6 additions & 4 deletions tone/Services/DirectoryLoaderService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -155,18 +155,20 @@ public IEnumerable<AudioBookPackage> BuildPackages(IEnumerable<IFileInfo> files,
// find baseDir by going up until the pattern does not match any more
var grokPattern = grokPatternContainer.patternAsString;
var baseDir = file.Directory;
while(pathMatcher.TryMatchSinglePattern(baseDir.Parent.FullName, out var grokPatternContainer2) && grokPatternContainer2.patternAsString == grokPattern)
var parent = baseDir?.Parent;
var parentFullName = parent?.FullName ?? "";
while(pathMatcher.TryMatchSinglePattern(parentFullName, out var grokPatternContainer2) && grokPatternContainer2.patternAsString == grokPattern)
{
baseDir = baseDir.Parent;
if(baseDir.Root.FullName == baseDir.FullName)
baseDir = baseDir?.Parent;
if(baseDir?.Root.FullName == baseDir?.FullName)
{
break;
}
}

var identifier = string.Join(",",grokResult.Select(r => r.Key+"="+r.Value));

var existingDirectoryPackage = packages.FirstOrDefault(p => p.Id == identifier && p.BaseDirectory?.FullName == baseDir.FullName);
var existingDirectoryPackage = packages.FirstOrDefault(p => p.Id == identifier && p.BaseDirectory?.FullName == baseDir?.FullName);
if (existingDirectoryPackage == null)
{
packages.Add(new AudioBookPackage
Expand Down
19 changes: 12 additions & 7 deletions tone/Services/JavaScriptApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,9 @@ public JavaScriptApi()
// fallback "dummy" constructor in case of missing prerequisites
_jint = new Engine();
_tagger = new TaggerComposite();
_idTagger = new IdTaggerComposite(_jint, null);
_idTagger = new IdTaggerComposite(_jint);
_fs = new FileSystem();
_http = new HttpClient();

}
public JavaScriptApi(Engine jint, FileSystem fs, HttpClient http, TaggerComposite tagger, IdTaggerComposite idTagger, IScriptSettings scriptSettings)
{
Expand Down Expand Up @@ -81,15 +80,21 @@ private string _fetch(string url, FetchData fetchData, object? data=null)
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}

var destinationFile = _fs.FileInfo.FromFileName(fetchData.DownloadPath);
var destinationFile = _fs.FileInfo.New(fetchData.DownloadPath);

if(destinationFile.Exists && !fetchData.Overwrite)
{
return "";
}

if(!_fs.Directory.Exists(destinationFile.DirectoryName))
{
_fs.Directory.CreateDirectory(destinationFile.DirectoryName);
var dirname = destinationFile.DirectoryName;
if (dirname is null)
{
return "";
}
_fs.Directory.CreateDirectory(dirname);
}

await _fs.File.WriteAllBytesAsync(destinationFile.FullName, await response.Content.ReadAsByteArrayAsync());
Expand All @@ -113,12 +118,12 @@ private HttpRequestMessage BuildRequestMessage(string url, object? data, FetchDa
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(url),
RequestUri = new Uri(url)

};

if(data != null){
httpRequestMessage = new HttpRequestMessage() {
httpRequestMessage = new HttpRequestMessage {
Method = ConvertStringToHttpMethod(fetchData.Method),
RequestUri = new Uri(url),
Content = new StringContent(fetchData.Body)
Expand Down Expand Up @@ -167,7 +172,7 @@ public TimeSpan CreateDateTime(int milliseconds)
return TimeSpan.FromMilliseconds(milliseconds);
}
public ChapterInfo CreateChapter(string title, uint start, uint length, PictureInfo? picture=null, string subtitle="",string uniqueId="") {
return new ChapterInfo()
return new ChapterInfo
{
Title = title,
StartTime = start,
Expand Down
Loading

0 comments on commit 421506f

Please sign in to comment.