### Implement Plugins with IPlugin Source: https://context7.com/beyonddimension/steamtools/llms.txt The IPlugin interface is central to Watt Toolkit's plugin system, defining the lifecycle, configuration, and service injection for plugins. This example demonstrates implementing a plugin by overriding base class methods for unique identification, display name, description, icon, validation, menu item generation, configuration retrieval, dependency injection, AutoMapper configuration, initialization, command execution, and cleanup. ```csharp public sealed class MyPlugin : PluginBase, IPlugin { // Plugin unique identifier public override Guid Id => Guid.Parse("00000000-0000-0000-0000-000000000001"); // Plugin display name public override string Name => "我的插件"; // Unique English name public override string UniqueEnglishName => "MyPlugin"; // Plugin description public override string Description => "这是一个示例插件"; // Plugin icon public override object? Icon => null; // Validate if the plugin meets running requirements public bool HasValue(out string? error) { error = null; return true; // Return true to indicate it can be loaded } // Return menu item view models public override IEnumerable? GetMenuTabItems() { yield return new MenuTabItemViewModel(this, "MyPlugin") { PageType = typeof(MyPluginPage), IsResourceGet = true, IconKey = Icon, }; } // Get plugin configuration items public override IEnumerable<(Action? @delegate, bool isInvalid, string name)>? GetConfiguration(bool directoryExists) { yield return GetConfiguration(directoryExists); } // Configure on-demand dependency injection services public override void ConfigureDemandServices(IServiceCollection services, Startup startup) { if (startup.HasServerApiClient) { services.AddSingleton(); } } // Configure required dependency injection services public override void ConfigureRequiredServices(IServiceCollection services, Startup startup) { services.AddSingleton(s => s.GetRequiredService>().CurrentValue); } // Configure AutoMapper mapping public override void OnAddAutoMapper(IMapperConfigurationExpression cfg) { cfg.CreateMap(); } // Plugin initialization public override async ValueTask OnInitializeAsync() { IViewModelManager.Instance.Get(); await ValueTask.CompletedTask; } // Handle command line arguments public override async ValueTask OnCommandRun(params string[] commandParams) { if (commandParams.Length >= 1) { var action = commandParams[0]; // Handle command... } await ValueTask.CompletedTask; } // Cleanup when the plugin exits public override async ValueTask OnExit() { // Clean up resources... await ValueTask.CompletedTask; } } ``` -------------------------------- ### Manage Application Lifecycle with IApplication Source: https://context7.com/beyonddimension/steamtools/llms.txt Demonstrates how to access the application singleton, check platform compatibility, manage system-level settings like auto-start, and interact with browser and screen utilities. ```csharp IApplication app = IApplication.Instance; if (IApplication.IsDesktop()) { Console.WriteLine("运行在桌面平台"); } ClientPlatform platform = IApplication.ClientPlatform; object uiHost = app.CurrentPlatformUIHost; IApplication.SetBootAutoStart(true); app.OpenBrowserCommandCore("https://steampp.net"); System.Drawing.Size? screenSize = app.GetScreenSize(); DeploymentMode mode = app.DeploymentMode; ``` -------------------------------- ### Avalonia Application Lifecycle and Commands - App (C#) Source: https://context7.com/beyonddimension/steamtools/llms.txt Illustrates the structure and functionality of the Avalonia `App` class, serving as the application's entry point. It covers initialization, window management, Steamworks integration, application shutdown, transparency settings, and the use of global commands for actions like opening browsers or copying to the clipboard. It also shows how to access default fonts and customize main window initialization. ```csharp // 在 App.axaml.cs 中 public partial class App : Application { // 获取当前主窗口 public Window? MainWindow { get; internal set; } // 初始化应用 public override void Initialize() { AvaloniaXamlLoader.Load(this); // 初始化 Steamworks(如果从 Steam 启动) if (Startup.Instance.IsSteamRun) { Steamworks.SteamClient.Init(2425030); // Watt Toolkit 的 Steam AppId } } public override void OnFrameworkInitializationCompleted() { if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { // 创建主窗口 MainWindow = new MainWindow(); desktop.MainWindow = MainWindow; } base.OnFrameworkInitializationCompleted(); } } // 获取 App 实例 if (Application.Current is App app) { // 获取第一个可用窗口 Window? window = app.GetFirstOrDefaultWindow(); // 关闭应用 app.Shutdown(exitCode: 0); // 设置窗口透明材质 app.SetAllWindowransparencyMateria(WindowBackgroundMaterial.Mica); // 初始化设置订阅 app.InitSettingSubscribe(); } // 使用全局命令 ICommand openBrowserCmd = ((App)Application.Current!).OpenBrowserCommand; openBrowserCmd.Execute("https://steampp.net"); ICommand copyCmd = ((App)Application.Current!).CopyToClipboardCommand; copyCmd.Execute("要复制的文本"); // 默认字体 FontFamily defaultFont = App.DefaultFontFamily; Console.WriteLine($"默认字体名: {App.DefaultFontFamilyName}"); // 输出: avares://BD.WTTS.Client.Avalonia/UI/Assets/Fonts/HarmonyOS_Sans_SC_Regular.ttf#HarmonyOS Sans SC // 自定义主窗口初始化 App.InitializeMainWindow += (sender) => { // 返回自定义窗口 return new CustomMainWindow(); }; ``` -------------------------------- ### Configure Network Acceleration with ProxyService Source: https://context7.com/beyonddimension/steamtools/llms.txt Shows how to initialize the proxy service, toggle acceleration, manage proxy domains and scripts, and perform network environment repairs. ```csharp ProxyService proxyService = ProxyService.Current; await proxyService.InitializeAsync(); await proxyService.StartOrStopProxyService(true); proxyService.IsEnableScript = true; proxyService.FixNetwork(); await proxyService.RefreshScript(); await ProxyService.OnExitRestoreHosts(); await proxyService.DisposeAsync(); ``` -------------------------------- ### Platform Service Operations - IPlatformService (C#) Source: https://context7.com/beyonddimension/steamtools/llms.txt Demonstrates various system and platform-related operations using the IPlatformService interface. This includes setting startup behavior, managing system proxies, controlling system power states, checking administrator privileges, performing file operations, managing processes, and interacting with hosts files. It also shows how to obtain an elevated IPC service for operations requiring administrator rights. ```csharp // 获取平台服务实例 IPlatformService platformService = IPlatformService.Instance; // 设置开机自启动 platformService.SetBootAutoStart(true, "Watt Toolkit"); // 系统代理设置(Windows) await platformService.SetAsSystemProxyAsync(true); await platformService.SetAsSystemPACProxyAsync(true); // 系统电源管理 platformService.SystemSleep(); // 系统休眠 platformService.SystemHibernate(); // 系统待机 platformService.SystemShutdown(); // 系统关机 // 检查是否以管理员权限运行 bool isAdmin = platformService.IsAdministrator; // 获取机器唯一标识符 string machineId = platformService.MachineUniqueIdentifier; // 文件/文件夹操作 platformService.OpenFolder("/path/to/folder"); platformService.OpenFileByTextReader("/path/to/file.txt"); // 获取系统字体列表 IEnumerable fonts = platformService.GetFontFamilies(); // 进程管理 platformService.StartProcess("/path/to/app.exe", arguments: "--arg1 value1"); platformService.KillProcess(processId: 1234); // 获取 IPC 管理员权限服务(用于需要提权的操作) IPCPlatformService adminService = await IPlatformService.IPCRoot.Instance; // 使用管理员权限执行文件操作 await adminService.CopyFileAsync("/source/path", "/dest/path"); await adminService.DeleteFileAsync("/path/to/file"); // Hosts 文件操作 await platformService.WriteHostsFileAsync(new[] { new HostsRecord("127.0.0.1", "example.com"), new HostsRecord("127.0.0.1", "test.example.com") }); // 获取默认字体 string defaultFont = platformService.GetDefaultFontFamily(); // 系统会话结束回调 platformService.SetSystemSessionEnding(() => { Console.WriteLine("系统即将关闭,执行清理操作..."); }); ``` -------------------------------- ### IPlatformService - Platform Services API Source: https://context7.com/beyonddimension/steamtools/llms.txt Provides system-level operations such as boot startup, proxy settings, process management, file operations, and power management. ```APIDOC ## IPlatformService - Platform Services API ### Description Provides system-level operations including boot startup, system proxy configuration, process management, file operations, and system power management. ### Method Various (Instance access, static methods, instance methods) ### Endpoint N/A (This is a service interface, not a REST endpoint) ### Parameters N/A for interface access. Methods have specific parameters as shown in examples. ### Request Example ```csharp // Get platform service instance IPlatformService platformService = IPlatformService.Instance; // Set boot auto-start platformService.SetBootAutoStart(true, "Watt Toolkit"); // Set as system proxy (Windows) await platformService.SetAsSystemProxyAsync(true); // System sleep platformService.SystemSleep(); // Check administrator privileges bool isAdmin = platformService.IsAdministrator; // Get machine unique identifier string machineId = platformService.MachineUniqueIdentifier; // Open a folder platformService.OpenFolder("/path/to/folder"); // Get system font list IEnumerable fonts = platformService.GetFontFamilies(); // Start a process platformService.StartProcess("/path/to/app.exe", arguments: "--arg1 value1"); // Kill a process platformService.KillProcess(processId: 1234); // Get IPC administrator service IPCPlatformService adminService = await IPlatformService.IPCRoot.Instance; // Copy a file with admin privileges await adminService.CopyFileAsync("/source/path", "/dest/path"); // Write to hosts file await platformService.WriteHostsFileAsync(new[] { new HostsRecord("127.0.0.1", "example.com") }); // Set system session ending callback platformService.SetSystemSessionEnding(() => { Console.WriteLine("System is shutting down, performing cleanup..."); }); ``` ### Response N/A (Methods return values or perform actions directly) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### 使用 IUserManager 管理用户身份 Source: https://context7.com/beyonddimension/steamtools/llms.txt 展示如何通过 IUserManager 获取当前登录用户、更新用户信息、处理登录状态以及监听用户登出事件。该服务支持同步与异步操作,并提供手机号脱敏处理功能。 ```csharp IUserManager userManager = IUserManager.Instance; CurrentUser? currentUser = userManager.GetCurrentUser(); CurrentUser? user = await userManager.GetCurrentUserAsync(); if (user != null) { Console.WriteLine($"用户ID: {user.UserId}"); } await userManager.SetCurrentUserAsync(null); userManager.OnSignOut += () => { Console.WriteLine("用户已登出"); }; ``` -------------------------------- ### 使用 IAccountPlatformAuthenticatorRepository 管理令牌 Source: https://context7.com/beyonddimension/steamtools/llms.txt 演示如何通过 IAccountPlatformAuthenticatorRepository 进行令牌的本地加密存储、导入导出、重命名及排序操作。支持处理 TOTP/HOTP 令牌,并提供基于二级密码的安全验证机制。 ```csharp var repository = Ioc.Get(); AccountPlatformAuthenticator[] sources = await repository.GetAllSourceAsync(); string? secondaryPassword = "your_password"; List authenticators = await repository.ConvertToListAsync(sources, secondaryPassword); var (isSuccess, isUpdate) = await repository.InsertOrUpdateAsync(newAuth, true, secondaryPassword); byte[] exportData = await repository.ExportAsync(true, secondaryPassword, authenticators); var (resultCode, result, sourcesCount) = await repository.ImportAsync(secondaryPassword, importData); ``` -------------------------------- ### Interact with Steam Services via SteamConnectService Source: https://context7.com/beyonddimension/steamtools/llms.txt Provides methods to initialize the Steam connection, monitor running processes, retrieve user account information, and manage game lists and download status. ```csharp SteamConnectService steamService = SteamConnectService.Current; steamService.Initialize(); if (steamService.IsRunningSteamProcess) { Console.WriteLine("Steam 正在运行"); } if (steamService.IsConnectToSteam) { SteamUser? currentUser = steamService.CurrentSteamUser; Console.WriteLine($"当前用户: {currentUser?.SteamNickName}"); } await steamService.RefreshGamesListAsync(); steamService.WatchDownloadingSteamAppIds.Add(730); steamService.DisposeSteamClient(); ``` -------------------------------- ### IPlugin System Source: https://context7.com/beyonddimension/steamtools/llms.txt The IPlugin interface defines the structure, lifecycle, and dependency injection requirements for plugins in the Watt Toolkit. ```APIDOC ## IPlugin Interface ### Description Defines the core contract for plugins, including metadata, service configuration, and lifecycle hooks like initialization and cleanup. ### Method Interface Implementation ### Key Properties - **Id** (Guid) - Required - Unique identifier for the plugin. - **Name** (string) - Required - Display name of the plugin. - **UniqueEnglishName** (string) - Required - Unique identifier for internal referencing. ### Lifecycle Methods - **OnInitializeAsync()** - Called when the plugin is loaded. - **OnExit()** - Called when the plugin is unloaded or the application exits. - **ConfigureRequiredServices()** - Used to inject necessary dependencies into the service container. ### Response Example public sealed class MyPlugin : PluginBase, IPlugin { ... } ``` -------------------------------- ### Serialize WinDivert Resources to MPO Source: https://github.com/beyonddimension/steamtools/blob/develop/ref/WinDivert.mpo.txt Reads WinDivert binary files from the project reference directory, serializes them into a byte array using MemoryPack, and performs a byte reversal before saving to disk. This is typically used to obfuscate or package dependencies for the application. ```csharp static void WinDivert() { var dllWinDivert = Path.Combine(ProjectUtils.ProjPath, "ref", "WinDivert.dll"); var sysWinDivert64 = Path.Combine(ProjectUtils.ProjPath, "ref", "WinDivert64.sys"); byte[][] data = [File.ReadAllBytes(dllWinDivert), File.ReadAllBytes(sysWinDivert64)]; var bytes = MemoryPackSerializer.Serialize(data); bytes.AsSpan().Reverse(); File.WriteAllBytes(Path.Combine(ProjectUtils.ProjPath, "ref", "WinDivert.mpo"), bytes); } ``` -------------------------------- ### IAccountPlatformAuthenticatorRepository Source: https://context7.com/beyonddimension/steamtools/llms.txt Handles local storage, management, encryption, and import/export of game platform authentication tokens. ```APIDOC ## IAccountPlatformAuthenticatorRepository ### Description Provides functionality to manage TOTP/HOTP/Steam Guard tokens with support for secondary password encryption. ### Method N/A (Repository Interface) ### Parameters #### Request Body - **IAuthenticatorDTO** (object) - Required - Authenticator data including Name, Platform, and current token code. - **secondaryPassword** (string) - Optional - Password for encrypted storage access. ### Response #### Success Response (200) - **isSuccess** (boolean) - Indicates if the operation was successful. - **result** (list) - List of imported or converted authenticators. ### Response Example { "isSuccess": true, "isUpdate": false } ``` -------------------------------- ### App Class - Avalonia Application Source: https://context7.com/beyonddimension/steamtools/llms.txt Manages the Avalonia UI application lifecycle, including window management, theme settings, and global commands. ```APIDOC ## Avalonia Application - App ### Description The `App` class serves as the entry point for Avalonia UI applications, managing window lifecycles, theme settings, and global commands. It also handles initialization for Steamworks if the application is launched via Steam. ### Method Various (Instance access, static properties, instance methods) ### Endpoint N/A (This is an application class, not a REST endpoint) ### Parameters N/A for class access. Methods and properties have specific usage as shown in examples. ### Request Example ```csharp // In App.axaml.cs public partial class App : Application { public Window? MainWindow { get; internal set; } public override void Initialize() { AvaloniaXamlLoader.Load(this); if (Startup.Instance.IsSteamRun) { Steamworks.SteamClient.Init(2425030); // Watt Toolkit's Steam AppId } } public override void OnFrameworkInitializationCompleted() { if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { MainWindow = new MainWindow(); desktop.MainWindow = MainWindow; } base.OnFrameworkInitializationCompleted(); } } // Accessing App instance and methods if (Application.Current is App app) { // Get the first available window Window? window = app.GetFirstOrDefaultWindow(); // Shutdown the application app.Shutdown(exitCode: 0); // Set window transparency material app.SetAllWindowransparencyMateria(WindowBackgroundMaterial.Mica); // Initialize setting subscriptions app.InitSettingSubscribe(); } // Using global commands ICommand openBrowserCmd = ((App)Application.Current!).OpenBrowserCommand; openBrowserCmd.Execute("https://steampp.net"); ICommand copyCmd = ((App)Application.Current!).CopyToClipboardCommand; copyCmd.Execute("Text to copy"); // Default font FontFamily defaultFont = App.DefaultFontFamily; Console.WriteLine($"Default font name: {App.DefaultFontFamilyName}"); // Custom main window initialization App.InitializeMainWindow += (sender) => { return new CustomMainWindow(); }; ``` ### Response N/A (Methods return values or perform actions directly) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### IUserManager Service Source: https://context7.com/beyonddimension/steamtools/llms.txt Provides user identity management, including login state, profile retrieval, and user data persistence. ```APIDOC ## IUserManager ### Description Manages user authentication, profile information, and login sessions. ### Method N/A (Service Interface) ### Endpoint IUserManager.Instance ### Parameters #### Request Body - **CurrentUser** (object) - Required - User profile data including UserId, NickName, and PhoneNumber. ### Response #### Success Response (200) - **IdentityUserInfoDTO** (object) - Detailed user profile information. ### Response Example { "UserId": "guid", "NickName": "TestUser", "PhoneNumber": "13800138000" } ``` -------------------------------- ### Manage Scripts with IScriptManager Source: https://context7.com/beyonddimension/steamtools/llms.txt The IScriptManager interface provides comprehensive functionality for managing JavaScript scripts, including adding, deleting, downloading, compiling, and managing their status. It supports reading script files, adding new scripts with various options, saving script content, downloading scripts from URLs, deleting scripts, compiling them, loading their content, saving their enabled state, and checking file validity. ```csharp IScriptManager scriptManager = IScriptManager.Instance; // Get all scripts IEnumerable allScripts = await scriptManager.GetAllScriptAsync(); // Read script file and parse into DTO ScriptDTO? scriptInfo = await scriptManager.ReadScriptAsync("/path/to/script.js"); // Add new script IApiRsp result = await scriptManager.AddScriptAsync( path: "/path/to/script.js", oldInfo: null, // Pass old script info if updating isCompile: true, // Compile or not order: 10, // Sort order deleteFile: false, // Delete source file after adding pid: null, // Parent script ID ignoreCache: false // Ignore cache or not ); if (result.IsSuccess && result.Content != null) { Console.WriteLine($"Script added successfully: {result.Content.Name}"); } // Save script FileInfo fileInfo = new FileInfo("/path/to/script.js"); IApiRsp saveResult = await scriptManager.SaveScriptAsync( path: fileInfo, info: scriptInfo, oldInfo: null, isCompile: true, order: 10 ); // Download script IApiRsp downloadResult = await scriptManager.DownloadScriptAsync( "https://example.com/script.user.js" ); if (downloadResult.IsSuccess) { Console.WriteLine($"Script downloaded to: {downloadResult.Content}"); } // Delete script ScriptDTO scriptToDelete = allScripts.First(); IApiRsp deleteResult = await scriptManager.DeleteScriptAsync(scriptToDelete); // Compile script bool buildSuccess = await scriptManager.BuildScriptAsync( model: scriptInfo!, fileInfo: fileInfo, build: true ); // Load script content IEnumerable? scriptsWithContent = await scriptManager.LoadingScriptContentAsync(allScripts); // Save script enabled state await scriptManager.SaveEnableScriptAsync(scriptInfo!); // Check if script file exists IEnumerable validScripts = await scriptManager.CheckFiles(allScripts); ``` -------------------------------- ### IScriptManager API Source: https://context7.com/beyonddimension/steamtools/llms.txt The IScriptManager interface provides methods to manage, compile, download, and persist JavaScript scripts. ```APIDOC ## IScriptManager API ### Description Provides functionality to manage the lifecycle of JavaScript scripts, including adding, deleting, compiling, and loading script content. ### Method Async Methods ### Parameters - **path** (string) - Required - File path to the script. - **isCompile** (bool) - Optional - Whether to compile the script upon addition. - **order** (int) - Optional - Sorting priority of the script. ### Request Example await scriptManager.AddScriptAsync(path: "/path/to/script.js", isCompile: true, order: 10); ### Response #### Success Response (200) - **IApiRsp** - Returns the result containing the script DTO if successful. #### Response Example { "IsSuccess": true, "Content": { "Name": "ExampleScript", "Id": 1 } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.