2021-12-19 23:13:30 +08:00
|
|
|
using System;
|
|
|
|
using System.IO;
|
2022-08-01 21:34:09 +08:00
|
|
|
using System.Text.RegularExpressions;
|
2022-05-06 19:36:40 +08:00
|
|
|
using System.Threading.Tasks;
|
2021-12-19 23:13:30 +08:00
|
|
|
using BililiveRecorder.Core.Config.V3;
|
|
|
|
using Fluid;
|
|
|
|
using Fluid.Ast;
|
2022-05-06 19:36:40 +08:00
|
|
|
using Fluid.Values;
|
|
|
|
using Newtonsoft.Json.Linq;
|
2021-12-19 23:13:30 +08:00
|
|
|
using Serilog;
|
2022-06-28 16:10:06 +08:00
|
|
|
using Serilog.Core;
|
2021-12-19 23:13:30 +08:00
|
|
|
|
|
|
|
namespace BililiveRecorder.Core.Templating
|
|
|
|
{
|
2022-06-09 15:40:08 +08:00
|
|
|
public sealed class FileNameGenerator
|
2021-12-19 23:13:30 +08:00
|
|
|
{
|
2021-12-22 18:06:55 +08:00
|
|
|
private static readonly FluidParser parser;
|
|
|
|
private static readonly IFluidTemplate defaultTemplate;
|
2021-12-19 23:13:30 +08:00
|
|
|
|
|
|
|
private static readonly Random _globalRandom = new();
|
|
|
|
[ThreadStatic] private static Random? _localRandom;
|
|
|
|
private static Random Random
|
|
|
|
{
|
|
|
|
get
|
|
|
|
{
|
|
|
|
if (_localRandom == null)
|
|
|
|
{
|
|
|
|
int seed;
|
|
|
|
lock (_globalRandom)
|
|
|
|
{
|
|
|
|
seed = _globalRandom.Next();
|
|
|
|
}
|
|
|
|
_localRandom = new Random(seed);
|
|
|
|
}
|
|
|
|
return _localRandom;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-28 16:10:06 +08:00
|
|
|
private readonly IFileNameConfig config;
|
|
|
|
private readonly ILogger logger;
|
2021-12-19 23:13:30 +08:00
|
|
|
|
|
|
|
static FileNameGenerator()
|
|
|
|
{
|
2021-12-22 18:06:55 +08:00
|
|
|
parser = new FluidParser();
|
2021-12-19 23:13:30 +08:00
|
|
|
parser.RegisterExpressionTag("random", async static (expression, writer, encoder, context) =>
|
|
|
|
{
|
|
|
|
var value = await expression.EvaluateAsync(context);
|
|
|
|
var valueStr = value.ToStringValue();
|
|
|
|
if (!int.TryParse(valueStr, out var count))
|
|
|
|
count = 3;
|
|
|
|
|
|
|
|
var text = string.Empty;
|
|
|
|
|
|
|
|
while (count > 0)
|
|
|
|
{
|
|
|
|
var step = count > 9 ? 9 : count;
|
|
|
|
count -= step;
|
|
|
|
var num = Random.Next((int)Math.Pow(10, step));
|
|
|
|
text += num.ToString("D" + step);
|
|
|
|
}
|
|
|
|
|
|
|
|
await writer.WriteAsync(text);
|
|
|
|
|
|
|
|
return Completion.Normal;
|
|
|
|
});
|
2021-12-22 18:06:55 +08:00
|
|
|
|
|
|
|
parser = parser.Compile();
|
|
|
|
|
|
|
|
defaultTemplate = parser.Parse(DefaultConfig.Instance.FileNameRecordTemplate);
|
2021-12-19 23:13:30 +08:00
|
|
|
}
|
|
|
|
|
2022-06-28 16:10:06 +08:00
|
|
|
public FileNameGenerator(IFileNameConfig config, ILogger? logger)
|
2021-12-19 23:13:30 +08:00
|
|
|
{
|
|
|
|
this.config = config ?? throw new ArgumentNullException(nameof(config));
|
2022-06-28 16:10:06 +08:00
|
|
|
this.logger = logger?.ForContext<FileNameGenerator>() ?? Logger.None;
|
2021-12-19 23:13:30 +08:00
|
|
|
}
|
|
|
|
|
2022-06-28 16:10:06 +08:00
|
|
|
public FileNameTemplateOutput CreateFilePath(FileNameTemplateContext data)
|
2021-12-19 23:13:30 +08:00
|
|
|
{
|
2022-06-28 16:10:06 +08:00
|
|
|
var status = FileNameTemplateStatus.Success;
|
|
|
|
string? errorMessage = null;
|
|
|
|
string relativePath;
|
|
|
|
string? fullPath;
|
|
|
|
|
|
|
|
var workDirectory = this.config.WorkDirectory;
|
|
|
|
var skipFullPath = workDirectory is null;
|
2021-12-19 23:13:30 +08:00
|
|
|
|
|
|
|
var now = DateTimeOffset.Now;
|
|
|
|
var templateOptions = new TemplateOptions
|
|
|
|
{
|
|
|
|
Now = () => now,
|
|
|
|
};
|
|
|
|
templateOptions.MemberAccessStrategy.MemberNameStrategy = MemberNameStrategies.CamelCase;
|
2022-05-06 19:36:40 +08:00
|
|
|
templateOptions.ValueConverters.Add(o => o is JContainer j ? new JContainerValue(j) : null);
|
2022-06-28 16:10:06 +08:00
|
|
|
templateOptions.Filters.AddFilter("format_qn",
|
|
|
|
static (FluidValue input, FilterArguments arguments, TemplateContext context) => new StringValue(StreamQualityNumber.MapToString((int)input.ToNumberValue())));
|
2022-05-06 19:36:40 +08:00
|
|
|
|
2021-12-19 23:13:30 +08:00
|
|
|
var context = new TemplateContext(data, templateOptions);
|
|
|
|
|
2022-06-28 16:10:06 +08:00
|
|
|
if (!parser.TryParse(this.config.FileNameRecordTemplate, out var template, out var error))
|
2021-12-19 23:13:30 +08:00
|
|
|
{
|
2022-06-28 16:10:06 +08:00
|
|
|
this.logger.Warning("文件名模板格式不正确,请修改: {ParserError}", error);
|
|
|
|
errorMessage = "文件名模板格式不正确,请修改: " + error;
|
|
|
|
status = FileNameTemplateStatus.TemplateError;
|
2021-12-19 23:13:30 +08:00
|
|
|
goto returnDefaultPath;
|
|
|
|
}
|
|
|
|
|
2022-06-28 16:10:06 +08:00
|
|
|
relativePath = template.Render(context);
|
2021-12-19 23:13:30 +08:00
|
|
|
relativePath = RemoveInvalidFileName(relativePath);
|
|
|
|
|
2022-06-28 16:10:06 +08:00
|
|
|
fullPath = skipFullPath ? null : Path.GetFullPath(Path.Combine(workDirectory, relativePath));
|
|
|
|
|
2022-07-01 17:23:17 +08:00
|
|
|
if (!skipFullPath && !CheckIsWithinPath(workDirectory!, fullPath!))
|
2021-12-19 23:13:30 +08:00
|
|
|
{
|
2022-06-28 16:10:06 +08:00
|
|
|
this.logger.Warning("录制文件位置超出允许范围,请检查设置。将写入到默认路径。");
|
|
|
|
status = FileNameTemplateStatus.OutOfRange;
|
|
|
|
errorMessage = "录制文件位置超出允许范围";
|
2021-12-19 23:13:30 +08:00
|
|
|
goto returnDefaultPath;
|
|
|
|
}
|
|
|
|
|
2022-06-28 16:10:06 +08:00
|
|
|
var ext = Path.GetExtension(relativePath);
|
2021-12-22 17:49:08 +08:00
|
|
|
if (!ext.Equals(".flv", StringComparison.OrdinalIgnoreCase))
|
|
|
|
{
|
2022-06-28 16:10:06 +08:00
|
|
|
this.logger.Warning("录播姬只支持 FLV 文件格式,将在录制文件后缀名 {ExtensionName} 后添加 {DotFlv}。", ext, ".flv");
|
2021-12-22 17:49:08 +08:00
|
|
|
relativePath += ".flv";
|
2022-06-28 16:10:06 +08:00
|
|
|
|
|
|
|
if (!skipFullPath)
|
|
|
|
fullPath += ".flv";
|
2021-12-22 17:49:08 +08:00
|
|
|
}
|
|
|
|
|
2022-06-28 16:10:06 +08:00
|
|
|
if (!skipFullPath && File.Exists(fullPath))
|
2021-12-19 23:13:30 +08:00
|
|
|
{
|
2022-06-28 16:10:06 +08:00
|
|
|
this.logger.Warning("录制文件名冲突,将写入到默认路径。");
|
|
|
|
status = FileNameTemplateStatus.FileConflict;
|
|
|
|
errorMessage = "录制文件名冲突";
|
2021-12-19 23:13:30 +08:00
|
|
|
goto returnDefaultPath;
|
|
|
|
}
|
|
|
|
|
2022-06-28 16:10:06 +08:00
|
|
|
return new FileNameTemplateOutput(status, errorMessage, relativePath, fullPath);
|
2021-12-19 23:13:30 +08:00
|
|
|
|
|
|
|
returnDefaultPath:
|
|
|
|
var defaultRelativePath = RemoveInvalidFileName(defaultTemplate.Render(context));
|
2022-06-28 16:10:06 +08:00
|
|
|
var defaultFullPath = skipFullPath ? null : Path.GetFullPath(Path.Combine(workDirectory, defaultRelativePath));
|
|
|
|
|
|
|
|
return new FileNameTemplateOutput(status, errorMessage, defaultRelativePath, defaultFullPath);
|
2021-12-19 23:13:30 +08:00
|
|
|
}
|
|
|
|
|
2022-05-06 19:36:40 +08:00
|
|
|
private class JContainerValue : ObjectValueBase
|
|
|
|
{
|
|
|
|
public JContainerValue(JContainer value) : base(value)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
public override ValueTask<FluidValue> GetValueAsync(string name, TemplateContext context)
|
|
|
|
{
|
|
|
|
var j = (JContainer)this.Value;
|
|
|
|
JToken? value;
|
|
|
|
|
|
|
|
if (j is JObject jobject)
|
|
|
|
{
|
|
|
|
value = jobject[name];
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
return NilValue.Instance;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (value is null)
|
|
|
|
{
|
|
|
|
return NilValue.Instance;
|
|
|
|
}
|
|
|
|
else if (value is JContainer)
|
|
|
|
{
|
|
|
|
return Create(value, context.Options);
|
|
|
|
}
|
|
|
|
else if (value is JValue jValue)
|
|
|
|
{
|
|
|
|
return Create(jValue.Value, context.Options);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
// WHAT ARE YOU !?
|
|
|
|
return NilValue.Instance;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public override ValueTask<FluidValue> GetIndexAsync(FluidValue index, TemplateContext context)
|
|
|
|
{
|
|
|
|
var j = (JContainer)this.Value;
|
|
|
|
JToken? value;
|
|
|
|
|
|
|
|
try
|
|
|
|
{
|
|
|
|
if (index.Type == FluidValues.Number)
|
|
|
|
{
|
|
|
|
value = j[(int)index.ToNumberValue()];
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
value = j[index.ToStringValue()];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
catch (Exception)
|
|
|
|
{
|
|
|
|
return NilValue.Instance;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (value is null)
|
|
|
|
{
|
|
|
|
return NilValue.Instance;
|
|
|
|
}
|
|
|
|
else if (value is JContainer)
|
|
|
|
{
|
|
|
|
return Create(value, context.Options);
|
|
|
|
}
|
|
|
|
else if (value is JValue jValue)
|
|
|
|
{
|
|
|
|
return Create(jValue.Value, context.Options);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
// WHAT ARE YOU !?
|
|
|
|
return NilValue.Instance;
|
|
|
|
}
|
|
|
|
}
|
2021-12-19 23:13:30 +08:00
|
|
|
}
|
|
|
|
|
2022-08-01 21:34:09 +08:00
|
|
|
private static readonly Regex invalidDirectoryNameRegex = new Regex(@"([ .])([\\\/])", RegexOptions.Compiled);
|
|
|
|
|
2021-12-19 23:13:30 +08:00
|
|
|
internal static string RemoveInvalidFileName(string input, bool ignore_slash = true)
|
|
|
|
{
|
|
|
|
foreach (var c in Path.GetInvalidFileNameChars())
|
|
|
|
if (!ignore_slash || c != '\\' && c != '/')
|
|
|
|
input = input.Replace(c, '_');
|
2022-08-01 21:34:09 +08:00
|
|
|
|
|
|
|
input = invalidDirectoryNameRegex.Replace(input, "$1_$2");
|
|
|
|
|
2021-12-19 23:13:30 +08:00
|
|
|
return input;
|
|
|
|
}
|
|
|
|
|
2022-06-28 16:10:06 +08:00
|
|
|
private static readonly char[] separator = new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar };
|
|
|
|
|
2021-12-19 23:13:30 +08:00
|
|
|
internal static bool CheckIsWithinPath(string parent, string child)
|
|
|
|
{
|
2022-06-28 16:10:06 +08:00
|
|
|
var fullParent = Path.GetFullPath(parent);
|
|
|
|
var fullChild = Path.GetFullPath(child);
|
2021-12-19 23:13:30 +08:00
|
|
|
|
2022-06-28 16:10:06 +08:00
|
|
|
var parentSegments = fullParent.Split(separator, StringSplitOptions.None).AsSpan();
|
|
|
|
if (parentSegments[parentSegments.Length - 1] == "")
|
|
|
|
{
|
|
|
|
parentSegments = parentSegments.Slice(0, parentSegments.Length - 1);
|
|
|
|
}
|
|
|
|
|
|
|
|
var childSegments = fullChild.Split(separator, StringSplitOptions.None).AsSpan();
|
|
|
|
if (childSegments[childSegments.Length - 1] == "")
|
|
|
|
{
|
|
|
|
childSegments = childSegments.Slice(0, childSegments.Length - 1);
|
|
|
|
}
|
2021-12-19 23:13:30 +08:00
|
|
|
|
2022-06-28 16:10:06 +08:00
|
|
|
if (parentSegments.Length >= childSegments.Length)
|
|
|
|
return false;
|
2021-12-19 23:13:30 +08:00
|
|
|
|
2022-06-28 16:10:06 +08:00
|
|
|
return childSegments.Slice(0, parentSegments.Length).SequenceEqual(parentSegments);
|
2021-12-19 23:13:30 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|