Skip to content

Commit

Permalink
feat: fs模块添加更多函数
Browse files Browse the repository at this point in the history
fix: 异常重复上报
fix: Js定时器异常未捕获
fix: 在部分设备上无法更新硬件信息
fix: 启用Pty的服务器时可能无法启动
fix: 更新链接
fix: Plus版控制台报错
  • Loading branch information
Zaitonn committed Dec 18, 2024
1 parent b87acba commit e3d7088
Show file tree
Hide file tree
Showing 14 changed files with 188 additions and 48 deletions.
3 changes: 0 additions & 3 deletions src/Serein.Cli/Utils/CommandLineParserBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using System.CommandLine.Invocation;
using System.CommandLine.Parsing;
using System.Text;
using Sentry;
using Serein.Core.Utils;

namespace Serein.Cli.Utils;
Expand Down Expand Up @@ -34,8 +33,6 @@ public static Parser Build(Action mainMethod)

private static void OnException(Exception e, InvocationContext? context)
{
SentrySdk.CaptureException(e);

var fileName = CrashHelper.CreateLog(e);

Console.ForegroundColor = ConsoleColor.Red;
Expand Down
2 changes: 1 addition & 1 deletion src/Serein.Core/Models/Plugins/Js/JsPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ JsPluginConfig config
Info = pluginInfo;
FileName = fileName;
Config = config;
TimerFactory = new(_cancellationTokenSource.Token);
TimerFactory = new(Info.Name, _pluginLogger, _cancellationTokenSource.Token);
Console = new(_pluginLogger, Info.Name);
ScriptInstance = new(serviceProvider, this);
Engine = serviceProvider.GetRequiredService<JsEngineFactory>().Create(this);
Expand Down
40 changes: 37 additions & 3 deletions src/Serein.Core/Services/Commands/HardwareInfoProvider.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Timers;
using Hardware.Info;
Expand Down Expand Up @@ -42,6 +43,7 @@ public void Update()
}

lock (_lock)
{
try
{
_isLoading = true;
Expand All @@ -52,17 +54,49 @@ public void Update()
}
else
{
Info.RefreshAll();
Try(Info.RefreshBatteryList);
Try(Info.RefreshBIOSList);
Try(Info.RefreshComputerSystemList);
Try(() => Info.RefreshCPUList());
Try(Info.RefreshDriveList);
Try(Info.RefreshKeyboardList);
Try(Info.RefreshMemoryList);
Try(Info.RefreshMemoryStatus);
Try(Info.RefreshMonitorList);
Try(Info.RefreshMotherboardList);
Try(Info.RefreshMouseList);
Try(() => Info.RefreshNetworkAdapterList());
Try(Info.RefreshOperatingSystem);
Try(Info.RefreshPrinterList);
Try(Info.RefreshSoundDeviceList);
Try(Info.RefreshVideoControllerList);
}
}
catch (Exception e)
{
_logger.LogError("更新信息失败:{}", e.Message);
_logger.LogDebug(e, "更新信息失败");
_logger.LogError("初始化失败:{}", e.Message);
_logger.LogDebug(e, "初始化失败");
}
finally
{
_isLoading = false;
}
}

void Try(
Action action,
[CallerArgumentExpression(nameof(action))] string? expression = null
)
{
try
{
action();
}
catch (Exception e)
{
_logger.LogError("更新信息失败:{}({})", e.Message, expression);
_logger.LogDebug(e, "更新信息失败");
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,27 @@

namespace Serein.Core.Services.Plugins.Js.BuiltInModules;

#pragma warning disable CA1822

public static partial class FileSystem
{
internal static void DisposeAll()
{
foreach (var stream in FileStreams.Values)
{
stream.Close();
stream.Dispose();
}
FileStreams.Clear();
}

internal static readonly Dictionary<int, FileStream> FileStreams = [];

private static FileStream GetFileStream(int fd)
{
return !FileStreams.TryGetValue(fd, out var stream)
? throw new IOException("Invalid file descriptor")
: stream;
}

public static void AccessSync(string path, int mode = 0)
{
throw new NotSupportedException();
Expand Down Expand Up @@ -56,15 +73,18 @@ public static void ChownSync(string path, int uid, int gid)

public static void CloseSync(int fd)
{
throw new NotSupportedException();
var fileStream = GetFileStream(fd);
fileStream.Close();
fileStream.Dispose();
FileStreams.Remove(fd);
}

public static void CopyFileSync(string src, string dest, int flags = 0)
{
File.Copy(src, dest, flags != 1);
}

public static void Cp(string src, string dest, JsValue? options = default)
public static void CpSync(string src, string dest, JsValue? options = default)
{
throw new NotSupportedException();
}
Expand Down Expand Up @@ -96,17 +116,19 @@ public static void FstatSync(int fd, JsValue? options = default)

public static void FsyncSync(int fd)
{
throw new NotSupportedException();
GetFileStream(fd).Flush();
}

public static void FtruncateSync(int fd, int len)
public static void FtruncateSync(int fd, int len = 0)
{
throw new NotSupportedException();
GetFileStream(fd).SetLength(len);
}

public static void FutimesSync(int fd, int atime, int mtime)
public static void FutimesSync(int fd, DateTime atime, DateTime mtime)
{
throw new NotSupportedException();
var fileStream = GetFileStream(fd);
File.SetLastAccessTime(fileStream.Name, atime);
File.SetLastWriteTime(fileStream.Name, mtime);
}

public static string[] GlobSync(string pattern, JsValue? options = default)
Expand Down Expand Up @@ -211,7 +233,7 @@ public static void MkdirSync(
{
#pragma warning disable CA1416
Directory.CreateDirectory(path, (UnixFileMode)mode);
#pragma warning restore format
#pragma warning restore CA1416
}
}

Expand All @@ -227,9 +249,31 @@ public static void OpendirSync(string path, JsValue? options = default)
throw new NotSupportedException();
}

public static void OpenSync(string path, string flags, JsValue? mode = default)
public static int OpenSync(string path, string flags, JsValue? mode = default)
{
throw new NotSupportedException();
var fileStream = new FileStream(
path,
flags switch
{
"r" => FileMode.Open,
"r+" => FileMode.Open,
"rs" => FileMode.Open,
"rs+" => FileMode.Open,
"w" => FileMode.Create,
"wx" => FileMode.CreateNew,
"w+" => FileMode.OpenOrCreate,
"wx+" => FileMode.CreateNew,
"a" => FileMode.Append,
"ax" => FileMode.Append,
"a+" => FileMode.Append,
"ax+" => FileMode.Append,
_ => throw new ArgumentException("Invalid flags", nameof(flags)),
}
);

FileStreams.Add(FileStreams.GetHashCode(), fileStream);

return FileStreams.GetHashCode();
}

public static string ReadFileSync(string path, JsValue? options = default)
Expand All @@ -253,19 +297,21 @@ public static string ReadFileSync(string path, JsValue? options = default)
}
}

public static void ReaddirSync(string path, JsValue? options = default)
public static string[] ReaddirSync(string path, JsValue? options = default)
{
throw new NotSupportedException();
return Directory.GetFiles(path);
}

public static void ReadlinkSync(string path, JsValue? options = default)
{
throw new NotSupportedException();
}

public static void ReadSync(int fd, byte[] buffer, int offset, int length, int position)
public static int ReadSync(int fd, byte[] buffer, int offset, int length, int position = 0)
{
throw new NotSupportedException();
var fileStream = GetFileStream(fd);
fileStream.Seek(position, SeekOrigin.Begin);
return fileStream.Read(buffer, offset, length);
}

public static void RealpathSync(string path, JsValue? options = default)
Expand Down Expand Up @@ -344,6 +390,7 @@ public static void TruncateSync(string path, int len = 0)
{
using var file = File.Open(path, FileMode.Open);
file.SetLength(len);
file.Flush();
file.Close();
}

Expand Down Expand Up @@ -383,13 +430,37 @@ public static void WriteFileSync(string path, byte[] data, JsValue? options = de
file.Close();
}

public static void WriteSync(int fd, byte[] buffer)
public static int WriteSync(int fd, byte[] buffer)
{
throw new NotSupportedException();
return WriteSync(fd, buffer, 0, buffer.Length, 0);
}

public static void WriteSync(int fd, byte[] buffer, int offset, int length, int position)
public static int WriteSync(
int fd,
byte[] buffer,
int offset = 0,
int? length = null,
int position = 0
)
{
throw new NotSupportedException();
var l = length ?? (buffer.Length - offset);

var fileStream = GetFileStream(fd);
fileStream.Seek(position, SeekOrigin.Begin);
fileStream.Write(buffer, offset, l);
fileStream.Flush();

return l;
}

public static int WriteSync(int fd, string data, int position = 0, string encoding = "utf8")
{
var buffer = (
encoding.Equals("utf8", StringComparison.InvariantCultureIgnoreCase)
? EncodingMap.UTF8
: Encoding.GetEncoding(encoding)
).GetBytes(data);

return WriteSync(fd, buffer, 0, buffer.Length, position);
}
}
25 changes: 22 additions & 3 deletions src/Serein.Core/Services/Plugins/Js/TimerFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
using System.Threading;
using Jint.Native;
using Jint.Native.Function;
using Microsoft.Extensions.Logging;
using Serein.Core.Models.Output;
using Serein.Core.Utils.Extensions;
using Timer = System.Timers.Timer;

namespace Serein.Core.Services.Plugins.Js;
Expand All @@ -13,8 +16,14 @@ public sealed class TimerFactory
private long _intervalTimerId;
private readonly Dictionary<long, Timer> _timeoutTimers;
private readonly Dictionary<long, Timer> _intervalTimers;

internal TimerFactory(CancellationToken cancellationToken)
private readonly IPluginLogger _pluginLogger;
private readonly string _name;

internal TimerFactory(
string name,
IPluginLogger pluginLogger,
CancellationToken cancellationToken
)
{
_timeoutTimers = [];
_intervalTimers = [];
Expand All @@ -36,6 +45,8 @@ internal TimerFactory(CancellationToken cancellationToken)
_timeoutTimers.Clear();
_intervalTimers.Clear();
});
_pluginLogger = pluginLogger;
_name = name;
}

public long SetTimeout(JsValue jsValue, long milliseconds, params JsValue[] args)
Expand Down Expand Up @@ -92,7 +103,7 @@ public void ClearInterval(long id)
}
}

private static void SafeCall(Function function, params JsValue[] args)
private void SafeCall(Function function, params JsValue[] args)
{
var entered = false;

Expand All @@ -108,6 +119,14 @@ private static void SafeCall(Function function, params JsValue[] args)
throw new TimeoutException();
}
}
catch (Exception e)
{
_pluginLogger.Log(
LogLevel.Error,
_name,
$"An error occurred while calling the function: {e.GetDetailString()}"
);
}
finally
{
if (entered)
Expand Down
2 changes: 2 additions & 0 deletions src/Serein.Core/Services/Plugins/PluginManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using Serein.Core.Models.Plugins.Info;
using Serein.Core.Services.Permissions;
using Serein.Core.Services.Plugins.Js;
using Serein.Core.Services.Plugins.Js.BuiltInModules;
using Serein.Core.Services.Plugins.Net;
using Serein.Core.Services.Plugins.Storages;
using Serein.Core.Utils;
Expand Down Expand Up @@ -191,6 +192,7 @@ public void Unload()
{
_eventDispatcher.Dispatch(Event.PluginsUnloading);

FileSystem.DisposeAll();
_netPluginLoader.Unload();
_jsPluginLoader.Unload();
_sessionStorage.Clear();
Expand Down
16 changes: 11 additions & 5 deletions src/Serein.Core/Services/Servers/ServerBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -166,18 +166,24 @@ protected void OnServerOutput(string line)
return;
}

_cache.Add(filtered);

if (_cache.Count > 1)
{
_matcher.QueueServerOutputLine(Id, string.Join('\n', _cache));
}

if (
_settingProvider.Value.Application.PattenForEnableMatchingMuiltLines.Any(
!_settingProvider.Value.Application.PattenForEnableMatchingMuiltLines.Any(
filtered.Contains
)
)
{
_cache.Add(filtered);
_matcher.QueueServerOutputLine(Id, string.Join('\n', _cache));
_cache.Clear();
}
else
else if (_cache.Count > 100)
{
_cache.Clear();
_cache.RemoveRange(0, _cache.Count - 100);
}

_matcher.QueueServerOutputLine(Id, filtered);
Expand Down
Loading

0 comments on commit e3d7088

Please sign in to comment.