repo creation with initial code after cloning public repo
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
using Emby.Naming.Common;
|
||||
using Jellyfin.Extensions;
|
||||
|
||||
namespace Emby.Naming.Audio
|
||||
{
|
||||
/// <summary>
|
||||
/// Helper class to determine if Album is multipart.
|
||||
/// </summary>
|
||||
public partial class AlbumParser
|
||||
{
|
||||
private readonly NamingOptions _options;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AlbumParser"/> class.
|
||||
/// </summary>
|
||||
/// <param name="options">Naming options containing AlbumStackingPrefixes.</param>
|
||||
public AlbumParser(NamingOptions options)
|
||||
{
|
||||
_options = options;
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"[-\.\(\)\s]+")]
|
||||
private static partial Regex CleanRegex();
|
||||
|
||||
/// <summary>
|
||||
/// Function that determines if album is multipart.
|
||||
/// </summary>
|
||||
/// <param name="path">Path to file.</param>
|
||||
/// <returns>True if album is multipart.</returns>
|
||||
public bool IsMultiPart(string path)
|
||||
{
|
||||
var filename = Path.GetFileName(path);
|
||||
if (filename.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// TODO: Move this logic into options object
|
||||
// Even better, remove the prefixes and come up with regexes
|
||||
// But Kodi documentation seems to be weak for audio
|
||||
|
||||
// Normalize
|
||||
// Remove whitespace
|
||||
filename = CleanRegex().Replace(filename, " ");
|
||||
|
||||
ReadOnlySpan<char> trimmedFilename = filename.AsSpan().TrimStart();
|
||||
|
||||
foreach (var prefix in _options.AlbumStackingPrefixes)
|
||||
{
|
||||
if (!trimmedFilename.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var tmp = trimmedFilename.Slice(prefix.Length).Trim();
|
||||
|
||||
if (int.TryParse(tmp.LeftPart(' '), CultureInfo.InvariantCulture, out _))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Emby.Naming.Common;
|
||||
using Jellyfin.Extensions;
|
||||
|
||||
namespace Emby.Naming.Audio
|
||||
{
|
||||
/// <summary>
|
||||
/// Static helper class to determine if file at path is audio file.
|
||||
/// </summary>
|
||||
public static class AudioFileParser
|
||||
{
|
||||
/// <summary>
|
||||
/// Static helper method to determine if file at path is audio file.
|
||||
/// </summary>
|
||||
/// <param name="path">Path to file.</param>
|
||||
/// <param name="options"><see cref="NamingOptions"/> containing AudioFileExtensions.</param>
|
||||
/// <returns>True if file at path is audio file.</returns>
|
||||
public static bool IsAudioFile(string path, NamingOptions options)
|
||||
{
|
||||
var extension = Path.GetExtension(path.AsSpan());
|
||||
return options.AudioFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
using System;
|
||||
|
||||
namespace Emby.Naming.AudioBook
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a single video file.
|
||||
/// </summary>
|
||||
public class AudioBookFileInfo : IComparable<AudioBookFileInfo>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AudioBookFileInfo"/> class.
|
||||
/// </summary>
|
||||
/// <param name="path">Path to audiobook file.</param>
|
||||
/// <param name="container">File type.</param>
|
||||
/// <param name="partNumber">Number of part this file represents.</param>
|
||||
/// <param name="chapterNumber">Number of chapter this file represents.</param>
|
||||
public AudioBookFileInfo(string path, string container, int? partNumber = default, int? chapterNumber = default)
|
||||
{
|
||||
Path = path;
|
||||
Container = container;
|
||||
PartNumber = partNumber;
|
||||
ChapterNumber = chapterNumber;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the path.
|
||||
/// </summary>
|
||||
/// <value>The path.</value>
|
||||
public string Path { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the container.
|
||||
/// </summary>
|
||||
/// <value>The container.</value>
|
||||
public string Container { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the part number.
|
||||
/// </summary>
|
||||
/// <value>The part number.</value>
|
||||
public int? PartNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the chapter number.
|
||||
/// </summary>
|
||||
/// <value>The chapter number.</value>
|
||||
public int? ChapterNumber { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public int CompareTo(AudioBookFileInfo? other)
|
||||
{
|
||||
if (ReferenceEquals(this, other))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (ReferenceEquals(null, other))
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
var chapterNumberComparison = Nullable.Compare(ChapterNumber, other.ChapterNumber);
|
||||
if (chapterNumberComparison != 0)
|
||||
{
|
||||
return chapterNumberComparison;
|
||||
}
|
||||
|
||||
var partNumberComparison = Nullable.Compare(PartNumber, other.PartNumber);
|
||||
if (partNumberComparison != 0)
|
||||
{
|
||||
return partNumberComparison;
|
||||
}
|
||||
|
||||
return string.Compare(Path, other.Path, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
using Emby.Naming.Common;
|
||||
|
||||
namespace Emby.Naming.AudioBook
|
||||
{
|
||||
/// <summary>
|
||||
/// Parser class to extract part and/or chapter number from audiobook filename.
|
||||
/// </summary>
|
||||
public class AudioBookFilePathParser
|
||||
{
|
||||
private readonly NamingOptions _options;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AudioBookFilePathParser"/> class.
|
||||
/// </summary>
|
||||
/// <param name="options">Naming options containing AudioBookPartsExpressions.</param>
|
||||
public AudioBookFilePathParser(NamingOptions options)
|
||||
{
|
||||
_options = options;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Based on regex determines if filename includes part/chapter number.
|
||||
/// </summary>
|
||||
/// <param name="path">Path to audiobook file.</param>
|
||||
/// <returns>Returns <see cref="AudioBookFilePathParser"/> object.</returns>
|
||||
public AudioBookFilePathParserResult Parse(string path)
|
||||
{
|
||||
AudioBookFilePathParserResult result = default;
|
||||
var fileName = Path.GetFileNameWithoutExtension(path);
|
||||
foreach (var expression in _options.AudioBookPartsExpressions)
|
||||
{
|
||||
var match = Regex.Match(fileName, expression, RegexOptions.IgnoreCase);
|
||||
if (match.Success)
|
||||
{
|
||||
if (!result.ChapterNumber.HasValue)
|
||||
{
|
||||
var value = match.Groups["chapter"];
|
||||
if (value.Success)
|
||||
{
|
||||
if (int.TryParse(value.ValueSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intValue))
|
||||
{
|
||||
result.ChapterNumber = intValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!result.PartNumber.HasValue)
|
||||
{
|
||||
var value = match.Groups["part"];
|
||||
if (value.Success)
|
||||
{
|
||||
if (int.TryParse(value.ValueSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intValue))
|
||||
{
|
||||
result.PartNumber = intValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace Emby.Naming.AudioBook
|
||||
{
|
||||
/// <summary>
|
||||
/// Data object for passing result of audiobook part/chapter extraction.
|
||||
/// </summary>
|
||||
public record struct AudioBookFilePathParserResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets optional number of path extracted from audiobook filename.
|
||||
/// </summary>
|
||||
public int? PartNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets optional number of chapter extracted from audiobook filename.
|
||||
/// </summary>
|
||||
public int? ChapterNumber { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Emby.Naming.AudioBook
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a complete video, including all parts and subtitles.
|
||||
/// </summary>
|
||||
public class AudioBookInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AudioBookInfo" /> class.
|
||||
/// </summary>
|
||||
/// <param name="name">Name of audiobook.</param>
|
||||
/// <param name="year">Year of audiobook release.</param>
|
||||
/// <param name="files">List of files composing the actual audiobook.</param>
|
||||
/// <param name="extras">List of extra files.</param>
|
||||
/// <param name="alternateVersions">Alternative version of files.</param>
|
||||
public AudioBookInfo(string name, int? year, IReadOnlyList<AudioBookFileInfo> files, IReadOnlyList<AudioBookFileInfo> extras, IReadOnlyList<AudioBookFileInfo> alternateVersions)
|
||||
{
|
||||
Name = name;
|
||||
Year = year;
|
||||
Files = files;
|
||||
Extras = extras;
|
||||
AlternateVersions = alternateVersions;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name.
|
||||
/// </summary>
|
||||
/// <value>The name.</value>
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the year.
|
||||
/// </summary>
|
||||
public int? Year { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the files.
|
||||
/// </summary>
|
||||
/// <value>The files.</value>
|
||||
public IReadOnlyList<AudioBookFileInfo> Files { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the extras.
|
||||
/// </summary>
|
||||
/// <value>The extras.</value>
|
||||
public IReadOnlyList<AudioBookFileInfo> Extras { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the alternate versions.
|
||||
/// </summary>
|
||||
/// <value>The alternate versions.</value>
|
||||
public IReadOnlyList<AudioBookFileInfo> AlternateVersions { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Emby.Naming.Common;
|
||||
using Emby.Naming.Video;
|
||||
using MediaBrowser.Model.IO;
|
||||
|
||||
namespace Emby.Naming.AudioBook
|
||||
{
|
||||
/// <summary>
|
||||
/// Class used to resolve Name, Year, alternative files and extras from stack of files.
|
||||
/// </summary>
|
||||
public class AudioBookListResolver
|
||||
{
|
||||
private readonly NamingOptions _options;
|
||||
private readonly AudioBookResolver _audioBookResolver;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AudioBookListResolver"/> class.
|
||||
/// </summary>
|
||||
/// <param name="options">Naming options passed along to <see cref="AudioBookResolver"/> and <see cref="AudioBookNameParser"/>.</param>
|
||||
public AudioBookListResolver(NamingOptions options)
|
||||
{
|
||||
_options = options;
|
||||
_audioBookResolver = new AudioBookResolver(_options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves Name, Year and differentiate alternative files and extras from regular audiobook files.
|
||||
/// </summary>
|
||||
/// <param name="files">List of files related to audiobook.</param>
|
||||
/// <returns>Returns IEnumerable of <see cref="AudioBookInfo"/>.</returns>
|
||||
public IEnumerable<AudioBookInfo> Resolve(IEnumerable<FileSystemMetadata> files)
|
||||
{
|
||||
// File with empty fullname will be sorted out here.
|
||||
var audiobookFileInfos = files
|
||||
.Select(i => _audioBookResolver.Resolve(i.FullName))
|
||||
.OfType<AudioBookFileInfo>();
|
||||
|
||||
var stackResult = StackResolver.ResolveAudioBooks(audiobookFileInfos);
|
||||
|
||||
foreach (var stack in stackResult)
|
||||
{
|
||||
var stackFiles = stack.Files
|
||||
.Select(i => _audioBookResolver.Resolve(i))
|
||||
.OfType<AudioBookFileInfo>()
|
||||
.ToList();
|
||||
|
||||
stackFiles.Sort();
|
||||
|
||||
var nameParserResult = new AudioBookNameParser(_options).Parse(stack.Name);
|
||||
|
||||
FindExtraAndAlternativeFiles(ref stackFiles, out var extras, out var alternativeVersions, nameParserResult);
|
||||
|
||||
var info = new AudioBookInfo(
|
||||
nameParserResult.Name,
|
||||
nameParserResult.Year,
|
||||
stackFiles,
|
||||
extras,
|
||||
alternativeVersions);
|
||||
|
||||
yield return info;
|
||||
}
|
||||
}
|
||||
|
||||
private void FindExtraAndAlternativeFiles(ref List<AudioBookFileInfo> stackFiles, out List<AudioBookFileInfo> extras, out List<AudioBookFileInfo> alternativeVersions, AudioBookNameParserResult nameParserResult)
|
||||
{
|
||||
extras = new List<AudioBookFileInfo>();
|
||||
alternativeVersions = new List<AudioBookFileInfo>();
|
||||
|
||||
var haveChaptersOrPages = stackFiles.Any(x => x.ChapterNumber is not null || x.PartNumber is not null);
|
||||
var groupedBy = stackFiles.GroupBy(file => new { file.ChapterNumber, file.PartNumber });
|
||||
var nameWithReplacedDots = nameParserResult.Name.Replace(' ', '.');
|
||||
|
||||
foreach (var group in groupedBy)
|
||||
{
|
||||
if (group.Key.ChapterNumber is null && group.Key.PartNumber is null)
|
||||
{
|
||||
if (group.Count() > 1 || haveChaptersOrPages)
|
||||
{
|
||||
List<AudioBookFileInfo>? ex = null;
|
||||
List<AudioBookFileInfo>? alt = null;
|
||||
|
||||
foreach (var audioFile in group)
|
||||
{
|
||||
var name = Path.GetFileNameWithoutExtension(audioFile.Path.AsSpan());
|
||||
if (name.Equals("audiobook", StringComparison.OrdinalIgnoreCase)
|
||||
|| name.Contains(nameParserResult.Name, StringComparison.OrdinalIgnoreCase)
|
||||
|| name.Contains(nameWithReplacedDots, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
(alt ??= new()).Add(audioFile);
|
||||
}
|
||||
else
|
||||
{
|
||||
(ex ??= new()).Add(audioFile);
|
||||
}
|
||||
}
|
||||
|
||||
if (ex is not null)
|
||||
{
|
||||
var extra = ex
|
||||
.OrderBy(x => x.Container)
|
||||
.ThenBy(x => x.Path)
|
||||
.ToList();
|
||||
|
||||
stackFiles = stackFiles.Except(extra).ToList();
|
||||
extras.AddRange(extra);
|
||||
}
|
||||
|
||||
if (alt is not null)
|
||||
{
|
||||
var alternatives = alt
|
||||
.OrderBy(x => x.Container)
|
||||
.ThenBy(x => x.Path)
|
||||
.ToList();
|
||||
|
||||
var main = FindMainAudioBookFile(alternatives, nameParserResult.Name);
|
||||
alternatives.Remove(main);
|
||||
stackFiles = stackFiles.Except(alternatives).ToList();
|
||||
alternativeVersions.AddRange(alternatives);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (group.Count() > 1)
|
||||
{
|
||||
var alternatives = group
|
||||
.OrderBy(x => x.Container)
|
||||
.ThenBy(x => x.Path)
|
||||
.Skip(1)
|
||||
.ToList();
|
||||
|
||||
stackFiles = stackFiles.Except(alternatives).ToList();
|
||||
alternativeVersions.AddRange(alternatives);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private AudioBookFileInfo FindMainAudioBookFile(List<AudioBookFileInfo> files, string name)
|
||||
{
|
||||
var main = files.Find(x => Path.GetFileNameWithoutExtension(x.Path).Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
main ??= files.FirstOrDefault(x => Path.GetFileNameWithoutExtension(x.Path).Equals("audiobook", StringComparison.OrdinalIgnoreCase));
|
||||
main ??= files.OrderBy(x => x.Container)
|
||||
.ThenBy(x => x.Path)
|
||||
.First();
|
||||
|
||||
return main;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using Emby.Naming.Common;
|
||||
|
||||
namespace Emby.Naming.AudioBook
|
||||
{
|
||||
/// <summary>
|
||||
/// Helper class to retrieve name and year from audiobook previously retrieved name.
|
||||
/// </summary>
|
||||
public class AudioBookNameParser
|
||||
{
|
||||
private readonly NamingOptions _options;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AudioBookNameParser"/> class.
|
||||
/// </summary>
|
||||
/// <param name="options">Naming options containing AudioBookNamesExpressions.</param>
|
||||
public AudioBookNameParser(NamingOptions options)
|
||||
{
|
||||
_options = options;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parse name and year from previously determined name of audiobook.
|
||||
/// </summary>
|
||||
/// <param name="name">Name of the audiobook.</param>
|
||||
/// <returns>Returns <see cref="AudioBookNameParserResult"/> object.</returns>
|
||||
public AudioBookNameParserResult Parse(string name)
|
||||
{
|
||||
AudioBookNameParserResult result = default;
|
||||
foreach (var expression in _options.AudioBookNamesExpressions)
|
||||
{
|
||||
var match = Regex.Match(name, expression, RegexOptions.IgnoreCase);
|
||||
if (match.Success)
|
||||
{
|
||||
if (result.Name is null)
|
||||
{
|
||||
var value = match.Groups["name"];
|
||||
if (value.Success)
|
||||
{
|
||||
result.Name = value.Value;
|
||||
}
|
||||
}
|
||||
|
||||
if (!result.Year.HasValue)
|
||||
{
|
||||
var value = match.Groups["year"];
|
||||
if (value.Success)
|
||||
{
|
||||
if (int.TryParse(value.ValueSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intValue))
|
||||
{
|
||||
result.Year = intValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(result.Name))
|
||||
{
|
||||
result.Name = name;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace Emby.Naming.AudioBook
|
||||
{
|
||||
/// <summary>
|
||||
/// Data object used to pass result of name and year parsing.
|
||||
/// </summary>
|
||||
public struct AudioBookNameParserResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets name of audiobook.
|
||||
/// </summary>
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets optional year of release.
|
||||
/// </summary>
|
||||
public int? Year { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Emby.Naming.Common;
|
||||
using Jellyfin.Extensions;
|
||||
|
||||
namespace Emby.Naming.AudioBook
|
||||
{
|
||||
/// <summary>
|
||||
/// Resolve specifics (path, container, partNumber, chapterNumber) about audiobook file.
|
||||
/// </summary>
|
||||
public class AudioBookResolver
|
||||
{
|
||||
private readonly NamingOptions _options;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AudioBookResolver"/> class.
|
||||
/// </summary>
|
||||
/// <param name="options"><see cref="NamingOptions"/> containing AudioFileExtensions and also used to pass to AudioBookFilePathParser.</param>
|
||||
public AudioBookResolver(NamingOptions options)
|
||||
{
|
||||
_options = options;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolve specifics (path, container, partNumber, chapterNumber) about audiobook file.
|
||||
/// </summary>
|
||||
/// <param name="path">Path to audiobook file.</param>
|
||||
/// <returns>Returns <see cref="AudioBookResolver"/> object.</returns>
|
||||
public AudioBookFileInfo? Resolve(string path)
|
||||
{
|
||||
if (path.Length == 0 || Path.GetFileNameWithoutExtension(path).Length == 0)
|
||||
{
|
||||
// Return null to indicate this path will not be used, instead of stopping whole process with exception
|
||||
return null;
|
||||
}
|
||||
|
||||
var extension = Path.GetExtension(path);
|
||||
|
||||
// Check supported extensions
|
||||
if (!_options.AudioFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var container = extension.TrimStart('.');
|
||||
|
||||
var parsingResult = new AudioBookFilePathParser(_options).Parse(path);
|
||||
|
||||
return new AudioBookFileInfo(
|
||||
path,
|
||||
container,
|
||||
chapterNumber: parsingResult.ChapterNumber,
|
||||
partNumber: parsingResult.PartNumber);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Emby.Naming.Book
|
||||
{
|
||||
/// <summary>
|
||||
/// Helper class to retrieve basic metadata from a book filename.
|
||||
/// </summary>
|
||||
public static class BookFileNameParser
|
||||
{
|
||||
private const string NameMatchGroup = "name";
|
||||
private const string IndexMatchGroup = "index";
|
||||
private const string YearMatchGroup = "year";
|
||||
private const string SeriesNameMatchGroup = "seriesName";
|
||||
|
||||
private static readonly Regex[] _nameMatches =
|
||||
[
|
||||
// seriesName (seriesYear) #index (of count) (year) where only seriesName and index are required
|
||||
new Regex(@"^(?<seriesName>.+?)((\s\((?<seriesYear>[0-9]{4})\))?)\s#(?<index>[0-9]+)((\s\(of\s(?<count>[0-9]+)\))?)((\s\((?<year>[0-9]{4})\))?)$"),
|
||||
new Regex(@"^(?<name>.+?)\s\((?<seriesName>.+?),\s#(?<index>[0-9]+)\)((\s\((?<year>[0-9]{4})\))?)$"),
|
||||
new Regex(@"^(?<index>[0-9]+)\s\-\s(?<name>.+?)((\s\((?<year>[0-9]{4})\))?)$"),
|
||||
new Regex(@"(?<name>.*)\((?<year>[0-9]{4})\)"),
|
||||
// last resort matches the whole string as the name
|
||||
new Regex(@"(?<name>.*)")
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Parse a filename name to retrieve the book name, series name, index, and year.
|
||||
/// </summary>
|
||||
/// <param name="name">Book filename to parse for information.</param>
|
||||
/// <returns>Returns <see cref="BookFileNameParserResult"/> object.</returns>
|
||||
public static BookFileNameParserResult Parse(string? name)
|
||||
{
|
||||
var result = new BookFileNameParserResult();
|
||||
|
||||
if (name == null)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
foreach (var regex in _nameMatches)
|
||||
{
|
||||
var match = regex.Match(name);
|
||||
|
||||
if (!match.Success)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (match.Groups.TryGetValue(NameMatchGroup, out Group? nameGroup) && nameGroup.Success)
|
||||
{
|
||||
result.Name = nameGroup.Value.Trim();
|
||||
}
|
||||
|
||||
if (match.Groups.TryGetValue(IndexMatchGroup, out Group? indexGroup) && indexGroup.Success && int.TryParse(indexGroup.Value, out var index))
|
||||
{
|
||||
result.Index = index;
|
||||
}
|
||||
|
||||
if (match.Groups.TryGetValue(YearMatchGroup, out Group? yearGroup) && yearGroup.Success && int.TryParse(yearGroup.Value, out var year))
|
||||
{
|
||||
result.Year = year;
|
||||
}
|
||||
|
||||
if (match.Groups.TryGetValue(SeriesNameMatchGroup, out Group? seriesGroup) && seriesGroup.Success)
|
||||
{
|
||||
result.SeriesName = seriesGroup.Value.Trim();
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using System;
|
||||
|
||||
namespace Emby.Naming.Book
|
||||
{
|
||||
/// <summary>
|
||||
/// Data object used to pass metadata parsed from a book filename.
|
||||
/// </summary>
|
||||
public class BookFileNameParserResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookFileNameParserResult"/> class.
|
||||
/// </summary>
|
||||
public BookFileNameParserResult()
|
||||
{
|
||||
Name = null;
|
||||
Index = null;
|
||||
Year = null;
|
||||
SeriesName = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the book.
|
||||
/// </summary>
|
||||
public string? Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the book index.
|
||||
/// </summary>
|
||||
public int? Index { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the publication year.
|
||||
/// </summary>
|
||||
public int? Year { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the series name.
|
||||
/// </summary>
|
||||
public string? SeriesName { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Emby.Naming.Common
|
||||
{
|
||||
/// <summary>
|
||||
/// Regular expressions for parsing TV Episodes.
|
||||
/// </summary>
|
||||
public class EpisodeExpression
|
||||
{
|
||||
private string _expression;
|
||||
private Regex? _regex;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EpisodeExpression"/> class.
|
||||
/// </summary>
|
||||
/// <param name="expression">Regular expressions.</param>
|
||||
/// <param name="byDate">True if date is expected.</param>
|
||||
public EpisodeExpression(string expression, bool byDate = false)
|
||||
{
|
||||
_expression = expression;
|
||||
IsByDate = byDate;
|
||||
DateTimeFormats = Array.Empty<string>();
|
||||
SupportsAbsoluteEpisodeNumbers = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets raw expressions string.
|
||||
/// </summary>
|
||||
public string Expression
|
||||
{
|
||||
get => _expression;
|
||||
set
|
||||
{
|
||||
_expression = value;
|
||||
_regex = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether gets or sets property indicating if date can be find in expression.
|
||||
/// </summary>
|
||||
public bool IsByDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether gets or sets property indicating if expression is optimistic.
|
||||
/// </summary>
|
||||
public bool IsOptimistic { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether gets or sets property indicating if expression is named.
|
||||
/// </summary>
|
||||
public bool IsNamed { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether gets or sets property indicating if expression supports episodes with absolute numbers.
|
||||
/// </summary>
|
||||
public bool SupportsAbsoluteEpisodeNumbers { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets optional list of date formats used for date parsing.
|
||||
/// </summary>
|
||||
public string[] DateTimeFormats { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="Regex"/> expressions objects (creates it if null).
|
||||
/// </summary>
|
||||
public Regex Regex => _regex ??= new Regex(Expression, RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
namespace Emby.Naming.Common
|
||||
{
|
||||
/// <summary>
|
||||
/// Type of audiovisual media.
|
||||
/// </summary>
|
||||
public enum MediaType
|
||||
{
|
||||
/// <summary>
|
||||
/// The audio.
|
||||
/// </summary>
|
||||
Audio = 0,
|
||||
|
||||
/// <summary>
|
||||
/// The photo.
|
||||
/// </summary>
|
||||
Photo = 1,
|
||||
|
||||
/// <summary>
|
||||
/// The video.
|
||||
/// </summary>
|
||||
Video = 2
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,913 @@
|
||||
#pragma warning disable CA1819
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using Emby.Naming.Video;
|
||||
using MediaBrowser.Model.Entities;
|
||||
|
||||
// ReSharper disable StringLiteralTypo
|
||||
|
||||
namespace Emby.Naming.Common
|
||||
{
|
||||
/// <summary>
|
||||
/// Big ugly class containing lot of different naming options that should be split and injected instead of passes everywhere.
|
||||
/// </summary>
|
||||
public class NamingOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="NamingOptions"/> class.
|
||||
/// </summary>
|
||||
public NamingOptions()
|
||||
{
|
||||
VideoFileExtensions =
|
||||
[
|
||||
".001",
|
||||
".3g2",
|
||||
".3gp",
|
||||
".amv",
|
||||
".asf",
|
||||
".asx",
|
||||
".avi",
|
||||
".bin",
|
||||
".bivx",
|
||||
".divx",
|
||||
".dv",
|
||||
".dvr-ms",
|
||||
".f4v",
|
||||
".fli",
|
||||
".flv",
|
||||
".ifo",
|
||||
".img",
|
||||
".iso",
|
||||
".m2t",
|
||||
".m2ts",
|
||||
".m2v",
|
||||
".m4v",
|
||||
".mkv",
|
||||
".mk3d",
|
||||
".mov",
|
||||
".mp4",
|
||||
".mpe",
|
||||
".mpeg",
|
||||
".mpg",
|
||||
".mts",
|
||||
".mxf",
|
||||
".nrg",
|
||||
".nsv",
|
||||
".nuv",
|
||||
".ogg",
|
||||
".ogm",
|
||||
".ogv",
|
||||
".pva",
|
||||
".qt",
|
||||
".rec",
|
||||
".rm",
|
||||
".rmvb",
|
||||
".strm",
|
||||
".svq3",
|
||||
".tp",
|
||||
".ts",
|
||||
".ty",
|
||||
".viv",
|
||||
".vob",
|
||||
".vp3",
|
||||
".webm",
|
||||
".wmv",
|
||||
".wtv",
|
||||
".xvid"
|
||||
];
|
||||
|
||||
VideoFlagDelimiters =
|
||||
[
|
||||
'(',
|
||||
')',
|
||||
'-',
|
||||
'.',
|
||||
'_',
|
||||
'[',
|
||||
']'
|
||||
];
|
||||
|
||||
StubFileExtensions =
|
||||
[
|
||||
".disc"
|
||||
];
|
||||
|
||||
StubTypes =
|
||||
[
|
||||
new StubTypeRule(
|
||||
stubType: "dvd",
|
||||
token: "dvd"),
|
||||
|
||||
new StubTypeRule(
|
||||
stubType: "hddvd",
|
||||
token: "hddvd"),
|
||||
|
||||
new StubTypeRule(
|
||||
stubType: "bluray",
|
||||
token: "bluray"),
|
||||
|
||||
new StubTypeRule(
|
||||
stubType: "bluray",
|
||||
token: "brrip"),
|
||||
|
||||
new StubTypeRule(
|
||||
stubType: "bluray",
|
||||
token: "bd25"),
|
||||
|
||||
new StubTypeRule(
|
||||
stubType: "bluray",
|
||||
token: "bd50"),
|
||||
|
||||
new StubTypeRule(
|
||||
stubType: "vhs",
|
||||
token: "vhs"),
|
||||
|
||||
new StubTypeRule(
|
||||
stubType: "tv",
|
||||
token: "HDTV"),
|
||||
|
||||
new StubTypeRule(
|
||||
stubType: "tv",
|
||||
token: "PDTV"),
|
||||
|
||||
new StubTypeRule(
|
||||
stubType: "tv",
|
||||
token: "DSR")
|
||||
];
|
||||
|
||||
VideoFileStackingRules =
|
||||
[
|
||||
new FileStackRule(@"^(?<filename>.*?)(?:(?<=[\]\)\}])|[ _.-]+)[\(\[]?(?<parttype>cd|dvd|part|pt|dis[ck])[ _.-]*(?<number>[0-9]+)[\)\]]?(?:\.[^.]+)?$", true),
|
||||
new FileStackRule(@"^(?<filename>.*?)(?:(?<=[\]\)\}])|[ _.-]+)[\(\[]?(?<parttype>cd|dvd|part|pt|dis[ck])[ _.-]*(?<number>[a-d])[\)\]]?(?:\.[^.]+)?$", false)
|
||||
];
|
||||
|
||||
CleanDateTimes =
|
||||
[
|
||||
@"(.+[^_\,\.\(\)\[\]\-])[_\.\(\)\[\]\-](19[0-9]{2}|20[0-9]{2})(?![0-9]+|\W[0-9]{2}\W[0-9]{2})([ _\,\.\(\)\[\]\-][^0-9]|).*(19[0-9]{2}|20[0-9]{2})*",
|
||||
@"(.+[^_\,\.\(\)\[\]\-])[ _\.\(\)\[\]\-]+(19[0-9]{2}|20[0-9]{2})(?![0-9]+|\W[0-9]{2}\W[0-9]{2})([ _\,\.\(\)\[\]\-][^0-9]|).*(19[0-9]{2}|20[0-9]{2})*"
|
||||
];
|
||||
|
||||
CleanStrings =
|
||||
[
|
||||
@"^\s*(?<cleaned>.+?)[ _\,\.\(\)\[\]\-](3d|sbs|tab|hsbs|htab|mvc|HDR|HDC|UHD|UltraHD|4k|ac3|dts|custom|dc|divx|divx5|dsr|dsrip|dutch|dvd|dvdrip|dvdscr|dvdscreener|screener|dvdivx|cam|fragment|fs|hdtv|hdrip|hdtvrip|internal|limited|multi|subs|ntsc|ogg|ogm|pal|pdtv|proper|repack|rerip|retail|cd[1-9]|r5|bd5|bd|se|svcd|swedish|german|read.nfo|nfofix|unrated|ws|telesync|ts|telecine|tc|brrip|bdrip|480p|480i|576p|576i|720p|720i|1080p|1080i|2160p|hrhd|hrhdtv|hddvd|bluray|blu-ray|x264|x265|h264|h265|xvid|xvidvd|xxx|www.www|AAC|DTS|\[.*\])([ _\,\.\(\)\[\]\-]|$)",
|
||||
@"^(?<cleaned>.+?)(\[.*\])",
|
||||
@"^\s*(?<cleaned>.+?)\WE[0-9]+(-|~)E?[0-9]+(\W|$)",
|
||||
@"^\s*\[[^\]]+\](?!\.\w+$)\s*(?<cleaned>.+)",
|
||||
@"^\s*(?<cleaned>.+?)\s+-\s+[0-9]+\s*$",
|
||||
@"^\s*(?<cleaned>.+?)(([-._ ](trailer|sample))|-(scene|clip|behindthescenes|deleted|deletedscene|featurette|short|interview|other|extra))$"
|
||||
];
|
||||
|
||||
SubtitleFileExtensions =
|
||||
[
|
||||
".ass",
|
||||
".mks",
|
||||
".sami",
|
||||
".smi",
|
||||
".srt",
|
||||
".ssa",
|
||||
".sub",
|
||||
".sup",
|
||||
".vtt",
|
||||
];
|
||||
|
||||
LyricFileExtensions =
|
||||
[
|
||||
".lrc",
|
||||
".elrc",
|
||||
".txt"
|
||||
];
|
||||
|
||||
AlbumStackingPrefixes =
|
||||
[
|
||||
"cd",
|
||||
"digital media",
|
||||
"disc",
|
||||
"disk",
|
||||
"vol",
|
||||
"volume",
|
||||
"part",
|
||||
"act"
|
||||
];
|
||||
|
||||
ArtistSubfolders =
|
||||
[
|
||||
"albums",
|
||||
"broadcasts",
|
||||
"bootlegs",
|
||||
"compilations",
|
||||
"dj-mixes",
|
||||
"eps",
|
||||
"live",
|
||||
"mixtapes",
|
||||
"others",
|
||||
"remixes",
|
||||
"singles",
|
||||
"soundtracks",
|
||||
"spokenwords",
|
||||
"streets"
|
||||
];
|
||||
|
||||
AudioFileExtensions =
|
||||
[
|
||||
".669",
|
||||
".3gp",
|
||||
".aa",
|
||||
".aac",
|
||||
".aax",
|
||||
".ac3",
|
||||
".act",
|
||||
".adp",
|
||||
".adplug",
|
||||
".adx",
|
||||
".afc",
|
||||
".amf",
|
||||
".aif",
|
||||
".aiff",
|
||||
".alac",
|
||||
".amr",
|
||||
".ape",
|
||||
".ast",
|
||||
".au",
|
||||
".awb",
|
||||
".cda",
|
||||
".cue",
|
||||
".dmf",
|
||||
".dsf",
|
||||
".dsm",
|
||||
".dsp",
|
||||
".dts",
|
||||
".dvf",
|
||||
".eac3",
|
||||
".ec3",
|
||||
".far",
|
||||
".flac",
|
||||
".gdm",
|
||||
".gsm",
|
||||
".gym",
|
||||
".hps",
|
||||
".imf",
|
||||
".it",
|
||||
".m15",
|
||||
".m4a",
|
||||
".m4b",
|
||||
".mac",
|
||||
".med",
|
||||
".mka",
|
||||
".mmf",
|
||||
".mod",
|
||||
".mogg",
|
||||
".mp2",
|
||||
".mp3",
|
||||
".mpa",
|
||||
".mpc",
|
||||
".mpp",
|
||||
".mp+",
|
||||
".msv",
|
||||
".nmf",
|
||||
".nsf",
|
||||
".nsv",
|
||||
".oga",
|
||||
".ogg",
|
||||
".okt",
|
||||
".opus",
|
||||
".pls",
|
||||
".ra",
|
||||
".rf64",
|
||||
".rm",
|
||||
".s3m",
|
||||
".sfx",
|
||||
".shn",
|
||||
".sid",
|
||||
".stm",
|
||||
".strm",
|
||||
".ult",
|
||||
".uni",
|
||||
".vox",
|
||||
".wav",
|
||||
".wma",
|
||||
".wv",
|
||||
".xm",
|
||||
".xsp",
|
||||
".ymf"
|
||||
];
|
||||
|
||||
MediaFlagDelimiters =
|
||||
[
|
||||
'.'
|
||||
];
|
||||
|
||||
MediaForcedFlags =
|
||||
[
|
||||
"foreign",
|
||||
"forced"
|
||||
];
|
||||
|
||||
MediaDefaultFlags =
|
||||
[
|
||||
"default"
|
||||
];
|
||||
|
||||
MediaHearingImpairedFlags =
|
||||
[
|
||||
"cc",
|
||||
"hi",
|
||||
"sdh"
|
||||
];
|
||||
|
||||
EpisodeExpressions =
|
||||
[
|
||||
// *** Begin Kodi Standard Naming
|
||||
// <!-- foo.s01.e01, foo.s01_e01, S01E02 foo, S01 - E02 -->
|
||||
new EpisodeExpression(@".*(\\|\/)(?<seriesname>((?[][ ._-]*[Ee]([0-9]+))[^\\\/])*)?[Ss](?<seasonnumber>[0-9]+)[][ ._-]*[Ee](?<epnumber>[0-9]+)([^\\/]*)$")
|
||||
{
|
||||
IsNamed = true
|
||||
},
|
||||
// <!-- foo.ep01, foo.EP_01 -->
|
||||
new EpisodeExpression(@"[\._ -]()[Ee][Pp]_?([0-9]+)([^\\/]*)$"),
|
||||
// <!-- foo.E01., foo.e01. -->
|
||||
new EpisodeExpression(@"[^\\/]*?()\.?[Ee]([0-9]+)\.([^\\/]*)$"),
|
||||
new EpisodeExpression("(?<year>[0-9]{4})[._ -](?<month>[0-9]{2})[._ -](?<day>[0-9]{2})", true)
|
||||
{
|
||||
DateTimeFormats =
|
||||
[
|
||||
"yyyy.MM.dd",
|
||||
"yyyy-MM-dd",
|
||||
"yyyy_MM_dd",
|
||||
"yyyy MM dd"
|
||||
]
|
||||
},
|
||||
new EpisodeExpression("(?<day>[0-9]{2})[._ -](?<month>[0-9]{2})[._ -](?<year>[0-9]{4})", true)
|
||||
{
|
||||
DateTimeFormats =
|
||||
[
|
||||
"dd.MM.yyyy",
|
||||
"dd-MM-yyyy",
|
||||
"dd_MM_yyyy",
|
||||
"dd MM yyyy"
|
||||
]
|
||||
},
|
||||
|
||||
// This isn't a Kodi naming rule, but the expression below causes false episode numbers for
|
||||
// Title Season X Episode X naming schemes.
|
||||
// "Series Season X Episode X - Title.avi", "Series S03 E09.avi", "s3 e9 - Title.avi"
|
||||
new EpisodeExpression(@".*[\\\/]((?<seriesname>[^\\/]+?)\s)?[Ss](?:eason)?\s*(?<seasonnumber>[0-9]+)\s+[Ee](?:pisode)?\s*(?<epnumber>[0-9]+).*$")
|
||||
{
|
||||
IsNamed = true
|
||||
},
|
||||
|
||||
// Not a Kodi rule as well, but the expression below also causes false positives,
|
||||
// so we make sure this one gets tested first.
|
||||
// "Foo Bar 889"
|
||||
new EpisodeExpression(@".*[\\\/](?![Ee]pisode)(?<seriesname>[\w\s]+?)\s(?<epnumber>[0-9]{1,4})(-(?<endingepnumber>[0-9]{2,4}))*[^\\\/x]*$")
|
||||
{
|
||||
IsNamed = true
|
||||
},
|
||||
|
||||
new EpisodeExpression(@"[\\\/\._ \[\(-]([0-9]+)x([0-9]+(?:(?:[a-i]|\.[1-9])(?![0-9]))?)([^\\\/]*)$")
|
||||
{
|
||||
SupportsAbsoluteEpisodeNumbers = true
|
||||
},
|
||||
|
||||
// Not a Kodi rule as well, but below rule also causes false positives for triple-digit episode names
|
||||
// [bar] Foo - 1 [baz] special case of below expression to prevent false positives with digits in the series name
|
||||
new EpisodeExpression(@".*[\\\/]?.*?(\[.*?\])+.*?(?<seriesname>[-\w\s]+?)[\s_]*-[\s_]*(?<epnumber>[0-9]+).*$")
|
||||
{
|
||||
IsNamed = true
|
||||
},
|
||||
|
||||
// /server/anything_102.mp4
|
||||
// /server/james.corden.2017.04.20.anne.hathaway.720p.hdtv.x264-crooks.mkv
|
||||
// /server/anything_1996.11.14.mp4
|
||||
new EpisodeExpression(@"[\\/._ -](?<seriesname>(?![0-9]+[0-9][0-9])([^\\\/_])*)[\\\/._ -](?<seasonnumber>[0-9]+)(?<epnumber>[0-9][0-9](?:(?:[a-i]|\.[1-9])(?![0-9]))?)([._ -][^\\\/]*)$")
|
||||
{
|
||||
IsOptimistic = true,
|
||||
IsNamed = true,
|
||||
SupportsAbsoluteEpisodeNumbers = false
|
||||
},
|
||||
new EpisodeExpression(@"[\/._ -]p(?:ar)?t[_. -]()([ivx]+|[0-9]+)([._ -][^\/]*)$")
|
||||
{
|
||||
SupportsAbsoluteEpisodeNumbers = true
|
||||
},
|
||||
|
||||
// *** End Kodi Standard Naming
|
||||
|
||||
// "Episode 16", "Episode 16 - Title"
|
||||
new EpisodeExpression(@"[Ee]pisode (?<epnumber>[0-9]+)(-(?<endingepnumber>[0-9]+))?[^\\\/]*$")
|
||||
{
|
||||
IsNamed = true
|
||||
},
|
||||
|
||||
new EpisodeExpression(@".*(\\|\/)[sS]?(?<seasonnumber>[0-9]+)[xX](?<epnumber>[0-9]+)[^\\\/]*$")
|
||||
{
|
||||
IsNamed = true
|
||||
},
|
||||
|
||||
new EpisodeExpression(@".*(\\|\/)[sS](?<seasonnumber>[0-9]+)[x,X]?[eE](?<epnumber>[0-9]+)[^\\\/]*$")
|
||||
{
|
||||
IsNamed = true
|
||||
},
|
||||
|
||||
new EpisodeExpression(@".*(\\|\/)(?<seriesname>((?![sS]?[0-9]{1,4}[xX][0-9]{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>[0-9]{1,4})[xX](?<epnumber>[0-9]+))[^\\\/]*$")
|
||||
{
|
||||
IsNamed = true
|
||||
},
|
||||
|
||||
new EpisodeExpression(@".*(\\|\/)(?<seriesname>[^\\\/]*)[sS](?<seasonnumber>[0-9]{1,4})[xX\.]?[eE](?<epnumber>[0-9]+)[^\\\/]*$")
|
||||
{
|
||||
IsNamed = true
|
||||
},
|
||||
|
||||
// "01.avi"
|
||||
new EpisodeExpression(@".*[\\\/](?<epnumber>[0-9]+)(-(?<endingepnumber>[0-9]+))*\.\w+$")
|
||||
{
|
||||
IsOptimistic = true,
|
||||
IsNamed = true
|
||||
},
|
||||
|
||||
// "1-12 episode title"
|
||||
new EpisodeExpression("([0-9]+)-([0-9]+)"),
|
||||
|
||||
// "01 - blah.avi", "01-blah.avi"
|
||||
new EpisodeExpression(@".*(\\|\/)(?<epnumber>[0-9]{1,3})(-(?<endingepnumber>[0-9]{2,3}))*\s?-\s?[^\\\/]*$")
|
||||
{
|
||||
IsOptimistic = true,
|
||||
IsNamed = true
|
||||
},
|
||||
|
||||
// "01.blah.avi"
|
||||
new EpisodeExpression(@".*(\\|\/)(?<epnumber>[0-9]{1,3})(-(?<endingepnumber>[0-9]{2,3}))*\.[^\\\/]+$")
|
||||
{
|
||||
IsOptimistic = true,
|
||||
IsNamed = true
|
||||
},
|
||||
|
||||
// "blah - 01.avi", "blah 2 - 01.avi", "blah - 01 blah.avi", "blah 2 - 01 blah", "blah - 01 - blah.avi", "blah 2 - 01 - blah"
|
||||
new EpisodeExpression(@".*[\\\/][^\\\/]* - (?<epnumber>[0-9]{1,3})(-(?<endingepnumber>[0-9]{2,3}))*[^\\\/]*$")
|
||||
{
|
||||
IsOptimistic = true,
|
||||
IsNamed = true
|
||||
},
|
||||
|
||||
// "01 episode title.avi"
|
||||
new EpisodeExpression(@"[Ss]eason[\._ ](?<seasonnumber>[0-9]+)[\\\/](?<epnumber>[0-9]{1,3})([^\\\/]*)$")
|
||||
{
|
||||
IsOptimistic = true,
|
||||
IsNamed = true
|
||||
},
|
||||
|
||||
// Series and season only expression
|
||||
// "the show/season 1", "the show/s01"
|
||||
new EpisodeExpression(@"(.*(\\|\/))*(?<seriesname>.+)\/[Ss](eason)?[\. _\-]*(?<seasonnumber>[0-9]+)")
|
||||
{
|
||||
IsNamed = true
|
||||
},
|
||||
|
||||
// Series and season only expression
|
||||
// "the show S01", "the show season 1"
|
||||
new EpisodeExpression(@"(.*(\\|\/))*(?<seriesname>.+)[\. _\-]+[sS](eason)?[\. _\-]*(?<seasonnumber>[0-9]+)")
|
||||
{
|
||||
IsNamed = true
|
||||
},
|
||||
|
||||
// Anime style expression
|
||||
// "[Group][Series Name][21][1080p][FLAC][HASH]"
|
||||
// "[Group] Series Name [04][BDRIP]"
|
||||
new EpisodeExpression(@"(?:\[(?:[^\]]+)\]\s*)?(?<seriesname>\[[^\]]+\]|[^[\]]+)\s*\[(?<epnumber>[0-9]+)\]")
|
||||
{
|
||||
IsNamed = true
|
||||
},
|
||||
];
|
||||
|
||||
VideoExtraRules =
|
||||
[
|
||||
new ExtraRule(
|
||||
ExtraType.Trailer,
|
||||
ExtraRuleType.DirectoryName,
|
||||
"trailers",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.ThemeVideo,
|
||||
ExtraRuleType.DirectoryName,
|
||||
"backdrops",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.ThemeSong,
|
||||
ExtraRuleType.DirectoryName,
|
||||
"theme-music",
|
||||
MediaType.Audio),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.BehindTheScenes,
|
||||
ExtraRuleType.DirectoryName,
|
||||
"behind the scenes",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.DeletedScene,
|
||||
ExtraRuleType.DirectoryName,
|
||||
"deleted scenes",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Interview,
|
||||
ExtraRuleType.DirectoryName,
|
||||
"interviews",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Scene,
|
||||
ExtraRuleType.DirectoryName,
|
||||
"scenes",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Sample,
|
||||
ExtraRuleType.DirectoryName,
|
||||
"samples",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Short,
|
||||
ExtraRuleType.DirectoryName,
|
||||
"shorts",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Featurette,
|
||||
ExtraRuleType.DirectoryName,
|
||||
"featurettes",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Unknown,
|
||||
ExtraRuleType.DirectoryName,
|
||||
"extras",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Unknown,
|
||||
ExtraRuleType.DirectoryName,
|
||||
"extra",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Unknown,
|
||||
ExtraRuleType.DirectoryName,
|
||||
"other",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Clip,
|
||||
ExtraRuleType.DirectoryName,
|
||||
"clips",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Trailer,
|
||||
ExtraRuleType.Filename,
|
||||
"trailer",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Sample,
|
||||
ExtraRuleType.Filename,
|
||||
"sample",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.ThemeSong,
|
||||
ExtraRuleType.Filename,
|
||||
"theme",
|
||||
MediaType.Audio),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Trailer,
|
||||
ExtraRuleType.Suffix,
|
||||
"-trailer",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Trailer,
|
||||
ExtraRuleType.Suffix,
|
||||
".trailer",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Trailer,
|
||||
ExtraRuleType.Suffix,
|
||||
"_trailer",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Trailer,
|
||||
ExtraRuleType.Suffix,
|
||||
"- trailer",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Sample,
|
||||
ExtraRuleType.Suffix,
|
||||
"-sample",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Sample,
|
||||
ExtraRuleType.Suffix,
|
||||
".sample",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Sample,
|
||||
ExtraRuleType.Suffix,
|
||||
"_sample",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Sample,
|
||||
ExtraRuleType.Suffix,
|
||||
"- sample",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Scene,
|
||||
ExtraRuleType.Suffix,
|
||||
"-scene",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Clip,
|
||||
ExtraRuleType.Suffix,
|
||||
"-clip",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Interview,
|
||||
ExtraRuleType.Suffix,
|
||||
"-interview",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.BehindTheScenes,
|
||||
ExtraRuleType.Suffix,
|
||||
"-behindthescenes",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.DeletedScene,
|
||||
ExtraRuleType.Suffix,
|
||||
"-deleted",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.DeletedScene,
|
||||
ExtraRuleType.Suffix,
|
||||
"-deletedscene",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Featurette,
|
||||
ExtraRuleType.Suffix,
|
||||
"-featurette",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Short,
|
||||
ExtraRuleType.Suffix,
|
||||
"-short",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Unknown,
|
||||
ExtraRuleType.Suffix,
|
||||
"-extra",
|
||||
MediaType.Video),
|
||||
|
||||
new ExtraRule(
|
||||
ExtraType.Unknown,
|
||||
ExtraRuleType.Suffix,
|
||||
"-other",
|
||||
MediaType.Video)
|
||||
];
|
||||
|
||||
AllExtrasTypesFolderNames = VideoExtraRules
|
||||
.Where(i => i.RuleType == ExtraRuleType.DirectoryName)
|
||||
.ToDictionary(i => i.Token, i => i.ExtraType, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
Format3DRules =
|
||||
[
|
||||
// Kodi rules:
|
||||
new Format3DRule(
|
||||
precedingToken: "3d",
|
||||
token: "hsbs"),
|
||||
|
||||
new Format3DRule(
|
||||
precedingToken: "3d",
|
||||
token: "sbs"),
|
||||
|
||||
new Format3DRule(
|
||||
precedingToken: "3d",
|
||||
token: "htab"),
|
||||
|
||||
new Format3DRule(
|
||||
precedingToken: "3d",
|
||||
token: "tab"),
|
||||
|
||||
// Media Browser rules:
|
||||
new Format3DRule("fsbs"),
|
||||
new Format3DRule("hsbs"),
|
||||
new Format3DRule("sbs"),
|
||||
new Format3DRule("ftab"),
|
||||
new Format3DRule("htab"),
|
||||
new Format3DRule("tab"),
|
||||
new Format3DRule("sbs3d"),
|
||||
new Format3DRule("mvc")
|
||||
];
|
||||
|
||||
AudioBookPartsExpressions =
|
||||
[
|
||||
// Detect specified chapters, like CH 01
|
||||
@"ch(?:apter)?[\s_-]?(?<chapter>[0-9]+)",
|
||||
// Detect specified parts, like Part 02
|
||||
@"p(?:ar)?t[\s_-]?(?<part>[0-9]+)",
|
||||
// Chapter is often beginning of filename
|
||||
"^(?<chapter>[0-9]+)",
|
||||
// Part if often ending of filename
|
||||
"(?<!ch(?:apter) )(?<part>[0-9]+)$",
|
||||
// Sometimes named as 0001_005 (chapter_part)
|
||||
"(?<chapter>[0-9]+)_(?<part>[0-9]+)",
|
||||
// Some audiobooks are ripped from cd's, and will be named by disk number.
|
||||
@"dis(?:c|k)[\s_-]?(?<chapter>[0-9]+)"
|
||||
];
|
||||
|
||||
AudioBookNamesExpressions =
|
||||
[
|
||||
// Detect year usually in brackets after name Batman (2020)
|
||||
@"^(?<name>.+?)\s*\(\s*(?<year>[0-9]{4})\s*\)\s*$",
|
||||
@"^\s*(?<name>[^ ].*?)\s*$"
|
||||
];
|
||||
|
||||
MultipleEpisodeExpressions = new[]
|
||||
{
|
||||
@".*(\\|\/)[sS]?(?<seasonnumber>[0-9]{1,4})[xX](?<epnumber>[0-9]{1,3})((-| - )[0-9]{1,4}[eExX](?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$",
|
||||
@".*(\\|\/)[sS]?(?<seasonnumber>[0-9]{1,4})[xX](?<epnumber>[0-9]{1,3})((-| - )[0-9]{1,4}[xX][eE](?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$",
|
||||
@".*(\\|\/)[sS]?(?<seasonnumber>[0-9]{1,4})[xX](?<epnumber>[0-9]{1,3})((-| - )?[xXeE](?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$",
|
||||
@".*(\\|\/)[sS]?(?<seasonnumber>[0-9]{1,4})[xX](?<epnumber>[0-9]{1,3})(-[xE]?[eE]?(?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$",
|
||||
@".*(\\|\/)(?<seriesname>((?![sS]?[0-9]{1,4}[xX][0-9]{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>[0-9]{1,4})[xX](?<epnumber>[0-9]{1,3}))((-| - )[0-9]{1,4}[xXeE](?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$",
|
||||
@".*(\\|\/)(?<seriesname>((?![sS]?[0-9]{1,4}[xX][0-9]{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>[0-9]{1,4})[xX](?<epnumber>[0-9]{1,3}))((-| - )[0-9]{1,4}[xX][eE](?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$",
|
||||
@".*(\\|\/)(?<seriesname>((?![sS]?[0-9]{1,4}[xX][0-9]{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>[0-9]{1,4})[xX](?<epnumber>[0-9]{1,3}))((-| - )?[xXeE](?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$",
|
||||
@".*(\\|\/)(?<seriesname>((?![sS]?[0-9]{1,4}[xX][0-9]{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>[0-9]{1,4})[xX](?<epnumber>[0-9]{1,3}))(-[xX]?[eE]?(?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$",
|
||||
@".*(\\|\/)(?<seriesname>[^\\\/]*)[sS](?<seasonnumber>[0-9]{1,4})[xX\.]?[eE](?<epnumber>[0-9]{1,3})((-| - )?[xXeE](?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$",
|
||||
@".*(\\|\/)(?<seriesname>[^\\\/]*)[sS](?<seasonnumber>[0-9]{1,4})[xX\.]?[eE](?<epnumber>[0-9]{1,3})(-[xX]?[eE]?(?<endingepnumber>[0-9]{1,3}))+[^\\\/]*$"
|
||||
}.Select(i => new EpisodeExpression(i)
|
||||
{
|
||||
IsNamed = true
|
||||
}).ToArray();
|
||||
|
||||
Compile();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the folder name to extra types mapping.
|
||||
/// </summary>
|
||||
public Dictionary<string, ExtraType> AllExtrasTypesFolderNames { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of audio file extensions.
|
||||
/// </summary>
|
||||
public string[] AudioFileExtensions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of external media flag delimiters.
|
||||
/// </summary>
|
||||
public char[] MediaFlagDelimiters { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of external media forced flags.
|
||||
/// </summary>
|
||||
public string[] MediaForcedFlags { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of external media default flags.
|
||||
/// </summary>
|
||||
public string[] MediaDefaultFlags { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of external media hearing impaired flags.
|
||||
/// </summary>
|
||||
public string[] MediaHearingImpairedFlags { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of album stacking prefixes.
|
||||
/// </summary>
|
||||
public string[] AlbumStackingPrefixes { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of artist subfolders.
|
||||
/// </summary>
|
||||
public string[] ArtistSubfolders { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of subtitle file extensions.
|
||||
/// </summary>
|
||||
public string[] SubtitleFileExtensions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of lyric file extensions.
|
||||
/// </summary>
|
||||
public string[] LyricFileExtensions { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of episode regular expressions.
|
||||
/// </summary>
|
||||
public EpisodeExpression[] EpisodeExpressions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of video file extensions.
|
||||
/// </summary>
|
||||
public string[] VideoFileExtensions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of video stub file extensions.
|
||||
/// </summary>
|
||||
public string[] StubFileExtensions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of raw audiobook parts regular expressions strings.
|
||||
/// </summary>
|
||||
public string[] AudioBookPartsExpressions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of raw audiobook names regular expressions strings.
|
||||
/// </summary>
|
||||
public string[] AudioBookNamesExpressions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of stub type rules.
|
||||
/// </summary>
|
||||
public StubTypeRule[] StubTypes { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of video flag delimiters.
|
||||
/// </summary>
|
||||
public char[] VideoFlagDelimiters { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of 3D Format rules.
|
||||
/// </summary>
|
||||
public Format3DRule[] Format3DRules { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the file stacking rules.
|
||||
/// </summary>
|
||||
public FileStackRule[] VideoFileStackingRules { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of raw clean DateTimes regular expressions strings.
|
||||
/// </summary>
|
||||
public string[] CleanDateTimes { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of raw clean strings regular expressions strings.
|
||||
/// </summary>
|
||||
public string[] CleanStrings { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of multi-episode regular expressions.
|
||||
/// </summary>
|
||||
public EpisodeExpression[] MultipleEpisodeExpressions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets list of extra rules for videos.
|
||||
/// </summary>
|
||||
public ExtraRule[] VideoExtraRules { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets list of clean datetime regular expressions.
|
||||
/// </summary>
|
||||
public Regex[] CleanDateTimeRegexes { get; private set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets list of clean string regular expressions.
|
||||
/// </summary>
|
||||
public Regex[] CleanStringRegexes { get; private set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Compiles raw regex strings into regexes.
|
||||
/// </summary>
|
||||
public void Compile()
|
||||
{
|
||||
CleanDateTimeRegexes = CleanDateTimes.Select(Compile).ToArray();
|
||||
CleanStringRegexes = CleanStrings.Select(Compile).ToArray();
|
||||
}
|
||||
|
||||
private Regex Compile(string exp)
|
||||
{
|
||||
return new Regex(exp, RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
|
||||
<PropertyGroup>
|
||||
<ProjectGuid>{E5AF7B26-2239-4CE0-B477-0AA2018EDAA2}</ProjectGuid>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<PublishRepositoryUrl>true</PublishRepositoryUrl>
|
||||
<EmbedUntrackedSources>true</EmbedUntrackedSources>
|
||||
<IncludeSymbols>true</IncludeSymbols>
|
||||
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
|
||||
<CodeAnalysisTreatWarningsAsErrors>false</CodeAnalysisTreatWarningsAsErrors>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition=" '$(Stability)'=='Unstable'">
|
||||
<!-- Include all symbols in the main nupkg until Azure Artifact Feed starts supporting ingesting NuGet symbol packages. -->
|
||||
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="../SharedVersion.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../MediaBrowser.Common/MediaBrowser.Common.csproj" />
|
||||
<ProjectReference Include="../MediaBrowser.Model/MediaBrowser.Model.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<Authors>Jellyfin Contributors</Authors>
|
||||
<PackageId>Jellyfin.Naming</PackageId>
|
||||
<VersionPrefix>10.12.0</VersionPrefix>
|
||||
<RepositoryUrl>https://github.com/jellyfin/jellyfin</RepositoryUrl>
|
||||
<PackageLicenseExpression>GPL-3.0-only</PackageLicenseExpression>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- Code Analyzers -->
|
||||
<ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
|
||||
<PackageReference Include="IDisposableAnalyzers">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.BannedApiAnalyzers">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="SerilogAnalyzer" PrivateAssets="All" />
|
||||
<PackageReference Include="StyleCop.Analyzers" PrivateAssets="All" />
|
||||
<PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" PrivateAssets="All" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,133 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Emby.Naming.Common;
|
||||
using Jellyfin.Extensions;
|
||||
using MediaBrowser.Model.Dlna;
|
||||
using MediaBrowser.Model.Globalization;
|
||||
|
||||
namespace Emby.Naming.ExternalFiles
|
||||
{
|
||||
/// <summary>
|
||||
/// External media file parser class.
|
||||
/// </summary>
|
||||
public class ExternalPathParser
|
||||
{
|
||||
private readonly NamingOptions _namingOptions;
|
||||
private readonly DlnaProfileType _type;
|
||||
private readonly ILocalizationManager _localizationManager;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ExternalPathParser"/> class.
|
||||
/// </summary>
|
||||
/// <param name="localizationManager">The localization manager.</param>
|
||||
/// <param name="namingOptions">The <see cref="NamingOptions"/> object containing FileExtensions, MediaDefaultFlags, MediaForcedFlags and MediaFlagDelimiters.</param>
|
||||
/// <param name="type">The <see cref="DlnaProfileType"/> of the parsed file.</param>
|
||||
public ExternalPathParser(NamingOptions namingOptions, ILocalizationManager localizationManager, DlnaProfileType type)
|
||||
{
|
||||
_localizationManager = localizationManager;
|
||||
_namingOptions = namingOptions;
|
||||
_type = type;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parse filename and extract information.
|
||||
/// </summary>
|
||||
/// <param name="path">Path to file.</param>
|
||||
/// <param name="extraString">Part of the filename only containing the extra information.</param>
|
||||
/// <returns>Returns null or an <see cref="ExternalPathParserResult"/> object if parsing is successful.</returns>
|
||||
public ExternalPathParserResult? ParseFile(string path, string? extraString)
|
||||
{
|
||||
if (path.Length == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var extension = Path.GetExtension(path.AsSpan());
|
||||
if (!(_type == DlnaProfileType.Subtitle && _namingOptions.SubtitleFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase))
|
||||
&& !(_type == DlnaProfileType.Audio && _namingOptions.AudioFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase))
|
||||
&& !(_type == DlnaProfileType.Lyric && _namingOptions.LyricFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var pathInfo = new ExternalPathParserResult(path);
|
||||
|
||||
if (string.IsNullOrEmpty(extraString))
|
||||
{
|
||||
return pathInfo;
|
||||
}
|
||||
|
||||
foreach (var separator in _namingOptions.MediaFlagDelimiters)
|
||||
{
|
||||
var languageString = extraString;
|
||||
var titleString = string.Empty;
|
||||
const int SeparatorLength = 1;
|
||||
|
||||
while (languageString.Length > 0)
|
||||
{
|
||||
int lastSeparator = languageString.LastIndexOf(separator);
|
||||
|
||||
if (lastSeparator == -1)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
string currentSlice = languageString[lastSeparator..];
|
||||
string currentSliceWithoutSeparator = currentSlice[SeparatorLength..];
|
||||
|
||||
if (_namingOptions.MediaDefaultFlags.Any(s => currentSliceWithoutSeparator.Contains(s, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
pathInfo.IsDefault = true;
|
||||
extraString = extraString.Replace(currentSlice, string.Empty, StringComparison.OrdinalIgnoreCase);
|
||||
languageString = languageString[..lastSeparator];
|
||||
continue;
|
||||
}
|
||||
|
||||
if (_namingOptions.MediaForcedFlags.Any(s => currentSliceWithoutSeparator.Contains(s, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
pathInfo.IsForced = true;
|
||||
extraString = extraString.Replace(currentSlice, string.Empty, StringComparison.OrdinalIgnoreCase);
|
||||
languageString = languageString[..lastSeparator];
|
||||
continue;
|
||||
}
|
||||
|
||||
// Try to translate to three character code
|
||||
var culture = _localizationManager.FindLanguageInfo(currentSliceWithoutSeparator);
|
||||
|
||||
if (culture is not null && pathInfo.Language is null)
|
||||
{
|
||||
pathInfo.Language = culture.Name.Contains('-', StringComparison.OrdinalIgnoreCase)
|
||||
? culture.Name
|
||||
: culture.ThreeLetterISOLanguageName;
|
||||
extraString = extraString.Replace(currentSlice, string.Empty, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
else if (culture is not null && pathInfo.Language == "hin")
|
||||
{
|
||||
// Hindi language code "hi" collides with a hearing impaired flag - use as Hindi only if no other language is set
|
||||
pathInfo.IsHearingImpaired = true;
|
||||
pathInfo.Language = culture.Name.Contains('-', StringComparison.OrdinalIgnoreCase)
|
||||
? culture.Name
|
||||
: culture.ThreeLetterISOLanguageName;
|
||||
extraString = extraString.Replace(currentSlice, string.Empty, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
else if (_namingOptions.MediaHearingImpairedFlags.Any(s => currentSliceWithoutSeparator.Equals(s, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
pathInfo.IsHearingImpaired = true;
|
||||
extraString = extraString.Replace(currentSlice, string.Empty, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
else
|
||||
{
|
||||
titleString = currentSlice + titleString;
|
||||
}
|
||||
|
||||
languageString = languageString[..lastSeparator];
|
||||
}
|
||||
|
||||
pathInfo.Title = titleString.Length >= SeparatorLength ? titleString[SeparatorLength..] : null;
|
||||
}
|
||||
|
||||
return pathInfo;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
namespace Emby.Naming.ExternalFiles
|
||||
{
|
||||
/// <summary>
|
||||
/// Class holding information about external files.
|
||||
/// </summary>
|
||||
public class ExternalPathParserResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ExternalPathParserResult"/> class.
|
||||
/// </summary>
|
||||
/// <param name="path">Path to file.</param>
|
||||
/// <param name="isDefault">Is default.</param>
|
||||
/// <param name="isForced">Is forced.</param>
|
||||
/// <param name="isHearingImpaired">For the hearing impaired.</param>
|
||||
public ExternalPathParserResult(string path, bool isDefault = false, bool isForced = false, bool isHearingImpaired = false)
|
||||
{
|
||||
Path = path;
|
||||
IsDefault = isDefault;
|
||||
IsForced = isForced;
|
||||
IsHearingImpaired = isHearingImpaired;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the path.
|
||||
/// </summary>
|
||||
/// <value>The path.</value>
|
||||
public string Path { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the language.
|
||||
/// </summary>
|
||||
/// <value>The language.</value>
|
||||
public string? Language { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the title.
|
||||
/// </summary>
|
||||
/// <value>The title.</value>
|
||||
public string? Title { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether this instance is default.
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if this instance is default; otherwise, <c>false</c>.</value>
|
||||
public bool IsDefault { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether this instance is forced.
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if this instance is forced; otherwise, <c>false</c>.</value>
|
||||
public bool IsForced { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether this instance is for the hearing impaired.
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if this instance is for the hearing impaired; otherwise, <c>false</c>.</value>
|
||||
public bool IsHearingImpaired { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.Reflection;
|
||||
using System.Resources;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("Emby.Naming")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("Jellyfin Project")]
|
||||
[assembly: AssemblyProduct("Jellyfin Server")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
[assembly: NeutralResourcesLanguage("en")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
@@ -0,0 +1,94 @@
|
||||
namespace Emby.Naming.TV
|
||||
{
|
||||
/// <summary>
|
||||
/// Holder object for Episode information.
|
||||
/// </summary>
|
||||
public class EpisodeInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EpisodeInfo"/> class.
|
||||
/// </summary>
|
||||
/// <param name="path">Path to the file.</param>
|
||||
public EpisodeInfo(string path)
|
||||
{
|
||||
Path = path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the path.
|
||||
/// </summary>
|
||||
/// <value>The path.</value>
|
||||
public string Path { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the container.
|
||||
/// </summary>
|
||||
/// <value>The container.</value>
|
||||
public string? Container { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the series.
|
||||
/// </summary>
|
||||
/// <value>The name of the series.</value>
|
||||
public string? SeriesName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the format3 d.
|
||||
/// </summary>
|
||||
/// <value>The format3 d.</value>
|
||||
public string? Format3D { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether [is3 d].
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if [is3 d]; otherwise, <c>false</c>.</value>
|
||||
public bool Is3D { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether this instance is stub.
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if this instance is stub; otherwise, <c>false</c>.</value>
|
||||
public bool IsStub { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the type of the stub.
|
||||
/// </summary>
|
||||
/// <value>The type of the stub.</value>
|
||||
public string? StubType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets optional season number.
|
||||
/// </summary>
|
||||
public int? SeasonNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets optional episode number.
|
||||
/// </summary>
|
||||
public int? EpisodeNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets optional ending episode number. For multi-episode files 1-13.
|
||||
/// </summary>
|
||||
public int? EndingEpisodeNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets optional year of release.
|
||||
/// </summary>
|
||||
public int? Year { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets optional year of release.
|
||||
/// </summary>
|
||||
public int? Month { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets optional day of release.
|
||||
/// </summary>
|
||||
public int? Day { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether by date expression was used.
|
||||
/// </summary>
|
||||
public bool IsByDate { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using Emby.Naming.Common;
|
||||
|
||||
namespace Emby.Naming.TV
|
||||
{
|
||||
/// <summary>
|
||||
/// Used to parse information about episode from path.
|
||||
/// </summary>
|
||||
public class EpisodePathParser
|
||||
{
|
||||
private readonly NamingOptions _options;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EpisodePathParser"/> class.
|
||||
/// </summary>
|
||||
/// <param name="options"><see cref="NamingOptions"/> object containing EpisodeExpressions and MultipleEpisodeExpressions.</param>
|
||||
public EpisodePathParser(NamingOptions options)
|
||||
{
|
||||
_options = options;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses information about episode from path.
|
||||
/// </summary>
|
||||
/// <param name="path">Path.</param>
|
||||
/// <param name="isDirectory">Is path for a directory or file.</param>
|
||||
/// <param name="isNamed">Do we want to use IsNamed expressions.</param>
|
||||
/// <param name="isOptimistic">Do we want to use Optimistic expressions.</param>
|
||||
/// <param name="supportsAbsoluteNumbers">Do we want to use expressions supporting absolute episode numbers.</param>
|
||||
/// <param name="fillExtendedInfo">Should we attempt to retrieve extended information.</param>
|
||||
/// <returns>Returns <see cref="EpisodePathParserResult"/> object.</returns>
|
||||
public EpisodePathParserResult Parse(
|
||||
string path,
|
||||
bool isDirectory,
|
||||
bool? isNamed = null,
|
||||
bool? isOptimistic = null,
|
||||
bool? supportsAbsoluteNumbers = null,
|
||||
bool fillExtendedInfo = true)
|
||||
{
|
||||
// Added to be able to use regex patterns which require a file extension.
|
||||
// There were no failed tests without this block, but to be safe, we can keep it until
|
||||
// the regex which require file extensions are modified so that they don't need them.
|
||||
if (isDirectory)
|
||||
{
|
||||
path += ".mp4";
|
||||
}
|
||||
|
||||
EpisodePathParserResult? result = null;
|
||||
|
||||
foreach (var expression in _options.EpisodeExpressions)
|
||||
{
|
||||
if (supportsAbsoluteNumbers.HasValue
|
||||
&& expression.SupportsAbsoluteEpisodeNumbers != supportsAbsoluteNumbers.Value)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isNamed.HasValue && expression.IsNamed != isNamed.Value)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isOptimistic.HasValue && expression.IsOptimistic != isOptimistic.Value)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var currentResult = Parse(path, expression);
|
||||
if (currentResult.Success)
|
||||
{
|
||||
result = currentResult;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (result is not null && fillExtendedInfo)
|
||||
{
|
||||
FillAdditional(path, result);
|
||||
|
||||
if (!string.IsNullOrEmpty(result.SeriesName))
|
||||
{
|
||||
result.SeriesName = result.SeriesName
|
||||
.Trim()
|
||||
.Trim('_', '.', '-')
|
||||
.Trim();
|
||||
}
|
||||
}
|
||||
|
||||
return result ?? new EpisodePathParserResult();
|
||||
}
|
||||
|
||||
private static EpisodePathParserResult Parse(string name, EpisodeExpression expression)
|
||||
{
|
||||
var result = new EpisodePathParserResult();
|
||||
|
||||
// This is a hack to handle wmc naming
|
||||
if (expression.IsByDate)
|
||||
{
|
||||
name = name.Replace('_', '-');
|
||||
}
|
||||
|
||||
var match = expression.Regex.Match(name);
|
||||
|
||||
// (Full)(Season)(Episode)(Extension)
|
||||
if (match.Success && match.Groups.Count >= 3)
|
||||
{
|
||||
if (expression.IsByDate)
|
||||
{
|
||||
DateTime date;
|
||||
if (expression.DateTimeFormats.Length > 0)
|
||||
{
|
||||
if (DateTime.TryParseExact(
|
||||
match.Groups[0].ValueSpan,
|
||||
expression.DateTimeFormats,
|
||||
CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.None,
|
||||
out date))
|
||||
{
|
||||
result.Year = date.Year;
|
||||
result.Month = date.Month;
|
||||
result.Day = date.Day;
|
||||
result.Success = true;
|
||||
}
|
||||
}
|
||||
else if (DateTime.TryParse(match.Groups[0].ValueSpan, out date))
|
||||
{
|
||||
result.Year = date.Year;
|
||||
result.Month = date.Month;
|
||||
result.Day = date.Day;
|
||||
result.Success = true;
|
||||
}
|
||||
|
||||
// TODO: Only consider success if date successfully parsed?
|
||||
result.Success = true;
|
||||
}
|
||||
else if (expression.IsNamed)
|
||||
{
|
||||
if (int.TryParse(match.Groups["seasonnumber"].ValueSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out var num))
|
||||
{
|
||||
result.SeasonNumber = num;
|
||||
}
|
||||
|
||||
if (int.TryParse(match.Groups["epnumber"].ValueSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out num))
|
||||
{
|
||||
result.EpisodeNumber = num;
|
||||
}
|
||||
|
||||
var endingNumberGroup = match.Groups["endingepnumber"];
|
||||
if (endingNumberGroup.Success)
|
||||
{
|
||||
// Will only set EndingEpisodeNumber if the captured number is not followed by additional numbers
|
||||
// or a 'p' or 'i' as what you would get with a pixel resolution specification.
|
||||
// It avoids erroneous parsing of something like "series-s09e14-1080p.mkv" as a multi-episode from E14 to E108
|
||||
int nextIndex = endingNumberGroup.Index + endingNumberGroup.Length;
|
||||
if (nextIndex >= name.Length
|
||||
|| !"0123456789iIpP".Contains(name[nextIndex], StringComparison.Ordinal))
|
||||
{
|
||||
if (int.TryParse(endingNumberGroup.ValueSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out num))
|
||||
{
|
||||
result.EndingEpisodeNumber = num;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result.SeriesName = match.Groups["seriesname"].Value;
|
||||
result.Success = result.EpisodeNumber.HasValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (int.TryParse(match.Groups[1].ValueSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out var num))
|
||||
{
|
||||
result.SeasonNumber = num;
|
||||
}
|
||||
|
||||
if (int.TryParse(match.Groups[2].ValueSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out num))
|
||||
{
|
||||
result.EpisodeNumber = num;
|
||||
}
|
||||
|
||||
result.Success = result.EpisodeNumber.HasValue;
|
||||
}
|
||||
|
||||
// Invalidate match when the season is 200 through 1927 or above 2500
|
||||
// because it is an error unless the TV show is intentionally using false season numbers.
|
||||
// It avoids erroneous parsing of something like "Series Special (1920x1080).mkv" as being season 1920 episode 1080.
|
||||
if ((result.SeasonNumber >= 200 && result.SeasonNumber < 1928)
|
||||
|| result.SeasonNumber > 2500)
|
||||
{
|
||||
result.Success = false;
|
||||
}
|
||||
|
||||
result.IsByDate = expression.IsByDate;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private void FillAdditional(string path, EpisodePathParserResult info)
|
||||
{
|
||||
var expressions = _options.MultipleEpisodeExpressions.Where(i => i.IsNamed).ToList();
|
||||
|
||||
if (string.IsNullOrEmpty(info.SeriesName))
|
||||
{
|
||||
expressions.InsertRange(0, _options.EpisodeExpressions.Where(i => i.IsNamed));
|
||||
}
|
||||
|
||||
FillAdditional(path, info, expressions);
|
||||
}
|
||||
|
||||
private void FillAdditional(string path, EpisodePathParserResult info, IEnumerable<EpisodeExpression> expressions)
|
||||
{
|
||||
foreach (var i in expressions)
|
||||
{
|
||||
var result = Parse(path, i);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(info.SeriesName))
|
||||
{
|
||||
info.SeriesName = result.SeriesName;
|
||||
}
|
||||
|
||||
if (!info.EndingEpisodeNumber.HasValue && info.EpisodeNumber.HasValue)
|
||||
{
|
||||
info.EndingEpisodeNumber = result.EndingEpisodeNumber;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(info.SeriesName)
|
||||
&& (!info.EpisodeNumber.HasValue || info.EndingEpisodeNumber.HasValue))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
namespace Emby.Naming.TV
|
||||
{
|
||||
/// <summary>
|
||||
/// Holder object for <see cref="EpisodePathParser"/> result.
|
||||
/// </summary>
|
||||
public class EpisodePathParserResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets optional season number.
|
||||
/// </summary>
|
||||
public int? SeasonNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets optional episode number.
|
||||
/// </summary>
|
||||
public int? EpisodeNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets optional ending episode number. For multi-episode files 1-13.
|
||||
/// </summary>
|
||||
public int? EndingEpisodeNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the series.
|
||||
/// </summary>
|
||||
/// <value>The name of the series.</value>
|
||||
public string? SeriesName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether parsing was successful.
|
||||
/// </summary>
|
||||
public bool Success { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether by date expression was used.
|
||||
/// </summary>
|
||||
public bool IsByDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets optional year of release.
|
||||
/// </summary>
|
||||
public int? Year { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets optional year of release.
|
||||
/// </summary>
|
||||
public int? Month { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets optional day of release.
|
||||
/// </summary>
|
||||
public int? Day { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Emby.Naming.Common;
|
||||
using Emby.Naming.Video;
|
||||
using Jellyfin.Extensions;
|
||||
|
||||
namespace Emby.Naming.TV
|
||||
{
|
||||
/// <summary>
|
||||
/// Used to resolve information about episode from path.
|
||||
/// </summary>
|
||||
public class EpisodeResolver
|
||||
{
|
||||
private readonly NamingOptions _options;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EpisodeResolver"/> class.
|
||||
/// </summary>
|
||||
/// <param name="options"><see cref="NamingOptions"/> object containing VideoFileExtensions and passed to <see cref="StubResolver"/>, <see cref="Format3DParser"/> and <see cref="EpisodePathParser"/>.</param>
|
||||
public EpisodeResolver(NamingOptions options)
|
||||
{
|
||||
_options = options;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolve information about episode from path.
|
||||
/// </summary>
|
||||
/// <param name="path">Path.</param>
|
||||
/// <param name="isDirectory">Is path for a directory or file.</param>
|
||||
/// <param name="isNamed">Do we want to use IsNamed expressions.</param>
|
||||
/// <param name="isOptimistic">Do we want to use Optimistic expressions.</param>
|
||||
/// <param name="supportsAbsoluteNumbers">Do we want to use expressions supporting absolute episode numbers.</param>
|
||||
/// <param name="fillExtendedInfo">Should we attempt to retrieve extended information.</param>
|
||||
/// <returns>Returns null or <see cref="EpisodeInfo"/> object if successful.</returns>
|
||||
public EpisodeInfo? Resolve(
|
||||
string path,
|
||||
bool isDirectory,
|
||||
bool? isNamed = null,
|
||||
bool? isOptimistic = null,
|
||||
bool? supportsAbsoluteNumbers = null,
|
||||
bool fillExtendedInfo = true)
|
||||
{
|
||||
bool isStub = false;
|
||||
string? container = null;
|
||||
string? stubType = null;
|
||||
|
||||
if (!isDirectory)
|
||||
{
|
||||
var extension = Path.GetExtension(path);
|
||||
// Check supported extensions
|
||||
if (!_options.VideoFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// It's not supported. Check stub extensions
|
||||
if (!StubResolver.TryResolveFile(path, _options, out stubType))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
isStub = true;
|
||||
}
|
||||
|
||||
container = extension.TrimStart('.');
|
||||
}
|
||||
|
||||
var format3DResult = Format3DParser.Parse(path, _options);
|
||||
|
||||
var parsingResult = new EpisodePathParser(_options)
|
||||
.Parse(path, isDirectory, isNamed, isOptimistic, supportsAbsoluteNumbers, fillExtendedInfo);
|
||||
|
||||
if (!parsingResult.Success && !isStub)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new EpisodeInfo(path)
|
||||
{
|
||||
Container = container,
|
||||
IsStub = isStub,
|
||||
EndingEpisodeNumber = parsingResult.EndingEpisodeNumber,
|
||||
EpisodeNumber = parsingResult.EpisodeNumber,
|
||||
SeasonNumber = parsingResult.SeasonNumber,
|
||||
SeriesName = parsingResult.SeriesName,
|
||||
StubType = stubType,
|
||||
Is3D = format3DResult.Is3D,
|
||||
Format3D = format3DResult.Format3D,
|
||||
IsByDate = parsingResult.IsByDate,
|
||||
Day = parsingResult.Day,
|
||||
Month = parsingResult.Month,
|
||||
Year = parsingResult.Year
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Emby.Naming.TV
|
||||
{
|
||||
/// <summary>
|
||||
/// Class to parse season paths.
|
||||
/// </summary>
|
||||
public static partial class SeasonPathParser
|
||||
{
|
||||
private static readonly Regex CleanNameRegex = new(@"[ ._\-\[\]]", RegexOptions.Compiled);
|
||||
|
||||
[GeneratedRegex(@"^\s*((?<seasonnumber>(?>\d+))(?:st|nd|rd|th|\.)*(?!\s*[Ee]\d+))\s*(?:[[시즌]*|[シーズン]*|[sS](?:eason|æson|aison|taffel|eries|tagione|äsong|eizoen|easong|ezon|ezona|ezóna|ezonul)*|[tT](?:emporada)*|[kK](?:ausi)*|[Сс](?:езон)*)\s*(?<rightpart>.*)$", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex ProcessPre();
|
||||
|
||||
[GeneratedRegex(@"^\s*(?:[[시즌]*|[シーズン]*|[sS](?:eason|æson|aison|taffel|eries|tagione|äsong|eizoen|easong|ezon|ezona|ezóna|ezonul)*|[tT](?:emporada)*|[kK](?:ausi)*|[Сс](?:езон)*)\s*(?<seasonnumber>\d+?)(?=\d{3,4}p|[^\d]|$)(?!\s*[Ee]\d)(?<rightpart>.*)$", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex ProcessPost();
|
||||
|
||||
[GeneratedRegex(@"[sS](\d{1,4})(?!\d|[eE]\d)(?=\.|_|-|\[|\]|\s|$)", RegexOptions.None)]
|
||||
private static partial Regex SeasonPrefix();
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to parse season number from path.
|
||||
/// </summary>
|
||||
/// <param name="path">Path to season.</param>
|
||||
/// <param name="parentPath">Folder name of the parent.</param>
|
||||
/// <param name="supportSpecialAliases">Support special aliases when parsing.</param>
|
||||
/// <param name="supportNumericSeasonFolders">Support numeric season folders when parsing.</param>
|
||||
/// <returns>Returns <see cref="SeasonPathParserResult"/> object.</returns>
|
||||
public static SeasonPathParserResult Parse(string path, string? parentPath, bool supportSpecialAliases, bool supportNumericSeasonFolders)
|
||||
{
|
||||
var result = new SeasonPathParserResult();
|
||||
var parentFolderName = parentPath is null ? null : new DirectoryInfo(parentPath).Name;
|
||||
|
||||
var (seasonNumber, isSeasonFolder) = GetSeasonNumberFromPath(path, parentFolderName, supportSpecialAliases, supportNumericSeasonFolders);
|
||||
|
||||
result.SeasonNumber = seasonNumber;
|
||||
|
||||
if (result.SeasonNumber.HasValue)
|
||||
{
|
||||
result.Success = true;
|
||||
result.IsSeasonFolder = isSeasonFolder;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the season number from path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path.</param>
|
||||
/// <param name="parentFolderName">The parent folder name.</param>
|
||||
/// <param name="supportSpecialAliases">if set to <c>true</c> [support special aliases].</param>
|
||||
/// <param name="supportNumericSeasonFolders">if set to <c>true</c> [support numeric season folders].</param>
|
||||
/// <returns>System.Nullable{System.Int32}.</returns>
|
||||
private static (int? SeasonNumber, bool IsSeasonFolder) GetSeasonNumberFromPath(
|
||||
string path,
|
||||
string? parentFolderName,
|
||||
bool supportSpecialAliases,
|
||||
bool supportNumericSeasonFolders)
|
||||
{
|
||||
var fileName = Path.GetFileName(path);
|
||||
|
||||
var seasonPrefixMatch = SeasonPrefix().Match(fileName);
|
||||
if (seasonPrefixMatch.Success &&
|
||||
int.TryParse(seasonPrefixMatch.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var val))
|
||||
{
|
||||
return (val, true);
|
||||
}
|
||||
|
||||
string filename = CleanNameRegex.Replace(fileName, string.Empty);
|
||||
|
||||
if (parentFolderName is not null)
|
||||
{
|
||||
var cleanParent = CleanNameRegex.Replace(parentFolderName, string.Empty);
|
||||
filename = filename.Replace(cleanParent, string.Empty, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
if (supportSpecialAliases &&
|
||||
(filename.Equals("specials", StringComparison.OrdinalIgnoreCase) ||
|
||||
filename.Equals("extras", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return (0, true);
|
||||
}
|
||||
|
||||
if (supportNumericSeasonFolders &&
|
||||
int.TryParse(filename, NumberStyles.Integer, CultureInfo.InvariantCulture, out val))
|
||||
{
|
||||
return (val, true);
|
||||
}
|
||||
|
||||
var preMatch = ProcessPre().Match(filename);
|
||||
if (preMatch.Success)
|
||||
{
|
||||
return CheckMatch(preMatch);
|
||||
}
|
||||
else
|
||||
{
|
||||
var postMatch = ProcessPost().Match(filename);
|
||||
return CheckMatch(postMatch);
|
||||
}
|
||||
}
|
||||
|
||||
private static (int? SeasonNumber, bool IsSeasonFolder) CheckMatch(Match match)
|
||||
{
|
||||
var numberString = match.Groups["seasonnumber"];
|
||||
if (numberString.Success)
|
||||
{
|
||||
if (int.TryParse(numberString.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var seasonNumber))
|
||||
{
|
||||
return (seasonNumber, true);
|
||||
}
|
||||
}
|
||||
|
||||
return (null, false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts the season number from the second half of the Season folder name (everything after "Season", or "Staffel").
|
||||
/// </summary>
|
||||
/// <param name="path">The path.</param>
|
||||
/// <returns>System.Nullable{System.Int32}.</returns>
|
||||
private static (int? SeasonNumber, bool IsSeasonFolder) GetSeasonNumberFromPathSubstring(ReadOnlySpan<char> path)
|
||||
{
|
||||
var numericStart = -1;
|
||||
var length = 0;
|
||||
|
||||
var hasOpenParenthesis = false;
|
||||
var isSeasonFolder = true;
|
||||
|
||||
// Find out where the numbers start, and then keep going until they end
|
||||
for (var i = 0; i < path.Length; i++)
|
||||
{
|
||||
if (char.IsNumber(path[i]))
|
||||
{
|
||||
if (!hasOpenParenthesis)
|
||||
{
|
||||
if (numericStart == -1)
|
||||
{
|
||||
numericStart = i;
|
||||
}
|
||||
|
||||
length++;
|
||||
}
|
||||
}
|
||||
else if (numericStart != -1)
|
||||
{
|
||||
// There's other stuff after the season number, e.g. episode number
|
||||
isSeasonFolder = false;
|
||||
break;
|
||||
}
|
||||
|
||||
var currentChar = path[i];
|
||||
if (currentChar == '(')
|
||||
{
|
||||
hasOpenParenthesis = true;
|
||||
}
|
||||
else if (currentChar == ')')
|
||||
{
|
||||
hasOpenParenthesis = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (numericStart == -1)
|
||||
{
|
||||
return (null, isSeasonFolder);
|
||||
}
|
||||
|
||||
return (int.Parse(path.Slice(numericStart, length), provider: CultureInfo.InvariantCulture), isSeasonFolder);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
namespace Emby.Naming.TV
|
||||
{
|
||||
/// <summary>
|
||||
/// Data object to pass result of <see cref="SeasonPathParser"/>.
|
||||
/// </summary>
|
||||
public class SeasonPathParserResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the season number.
|
||||
/// </summary>
|
||||
/// <value>The season number.</value>
|
||||
public int? SeasonNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether this <see cref="SeasonPathParserResult" /> is success.
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if success; otherwise, <c>false</c>.</value>
|
||||
public bool Success { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether "Is season folder".
|
||||
/// Seems redundant and barely used.
|
||||
/// </summary>
|
||||
public bool IsSeasonFolder { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
namespace Emby.Naming.TV
|
||||
{
|
||||
/// <summary>
|
||||
/// Holder object for Series information.
|
||||
/// </summary>
|
||||
public class SeriesInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SeriesInfo"/> class.
|
||||
/// </summary>
|
||||
/// <param name="path">Path to the file.</param>
|
||||
public SeriesInfo(string path)
|
||||
{
|
||||
Path = path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the path.
|
||||
/// </summary>
|
||||
/// <value>The path.</value>
|
||||
public string Path { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the series.
|
||||
/// </summary>
|
||||
/// <value>The name of the series.</value>
|
||||
public string? Name { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using Emby.Naming.Common;
|
||||
|
||||
namespace Emby.Naming.TV
|
||||
{
|
||||
/// <summary>
|
||||
/// Used to parse information about series from paths containing more information that only the series name.
|
||||
/// Uses the same regular expressions as the EpisodePathParser but have different success criteria.
|
||||
/// </summary>
|
||||
public static class SeriesPathParser
|
||||
{
|
||||
/// <summary>
|
||||
/// Parses information about series from path.
|
||||
/// </summary>
|
||||
/// <param name="options"><see cref="NamingOptions"/> object containing EpisodeExpressions and MultipleEpisodeExpressions.</param>
|
||||
/// <param name="path">Path.</param>
|
||||
/// <returns>Returns <see cref="SeriesPathParserResult"/> object.</returns>
|
||||
public static SeriesPathParserResult Parse(NamingOptions options, string path)
|
||||
{
|
||||
SeriesPathParserResult? result = null;
|
||||
|
||||
foreach (var expression in options.EpisodeExpressions)
|
||||
{
|
||||
var currentResult = Parse(path, expression);
|
||||
if (currentResult.Success)
|
||||
{
|
||||
result = currentResult;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (result is not null)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(result.SeriesName))
|
||||
{
|
||||
result.SeriesName = result.SeriesName.Trim(' ', '_', '.', '-');
|
||||
}
|
||||
}
|
||||
|
||||
return result ?? new SeriesPathParserResult();
|
||||
}
|
||||
|
||||
private static SeriesPathParserResult Parse(string name, EpisodeExpression expression)
|
||||
{
|
||||
var result = new SeriesPathParserResult();
|
||||
|
||||
var match = expression.Regex.Match(name);
|
||||
|
||||
if (match.Success && match.Groups.Count >= 3)
|
||||
{
|
||||
if (expression.IsNamed)
|
||||
{
|
||||
result.SeriesName = match.Groups["seriesname"].Value;
|
||||
result.Success = !string.IsNullOrEmpty(result.SeriesName) && !match.Groups["seasonnumber"].ValueSpan.IsEmpty;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace Emby.Naming.TV
|
||||
{
|
||||
/// <summary>
|
||||
/// Holder object for <see cref="SeriesPathParser"/> result.
|
||||
/// </summary>
|
||||
public class SeriesPathParserResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the series.
|
||||
/// </summary>
|
||||
/// <value>The name of the series.</value>
|
||||
public string? SeriesName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether parsing was successful.
|
||||
/// </summary>
|
||||
public bool Success { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
using Emby.Naming.Common;
|
||||
|
||||
namespace Emby.Naming.TV
|
||||
{
|
||||
/// <summary>
|
||||
/// Used to resolve information about series from path.
|
||||
/// </summary>
|
||||
public static partial class SeriesResolver
|
||||
{
|
||||
/// <summary>
|
||||
/// Regex that matches strings of at least 2 characters separated by a dot or underscore.
|
||||
/// Used for removing separators between words, i.e turns "The_show" into "The show" while
|
||||
/// preserving names like "S.H.O.W".
|
||||
/// </summary>
|
||||
[GeneratedRegex(@"((?<a>[^\._]{2,})[\._]*)|([\._](?<b>[^\._]{2,}))")]
|
||||
private static partial Regex SeriesNameRegex();
|
||||
|
||||
/// <summary>
|
||||
/// Regex that matches titles with year in parentheses. Captures the title (which may be
|
||||
/// numeric) before the year, i.e. turns "1923 (2022)" into "1923".
|
||||
/// </summary>
|
||||
[GeneratedRegex(@"(?<title>.+?)\s*\(\d{4}\)")]
|
||||
private static partial Regex TitleWithYearRegex();
|
||||
|
||||
/// <summary>
|
||||
/// Resolve information about series from path.
|
||||
/// </summary>
|
||||
/// <param name="options"><see cref="NamingOptions"/> object passed to <see cref="SeriesPathParser"/>.</param>
|
||||
/// <param name="path">Path to series.</param>
|
||||
/// <returns>SeriesInfo.</returns>
|
||||
public static SeriesInfo Resolve(NamingOptions options, string path)
|
||||
{
|
||||
string seriesName = Path.GetFileName(path);
|
||||
|
||||
// First check if the filename matches a title with year pattern (handles numeric titles)
|
||||
if (!string.IsNullOrEmpty(seriesName))
|
||||
{
|
||||
var titleWithYearMatch = TitleWithYearRegex().Match(seriesName);
|
||||
if (titleWithYearMatch.Success)
|
||||
{
|
||||
seriesName = titleWithYearMatch.Groups["title"].Value.Trim();
|
||||
return new SeriesInfo(path)
|
||||
{
|
||||
Name = seriesName
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
SeriesPathParserResult result = SeriesPathParser.Parse(options, path);
|
||||
if (result.Success)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(result.SeriesName))
|
||||
{
|
||||
seriesName = result.SeriesName;
|
||||
}
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(seriesName))
|
||||
{
|
||||
seriesName = SeriesNameRegex().Replace(seriesName, "${a} ${b}").Trim();
|
||||
}
|
||||
|
||||
return new SeriesInfo(path)
|
||||
{
|
||||
Name = seriesName
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using MediaBrowser.Model.Entities;
|
||||
|
||||
namespace Emby.Naming.TV;
|
||||
|
||||
/// <summary>
|
||||
/// Helper class for TV metadata parsing.
|
||||
/// </summary>
|
||||
public static class TvParserHelpers
|
||||
{
|
||||
private static readonly string[] _continuingState = ["Pilot", "Returning Series", "Returning"];
|
||||
private static readonly string[] _endedState = ["Cancelled", "Canceled"];
|
||||
|
||||
/// <summary>
|
||||
/// Tries to parse a string into <see cref="SeriesStatus"/>.
|
||||
/// </summary>
|
||||
/// <param name="status">The status string.</param>
|
||||
/// <param name="enumValue">The <see cref="SeriesStatus"/>.</param>
|
||||
/// <returns>Returns true if parsing was successful.</returns>
|
||||
public static bool TryParseSeriesStatus(string status, out SeriesStatus? enumValue)
|
||||
{
|
||||
if (Enum.TryParse(status, true, out SeriesStatus seriesStatus))
|
||||
{
|
||||
enumValue = seriesStatus;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (_continuingState.Contains(status, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
enumValue = SeriesStatus.Continuing;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (_endedState.Contains(status, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
enumValue = SeriesStatus.Ended;
|
||||
return true;
|
||||
}
|
||||
|
||||
enumValue = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Emby.Naming.Video
|
||||
{
|
||||
/// <summary>
|
||||
/// <see href="http://kodi.wiki/view/Advancedsettings.xml#video" />.
|
||||
/// </summary>
|
||||
public static class CleanDateTimeParser
|
||||
{
|
||||
/// <summary>
|
||||
/// Attempts to clean the name.
|
||||
/// </summary>
|
||||
/// <param name="name">Name of video.</param>
|
||||
/// <param name="cleanDateTimeRegexes">Optional list of regexes to clean the name.</param>
|
||||
/// <returns>Returns <see cref="CleanDateTimeResult"/> object.</returns>
|
||||
public static CleanDateTimeResult Clean(string name, IReadOnlyList<Regex> cleanDateTimeRegexes)
|
||||
{
|
||||
CleanDateTimeResult result = new CleanDateTimeResult(name);
|
||||
if (string.IsNullOrEmpty(name))
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
var len = cleanDateTimeRegexes.Count;
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
if (TryClean(name, cleanDateTimeRegexes[i], ref result))
|
||||
{
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static bool TryClean(string name, Regex expression, ref CleanDateTimeResult result)
|
||||
{
|
||||
var match = expression.Match(name);
|
||||
|
||||
if (match.Success
|
||||
&& match.Groups.Count == 5
|
||||
&& match.Groups[1].Success
|
||||
&& match.Groups[2].Success
|
||||
&& int.TryParse(match.Groups[2].ValueSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out var year))
|
||||
{
|
||||
result = new CleanDateTimeResult(match.Groups[1].Value.TrimEnd(), year);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
namespace Emby.Naming.Video
|
||||
{
|
||||
/// <summary>
|
||||
/// Holder structure for name and year.
|
||||
/// </summary>
|
||||
public readonly struct CleanDateTimeResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CleanDateTimeResult"/> struct.
|
||||
/// </summary>
|
||||
/// <param name="name">Name of video.</param>
|
||||
/// <param name="year">Year of release.</param>
|
||||
public CleanDateTimeResult(string name, int? year = null)
|
||||
{
|
||||
Name = name;
|
||||
Year = year;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name.
|
||||
/// </summary>
|
||||
/// <value>The name.</value>
|
||||
public string Name { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the year.
|
||||
/// </summary>
|
||||
/// <value>The year.</value>
|
||||
public int? Year { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Emby.Naming.Video
|
||||
{
|
||||
/// <summary>
|
||||
/// <see href="http://kodi.wiki/view/Advancedsettings.xml#video" />.
|
||||
/// </summary>
|
||||
public static class CleanStringParser
|
||||
{
|
||||
/// <summary>
|
||||
/// Attempts to extract clean name with regular expressions.
|
||||
/// </summary>
|
||||
/// <param name="name">Name of file.</param>
|
||||
/// <param name="expressions">List of regex to parse name and year from.</param>
|
||||
/// <param name="newName">Parsing result string.</param>
|
||||
/// <returns>True if parsing was successful.</returns>
|
||||
public static bool TryClean([NotNullWhen(true)] string? name, IReadOnlyList<Regex> expressions, out string newName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name))
|
||||
{
|
||||
newName = string.Empty;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Iteratively apply the regexps to clean the string.
|
||||
bool cleaned = false;
|
||||
for (int i = 0; i < expressions.Count; i++)
|
||||
{
|
||||
if (TryClean(name, expressions[i], out newName))
|
||||
{
|
||||
cleaned = true;
|
||||
name = newName;
|
||||
}
|
||||
}
|
||||
|
||||
newName = cleaned ? name : string.Empty;
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
private static bool TryClean(string name, Regex expression, out string newName)
|
||||
{
|
||||
var match = expression.Match(name);
|
||||
if (match.Success && match.Groups.TryGetValue("cleaned", out var cleaned))
|
||||
{
|
||||
newName = cleaned.Value;
|
||||
return true;
|
||||
}
|
||||
|
||||
newName = string.Empty;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using MediaBrowser.Model.Entities;
|
||||
|
||||
namespace Emby.Naming.Video
|
||||
{
|
||||
/// <summary>
|
||||
/// Holder object for passing results from ExtraResolver.
|
||||
/// </summary>
|
||||
public class ExtraResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the type of the extra.
|
||||
/// </summary>
|
||||
/// <value>The type of the extra.</value>
|
||||
public ExtraType? ExtraType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the rule.
|
||||
/// </summary>
|
||||
/// <value>The rule.</value>
|
||||
public ExtraRule? Rule { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaType = Emby.Naming.Common.MediaType;
|
||||
|
||||
namespace Emby.Naming.Video
|
||||
{
|
||||
/// <summary>
|
||||
/// A rule used to match a file path with an <see cref="MediaBrowser.Model.Entities.ExtraType"/>.
|
||||
/// </summary>
|
||||
public class ExtraRule
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ExtraRule"/> class.
|
||||
/// </summary>
|
||||
/// <param name="extraType">Type of extra.</param>
|
||||
/// <param name="ruleType">Type of rule.</param>
|
||||
/// <param name="token">Token.</param>
|
||||
/// <param name="mediaType">Media type.</param>
|
||||
public ExtraRule(ExtraType extraType, ExtraRuleType ruleType, string token, MediaType mediaType)
|
||||
{
|
||||
Token = token;
|
||||
ExtraType = extraType;
|
||||
RuleType = ruleType;
|
||||
MediaType = mediaType;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the token to use for matching against the file path.
|
||||
/// </summary>
|
||||
public string Token { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the type of the extra to return when matched.
|
||||
/// </summary>
|
||||
public ExtraType ExtraType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the type of the rule.
|
||||
/// </summary>
|
||||
public ExtraRuleType RuleType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the type of the media to return when matched.
|
||||
/// </summary>
|
||||
public MediaType MediaType { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
using Emby.Naming.Audio;
|
||||
using Emby.Naming.Common;
|
||||
|
||||
namespace Emby.Naming.Video
|
||||
{
|
||||
/// <summary>
|
||||
/// Resolve if file is extra for video.
|
||||
/// </summary>
|
||||
public static class ExtraRuleResolver
|
||||
{
|
||||
private static readonly char[] _digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to resolve if file is extra.
|
||||
/// </summary>
|
||||
/// <param name="path">Path to file.</param>
|
||||
/// <param name="namingOptions">The naming options.</param>
|
||||
/// <param name="libraryRoot">Top-level folder for the containing library.</param>
|
||||
/// <returns>Returns <see cref="ExtraResult"/> object.</returns>
|
||||
public static ExtraResult GetExtraInfo(string path, NamingOptions namingOptions, string? libraryRoot = "")
|
||||
{
|
||||
ExtraResult result = new ExtraResult();
|
||||
|
||||
bool isAudioFile = AudioFileParser.IsAudioFile(path, namingOptions);
|
||||
bool isVideoFile = VideoResolver.IsVideoFile(path, namingOptions);
|
||||
|
||||
ReadOnlySpan<char> pathSpan = path.AsSpan();
|
||||
ReadOnlySpan<char> fileName = Path.GetFileName(pathSpan);
|
||||
ReadOnlySpan<char> fileNameWithoutExtension = Path.GetFileNameWithoutExtension(pathSpan);
|
||||
// Trim the digits from the end of the filename so we can recognize things like -trailer2
|
||||
ReadOnlySpan<char> trimmedFileNameWithoutExtension = fileNameWithoutExtension.TrimEnd(_digits);
|
||||
ReadOnlySpan<char> directoryName = Path.GetFileName(Path.GetDirectoryName(pathSpan));
|
||||
string fullDirectory = Path.GetDirectoryName(pathSpan).ToString();
|
||||
|
||||
foreach (ExtraRule rule in namingOptions.VideoExtraRules)
|
||||
{
|
||||
if ((rule.MediaType == MediaType.Audio && !isAudioFile)
|
||||
|| (rule.MediaType == MediaType.Video && !isVideoFile))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
bool isMatch = rule.RuleType switch
|
||||
{
|
||||
ExtraRuleType.Filename => fileNameWithoutExtension.Equals(rule.Token, StringComparison.OrdinalIgnoreCase),
|
||||
ExtraRuleType.Suffix => trimmedFileNameWithoutExtension.EndsWith(rule.Token, StringComparison.OrdinalIgnoreCase),
|
||||
ExtraRuleType.Regex => Regex.IsMatch(fileName, rule.Token, RegexOptions.IgnoreCase | RegexOptions.Compiled),
|
||||
ExtraRuleType.DirectoryName => directoryName.Equals(rule.Token, StringComparison.OrdinalIgnoreCase)
|
||||
&& !string.Equals(fullDirectory, libraryRoot, StringComparison.OrdinalIgnoreCase),
|
||||
_ => false,
|
||||
};
|
||||
|
||||
if (!isMatch)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
result.ExtraType = rule.ExtraType;
|
||||
result.Rule = rule;
|
||||
return result;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
namespace Emby.Naming.Video
|
||||
{
|
||||
/// <summary>
|
||||
/// Extra rules type to determine against what <see cref="ExtraRule.Token"/> should be matched.
|
||||
/// </summary>
|
||||
public enum ExtraRuleType
|
||||
{
|
||||
/// <summary>
|
||||
/// Match <see cref="ExtraRule.Token"/> against a suffix in the file name.
|
||||
/// </summary>
|
||||
Suffix = 0,
|
||||
|
||||
/// <summary>
|
||||
/// Match <see cref="ExtraRule.Token"/> against the file name, excluding the file extension.
|
||||
/// </summary>
|
||||
Filename = 1,
|
||||
|
||||
/// <summary>
|
||||
/// Match <see cref="ExtraRule.Token"/> against the file name, including the file extension.
|
||||
/// </summary>
|
||||
Regex = 2,
|
||||
|
||||
/// <summary>
|
||||
/// Match <see cref="ExtraRule.Token"/> against the name of the directory containing the file.
|
||||
/// </summary>
|
||||
DirectoryName = 3
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Jellyfin.Extensions;
|
||||
|
||||
namespace Emby.Naming.Video
|
||||
{
|
||||
/// <summary>
|
||||
/// Object holding list of files paths with additional information.
|
||||
/// </summary>
|
||||
public class FileStack
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileStack"/> class.
|
||||
/// </summary>
|
||||
/// <param name="name">The stack name.</param>
|
||||
/// <param name="isDirectory">Whether the stack files are directories.</param>
|
||||
/// <param name="files">The stack files.</param>
|
||||
public FileStack(string name, bool isDirectory, IReadOnlyList<string> files)
|
||||
{
|
||||
Name = name;
|
||||
IsDirectoryStack = isDirectory;
|
||||
Files = files;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of file stack.
|
||||
/// </summary>
|
||||
public string Name { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of paths in stack.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> Files { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether stack is directory stack.
|
||||
/// </summary>
|
||||
public bool IsDirectoryStack { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Helper function to determine if path is in the stack.
|
||||
/// </summary>
|
||||
/// <param name="file">Path of desired file.</param>
|
||||
/// <param name="isDirectory">Requested type of stack.</param>
|
||||
/// <returns>True if file is in the stack.</returns>
|
||||
public bool ContainsFile(string file, bool isDirectory)
|
||||
{
|
||||
if (string.IsNullOrEmpty(file))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return IsDirectoryStack == isDirectory && Files.Contains(file, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Emby.Naming.Video;
|
||||
|
||||
/// <summary>
|
||||
/// Regex based rule for file stacking (eg. disc1, disc2).
|
||||
/// </summary>
|
||||
public class FileStackRule
|
||||
{
|
||||
private readonly Regex _tokenRegex;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileStackRule"/> class.
|
||||
/// </summary>
|
||||
/// <param name="token">Token.</param>
|
||||
/// <param name="isNumerical">Whether the file stack rule uses numerical or alphabetical numbering.</param>
|
||||
public FileStackRule(string token, bool isNumerical)
|
||||
{
|
||||
_tokenRegex = new Regex(token, RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||||
IsNumerical = isNumerical;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the rule uses numerical or alphabetical numbering.
|
||||
/// </summary>
|
||||
public bool IsNumerical { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Match the input against the rule regex.
|
||||
/// </summary>
|
||||
/// <param name="input">The input.</param>
|
||||
/// <param name="result">The part type and number or <c>null</c>.</param>
|
||||
/// <returns>A value indicating whether the input matched the rule.</returns>
|
||||
public bool Match(string input, [NotNullWhen(true)] out (string StackName, string PartType, string PartNumber)? result)
|
||||
{
|
||||
result = null;
|
||||
var match = _tokenRegex.Match(input);
|
||||
if (!match.Success)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var partType = match.Groups["parttype"].Success ? match.Groups["parttype"].Value : "unknown";
|
||||
result = (match.Groups["filename"].Value, partType, match.Groups["number"].Value);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using System;
|
||||
using Emby.Naming.Common;
|
||||
|
||||
namespace Emby.Naming.Video
|
||||
{
|
||||
/// <summary>
|
||||
/// Parse 3D format related flags.
|
||||
/// </summary>
|
||||
public static class Format3DParser
|
||||
{
|
||||
// Static default result to save on allocation costs.
|
||||
private static readonly Format3DResult _defaultResult = new(false, null);
|
||||
|
||||
/// <summary>
|
||||
/// Parse 3D format related flags.
|
||||
/// </summary>
|
||||
/// <param name="path">Path to file.</param>
|
||||
/// <param name="namingOptions">The naming options.</param>
|
||||
/// <returns>Returns <see cref="Format3DResult"/> object.</returns>
|
||||
public static Format3DResult Parse(ReadOnlySpan<char> path, NamingOptions namingOptions)
|
||||
{
|
||||
int oldLen = namingOptions.VideoFlagDelimiters.Length;
|
||||
Span<char> delimiters = stackalloc char[oldLen + 1];
|
||||
namingOptions.VideoFlagDelimiters.AsSpan().CopyTo(delimiters);
|
||||
delimiters[oldLen] = ' ';
|
||||
|
||||
return Parse(path, delimiters, namingOptions);
|
||||
}
|
||||
|
||||
private static Format3DResult Parse(ReadOnlySpan<char> path, ReadOnlySpan<char> delimiters, NamingOptions namingOptions)
|
||||
{
|
||||
foreach (var rule in namingOptions.Format3DRules)
|
||||
{
|
||||
var result = Parse(path, rule, delimiters);
|
||||
|
||||
if (result.Is3D)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
return _defaultResult;
|
||||
}
|
||||
|
||||
private static Format3DResult Parse(ReadOnlySpan<char> path, Format3DRule rule, ReadOnlySpan<char> delimiters)
|
||||
{
|
||||
bool is3D = false;
|
||||
string? format3D = null;
|
||||
|
||||
// If there's no preceding token we just consider it found
|
||||
var foundPrefix = string.IsNullOrEmpty(rule.PrecedingToken);
|
||||
while (path.Length > 0)
|
||||
{
|
||||
var index = path.IndexOfAny(delimiters);
|
||||
if (index == -1)
|
||||
{
|
||||
index = path.Length - 1;
|
||||
}
|
||||
|
||||
var currentSlice = path[..index];
|
||||
path = path[(index + 1)..];
|
||||
|
||||
if (!foundPrefix)
|
||||
{
|
||||
foundPrefix = currentSlice.Equals(rule.PrecedingToken, StringComparison.OrdinalIgnoreCase);
|
||||
continue;
|
||||
}
|
||||
|
||||
is3D = foundPrefix && currentSlice.Equals(rule.Token, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (is3D)
|
||||
{
|
||||
format3D = rule.Token;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return is3D ? new Format3DResult(true, format3D) : _defaultResult;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
namespace Emby.Naming.Video
|
||||
{
|
||||
/// <summary>
|
||||
/// Helper object to return data from <see cref="Format3DParser"/>.
|
||||
/// </summary>
|
||||
public class Format3DResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Format3DResult"/> class.
|
||||
/// </summary>
|
||||
/// <param name="is3D">A value indicating whether the parsed string contains 3D tokens.</param>
|
||||
/// <param name="format3D">The 3D format. Value might be null if [is3D] is <c>false</c>.</param>
|
||||
public Format3DResult(bool is3D, string? format3D)
|
||||
{
|
||||
Is3D = is3D;
|
||||
Format3D = format3D;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether [is3 d].
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if [is3 d]; otherwise, <c>false</c>.</value>
|
||||
public bool Is3D { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the format3 d.
|
||||
/// </summary>
|
||||
/// <value>The format3 d.</value>
|
||||
public string? Format3D { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
namespace Emby.Naming.Video
|
||||
{
|
||||
/// <summary>
|
||||
/// Data holder class for 3D format rule.
|
||||
/// </summary>
|
||||
public class Format3DRule
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Format3DRule"/> class.
|
||||
/// </summary>
|
||||
/// <param name="token">Token.</param>
|
||||
/// <param name="precedingToken">Token present before current token.</param>
|
||||
public Format3DRule(string token, string? precedingToken = null)
|
||||
{
|
||||
Token = token;
|
||||
PrecedingToken = precedingToken;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the token.
|
||||
/// </summary>
|
||||
/// <value>The token.</value>
|
||||
public string Token { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the preceding token.
|
||||
/// </summary>
|
||||
/// <value>The preceding token.</value>
|
||||
public string? PrecedingToken { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Emby.Naming.AudioBook;
|
||||
using Emby.Naming.Common;
|
||||
using MediaBrowser.Model.IO;
|
||||
|
||||
namespace Emby.Naming.Video
|
||||
{
|
||||
/// <summary>
|
||||
/// Resolve <see cref="FileStack"/> from list of paths.
|
||||
/// </summary>
|
||||
public static class StackResolver
|
||||
{
|
||||
/// <summary>
|
||||
/// Resolves only directories from paths.
|
||||
/// </summary>
|
||||
/// <param name="files">List of paths.</param>
|
||||
/// <param name="namingOptions">The naming options.</param>
|
||||
/// <returns>Enumerable <see cref="FileStack"/> of directories.</returns>
|
||||
public static IEnumerable<FileStack> ResolveDirectories(IEnumerable<string> files, NamingOptions namingOptions)
|
||||
{
|
||||
return Resolve(files.Select(i => new FileSystemMetadata { FullName = i, IsDirectory = true }), namingOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves only files from paths.
|
||||
/// </summary>
|
||||
/// <param name="files">List of paths.</param>
|
||||
/// <param name="namingOptions">The naming options.</param>
|
||||
/// <returns>Enumerable <see cref="FileStack"/> of files.</returns>
|
||||
public static IEnumerable<FileStack> ResolveFiles(IEnumerable<string> files, NamingOptions namingOptions)
|
||||
{
|
||||
return Resolve(files.Select(i => new FileSystemMetadata { FullName = i, IsDirectory = false }), namingOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves audiobooks from paths.
|
||||
/// </summary>
|
||||
/// <param name="files">List of paths.</param>
|
||||
/// <returns>Enumerable <see cref="FileStack"/> of directories.</returns>
|
||||
public static IEnumerable<FileStack> ResolveAudioBooks(IEnumerable<AudioBookFileInfo> files)
|
||||
{
|
||||
var groupedDirectoryFiles = files.GroupBy(file => Path.GetDirectoryName(file.Path));
|
||||
|
||||
foreach (var directory in groupedDirectoryFiles)
|
||||
{
|
||||
if (string.IsNullOrEmpty(directory.Key))
|
||||
{
|
||||
foreach (var file in directory)
|
||||
{
|
||||
var stack = new FileStack(Path.GetFileNameWithoutExtension(file.Path), false, new[] { file.Path });
|
||||
yield return stack;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var stack = new FileStack(Path.GetFileName(directory.Key), false, directory.Select(f => f.Path).ToArray());
|
||||
yield return stack;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves videos from paths.
|
||||
/// </summary>
|
||||
/// <param name="files">List of paths.</param>
|
||||
/// <param name="namingOptions">The naming options.</param>
|
||||
/// <returns>Enumerable <see cref="FileStack"/> of videos.</returns>
|
||||
public static IEnumerable<FileStack> Resolve(IEnumerable<FileSystemMetadata> files, NamingOptions namingOptions)
|
||||
{
|
||||
var potentialFiles = files
|
||||
.Where(i => i.IsDirectory || VideoResolver.IsVideoFile(i.FullName, namingOptions) || VideoResolver.IsStubFile(i.FullName, namingOptions))
|
||||
.OrderBy(i => i.FullName);
|
||||
|
||||
var potentialStacks = new Dictionary<string, StackMetadata>();
|
||||
foreach (var file in potentialFiles)
|
||||
{
|
||||
var name = file.Name;
|
||||
if (string.IsNullOrEmpty(name))
|
||||
{
|
||||
name = Path.GetFileName(file.FullName);
|
||||
}
|
||||
|
||||
for (var i = 0; i < namingOptions.VideoFileStackingRules.Length; i++)
|
||||
{
|
||||
var rule = namingOptions.VideoFileStackingRules[i];
|
||||
if (!rule.Match(name, out var stackParsingResult))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var stackName = stackParsingResult.Value.StackName;
|
||||
var partNumber = stackParsingResult.Value.PartNumber;
|
||||
var partType = stackParsingResult.Value.PartType;
|
||||
|
||||
if (!potentialStacks.TryGetValue(stackName, out var stackResult))
|
||||
{
|
||||
stackResult = new StackMetadata(file.IsDirectory, rule.IsNumerical, partType);
|
||||
potentialStacks[stackName] = stackResult;
|
||||
}
|
||||
|
||||
if (stackResult.Parts.Count > 0)
|
||||
{
|
||||
if (stackResult.IsDirectory != file.IsDirectory
|
||||
|| !string.Equals(partType, stackResult.PartType, StringComparison.OrdinalIgnoreCase)
|
||||
|| stackResult.ContainsPart(partNumber))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (rule.IsNumerical != stackResult.IsNumerical)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
stackResult.Parts.Add(partNumber, file);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var (fileName, stack) in potentialStacks)
|
||||
{
|
||||
if (stack.Parts.Count < 2)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
yield return new FileStack(fileName, stack.IsDirectory, stack.Parts.Select(kv => kv.Value.FullName).ToArray());
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class StackMetadata
|
||||
{
|
||||
public StackMetadata(bool isDirectory, bool isNumerical, string partType)
|
||||
{
|
||||
Parts = new Dictionary<string, FileSystemMetadata>(StringComparer.OrdinalIgnoreCase);
|
||||
IsDirectory = isDirectory;
|
||||
IsNumerical = isNumerical;
|
||||
PartType = partType;
|
||||
}
|
||||
|
||||
public Dictionary<string, FileSystemMetadata> Parts { get; }
|
||||
|
||||
public bool IsDirectory { get; }
|
||||
|
||||
public bool IsNumerical { get; }
|
||||
|
||||
public string PartType { get; }
|
||||
|
||||
public bool ContainsPart(string partNumber) => Parts.ContainsKey(partNumber);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Emby.Naming.Common;
|
||||
using Jellyfin.Extensions;
|
||||
|
||||
namespace Emby.Naming.Video
|
||||
{
|
||||
/// <summary>
|
||||
/// Resolve if file is stub (.disc).
|
||||
/// </summary>
|
||||
public static class StubResolver
|
||||
{
|
||||
/// <summary>
|
||||
/// Tries to resolve if file is stub (.disc).
|
||||
/// </summary>
|
||||
/// <param name="path">Path to file.</param>
|
||||
/// <param name="options">NamingOptions containing StubFileExtensions and StubTypes.</param>
|
||||
/// <param name="stubType">Stub type.</param>
|
||||
/// <returns>True if file is a stub.</returns>
|
||||
public static bool TryResolveFile(string path, NamingOptions options, out string? stubType)
|
||||
{
|
||||
stubType = default;
|
||||
|
||||
if (string.IsNullOrEmpty(path))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var extension = Path.GetExtension(path.AsSpan());
|
||||
|
||||
if (!options.StubFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var token = Path.GetExtension(Path.GetFileNameWithoutExtension(path.AsSpan())).TrimStart('.');
|
||||
|
||||
foreach (var rule in options.StubTypes)
|
||||
{
|
||||
if (token.Equals(rule.Token, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
stubType = rule.StubType;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
namespace Emby.Naming.Video
|
||||
{
|
||||
/// <summary>
|
||||
/// Data class holding information about Stub type rule.
|
||||
/// </summary>
|
||||
public class StubTypeRule
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StubTypeRule"/> class.
|
||||
/// </summary>
|
||||
/// <param name="token">Token.</param>
|
||||
/// <param name="stubType">Stub type.</param>
|
||||
public StubTypeRule(string token, string stubType)
|
||||
{
|
||||
Token = token;
|
||||
StubType = stubType;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the token.
|
||||
/// </summary>
|
||||
/// <value>The token.</value>
|
||||
public string Token { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the type of the stub.
|
||||
/// </summary>
|
||||
/// <value>The type of the stub.</value>
|
||||
public string StubType { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
using System;
|
||||
using MediaBrowser.Model.Entities;
|
||||
|
||||
namespace Emby.Naming.Video
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a single video file.
|
||||
/// </summary>
|
||||
public class VideoFileInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="VideoFileInfo"/> class.
|
||||
/// </summary>
|
||||
/// <param name="name">Name of file.</param>
|
||||
/// <param name="path">Path to the file.</param>
|
||||
/// <param name="container">Container type.</param>
|
||||
/// <param name="year">Year of release.</param>
|
||||
/// <param name="extraType">Extra type.</param>
|
||||
/// <param name="extraRule">Extra rule.</param>
|
||||
/// <param name="format3D">Format 3D.</param>
|
||||
/// <param name="is3D">Is 3D.</param>
|
||||
/// <param name="isStub">Is Stub.</param>
|
||||
/// <param name="stubType">Stub type.</param>
|
||||
/// <param name="isDirectory">Is directory.</param>
|
||||
public VideoFileInfo(string name, string path, string? container, int? year = default, ExtraType? extraType = default, ExtraRule? extraRule = default, string? format3D = default, bool is3D = default, bool isStub = default, string? stubType = default, bool isDirectory = default)
|
||||
{
|
||||
Path = path;
|
||||
Container = container;
|
||||
Name = name;
|
||||
Year = year;
|
||||
ExtraType = extraType;
|
||||
ExtraRule = extraRule;
|
||||
Format3D = format3D;
|
||||
Is3D = is3D;
|
||||
IsStub = isStub;
|
||||
StubType = stubType;
|
||||
IsDirectory = isDirectory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the path.
|
||||
/// </summary>
|
||||
/// <value>The path.</value>
|
||||
public string Path { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the container.
|
||||
/// </summary>
|
||||
/// <value>The container.</value>
|
||||
public string? Container { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name.
|
||||
/// </summary>
|
||||
/// <value>The name.</value>
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the year.
|
||||
/// </summary>
|
||||
/// <value>The year.</value>
|
||||
public int? Year { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the type of the extra, e.g. trailer, theme song, behind the scenes, etc.
|
||||
/// </summary>
|
||||
/// <value>The type of the extra.</value>
|
||||
public ExtraType? ExtraType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the extra rule.
|
||||
/// </summary>
|
||||
/// <value>The extra rule.</value>
|
||||
public ExtraRule? ExtraRule { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the format3 d.
|
||||
/// </summary>
|
||||
/// <value>The format3 d.</value>
|
||||
public string? Format3D { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether [is3 d].
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if [is3 d]; otherwise, <c>false</c>.</value>
|
||||
public bool Is3D { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether this instance is stub.
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if this instance is stub; otherwise, <c>false</c>.</value>
|
||||
public bool IsStub { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the type of the stub.
|
||||
/// </summary>
|
||||
/// <value>The type of the stub.</value>
|
||||
public string? StubType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether this instance is a directory.
|
||||
/// </summary>
|
||||
/// <value>The type.</value>
|
||||
public bool IsDirectory { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the file name without extension.
|
||||
/// </summary>
|
||||
/// <value>The file name without extension.</value>
|
||||
public ReadOnlySpan<char> FileNameWithoutExtension => !IsDirectory
|
||||
? System.IO.Path.GetFileNameWithoutExtension(Path.AsSpan())
|
||||
: System.IO.Path.GetFileName(Path.AsSpan());
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string ToString()
|
||||
{
|
||||
return "VideoFileInfo(Name: '" + Name + "')";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using MediaBrowser.Model.Entities;
|
||||
|
||||
namespace Emby.Naming.Video
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a complete video, including all parts and subtitles.
|
||||
/// </summary>
|
||||
public class VideoInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="VideoInfo" /> class.
|
||||
/// </summary>
|
||||
/// <param name="name">The name.</param>
|
||||
public VideoInfo(string? name)
|
||||
{
|
||||
Name = name;
|
||||
|
||||
Files = Array.Empty<VideoFileInfo>();
|
||||
AlternateVersions = Array.Empty<VideoFileInfo>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name.
|
||||
/// </summary>
|
||||
/// <value>The name.</value>
|
||||
public string? Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the year.
|
||||
/// </summary>
|
||||
/// <value>The year.</value>
|
||||
public int? Year { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the files.
|
||||
/// </summary>
|
||||
/// <value>The files.</value>
|
||||
public IReadOnlyList<VideoFileInfo> Files { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the alternate versions.
|
||||
/// </summary>
|
||||
/// <value>The alternate versions.</value>
|
||||
public IReadOnlyList<VideoFileInfo> AlternateVersions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the extra type.
|
||||
/// </summary>
|
||||
public ExtraType? ExtraType { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using Emby.Naming.Common;
|
||||
using Jellyfin.Extensions;
|
||||
using MediaBrowser.Model.IO;
|
||||
|
||||
namespace Emby.Naming.Video
|
||||
{
|
||||
/// <summary>
|
||||
/// Resolves alternative versions and extras from list of video files.
|
||||
/// </summary>
|
||||
public static partial class VideoListResolver
|
||||
{
|
||||
[GeneratedRegex("[0-9]{2}[0-9]+[ip]", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex ResolutionRegex();
|
||||
|
||||
[GeneratedRegex(@"^\[([^]]*)\]")]
|
||||
private static partial Regex CheckMultiVersionRegex();
|
||||
|
||||
/// <summary>
|
||||
/// Resolves alternative versions and extras from list of video files.
|
||||
/// </summary>
|
||||
/// <param name="videoInfos">List of related video files.</param>
|
||||
/// <param name="namingOptions">The naming options.</param>
|
||||
/// <param name="supportMultiVersion">Indication we should consider multi-versions of content.</param>
|
||||
/// <param name="parseName">Whether to parse the name or use the filename.</param>
|
||||
/// <param name="libraryRoot">Top-level folder for the containing library.</param>
|
||||
/// <returns>Returns enumerable of <see cref="VideoInfo"/> which groups files together when related.</returns>
|
||||
public static IReadOnlyList<VideoInfo> Resolve(IReadOnlyList<VideoFileInfo> videoInfos, NamingOptions namingOptions, bool supportMultiVersion = true, bool parseName = true, string? libraryRoot = "")
|
||||
{
|
||||
// Filter out all extras, otherwise they could cause stacks to not be resolved
|
||||
// See the unit test TestStackedWithTrailer
|
||||
var nonExtras = videoInfos
|
||||
.Where(i => i.ExtraType is null)
|
||||
.Select(i => new FileSystemMetadata { FullName = i.Path, IsDirectory = i.IsDirectory });
|
||||
|
||||
var stackResult = StackResolver.Resolve(nonExtras, namingOptions).ToList();
|
||||
|
||||
var remainingFiles = new List<VideoFileInfo>();
|
||||
var standaloneMedia = new List<VideoFileInfo>();
|
||||
|
||||
for (var i = 0; i < videoInfos.Count; i++)
|
||||
{
|
||||
var current = videoInfos[i];
|
||||
if (stackResult.Any(s => s.ContainsFile(current.Path, current.IsDirectory)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (current.ExtraType is null)
|
||||
{
|
||||
standaloneMedia.Add(current);
|
||||
}
|
||||
else
|
||||
{
|
||||
remainingFiles.Add(current);
|
||||
}
|
||||
}
|
||||
|
||||
var list = new List<VideoInfo>();
|
||||
|
||||
foreach (var stack in stackResult)
|
||||
{
|
||||
var info = new VideoInfo(stack.Name)
|
||||
{
|
||||
Files = stack.Files.Select(i => VideoResolver.Resolve(i, stack.IsDirectoryStack, namingOptions, parseName, libraryRoot))
|
||||
.OfType<VideoFileInfo>()
|
||||
.ToList()
|
||||
};
|
||||
|
||||
info.Year = info.Files[0].Year;
|
||||
list.Add(info);
|
||||
}
|
||||
|
||||
foreach (var media in standaloneMedia)
|
||||
{
|
||||
var info = new VideoInfo(media.Name) { Files = new[] { media } };
|
||||
|
||||
info.Year = info.Files[0].Year;
|
||||
list.Add(info);
|
||||
}
|
||||
|
||||
if (supportMultiVersion)
|
||||
{
|
||||
list = GetVideosGroupedByVersion(list, namingOptions);
|
||||
}
|
||||
|
||||
// Whatever files are left, just add them
|
||||
list.AddRange(remainingFiles.Select(i => new VideoInfo(i.Name)
|
||||
{
|
||||
Files = new[] { i },
|
||||
Year = i.Year,
|
||||
ExtraType = i.ExtraType
|
||||
}));
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private static List<VideoInfo> GetVideosGroupedByVersion(List<VideoInfo> videos, NamingOptions namingOptions)
|
||||
{
|
||||
if (videos.Count == 0)
|
||||
{
|
||||
return videos;
|
||||
}
|
||||
|
||||
var folderName = Path.GetFileName(Path.GetDirectoryName(videos[0].Files[0].Path.AsSpan()));
|
||||
|
||||
if (folderName.Length <= 1 || !HaveSameYear(videos))
|
||||
{
|
||||
return videos;
|
||||
}
|
||||
|
||||
// Cannot use Span inside local functions and delegates thus we cannot use LINQ here nor merge with the above [if]
|
||||
VideoInfo? primary = null;
|
||||
for (var i = 0; i < videos.Count; i++)
|
||||
{
|
||||
var video = videos[i];
|
||||
if (video.ExtraType is not null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!IsEligibleForMultiVersion(folderName, video.Files[0].FileNameWithoutExtension, namingOptions))
|
||||
{
|
||||
return videos;
|
||||
}
|
||||
|
||||
if (folderName.Equals(video.Files[0].FileNameWithoutExtension, StringComparison.Ordinal))
|
||||
{
|
||||
primary = video;
|
||||
}
|
||||
}
|
||||
|
||||
if (videos.Count > 1)
|
||||
{
|
||||
var groups = videos
|
||||
.Select(x => (filename: x.Files[0].FileNameWithoutExtension.ToString(), value: x))
|
||||
.Select(x => (x.filename, resolutionMatch: ResolutionRegex().Match(x.filename), x.value))
|
||||
.GroupBy(x => x.resolutionMatch.Success)
|
||||
.ToList();
|
||||
|
||||
videos.Clear();
|
||||
|
||||
StringComparer comparer = StringComparer.Create(CultureInfo.InvariantCulture, CompareOptions.NumericOrdering);
|
||||
foreach (var group in groups)
|
||||
{
|
||||
if (group.Key)
|
||||
{
|
||||
videos.InsertRange(0, group
|
||||
.OrderByDescending(x => x.resolutionMatch.Value, comparer)
|
||||
.ThenBy(x => x.filename, comparer)
|
||||
.Select(x => x.value));
|
||||
}
|
||||
else
|
||||
{
|
||||
videos.AddRange(group.OrderBy(x => x.filename, comparer).Select(x => x.value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
primary ??= videos[0];
|
||||
videos.Remove(primary);
|
||||
|
||||
var list = new List<VideoInfo>
|
||||
{
|
||||
primary
|
||||
};
|
||||
|
||||
list[0].AlternateVersions = videos.Select(x => x.Files[0]).ToArray();
|
||||
list[0].Name = folderName.ToString();
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private static bool HaveSameYear(IReadOnlyList<VideoInfo> videos)
|
||||
{
|
||||
if (videos.Count == 1)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var firstYear = videos[0].Year ?? -1;
|
||||
for (var i = 1; i < videos.Count; i++)
|
||||
{
|
||||
if ((videos[i].Year ?? -1) != firstYear)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool IsEligibleForMultiVersion(ReadOnlySpan<char> folderName, ReadOnlySpan<char> testFilename, NamingOptions namingOptions)
|
||||
{
|
||||
if (!testFilename.StartsWith(folderName, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Remove the folder name before cleaning as we don't care about cleaning that part
|
||||
if (folderName.Length <= testFilename.Length)
|
||||
{
|
||||
testFilename = testFilename[folderName.Length..].Trim();
|
||||
}
|
||||
|
||||
// There are no span overloads for regex unfortunately
|
||||
if (CleanStringParser.TryClean(testFilename.ToString(), namingOptions.CleanStringRegexes, out var cleanName))
|
||||
{
|
||||
testFilename = cleanName.AsSpan().Trim();
|
||||
}
|
||||
|
||||
// The CleanStringParser should have removed common keywords etc.
|
||||
return testFilename.IsEmpty
|
||||
|| testFilename[0] == '-'
|
||||
|| CheckMultiVersionRegex().IsMatch(testFilename);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using Emby.Naming.Common;
|
||||
using Jellyfin.Extensions;
|
||||
|
||||
namespace Emby.Naming.Video
|
||||
{
|
||||
/// <summary>
|
||||
/// Resolves <see cref="VideoFileInfo"/> from file path.
|
||||
/// </summary>
|
||||
public static class VideoResolver
|
||||
{
|
||||
/// <summary>
|
||||
/// Resolves the directory.
|
||||
/// </summary>
|
||||
/// <param name="path">The path.</param>
|
||||
/// <param name="namingOptions">The naming options.</param>
|
||||
/// <param name="parseName">Whether to parse the name or use the filename.</param>
|
||||
/// <param name="libraryRoot">Top-level folder for the containing library.</param>
|
||||
/// <returns>VideoFileInfo.</returns>
|
||||
public static VideoFileInfo? ResolveDirectory(string? path, NamingOptions namingOptions, bool parseName = true, string? libraryRoot = "")
|
||||
{
|
||||
return Resolve(path, true, namingOptions, parseName, libraryRoot);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the file.
|
||||
/// </summary>
|
||||
/// <param name="path">The path.</param>
|
||||
/// <param name="namingOptions">The naming options.</param>
|
||||
/// <param name="libraryRoot">Top-level folder for the containing library.</param>
|
||||
/// <returns>VideoFileInfo.</returns>
|
||||
public static VideoFileInfo? ResolveFile(string? path, NamingOptions namingOptions, string? libraryRoot = "")
|
||||
{
|
||||
return Resolve(path, false, namingOptions, libraryRoot: libraryRoot);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path.</param>
|
||||
/// <param name="isDirectory">if set to <c>true</c> [is folder].</param>
|
||||
/// <param name="namingOptions">The naming options.</param>
|
||||
/// <param name="parseName">Whether or not the name should be parsed for info.</param>
|
||||
/// <param name="libraryRoot">Top-level folder for the containing library.</param>
|
||||
/// <returns>VideoFileInfo.</returns>
|
||||
/// <exception cref="ArgumentNullException"><c>path</c> is <c>null</c>.</exception>
|
||||
public static VideoFileInfo? Resolve(string? path, bool isDirectory, NamingOptions namingOptions, bool parseName = true, string? libraryRoot = "")
|
||||
{
|
||||
if (string.IsNullOrEmpty(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
bool isStub = false;
|
||||
ReadOnlySpan<char> container = ReadOnlySpan<char>.Empty;
|
||||
string? stubType = null;
|
||||
|
||||
if (!isDirectory)
|
||||
{
|
||||
var extension = Path.GetExtension(path.AsSpan());
|
||||
|
||||
// Check supported extensions
|
||||
if (!namingOptions.VideoFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// It's not supported. Check stub extensions
|
||||
if (!StubResolver.TryResolveFile(path, namingOptions, out stubType))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
isStub = true;
|
||||
}
|
||||
|
||||
container = extension.TrimStart('.');
|
||||
}
|
||||
|
||||
var format3DResult = Format3DParser.Parse(path, namingOptions);
|
||||
|
||||
var extraResult = ExtraRuleResolver.GetExtraInfo(path, namingOptions, libraryRoot);
|
||||
|
||||
var name = Path.GetFileNameWithoutExtension(path);
|
||||
|
||||
int? year = null;
|
||||
|
||||
if (parseName)
|
||||
{
|
||||
var cleanDateTimeResult = CleanDateTime(name, namingOptions);
|
||||
name = cleanDateTimeResult.Name;
|
||||
year = cleanDateTimeResult.Year;
|
||||
|
||||
if (TryCleanString(name, namingOptions, out var newName))
|
||||
{
|
||||
name = newName;
|
||||
}
|
||||
}
|
||||
|
||||
return new VideoFileInfo(
|
||||
path: path,
|
||||
container: container.IsEmpty ? null : container.ToString(),
|
||||
isStub: isStub,
|
||||
name: name,
|
||||
year: year,
|
||||
stubType: stubType,
|
||||
is3D: format3DResult.Is3D,
|
||||
format3D: format3DResult.Format3D,
|
||||
extraType: extraResult.ExtraType,
|
||||
isDirectory: isDirectory,
|
||||
extraRule: extraResult.Rule);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines if path is video file based on extension.
|
||||
/// </summary>
|
||||
/// <param name="path">Path to file.</param>
|
||||
/// <param name="namingOptions">The naming options.</param>
|
||||
/// <returns>True if is video file.</returns>
|
||||
public static bool IsVideoFile(string path, NamingOptions namingOptions)
|
||||
{
|
||||
var extension = Path.GetExtension(path.AsSpan());
|
||||
return namingOptions.VideoFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines if path is video file stub based on extension.
|
||||
/// </summary>
|
||||
/// <param name="path">Path to file.</param>
|
||||
/// <param name="namingOptions">The naming options.</param>
|
||||
/// <returns>True if is video file stub.</returns>
|
||||
public static bool IsStubFile(string path, NamingOptions namingOptions)
|
||||
{
|
||||
var extension = Path.GetExtension(path.AsSpan());
|
||||
return namingOptions.StubFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to clean name of clutter.
|
||||
/// </summary>
|
||||
/// <param name="name">Raw name.</param>
|
||||
/// <param name="namingOptions">The naming options.</param>
|
||||
/// <param name="newName">Clean name.</param>
|
||||
/// <returns>True if cleaning of name was successful.</returns>
|
||||
public static bool TryCleanString([NotNullWhen(true)] string? name, NamingOptions namingOptions, out string newName)
|
||||
{
|
||||
return CleanStringParser.TryClean(name, namingOptions.CleanStringRegexes, out newName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get name and year from raw name.
|
||||
/// </summary>
|
||||
/// <param name="name">Raw name.</param>
|
||||
/// <param name="namingOptions">The naming options.</param>
|
||||
/// <returns>Returns <see cref="CleanDateTimeResult"/> with name and optional year.</returns>
|
||||
public static CleanDateTimeResult CleanDateTime(string name, NamingOptions namingOptions)
|
||||
{
|
||||
return CleanDateTimeParser.Clean(name, namingOptions.CleanDateTimeRegexes);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// <autogenerated />
|
||||
using System;
|
||||
using System.Reflection;
|
||||
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETCoreApp,Version=v10.0", FrameworkDisplayName = ".NET 10.0")]
|
||||
@@ -0,0 +1,27 @@
|
||||
is_global = true
|
||||
build_property.TargetFramework = net10.0
|
||||
build_property.TargetFramework = net10.0
|
||||
build_property.TargetFrameworkIdentifier = .NETCoreApp
|
||||
build_property.TargetFrameworkIdentifier = .NETCoreApp
|
||||
build_property.TargetFrameworkVersion = v10.0
|
||||
build_property.TargetFrameworkVersion = v10.0
|
||||
build_property.TargetPlatformMinVersion =
|
||||
build_property.TargetPlatformMinVersion =
|
||||
build_property.UsingMicrosoftNETSdkWeb =
|
||||
build_property.UsingMicrosoftNETSdkWeb =
|
||||
build_property.ProjectTypeGuids =
|
||||
build_property.ProjectTypeGuids =
|
||||
build_property.InvariantGlobalization =
|
||||
build_property.InvariantGlobalization =
|
||||
build_property.PlatformNeutralAssembly =
|
||||
build_property.PlatformNeutralAssembly =
|
||||
build_property.EnforceExtendedAnalyzerRules =
|
||||
build_property.EnforceExtendedAnalyzerRules =
|
||||
build_property._SupportedPlatformList = Linux,macOS,Windows
|
||||
build_property._SupportedPlatformList = Linux,macOS,Windows
|
||||
build_property.RootNamespace = Emby.Naming
|
||||
build_property.ProjectDir = /srv/common_drive/Projects/pgsql-jellyfin/Emby.Naming/
|
||||
build_property.EnableComHosting =
|
||||
build_property.EnableGeneratedComInterfaceComImportInterop =
|
||||
build_property.EffectiveAnalysisLevelStyle = 10.0
|
||||
build_property.EnableCodeStyleSeverity =
|
||||
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,26 @@
|
||||
<?xml version="1.0" encoding="utf-8" standalone="no"?>
|
||||
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<RestoreSuccess Condition=" '$(RestoreSuccess)' == '' ">True</RestoreSuccess>
|
||||
<RestoreTool Condition=" '$(RestoreTool)' == '' ">NuGet</RestoreTool>
|
||||
<ProjectAssetsFile Condition=" '$(ProjectAssetsFile)' == '' ">$(MSBuildThisFileDirectory)project.assets.json</ProjectAssetsFile>
|
||||
<NuGetPackageRoot Condition=" '$(NuGetPackageRoot)' == '' ">/home/wjones/.nuget/packages/</NuGetPackageRoot>
|
||||
<NuGetPackageFolders Condition=" '$(NuGetPackageFolders)' == '' ">/home/wjones/.nuget/packages/</NuGetPackageFolders>
|
||||
<NuGetProjectStyle Condition=" '$(NuGetProjectStyle)' == '' ">PackageReference</NuGetProjectStyle>
|
||||
<NuGetToolVersion Condition=" '$(NuGetToolVersion)' == '' ">7.0.0</NuGetToolVersion>
|
||||
</PropertyGroup>
|
||||
<ItemGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<SourceRoot Include="/home/wjones/.nuget/packages/" />
|
||||
</ItemGroup>
|
||||
<ImportGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<Import Project="$(NuGetPackageRoot)microsoft.entityframeworkcore/10.0.3/buildTransitive/net10.0/Microsoft.EntityFrameworkCore.props" Condition="Exists('$(NuGetPackageRoot)microsoft.entityframeworkcore/10.0.3/buildTransitive/net10.0/Microsoft.EntityFrameworkCore.props')" />
|
||||
<Import Project="$(NuGetPackageRoot)microsoft.codeanalysis.bannedapianalyzers/4.14.0/buildTransitive/Microsoft.CodeAnalysis.BannedApiAnalyzers.props" Condition="Exists('$(NuGetPackageRoot)microsoft.codeanalysis.bannedapianalyzers/4.14.0/buildTransitive/Microsoft.CodeAnalysis.BannedApiAnalyzers.props')" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<PkgStyleCop_Analyzers_Unstable Condition=" '$(PkgStyleCop_Analyzers_Unstable)' == '' ">/home/wjones/.nuget/packages/stylecop.analyzers.unstable/1.2.0.556</PkgStyleCop_Analyzers_Unstable>
|
||||
<PkgSmartAnalyzers_MultithreadingAnalyzer Condition=" '$(PkgSmartAnalyzers_MultithreadingAnalyzer)' == '' ">/home/wjones/.nuget/packages/smartanalyzers.multithreadinganalyzer/1.1.31</PkgSmartAnalyzers_MultithreadingAnalyzer>
|
||||
<PkgSerilogAnalyzer Condition=" '$(PkgSerilogAnalyzer)' == '' ">/home/wjones/.nuget/packages/seriloganalyzer/0.15.0</PkgSerilogAnalyzer>
|
||||
<PkgMicrosoft_CodeAnalysis_BannedApiAnalyzers Condition=" '$(PkgMicrosoft_CodeAnalysis_BannedApiAnalyzers)' == '' ">/home/wjones/.nuget/packages/microsoft.codeanalysis.bannedapianalyzers/4.14.0</PkgMicrosoft_CodeAnalysis_BannedApiAnalyzers>
|
||||
<PkgIDisposableAnalyzers Condition=" '$(PkgIDisposableAnalyzers)' == '' ">/home/wjones/.nuget/packages/idisposableanalyzers/4.0.8</PkgIDisposableAnalyzers>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8" standalone="no"?>
|
||||
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ImportGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
|
||||
<Import Project="$(NuGetPackageRoot)microsoft.extensions.options/10.0.3/buildTransitive/net8.0/Microsoft.Extensions.Options.targets" Condition="Exists('$(NuGetPackageRoot)microsoft.extensions.options/10.0.3/buildTransitive/net8.0/Microsoft.Extensions.Options.targets')" />
|
||||
<Import Project="$(NuGetPackageRoot)microsoft.extensions.logging.abstractions/10.0.3/buildTransitive/net8.0/Microsoft.Extensions.Logging.Abstractions.targets" Condition="Exists('$(NuGetPackageRoot)microsoft.extensions.logging.abstractions/10.0.3/buildTransitive/net8.0/Microsoft.Extensions.Logging.Abstractions.targets')" />
|
||||
<Import Project="$(NuGetPackageRoot)microsoft.codeanalysis.bannedapianalyzers/4.14.0/buildTransitive/Microsoft.CodeAnalysis.BannedApiAnalyzers.targets" Condition="Exists('$(NuGetPackageRoot)microsoft.codeanalysis.bannedapianalyzers/4.14.0/buildTransitive/Microsoft.CodeAnalysis.BannedApiAnalyzers.targets')" />
|
||||
</ImportGroup>
|
||||
</Project>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"version": 2,
|
||||
"dgSpecHash": "nPaubMzeXPg=",
|
||||
"success": true,
|
||||
"projectFilePath": "/srv/common_drive/Projects/pgsql-jellyfin/Emby.Naming/Emby.Naming.csproj",
|
||||
"expectedPackageFiles": [
|
||||
"/home/wjones/.nuget/packages/diacritics/4.1.4/diacritics.4.1.4.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/icu4n/60.1.0-alpha.356/icu4n.60.1.0-alpha.356.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/icu4n.transliterator/60.1.0-alpha.356/icu4n.transliterator.60.1.0-alpha.356.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/idisposableanalyzers/4.0.8/idisposableanalyzers.4.0.8.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/j2n/2.0.0/j2n.2.0.0.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.codeanalysis.bannedapianalyzers/4.14.0/microsoft.codeanalysis.bannedapianalyzers.4.14.0.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.entityframeworkcore/10.0.3/microsoft.entityframeworkcore.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.entityframeworkcore.abstractions/10.0.3/microsoft.entityframeworkcore.abstractions.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.entityframeworkcore.analyzers/10.0.3/microsoft.entityframeworkcore.analyzers.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.entityframeworkcore.relational/10.0.3/microsoft.entityframeworkcore.relational.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.caching.abstractions/10.0.3/microsoft.extensions.caching.abstractions.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.caching.memory/10.0.3/microsoft.extensions.caching.memory.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.configuration.abstractions/10.0.3/microsoft.extensions.configuration.abstractions.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.dependencyinjection/10.0.3/microsoft.extensions.dependencyinjection.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.dependencyinjection.abstractions/10.0.3/microsoft.extensions.dependencyinjection.abstractions.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.logging/10.0.3/microsoft.extensions.logging.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.logging.abstractions/10.0.3/microsoft.extensions.logging.abstractions.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.options/10.0.3/microsoft.extensions.options.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/microsoft.extensions.primitives/10.0.3/microsoft.extensions.primitives.10.0.3.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/polly/8.6.5/polly.8.6.5.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/polly.core/8.6.5/polly.core.8.6.5.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/seriloganalyzer/0.15.0/seriloganalyzer.0.15.0.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/smartanalyzers.multithreadinganalyzer/1.1.31/smartanalyzers.multithreadinganalyzer.1.1.31.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/stylecop.analyzers/1.2.0-beta.556/stylecop.analyzers.1.2.0-beta.556.nupkg.sha512",
|
||||
"/home/wjones/.nuget/packages/stylecop.analyzers.unstable/1.2.0.556/stylecop.analyzers.unstable.1.2.0.556.nupkg.sha512"
|
||||
],
|
||||
"logs": []
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
17714532054800000
|
||||
@@ -0,0 +1 @@
|
||||
17715044167700000
|
||||
Reference in New Issue
Block a user