aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-03-22 22:09:02 -0500
committerGitHub <noreply@github.com>2022-03-22 22:09:02 -0500
commit96fbcedad364b89811d0c4bbdfeb21c846688f15 (patch)
tree62b033a2407b2c79bd534292e9525275eb5fca54 /src
parentebd9918bfb3315199f5554c790e1cb6c76cb0247 (diff)
parentbe08820cb3dd9ff88373493310d12a134a7e6994 (diff)
downloadslskd-96fbcedad364b89811d0c4bbdfeb21c846688f15.tar.gz
Merge pull request #394 from slskd/metadata
Add metadata to files when scanning shares
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Shares/Domain/Share.cs75
-rw-r--r--src/slskd/Shares/SharedFileCache.cs56
-rw-r--r--src/slskd/Shares/SoulseekFileFactory.cs120
-rw-r--r--src/slskd/slskd.csproj1
4 files changed, 203 insertions, 49 deletions
diff --git a/src/slskd/Shares/Domain/Share.cs b/src/slskd/Shares/Domain/Share.cs
new file mode 100644
index 00000000..890c8565
--- /dev/null
+++ b/src/slskd/Shares/Domain/Share.cs
@@ -0,0 +1,75 @@
+// <copyright file="Share.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.Shares
+{
+ using System.Linq;
+ using System.Text.RegularExpressions;
+
+ /// <summary>
+ /// A file share.
+ /// </summary>
+ public sealed class Share
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="Share"/> class.
+ /// </summary>
+ /// <param name="share"></param>
+ public Share(string share)
+ {
+ Raw = share;
+ IsExcluded = share.StartsWith('-') || share.StartsWith('!');
+
+ if (IsExcluded)
+ {
+ share = share[1..];
+ }
+
+ // test to see whether an alias has been specified
+ var matches = Regex.Matches(share, @"^\[(.*)\](.*)$");
+
+ if (matches.Any())
+ {
+ // split the alias from the path, and validate the alias
+ var groups = matches[0].Groups;
+ Alias = groups[1].Value;
+ LocalPath = groups[2].Value;
+ }
+ else
+ {
+ Alias = share.Split(new[] { '/', '\\' }).Last();
+ LocalPath = share;
+ }
+
+ var parent = System.IO.Directory.GetParent(LocalPath).FullName.TrimEnd('/', '\\');
+
+ Mask = Compute.MaskHash(parent);
+
+ var maskedPath = LocalPath.ReplaceFirst(parent, Mask);
+
+ var aliasedSegment = LocalPath[(parent.Length + 1)..];
+ RemotePath = maskedPath.ReplaceFirst(aliasedSegment, Alias);
+ }
+
+ public string Alias { get; init; }
+ public bool IsExcluded { get; init; }
+ public string LocalPath { get; init; }
+ public string Mask { get; init; }
+ public string Raw { get; init; }
+ public string RemotePath { get; init; }
+ }
+}
diff --git a/src/slskd/Shares/SharedFileCache.cs b/src/slskd/Shares/SharedFileCache.cs
index ad2468da..02068e2a 100644
--- a/src/slskd/Shares/SharedFileCache.cs
+++ b/src/slskd/Shares/SharedFileCache.cs
@@ -86,10 +86,13 @@ namespace slskd.Shares
/// Initializes a new instance of the <see cref="SharedFileCache"/> class.
/// </summary>
/// <param name="optionsMonitor"></param>
+ /// <param name="soulseekFileFactory"></param>
public SharedFileCache(
- IOptionsMonitor<Options> optionsMonitor)
+ IOptionsMonitor<Options> optionsMonitor,
+ ISoulseekFileFactory soulseekFileFactory = null)
{
OptionsMonitor = optionsMonitor;
+ SoulseekFileFactory = soulseekFileFactory ?? new SoulseekFileFactory();
}
/// <summary>
@@ -105,6 +108,7 @@ namespace slskd.Shares
private List<Share> Shares { get; set; }
private SqliteConnection SQLite { get; set; }
private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1);
+ private ISoulseekFileFactory SoulseekFileFactory { get; }
/// <summary>
/// Returns the contents of the cache.
@@ -249,8 +253,8 @@ namespace slskd.Shares
try
{
var newFiles = System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly)
- .Select(f => new File(1, f.ReplaceFirst(share.LocalPath, share.RemotePath), new FileInfo(f).Length, Path.GetExtension(f)))
- .ToDictionary(f => f.Filename, f => f);
+ .Select(filename => SoulseekFileFactory.Create(filename, maskedFilename: filename.ReplaceFirst(share.LocalPath, share.RemotePath)))
+ .ToDictionary(file => file.Filename, file => file);
// merge the new dictionary with the rest this will overwrite any duplicate keys, but keys are the fully
// qualified name the only time this *should* cause problems is if one of the shares is a subdirectory of another.
@@ -462,51 +466,5 @@ namespace slskd.Shares
MaskedFiles = new Dictionary<string, File>();
State.SetValue(state => state with { Directories = 0, Files = 0 });
}
-
- private sealed class Share
- {
- public Share(string share)
- {
- Raw = share;
- IsExcluded = share.StartsWith('-') || share.StartsWith('!');
-
- if (IsExcluded)
- {
- share = share[1..];
- }
-
- // test to see whether an alias has been specified
- var matches = Regex.Matches(share, @"^\[(.*)\](.*)$");
-
- if (matches.Any())
- {
- // split the alias from the path, and validate the alias
- var groups = matches[0].Groups;
- Alias = groups[1].Value;
- LocalPath = groups[2].Value;
- }
- else
- {
- Alias = share.Split(new[] { '/', '\\' }).Last();
- LocalPath = share;
- }
-
- var parent = System.IO.Directory.GetParent(LocalPath).FullName.TrimEnd('/', '\\');
-
- Mask = Compute.MaskHash(parent);
-
- var maskedPath = LocalPath.ReplaceFirst(parent, Mask);
-
- var aliasedSegment = LocalPath[(parent.Length + 1)..];
- RemotePath = maskedPath.ReplaceFirst(aliasedSegment, Alias);
- }
-
- public string Alias { get; init; }
- public bool IsExcluded { get; init; }
- public string LocalPath { get; init; }
- public string Mask { get; init; }
- public string Raw { get; init; }
- public string RemotePath { get; init; }
- }
}
} \ No newline at end of file
diff --git a/src/slskd/Shares/SoulseekFileFactory.cs b/src/slskd/Shares/SoulseekFileFactory.cs
new file mode 100644
index 00000000..ccc3e6b0
--- /dev/null
+++ b/src/slskd/Shares/SoulseekFileFactory.cs
@@ -0,0 +1,120 @@
+// <copyright file="SoulseekFileFactory.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+using System.IO;
+
+namespace slskd.Shares
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using Serilog;
+ using Soulseek;
+
+ /// <summary>
+ /// Creates instances of <see cref="Soulseek.File"/>.
+ /// </summary>
+ public interface ISoulseekFileFactory
+ {
+ /// <summary>
+ /// Creates an instance of <see cref="Soulseek.File"/> from the given path.
+ /// </summary>
+ /// <param name="filename">The fully qualified path to the file.</param>
+ /// <param name="maskedFilename">The masked filename.</param>
+ /// <returns>The created instance.</returns>
+ File Create(string filename, string maskedFilename);
+ }
+
+ /// <summary>
+ /// Creates instances of <see cref="Soulseek.File"/>.
+ /// </summary>
+ public class SoulseekFileFactory : ISoulseekFileFactory
+ {
+ private static readonly string[] AudioExtensions = { "aa", "aax", "aac", "aiff", "ape", "dsf", "flac", "m4a", "m4b", "m4p", "mp3", "mpc", "mpp", "ogg", "oga", "wav", "wma", "wv", "webm" };
+ private static readonly string[] VideoExtensions = { "mkv", "ogv", "avi", "wmv", "asf", "mp4", "m4p", "m4v", "mpg", "mpe", "mpv", "mpg", "m2v" };
+ private static readonly HashSet<string> SupportedExtensions = AudioExtensions.Concat(VideoExtensions).ToHashSet();
+
+ private ILogger Log { get; } = Serilog.Log.ForContext<SharedFileCache>();
+
+ /// <summary>
+ /// Creates an instance of <see cref="Soulseek.File"/> from the given path.
+ /// </summary>
+ /// <param name="filename">The fully qualified path to the file.</param>
+ /// <param name="maskedFilename">The masked filename.</param>
+ /// <returns>The created instance.</returns>
+ public File Create(string filename, string maskedFilename)
+ {
+ var code = 1;
+ var size = new FileInfo(filename).Length;
+ var extension = Path.GetExtension(filename)[1..].ToLowerInvariant();
+ List<FileAttribute> attributeList = default;
+
+ if (SupportedExtensions.Contains(extension))
+ {
+ attributeList = new List<FileAttribute>();
+ TagLib.File file = default;
+
+ try
+ {
+ file = TagLib.File.Create(filename, TagLib.ReadStyle.Average | TagLib.ReadStyle.PictureLazy);
+
+ // try to mimick the behavior of existing clients by providing attributes selectively and in a specific order,
+ // depending on whether files use a lossless or lossy codec. lossless files should have BitsPerSample, while lossy
+ // will not. this may not be the best way to determine this.
+ bool isLossless = file.Properties.BitsPerSample > 0;
+
+ if (!isLossless)
+ {
+ // per Nicotine+ docs, Soulseek NS, Nicotine+, Museek+, SoulSeeX all send bit rate, length, then VBR
+ attributeList.Add(new FileAttribute(FileAttributeType.BitRate, file.Properties.AudioBitrate));
+ attributeList.Add(new FileAttribute(FileAttributeType.Length, (int)file.Properties.Duration.TotalSeconds));
+ attributeList.Add(new FileAttribute(FileAttributeType.VariableBitRate, IsVBR(file) ? 1 : 0));
+ }
+ else
+ {
+ // SoulseekQt 2015-6-12 and later provides the length, sample rate and bit depth for lossless files
+ // bitrate can be deduced from this information
+ attributeList.Add(new FileAttribute(FileAttributeType.Length, (int)file.Properties.Duration.TotalSeconds));
+ attributeList.Add(new FileAttribute(FileAttributeType.SampleRate, file.Properties.AudioSampleRate));
+ attributeList.Add(new FileAttribute(FileAttributeType.BitDepth, file.Properties.BitsPerSample));
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Warning("Failed to read metadata from file '{Filename}'; the file is an unsupported format or may be corrupt ({ExceptionType})", filename, ex.GetType().Name);
+ }
+ finally
+ {
+ file?.Dispose();
+ }
+ }
+
+ return new File(code, maskedFilename, size, extension, attributeList);
+ }
+
+ private bool IsVBR(TagLib.File file)
+ {
+ static bool HasVBRIHeader(TagLib.Mpeg.AudioHeader header) => header.VBRIHeader.Present && header.VBRIHeader.TotalSize > 0;
+ static bool HasXingHeader(TagLib.Mpeg.AudioHeader header) => header.XingHeader.Present && header.XingHeader.TotalSize > 0;
+
+ return file.Properties.Codecs.Any(c =>
+ (c is TagLib.Mpeg.AudioHeader h && (HasVBRIHeader(h) || HasXingHeader(h)))
+ || c is TagLib.Aac.AudioHeader
+ || c is TagLib.Ogg.Codec);
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj
index 70c689b8..e2c34310 100644
--- a/src/slskd/slskd.csproj
+++ b/src/slskd/slskd.csproj
@@ -76,6 +76,7 @@
</PackageReference>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.15.1" />
+ <PackageReference Include="TagLibSharp" Version="2.2.0" />
<PackageReference Include="Utility.CommandLine.Arguments" Version="6.0.0" />
<PackageReference Include="Utility.EnvironmentVariables" Version="1.0.5" />
<PackageReference Include="YamlDotNet" Version="11.2.1" />