Files
v2rayN/v2rayN/v2rayN.WebAPI/Services/V2rayRuntime.Profiles.cs
T
Nozilla-X 66dd7da6e6 feat(web): 添加无头 WebAPI 支持 (#10300)
* feat(web): add headless ServiceLib API and replaceable UI host

* build(web): package API without bundled WebUI

* ci(web): build and test headless API packages

* docs(web): document the headless API and optional WebUI

* test(web): verify restore and build before API tests

* docs(web): align API release examples with current upstream

* test(web): cover creating and editing an empty-URL subscription group

Verify the API accepts and persists a subscription whose Url and MoreUrl stay empty, that an edit keeps the empty URL and zero interval, and that ServiceLib is untouched.

* fix(web): support per-target prerelease update preferences

* fix(web): require management key for non-loopback listeners

* ci: reduce development Web API build matrix

* fix(web): make native self-update rollback atomic and preserve progress

* docs(web): remove self-update E2E report

* ci(web): decouple Web releases from Linux Desktop

* feat(web): support standalone WebUI clients and rename the API to v2rayN.WebAPI

- Resolve every REST, login, setup, download, SSE-ticket and EventSource
  request through one configurable Backend base per WebUI origin, with a
  strict exact-match origin allowlist and no wildcard or credential CORS.
- Run the origin guard before authentication, and keep first-run setup,
  instance diagnostics and the hosted-UI CSP same-origin as before.
- Rename the project directory, csproj, namespace, executable, lock,
  build identity and self-update target to v2rayN.WebAPI while retaining
  V2RAYN_WEB_* settings, WebVersion metadata, webVersion fields and the
  existing release asset contracts.
- Migrate API-owned update preference identifiers and reject legacy
  v2rayN.Web update packages with a manual reinstall instruction.
- Require staged native executables to be Linux ELF images for their RID.
- Add CORS, update-identity and setup-security tests, and record the
  standalone-WebUI audit under v2rayN.WebAPI/STANDALONE-WEBUI-AUDIT.md.

* Remove WebUI hosting and configuration coupling from WebAPI

* Finish WebAPI cleanup and isolate native self-update worker

* Keep WebAPI client documentation implementation-neutral

* ci(webapi): verify Windows win-x64 build and startup

* fix(webapi): validate keys and unify loopback limits

* test(webapi): isolate update smoke from systemd runner

* feat(webapi): add Windows x64 release and self-update

* fix(webapi): verify release manifest version

* ci(webapi): publish web packages through the official release flow

* ci(webapi): run the web release inside the release-all workflow

* webapi: finish the rename and fix shutdown, terminal launch and help

- finish the Web -> WebAPI product rename: workflow files build-WebAPI.yml /
  release-WebAPI.yml (path filters, reusable call sites, container tag),
  solution entry, health headers X-v2rayn-WebAPI-*, WebAPI.self-update
  capability, WebAPI-update-progress.json / WebAPI-update-runtime-state.json,
  WebAPIData/WebAPI-auth.json with a migration from the legacy locations,
  and the README compatibility notes
- end /api/events when the host starts stopping so Kestrel's graceful stop
  cannot pin the whole shutdown budget with a client attached; a runtime
  cleanup that starts after the host budget was exhausted now runs a reduced
  fresh pass instead of skipping Core stop and shared-state saves entirely
- record the interactive launch context for detached children and helpers so
  systemd markers leaked into a terminal (INVOCATION_ID / JOURNAL_STREAM) no
  longer force foreground mode or misfire the supervised-deployment key check,
  self-update gating and lifecycle decisions
- add --help / -h with the options and common environment variables in all
  three launcher locales, and keep help flags out of the host arguments

* fix(webapi): retry transient file replacements during native updates

Windows antivirus and the search indexer can hold a freshly written
executable open for a moment, so replacing the installed executable or its
build identity could fail with a bare access-denied error and abort the
update or its rollback. Retry these replacements for a bounded window and
report the operation, target path and cause when they still fail.

* ci(webapi): display the release-all Web job as release-WebAPI

The reusable-workflow job key still used the pre-rename name, which is the
label the Actions UI shows for the nested Web release jobs.

* feat(webapi): add win-arm64, linux-riscv64 and linux-loongarch64 coverage

- build, package, sign and self-update support for the three architectures:
  win-arm64 (windows-11-arm native startup smoke), linux-riscv64 (RISE RISC-V
  runners with the community xujiegb/dotnet-riscv SDK; single-file publishing
  verified on real hardware) and linux-loongarch64 (the upstream QEMU loong64
  VM with the official Loongson SDK, smoke-tested inside the VM)
- per-RID native executable validation: ELF machines x86-64/AArch64/RISC-V
  (0xF3)/LoongArch (0x102) and Windows PE AMD64/ARM64 (0xAA64), behind a
  single IsSupportedRid gate
- release asset map and packager/manifest tables extended; the riscv64 and
  loongarch64 Core bundles ship without the cronet payload
- release manifests now ignore unknown RID entries so a newer manifest cannot
  be rejected wholesale by an older build

* fix(webapi): keep the loongarch64 QEMU smoke out of the packaged publish tree

The in-VM smoke ran the app inside the virtiofs-shared publish directory and
left runtime files owned by the VM root (v2rayN.WebAPI.instance.lock) that the
host runner could not read, so packaging failed with EACCES. The smoke now runs
in a VM-local copy, and a host-side guard verifies the shared tree is complete
and readable before packaging.

* docs(webapi): document the six-platform release matrix

Releases now cover linux-x64/arm64/riscv64/loongarch64 and win-x64/arm64;
note the per-RID machine validation and the forward-compatible manifest
behavior in the API release documentation.

* ci(webapi): keep the release-all desktop dispatch exactly upstream

build-all.yml dispatches the desktop workflows with "ref": "master" exactly
as upstream does. The fork-only github.ref_name change is reverted so the PR
leaves the existing release behavior untouched; the WebAPI release stays an
additive reusable job in the same workflow.

* fix(webapi): probe the effective listener and refuse unverifiable updates

GetCurrentHealthUri and GetLauncherUris forced every probe to 127.0.0.1 and
fell back to port 5080, so IPv6-only, wildcard and port-only listeners could
be checked at the wrong endpoint. The detached update helper then either
rolled back a healthy replacement or restarted without being able to verify
the old instance, and --stop could probe the wrong process.

Both callers now resolve the probe through one WebProbeUriResolver that uses
the same effective Kestrel configuration as the host (command line, urls,
http/https ports, Kestrel endpoints, preferHostingUrls) and maps each
listener to its matching loopback address: "*", "+" and host names probe
localhost, 0.0.0.0 probes 127.0.0.1, [::] probes [::1], and loopback
literals keep their family. When no loopback HTTP probe exists (HTTPS-only
or an explicit non-loopback address), GetWebUpdateTarget reports
canInstall=false with maintenance.webUpdateProbeUnavailable and the update
is refused before anything is stopped; the helper still accepts only
loopback HTTP plan URIs, now including [::1]. --stop reports the new
stopUnprobeable result instead of signalling an unverified owner, and the
background launcher fails closed with startUnprobeable.

Regression: new resolver/listener tests (default, custom port, IPv6-only,
HTTP_PORTS, Kestrel override, HTTPS-only) and the real update fixture now
covers an IPv6-only replacement, asserts that a failed update leaves the old
build running (replacement PID), and proves that an unprobeable instance
refuses both the API and --stop while staying up.

* ci(webapi): capture the real smoke PID and bound the SIGTERM waits

The riscv64 smoke backgrounded "cd && app" and recorded the subshell PID,
so the later kill could target the wrapper while the app kept running. Both
the riscv64 and loong64 smokes now start the app directly, record the
application PID, fail fast when the process exits before health, wait a
bounded time for SIGTERM before printing the log and force-killing, and
assert a zero exit status. The loong64 VM smoke replaces its fixed
two-second sleep with the same exit assertion.

* chore(webapi): drop unreferenced legacy scripts

bootstrap-xray.sh installed the removed bundled core-bin layout, and
test-backup-fixtures.py compared desktop/Web backup ZIPs from before the
WebUI decoupling; nothing references either script.

* fix(webapi): unify the loopback probe, diagnostics and helper rules

The resolver rewrote a configured localhost to 127.0.0.1 while the health
diagnostics and the update helper each carried their own copy of the
accepted-host rule. Keep localhost as localhost (resolving it covers both
families instead of forcing one IPv4 literal) and make
WebProbeUriResolver.IsProbeableLoopbackUri the single rule: plain HTTP to a
host the diagnostics accept as local (localhost, 127.0.0.1 or ::1). The
helper validates plans with that rule, the health endpoint uses the shared
WebSetupAccessPolicy.IsLocalDiagnosticSource predicate, and every probe URI
the resolver produces satisfies the rule. Unprobeable listeners
(HTTPS-only or an explicit non-loopback address) still refuse the
self-update up front: canInstall=false with
maintenance.webUpdateProbeUnavailable while the current instance keeps
running.

Regression: localhost stays localhost across the resolver and launcher
tests, the probe-rule invariant, the shared diagnostics/probe address
rule, a direct unit test of the refusal reason, and a real
localhost-listener replacement scenario in the update fixture.

* fix(webapi): gate generated probes through the shared loopback rule

MapToLoopbackHost accepted every address the OS reports as loopback, which in
.NET is the whole 127.0.0.0/8 range, and TryCreateHealthUri returned true
without checking the generated URI against the same rule the diagnostics and
the update helper use. A listener on 127.0.0.2 therefore passed the up-front
canInstall check, but the helper rejected its plan (and refused to restart
the previous build for the same reason), so an update could stop the service
without bringing anything back.

TryCreateHealthUri now gates the constructed probe through
IsProbeableLoopbackUri, so loopback aliases are refused before the instance
is stopped and a mixed listener list falls through to the next verifiable
endpoint.

Regression: 127.0.0.2/127.255.255.254 mapping rows, a dedicated
loopback-alias rejection test, the alias canInstall=false reason case, the
mixed-list fall-through, and a real 127.0.0.2-listener fixture scenario that
proves the update is refused while the current instance keeps running.

* refactor(webapi): centralize integration tests and simplify release scripts

Move the Linux integration tests (startup security, release packaging
dry-run, full-ZIP runtime, native update regression and its fixture) from
Scripts/ into Tests/Integration/; Scripts/verify.sh stays the unified entry
and all path resolution, workflow calls, README text and cross-script
invocations were updated. No test coverage changes.

Merge Test-Windows.ps1 and Test-WindowsUpdate.ps1 into one
Tests/Integration/Test-Windows.ps1 with -Mode startup|update: both modes
share the native process control (CREATE_NEW_PROCESS_GROUP + CTRL_BREAK),
environment isolation, free-port selection, no-proxy health waiting, JSON
fixtures and retained-on-failure cleanup. CI keeps the Windows x64/ARM64
startup smokes and the x64 replacement/rollback smoke.

Delete the package-native.sh thin wrapper; the workflow and the packaging
dry-run now call web-release-assets.py package directly with the same
--rid/--publish/--dist arguments, so asset names and ZIP boundaries stay
unchanged.

* test(webapi): keep the Windows health-body assertion in the merged smoke

The merged Wait-TestHealth only accepted HTTP 200 in startup mode, while
the original startup smoke parsed the health JSON and required
status == "ok". Restore the body assertion in the shared helper so both
modes verify the health payload instead of trusting the status code alone.

* fix(webapi): preflight and verify native backup restores

* test(webapi): isolate restore preflight smoke from systemd

* test(webapi): set Windows smoke autostart default

* test(webapi): retry transient Windows smoke cleanup

* test(webapi): retry Windows smoke temp cleanup longer

* ci(webapi): check whitespace on workflow dispatch
2026-10-20 10:52:23 +08:00

573 lines
25 KiB
C#

using ServiceLib;
using ServiceLib.Common;
using ServiceLib.Enums;
using ServiceLib.Handler;
using ServiceLib.Handler.Builder;
using ServiceLib.Handler.Fmt;
using ServiceLib.Manager;
using ServiceLib.Models.Dto;
using ServiceLib.Models.Entities;
using ServiceLib.Services;
using v2rayN.WebAPI.Contracts;
namespace v2rayN.WebAPI.Services;
public sealed partial class V2rayRuntime
{
public async Task<IReadOnlyList<ProfileGroupView>> GetProfileGroupsAsync()
{
var subscriptions = await AppManager.Instance.SubItems() ?? [];
var profiles = await AppManager.Instance.ProfileItems(string.Empty) ?? [];
var counts = profiles.GroupBy(item => item.Subid).ToDictionary(group => group.Key, group => group.Count());
var groups = new List<ProfileGroupView>
{
new(string.Empty, "all", null, ApiMessageKeys.ProfilesAllGroup, profiles.Count, string.IsNullOrEmpty(Config.SubIndexId)),
};
groups.AddRange(subscriptions.Select(item => new ProfileGroupView(
item.Id,
"subscription",
item.Remarks,
null,
counts.GetValueOrDefault(item.Id),
item.Id == Config.SubIndexId)));
return groups;
}
public async Task<OperationView> SelectProfileGroupAsync(string? subscriptionId)
{
if (!string.IsNullOrWhiteSpace(subscriptionId)
&& await AppManager.Instance.GetSubItem(subscriptionId) is null)
{
return OperationView.Fail("subscription_not_found", ApiMessageKeys.SubscriptionNotFound);
}
await _mutations.RunAsync(async () =>
{
Config.SubIndexId = subscriptionId ?? string.Empty;
await EnsureConfigSaveSucceededAsync(() => ConfigHandler.SaveConfig(Config));
});
_events.Publish("profiles-changed", new { subscriptionId = Config.SubIndexId });
return OperationView.Ok(ApiMessageKeys.CommonCompleted, new { subscriptionId = Config.SubIndexId });
}
public async Task<OperationView> ImportProfilesAsync(ProfileImportRequest request)
{
if (string.IsNullOrWhiteSpace(request.Content))
{
return OperationView.Fail("profile_content_required", ApiMessageKeys.CommonInvalidInput, new { imported = 0 });
}
var groupId = request.SubscriptionId ?? Config.SubIndexId ?? string.Empty;
if (!string.IsNullOrEmpty(groupId) && await AppManager.Instance.GetSubItem(groupId) is null)
{
return OperationView.Fail("subscription_not_found", ApiMessageKeys.SubscriptionNotFound, new { imported = 0 });
}
var count = await _mutations.RunAsync(async () =>
{
var imported = await ConfigHandler.AddBatchServers(Config, request.Content, groupId, request.IsSubscription);
if (imported > 0)
{
await EnsureConfigSaveSucceededAsync(() => ConfigHandler.SaveConfig(Config));
}
return imported;
});
if (count <= 0)
{
return OperationView.Fail("profile_import_empty", ApiMessageKeys.ProfileInvalid, new { imported = Math.Max(count, 0) });
}
_events.Publish("profiles-changed", new { subscriptionId = groupId });
AddLog("profile", $"Imported {count} profile(s).");
return OperationView.Ok(ApiMessageKeys.ProfileImported, new { imported = count });
}
public async Task<OperationView> SaveProfileAsync(ProfileItem profile, string? profileId = null)
{
if (profile is null)
{
return OperationView.Fail("profile_data_required", ApiMessageKeys.CommonInvalidInput);
}
var isNew = string.IsNullOrWhiteSpace(profileId);
if (!isNew)
{
var existing = await AppManager.Instance.GetProfileItem(profileId!);
if (existing is null)
{
return OperationView.Fail("profile_not_found", ApiMessageKeys.ProfileNotFound);
}
if (!IsConfigTypeUnchanged(profile, existing))
{
return OperationView.Fail("profile_config_type_immutable", ApiMessageKeys.ProfileInvalid);
}
profile.IndexId = profileId!;
profile.Subid = existing.Subid;
profile.IsSub = existing.IsSub;
}
else
{
profile.IndexId = string.Empty;
profile.Subid = Config.SubIndexId ?? string.Empty;
profile.IsSub = false;
if (!string.IsNullOrEmpty(profile.Subid)
&& await AppManager.Instance.GetSubItem(profile.Subid) is null)
{
AddLog("profile", $"Rejected profile creation for missing subscription group {profile.Subid}.");
return OperationView.Fail("subscription_not_found", ApiMessageKeys.SubscriptionNotFound,
new { subscriptionId = profile.Subid });
}
}
if (profile.ConfigType.IsGroupType())
{
profile.CoreType ??= ECoreType.Xray;
var protocolExtra = profile.GetProtocolExtra();
var childIds = Utils.String2List(protocolExtra.ChildItems) ?? [];
if (string.IsNullOrWhiteSpace(profile.Remarks)
|| (childIds.Count == 0 && string.IsNullOrWhiteSpace(protocolExtra.SubChildItems))
|| profile.CoreType is not (ECoreType.Xray or ECoreType.sing_box))
{
return OperationView.Fail("profile_group_invalid", ApiMessageKeys.ProfileInvalid);
}
if (!string.IsNullOrWhiteSpace(protocolExtra.SubChildItems)
&& await AppManager.Instance.GetSubItem(protocolExtra.SubChildItems) is null)
{
return OperationView.Fail("subscription_not_found", ApiMessageKeys.SubscriptionNotFound);
}
var children = await AppManager.Instance.GetProfileItemsByIndexIds(childIds);
if (children.Count != childIds.Distinct(StringComparer.Ordinal).Count()
|| await GroupProfileManager.HasCycle(profile))
{
return OperationView.Fail("profile_group_children_invalid", ApiMessageKeys.ProfileInvalid);
}
}
else if (profile.ConfigType is EConfigType.Custom or EConfigType.Outbound)
{
if (string.IsNullOrWhiteSpace(profile.Remarks) || string.IsNullOrWhiteSpace(profile.Address))
{
return OperationView.Fail("profile_validation_failed", ApiMessageKeys.ProfileInvalid);
}
}
else if (profile.ConfigType.IsComplexType())
{
return OperationView.Fail("profile_complex_type_requires_import", ApiMessageKeys.CommonInvalidInput);
}
else if (!TryValidateProfile(profile, out var code, out var messageKey))
{
return OperationView.Fail(code, messageKey);
}
var wasRunning = !isNew
&& profile.IndexId == CurrentCoreRuntime.ProfileId
&& CurrentCoreRuntime.State == CoreRuntimeState.Running;
int result;
try
{
result = await _mutations.RunAsync(() => profile.ConfigType.IsGroupType()
? ConfigHandler.AddServerCommon(Config, profile)
: profile.ConfigType switch
{
EConfigType.Custom when isNew => ConfigHandler.AddCustomServer(Config, profile, blDelete: false),
EConfigType.Outbound when isNew => ConfigHandler.AddCustomOutboundServer(Config, profile, blDelete: false, toFile: true),
EConfigType.Custom or EConfigType.Outbound => ConfigHandler.EditCustomServer(Config, profile),
_ => ConfigHandler.AddServer(Config, profile),
});
}
catch (Exception exception)
{
AddLog("profile", $"Profile save failed for {profile.ConfigType} ({profile.IndexId}): {exception}");
return OperationView.Fail("profile_persistence_failed", ApiMessageKeys.ProfileSaveFailed,
new { stage = "servicelib_or_sqlite_write", exceptionType = exception.GetType().Name, detail = exception.Message });
}
if (result != 0)
{
AddLog("profile", $"ServiceLib rejected profile save for {profile.ConfigType} ({profile.IndexId}); result={result}.");
return OperationView.Fail("profile_save_rejected", ApiMessageKeys.ProfileSaveFailed,
new { stage = "servicelib_validation_or_persistence", result });
}
if (wasRunning)
{
var restart = await RestartCoreAsync(CancellationToken.None);
_events.Publish("profiles-changed", new { subscriptionId = Config.SubIndexId });
return restart.Success
? OperationView.Ok(ApiMessageKeys.ProfileSaved, new { profileId = profile.IndexId, coreRestarted = true })
: OperationView.Fail("profile_saved_core_restart_failed", ApiMessageKeys.ProfileSaved,
new { profileId = profile.IndexId, coreRestartRequired = true, coreResultCode = restart.Code });
}
_events.Publish("profiles-changed", new { subscriptionId = Config.SubIndexId });
return OperationView.Ok(ApiMessageKeys.ProfileSaved, new { profileId = profile.IndexId, coreRestarted = false });
}
internal static bool TryValidateProfile(ProfileItem profile, out string code, out string messageKey)
{
if (string.IsNullOrEmpty(profile.Remarks)
|| string.IsNullOrEmpty(profile.Address)
|| profile.Port <= 0
|| profile.Port >= Global.MaxPort
|| (profile.ConfigType is not EConfigType.SOCKS and not EConfigType.HTTP
&& string.IsNullOrEmpty(profile.Password)))
{
code = "profile_validation_failed";
messageKey = ApiMessageKeys.ProfileInvalid;
return false;
}
var protocolExtra = profile.GetProtocolExtra();
if (profile.ConfigType == EConfigType.Shadowsocks && string.IsNullOrEmpty(protocolExtra.SsMethod))
{
code = "profile_validation_failed";
messageKey = ApiMessageKeys.ProfileInvalid;
return false;
}
if (profile.ConfigType == EConfigType.HTTP
&& !string.IsNullOrEmpty(protocolExtra.HttpHeaders)
&& JsonUtils.ParseJson(protocolExtra.HttpHeaders) is null)
{
code = "profile_http_headers_invalid";
messageKey = ApiMessageKeys.ProfileInvalid;
return false;
}
code = "ok";
messageKey = string.Empty;
return true;
}
internal static bool IsConfigTypeUnchanged(ProfileItem input, ProfileItem existing) =>
input.ConfigType == existing.ConfigType;
public async Task<OperationView> DeleteProfilesAsync(IEnumerable<string> profileIds)
{
var ids = profileIds.Where(id => !string.IsNullOrWhiteSpace(id)).Distinct(StringComparer.Ordinal).ToArray();
if (ids.Length == 0)
{
return OperationView.Fail("profile_selection_required", ApiMessageKeys.ProfileSelectRequired);
}
var selected = await AppManager.Instance.GetProfileItemsByIndexIds(ids);
if (selected.Count == 0)
{
return OperationView.Fail("profile_not_found", ApiMessageKeys.ProfileNotFound);
}
var runningProfileId = CurrentCoreRuntime.ProfileId;
var removesCurrent = ids.Contains(runningProfileId ?? Config.IndexId, StringComparer.Ordinal);
var wasRunning = CurrentCoreRuntime.State == CoreRuntimeState.Running;
if (removesCurrent && wasRunning)
{
var stop = await StopCoreAsync(CancellationToken.None);
if (!stop.Success)
{
return stop;
}
}
await _mutations.RunAsync(async () =>
{
if (await ConfigHandler.RemoveServers(Config, selected) != 0)
{
throw new IOException("ServiceLib could not remove the selected profiles.");
}
if (removesCurrent)
{
_ = await ConfigHandler.GetDefaultServer(Config);
await EnsureConfigSaveSucceededAsync(() => ConfigHandler.SaveConfig(Config));
}
});
if (removesCurrent && wasRunning && !string.IsNullOrEmpty(Config.IndexId))
{
var restart = await StartCoreAsync(null, CancellationToken.None);
_events.Publish("profiles-changed", new { subscriptionId = Config.SubIndexId });
return restart.Success
? OperationView.Ok(ApiMessageKeys.ProfileDeleted, new { deleted = selected.Count, coreRestarted = true })
: OperationView.Fail("profiles_deleted_core_restart_failed", ApiMessageKeys.ProfileDeleted,
new { deleted = selected.Count, coreRestartRequired = true, coreResultCode = restart.Code });
}
_events.Publish("profiles-changed", new { subscriptionId = Config.SubIndexId });
return OperationView.Ok(ApiMessageKeys.ProfileDeleted, new { deleted = selected.Count });
}
public async Task<OperationView> CopyProfilesAsync(IEnumerable<string> profileIds)
{
var ids = profileIds.Where(id => !string.IsNullOrWhiteSpace(id)).Distinct(StringComparer.Ordinal).ToArray();
var items = await AppManager.Instance.GetProfileItemsOrderedByIndexIds(ids);
if (items.Count == 0)
{
return OperationView.Fail("profile_not_found", ApiMessageKeys.ProfileNotFound);
}
if (await _mutations.RunAsync(() => ConfigHandler.CopyServer(Config, items)) != 0)
{
return OperationView.Fail("profile_copy_failed", ApiMessageKeys.CommonInvalidInput);
}
_events.Publish("profiles-changed", new { subscriptionId = Config.SubIndexId });
return OperationView.Ok(ApiMessageKeys.ProfileCopied, new { copied = items.Count });
}
public async Task<OperationView> MoveProfilesToGroupAsync(MoveProfilesRequest request)
{
if (!string.IsNullOrEmpty(request.SubscriptionId)
&& await AppManager.Instance.GetSubItem(request.SubscriptionId) is null)
{
return OperationView.Fail("subscription_not_found", ApiMessageKeys.SubscriptionNotFound);
}
var items = await AppManager.Instance.GetProfileItemsByIndexIds(request.ProfileIds);
if (items.Count == 0)
{
return OperationView.Fail("profile_not_found", ApiMessageKeys.ProfileNotFound);
}
if (await _mutations.RunAsync(() => ConfigHandler.MoveToGroup(Config, items, request.SubscriptionId ?? string.Empty)) != 0)
{
return OperationView.Fail("profile_move_failed", ApiMessageKeys.CommonInvalidInput);
}
_events.Publish("profiles-changed", new { subscriptionId = Config.SubIndexId });
return OperationView.Ok(ApiMessageKeys.ProfileMoved, new { moved = items.Count, subscriptionId = request.SubscriptionId });
}
public async Task<OperationView> MoveProfileAsync(MoveProfileRequest request)
{
var groupId = Config.SubIndexId ?? string.Empty;
var profiles = await GetProfilesAsync(groupId, null);
var orderedIds = profiles.Select(item => item.IndexId).ToList();
var index = orderedIds.IndexOf(request.ProfileId);
if (index < 0)
{
return OperationView.Fail("profile_not_in_group", ApiMessageKeys.ProfileNotInGroup);
}
var result = await _mutations.RunAsync(() => ConfigHandler.MoveServer(Config, orderedIds, index, request.Direction, request.Position));
_events.Publish("profiles-changed", new { subscriptionId = groupId });
return result == 0
? OperationView.Ok(ApiMessageKeys.ProfileOrderSaved)
: OperationView.Fail("profile_order_failed", ApiMessageKeys.CommonInvalidInput);
}
public async Task<OperationView> SortProfilesAsync(SortProfilesRequest request)
{
var groupId = request.SubscriptionId ?? Config.SubIndexId ?? string.Empty;
if (!Enum.TryParse<EServerColName>(request.Column, true, out _))
{
return OperationView.Fail("profile_sort_column_invalid", ApiMessageKeys.CommonInvalidInput);
}
var result = await _mutations.RunAsync(() => ConfigHandler.SortServers(Config, groupId, request.Column, request.Ascending));
_events.Publish("profiles-changed", new { subscriptionId = groupId });
return result == 0
? OperationView.Ok(ApiMessageKeys.ProfileOrderSaved)
: OperationView.Fail("profile_sort_failed", ApiMessageKeys.CommonInvalidInput);
}
public async Task<OperationView> RemoveDuplicateProfilesAsync(string? subscriptionId)
{
var result = await _mutations.RunAsync(() => ConfigHandler.DedupServerList(Config, subscriptionId ?? Config.SubIndexId ?? string.Empty));
_events.Publish("profiles-changed", new { subscriptionId = subscriptionId ?? Config.SubIndexId });
return OperationView.Ok(ApiMessageKeys.ProfileDeduplicated, new { removed = result.Item1 - result.Item2 });
}
public async Task<OperationView> RemoveInvalidProfilesAsync(string? subscriptionId)
{
var count = await _mutations.RunAsync(() => ConfigHandler.RemoveInvalidServerResult(Config, subscriptionId ?? Config.SubIndexId ?? string.Empty));
_events.Publish("profiles-changed", new { subscriptionId = subscriptionId ?? Config.SubIndexId });
return count < 0
? OperationView.Ok(ApiMessageKeys.CommonCompleted, new { removed = 0 })
: OperationView.Ok(ApiMessageKeys.ProfileInvalidRemoved, new { removed = count });
}
public async Task<OperationView> GenerateProfileGroupsAsync(string? subscriptionId, bool byRegion)
{
SubItem? subscription = null;
if (!string.IsNullOrEmpty(subscriptionId))
{
subscription = await AppManager.Instance.GetSubItem(subscriptionId);
if (subscription is null)
{
return OperationView.Fail("subscription_not_found", ApiMessageKeys.SubscriptionNotFound);
}
}
var result = await _mutations.RunAsync(() => byRegion
? ConfigHandler.AddGroupRegionServer(Config, subscription)
: ConfigHandler.AddGroupAllServer(Config, subscription));
if (!result.Success)
{
return OperationView.Fail("profile_group_empty", ApiMessageKeys.ProfileGrouped, result.Data);
}
_events.Publish("profiles-changed", new { subscriptionId = subscription?.Id ?? string.Empty });
return OperationView.Ok(ApiMessageKeys.ProfileGrouped, result.Data);
}
public async Task<IReadOnlyList<ProfileExportItem>> ExportProfileDataAsync(ProfileExportRequest request)
{
var items = await AppManager.Instance.GetProfileItemsOrderedByIndexIds(request.ProfileIds);
var output = new List<ProfileExportItem>();
if (request.IncludeShareUris)
{
var uris = items.Select(FmtHandler.GetShareUri).Where(uri => !string.IsNullOrWhiteSpace(uri)).ToArray();
if (uris.Length > 0)
{
var content = string.Join(Environment.NewLine, uris) + Environment.NewLine;
output.Add(new(string.Empty, string.Empty, request.Base64ShareUris ? "share-uri-base64" : "share-uri",
request.Base64ShareUris ? Utils.Base64Encode(content) : content));
}
}
if (request.IncludeInnerUri && items.Count > 0)
{
var innerUri = InnerFmt.ToUri(items);
if (!string.IsNullOrWhiteSpace(innerUri))
{
output.Add(new(string.Empty, string.Empty, "inner-uri", innerUri));
}
}
if (request.IncludeClientConfig)
{
foreach (var item in items)
{
var (context, validation) = await CoreConfigContextBuilder.Build(Config, item);
if (validation.Success)
{
var generated = await CoreConfigHandler.GenerateClientConfig(context, null);
if (generated.Success && generated.Data is string configText)
{
output.Add(new(item.IndexId, item.Remarks, "client-config", configText));
}
}
}
}
return output;
}
public async Task<string?> GetSubscriptionShareAsync(string id)
{
return (await AppManager.Instance.GetSubItem(id))?.Url;
}
public async Task<OperationView> StartSpeedTestAsync(SpeedTestRequest request, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var action = request.Action == ESpeedActionType.FastRealping ? ESpeedActionType.Realping : request.Action;
var profiles = request.ProfileIds is { Length: > 0 }
? await AppManager.Instance.GetProfileItemsOrderedByIndexIds(request.ProfileIds)
: await AppManager.Instance.ProfileItems(Config.SubIndexId ?? string.Empty) ?? [];
if (profiles.Count == 0)
{
return OperationView.Fail("speedtest_profile_selection_required", ApiMessageKeys.SpeedTestSelectRequired);
}
if (action != ESpeedActionType.Tcping
&& profiles.Where(item => !item.ConfigType.IsComplexType())
.Any(item => AppManager.Instance.GetCoreType(item, item.ConfigType) is not (ECoreType.Xray or ECoreType.sing_box)))
{
return OperationView.Fail("speedtest_core_unsupported", ApiMessageKeys.SpeedTestUnsupportedCore);
}
lock (_speedtestGate)
{
if (_speedtestTask is { IsCompleted: false })
{
return OperationView.Fail("speedtest_busy", ApiMessageKeys.SpeedTestBusy);
}
var speedtestService = _speedtestService ??= CreateSpeedtestService();
var speedtestCancellation = new CancellationTokenSource();
_speedtestCancellation = speedtestCancellation;
_speedtestTask = Task.Run(async () =>
{
try
{
using var requested = CancellationTokenSource.CreateLinkedTokenSource(_operations.ShutdownToken, speedtestCancellation.Token);
await using var operation = await _operations.EnterOperationAsync(requested.Token);
operation.Token.ThrowIfCancellationRequested();
await speedtestService.RunLoop(action, profiles, operation.Token);
}
catch (OperationCanceledException) when (_operations.IsStopping)
{
// Expected during graceful service shutdown.
}
catch (OperationCanceledException) when (speedtestCancellation.IsCancellationRequested)
{
// Expected when the caller stops the active speed test.
}
catch (Exception ex)
{
AddLog("speedtest", ex.Message);
}
finally
{
lock (_speedtestGate)
{
if (ReferenceEquals(_speedtestCancellation, speedtestCancellation))
{
_speedtestCancellation = null;
}
}
speedtestCancellation.Dispose();
}
});
}
_events.Publish("speedtest-started", new
{
code = "speedtest_started",
messageKey = ApiMessageKeys.SpeedTestStarted,
action = System.Text.Json.JsonNamingPolicy.CamelCase.ConvertName(action.ToString()),
profileIds = profiles.Select(item => item.IndexId),
});
return OperationView.Ok(ApiMessageKeys.SpeedTestStarted, new { action = action.ToString(), profileCount = profiles.Count });
}
private SpeedtestService CreateSpeedtestService() => new(Config, result =>
{
int? delay = int.TryParse(result.Delay, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var parsedDelay)
? parsedDelay
: null;
decimal? speed = decimal.TryParse(result.Speed, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out var parsedSpeed)
? parsedSpeed
: null;
_events.Publish("speedtest-result", new
{
code = ApiMessageKeys.SpeedTestResult,
messageKey = ApiMessageKeys.SpeedTestResult,
indexId = result.IndexId,
delay,
speed,
ipInfo = result.IpInfo,
rawResult = delay is null && speed is null ? (result.Delay ?? result.Speed) : null,
});
if (!string.IsNullOrEmpty(result.IndexId))
{
AddLog("speedtest", $"{result.IndexId}: delay={result.Delay}, speed={result.Speed}");
}
return Task.CompletedTask;
});
public OperationView StopSpeedTests()
{
lock (_speedtestGate)
{
_speedtestCancellation?.Cancel();
_speedtestService?.ExitLoop();
}
return OperationView.Ok(ApiMessageKeys.CommonCompleted);
}
public IReadOnlyList<string> GetRunningSubscriptionUpdates()
{
lock (_subscriptionGate)
{
return _subscriptionTasks.Where(pair => !pair.Value.IsCompleted).Select(pair => pair.Key).ToArray();
}
}
}