mirror of
https://github.com/MikuLeaks/MikuSB.git
synced 2026-06-04 07:44:00 +00:00
Compare commits
47 Commits
v1.5
...
a555dd2930
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a555dd2930 | ||
|
|
85605a786c | ||
|
|
f3d6ff3873 | ||
|
|
41df375e21 | ||
|
|
5332d5fe1a | ||
|
|
da61f1e929 | ||
|
|
d9b16fb55d | ||
|
|
e92b214161 | ||
|
|
6740b8ecf7 | ||
|
|
233419eba3 | ||
|
|
a7a68418db | ||
|
|
f053359c41 | ||
|
|
0cf633a0e1 | ||
|
|
e4397f10ee | ||
|
|
bdb4ee3d51 | ||
|
|
7507d10072 | ||
|
|
8a7a919d04 | ||
|
|
2d1079a80d | ||
|
|
677e4027b9 | ||
|
|
4dc28ae423 | ||
|
|
1fce4ca2e6 | ||
|
|
93c59e5730 | ||
|
|
f7814b0537 | ||
|
|
2fdda3157f | ||
|
|
f07c5f77fd | ||
|
|
2883ac3d41 | ||
|
|
49f4fdfda5 | ||
|
|
bcc5716f97 | ||
|
|
4bd66621bf | ||
|
|
14a611bf8e | ||
|
|
283358f1ec | ||
|
|
5d8b3f2bad | ||
|
|
a992bc86c5 | ||
|
|
d97eae6f5b | ||
|
|
04121eb357 | ||
|
|
391879a483 | ||
|
|
8e3323dd94 | ||
|
|
7e83d2ccd2 | ||
|
|
408113963b | ||
|
|
fcf0bf0843 | ||
|
|
50121d619b | ||
|
|
5f3fc0c746 | ||
|
|
2fe795d29a | ||
|
|
b256fe7b01 | ||
|
|
e93dadafe8 | ||
|
|
34b93ad55d | ||
|
|
3eca16a661 |
57
.github/workflows/release.yml
vendored
57
.github/workflows/release.yml
vendored
@@ -9,6 +9,9 @@ on:
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
env:
|
||||
BRANCH_NAME: ${{ github.head_ref || github.ref_name }}
|
||||
|
||||
jobs:
|
||||
build-release:
|
||||
runs-on: windows-latest
|
||||
@@ -18,7 +21,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: 9.0.x
|
||||
dotnet-version: 10.0.x
|
||||
|
||||
- name: Read version
|
||||
id: version
|
||||
@@ -54,3 +57,55 @@ jobs:
|
||||
files: |
|
||||
artifacts/MikuSB-win-x64.zip
|
||||
artifacts/MikuSB-win-x64.zip.sha256
|
||||
|
||||
build-release-linux:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
- name: Publish server
|
||||
run: |
|
||||
dotnet publish ./MikuSB/MikuSB.csproj -c Release -r linux-x64 --self-contained true -p:PublishSingleFile=true --property:PublishDir=../artifacts/dist
|
||||
|
||||
- name: Read version
|
||||
id: version
|
||||
shell: bash
|
||||
run: |
|
||||
line=$(head -n 1 version.txt | xargs)
|
||||
VERSION=${line#v=}
|
||||
|
||||
SHORT_HASH="$(git rev-parse --short=7 HEAD)"
|
||||
if [ -z "$VERSION" ]; then
|
||||
echo "version.txt is empty."
|
||||
VERSION=${SHORT_HASH}
|
||||
fi
|
||||
if [[ "${{ env.BRANCH_NAME }}" == "main" ]]; then
|
||||
echo "tag=v${VERSION}" >> $GITHUB_OUTPUT
|
||||
else
|
||||
SAFE_NAME=$(echo "${{ env.BRANCH_NAME }}" | tr '/' '-')
|
||||
echo "tag=${SAFE_NAME}-v${VERSION}-${SHORT_HASH}" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Assemble release package
|
||||
run: |
|
||||
packageDir="./artifacts/dist/"
|
||||
zipFile="MikuSB-linux-x64.zip"
|
||||
cp ./version.txt ${packageDir}
|
||||
pushd ${packageDir}
|
||||
zip -r ../${zipFile} .
|
||||
popd
|
||||
sha256sum ./artifacts/${zipFile} > ./artifacts/${zipFile}.sha256
|
||||
|
||||
- name: Create release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ steps.version.outputs.tag }}
|
||||
name: ${{ steps.version.outputs.tag }}
|
||||
generate_release_notes: true
|
||||
files: |
|
||||
./artifacts/MikuSB-linux-x64.zip
|
||||
./artifacts/MikuSB-linux-x64.zip.sha256
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<CETCompat>false</CETCompat>
|
||||
@@ -21,7 +21,6 @@
|
||||
<PackageReference Include="SQLitePCLRaw.provider.e_sqlite3" Version="2.1.10" />
|
||||
<PackageReference Include="SqlSugarCore" Version="5.1.4.172" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" />
|
||||
<PackageReference Include="System.IO.Pipelines" Version="9.0.0" />
|
||||
<PackageReference Include="System.Management" Version="9.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ public class ConfigContainer
|
||||
public PathConfig Path { get; set; } = new();
|
||||
public ServerOption ServerOption { get; set; } = new();
|
||||
public ProxyOptions Proxy { get; set; } = new();
|
||||
public LoaderOptions Loader { get; set; } = new();
|
||||
}
|
||||
|
||||
public class HttpServerConfig
|
||||
@@ -60,7 +61,7 @@ public class ServerOption
|
||||
public string FallbackLanguage { get; set; } = "EN";
|
||||
public string[] DefaultPermissions { get; set; } = ["Admin"];
|
||||
public ServerProfile ServerProfile { get; set; } = new();
|
||||
public bool EnableGmMenu { get; set; } = true;
|
||||
public bool EnableGmMenu { get; set; } = false;
|
||||
public bool AutoCreateUser { get; set; } = true;
|
||||
public bool SavePersonalDebugFile { get; set; } = false;
|
||||
public bool AutoSendResponseWhenNoHandler { get; set; } = true;
|
||||
@@ -86,10 +87,13 @@ public class ServerProfile
|
||||
public class ProxyOptions
|
||||
{
|
||||
public bool Enabled { get; set; } = true;
|
||||
public int Port { get; set; } = 8888;
|
||||
public int ServerHttpPort { get; set; } = 21500;
|
||||
public bool InstallRootCertificate { get; set; } = true;
|
||||
public bool ManageSystemProxy { get; set; } = true;
|
||||
public bool RestoreSystemProxyOnStop { get; set; } = true;
|
||||
public string ProxyOverride { get; set; } = "localhost;127.*;10.*;192.168.*;<local>";
|
||||
public int Port { get; set; } = 18888;
|
||||
}
|
||||
|
||||
public class LoaderOptions
|
||||
{
|
||||
public string GamePath { get; set; } = "";
|
||||
public string[] PatchPaths { get; set; } = [@"Patch\MikuSB-Patch.dll"];
|
||||
public string[] Arguments { get; set; } = ["-FeatureLevelES31", "-channelid=seasun", "-NoSplash"];
|
||||
public bool SetAllProxy { get; set; } = true;
|
||||
}
|
||||
|
||||
24
Common/Data/Config/StringToUIntConverter.cs
Normal file
24
Common/Data/Config/StringToUIntConverter.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace MikuSB.Data.Config;
|
||||
|
||||
public class StringToUIntConverter : JsonConverter<uint>
|
||||
{
|
||||
public override uint ReadJson(JsonReader reader, Type objectType, uint existingValue, bool hasExistingValue, JsonSerializer serializer)
|
||||
{
|
||||
if (reader.Value == null)
|
||||
return 0;
|
||||
|
||||
var value = reader.Value.ToString();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
return 0;
|
||||
|
||||
return uint.TryParse(value, out var result) ? result : 0;
|
||||
}
|
||||
|
||||
public override void WriteJson(JsonWriter writer, uint value, JsonSerializer serializer)
|
||||
{
|
||||
writer.WriteValue(value);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace MikuSB.Data.Excel;
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("ar_item.json")]
|
||||
[ResourceEntity("item/templates/ar_item.json")]
|
||||
public class ArItemExcel : ExcelResource
|
||||
{
|
||||
public uint Genre { get; set; }
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("break.json")]
|
||||
[ResourceEntity("item/break.json")]
|
||||
public class BreakExcel : ExcelResource
|
||||
{
|
||||
[JsonProperty("ID")] public int Id { get; set; }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace MikuSB.Data.Excel;
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("break_level_limit.json")]
|
||||
[ResourceEntity("item/break_level_limit.json")]
|
||||
public class BreakLevelLimitExcel : ExcelResource
|
||||
{
|
||||
public int ID { get; set; }
|
||||
|
||||
24
Common/Data/Excel/CallItemExcel.cs
Normal file
24
Common/Data/Excel/CallItemExcel.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("item/templates/call_item.json")]
|
||||
public class CallItemExcel : ExcelResource
|
||||
{
|
||||
public uint Genre { get; set; }
|
||||
public uint Detail { get; set; }
|
||||
public uint Particular { get; set; }
|
||||
public uint Level { get; set; }
|
||||
public string I18n { get; set; } = "";
|
||||
|
||||
public override uint GetId()
|
||||
{
|
||||
return (uint)I18n.GetHashCode();
|
||||
}
|
||||
|
||||
public override void Loaded()
|
||||
{
|
||||
GameData.CallItemData.Add(GetId(), this);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("card.json")]
|
||||
[ResourceEntity("item/templates/card.json")]
|
||||
public class CardExcel : ExcelResource
|
||||
{
|
||||
public uint Genre { get; set; }
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("card_skin.json")]
|
||||
[ResourceEntity("item/templates/card_skin.json")]
|
||||
public class CardSkinExcel : ExcelResource
|
||||
{
|
||||
public uint Genre { get; set; }
|
||||
|
||||
27
Common/Data/Excel/CardSkinPartsExcel.cs
Normal file
27
Common/Data/Excel/CardSkinPartsExcel.cs
Normal file
@@ -0,0 +1,27 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("item/templates/card_skin_parts.json")]
|
||||
public class CardSkinPartsExcel : ExcelResource
|
||||
{
|
||||
public uint Genre { get; set; }
|
||||
public uint Detail { get; set; }
|
||||
public uint Particular { get; set; }
|
||||
public uint Level { get; set; }
|
||||
public uint Icon { get; set; }
|
||||
public int AppearID { get; set; }
|
||||
[JsonProperty("profile")] public List<List<int>> CardSkinID { get; set; } = [];
|
||||
public string I18n { get; set; } = "";
|
||||
[JsonIgnore] public ulong TemplateId { get; set; }
|
||||
public override uint GetId()
|
||||
{
|
||||
return (uint)I18n.GetHashCode();
|
||||
}
|
||||
|
||||
public override void Loaded()
|
||||
{
|
||||
TemplateId = GameResourceTemplateId.FromGdpl(Genre, Detail, Particular, Level);
|
||||
GameData.CardSkinPartsData.Add(Icon, this);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("level.json")]
|
||||
[ResourceEntity("chapter/level.json")]
|
||||
public class ChapterLevelExcel : ExcelResource
|
||||
{
|
||||
public uint ID { get; set; }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("daily_level.json")]
|
||||
[ResourceEntity("daily/level.json")]
|
||||
public class DailyLevelExcel : ExcelResource
|
||||
{
|
||||
public uint ID { get; set; }
|
||||
|
||||
21
Common/Data/Excel/DormGiftExcel.cs
Normal file
21
Common/Data/Excel/DormGiftExcel.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("item/templates/dorm_gift.json")]
|
||||
public class DormGiftExcel : ExcelResource
|
||||
{
|
||||
public uint Genre { get; set; }
|
||||
public uint Detail { get; set; }
|
||||
public uint Particular { get; set; }
|
||||
public uint Level { get; set; }
|
||||
public string I18n { get; set; } = "";
|
||||
|
||||
public override uint GetId()
|
||||
{
|
||||
return (Genre << 24) | (Detail << 16) | (Particular << 8) | Level;
|
||||
}
|
||||
|
||||
public override void Loaded()
|
||||
{
|
||||
GameData.DormGiftData.Add(GetId(), this);
|
||||
}
|
||||
}
|
||||
21
Common/Data/Excel/GuideExcel.cs
Normal file
21
Common/Data/Excel/GuideExcel.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
using MikuSB.Data.Config;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("guide/guide.json")]
|
||||
public class GuideExcel : ExcelResource
|
||||
{
|
||||
public uint ID { get; set; }
|
||||
[JsonConverter(typeof(StringToUIntConverter))] public uint Group { get; set; }
|
||||
|
||||
public override uint GetId()
|
||||
{
|
||||
return (ID << 48) | (Group << 32);
|
||||
}
|
||||
|
||||
public override void Loaded()
|
||||
{
|
||||
GameData.GuideData.TryAdd(GetId(), this);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("manifestation.json")]
|
||||
[ResourceEntity("item/templates/manifestation.json")]
|
||||
public class ManifestationExcel : ExcelResource
|
||||
{
|
||||
public uint Genre { get; set; }
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
// nodecondition.json: NodeConditionId → NodeXCost per sub-node (1-9)
|
||||
[ResourceEntity("nodecondition.json")]
|
||||
[ResourceEntity("item/skill/nodecondition.json")]
|
||||
public class NodeConditionExcel : ExcelResource
|
||||
{
|
||||
[JsonProperty("ID")] public uint Id { get; set; }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("profile.json")]
|
||||
[ResourceEntity("item/templates/profile.json")]
|
||||
public class ProfileExcel : ExcelResource
|
||||
{
|
||||
public uint Genre { get; set; }
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("recycle.json")]
|
||||
[ResourceEntity("item/recycle.json")]
|
||||
public class RecycleExcel : ExcelResource
|
||||
{
|
||||
public int ID { get; set; }
|
||||
|
||||
18
Common/Data/Excel/Rogue3DDailyBuffExcel.cs
Normal file
18
Common/Data/Excel/Rogue3DDailyBuffExcel.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("dlc/rogue3d/dailybuff.json")]
|
||||
public class Rogue3DDailyBuffExcel : ExcelResource
|
||||
{
|
||||
[JsonProperty("ID")] public uint Id { get; set; }
|
||||
[JsonProperty("GroupID")] public uint GroupId { get; set; }
|
||||
[JsonProperty("ScoreBuffID")] public uint ScoreBuffId { get; set; }
|
||||
|
||||
public override uint GetId() => Id;
|
||||
|
||||
public override void Loaded()
|
||||
{
|
||||
GameData.Rogue3DDailyBuffData[Id] = this;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("server_01_difficult.json")]
|
||||
[ResourceEntity("dlc/rogue3d/server_01_difficult.json")]
|
||||
public class Rogue3DDifficultExcel : ExcelResource
|
||||
{
|
||||
[JsonProperty("DifficultID")] public uint DifficultId { get; set; }
|
||||
|
||||
19
Common/Data/Excel/Rogue3DSeasonExcel.cs
Normal file
19
Common/Data/Excel/Rogue3DSeasonExcel.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("dlc/rogue3d/server_10_season.json")]
|
||||
public class Rogue3DSeasonExcel : ExcelResource
|
||||
{
|
||||
[JsonProperty("SeasonID")] public uint SeasonId { get; set; }
|
||||
[JsonProperty("Type")] public int Type { get; set; }
|
||||
[JsonProperty("OpenTime")] public string OpenTime { get; set; } = "";
|
||||
[JsonProperty("CloseTime")] public string CloseTime { get; set; } = "";
|
||||
|
||||
public override uint GetId() => SeasonId;
|
||||
|
||||
public override void Loaded()
|
||||
{
|
||||
GameData.Rogue3DSeasonData[SeasonId] = this;
|
||||
}
|
||||
}
|
||||
31
Common/Data/Excel/Rogue3DTalentExcel.cs
Normal file
31
Common/Data/Excel/Rogue3DTalentExcel.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("dlc/rogue3d/server_03_talent.json")]
|
||||
public class Rogue3DTalentExcel : ExcelResource
|
||||
{
|
||||
[JsonProperty("TalentID")] public uint TalentId { get; set; }
|
||||
[JsonProperty("UnlockCondition")] private object? UnlockConditionRaw { get; set; }
|
||||
[JsonIgnore] public uint UnlockCondition { get; private set; }
|
||||
|
||||
public override uint GetId() => TalentId;
|
||||
|
||||
public override void Loaded()
|
||||
{
|
||||
UnlockCondition = ParseUnlockCondition(UnlockConditionRaw);
|
||||
GameData.Rogue3DTalentData[TalentId] = this;
|
||||
}
|
||||
|
||||
private static uint ParseUnlockCondition(object? raw)
|
||||
{
|
||||
return raw switch
|
||||
{
|
||||
null => 0,
|
||||
long value when value > 0 => (uint)value,
|
||||
int value when value > 0 => (uint)value,
|
||||
string text when uint.TryParse(text, out var value) => value,
|
||||
_ => 0
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
// spine.json: SpineId → Node{i}Req (nodecondition ID per master node index)
|
||||
[ResourceEntity("spine.json")]
|
||||
[ResourceEntity("item/skill/spine.json")]
|
||||
public class SpineExcel : ExcelResource
|
||||
{
|
||||
[JsonProperty("ID")] public uint Id { get; set; }
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("suplies.json")]
|
||||
[ResourceEntity("item/templates/suplies.json")]
|
||||
public class SuppliesExcel : ExcelResource
|
||||
{
|
||||
public uint Genre { get; set; }
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("support_card.json")]
|
||||
[ResourceEntity("item/templates/support_card.json")]
|
||||
public class SupportCardExcel : ExcelResource
|
||||
{
|
||||
public uint Genre { get; set; }
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("upgrade_exp.json")]
|
||||
[ResourceEntity("item/upgrade_exp.json")]
|
||||
public class UpgradeExpExcel : ExcelResource
|
||||
{
|
||||
public int Lv { get; set; }
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("weapon.json")]
|
||||
[ResourceEntity("item/templates/weapon.json")]
|
||||
public class WeaponExcel : ExcelResource
|
||||
{
|
||||
public uint Genre { get; set; }
|
||||
|
||||
24
Common/Data/Excel/WeaponPartsExcel.cs
Normal file
24
Common/Data/Excel/WeaponPartsExcel.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("item/templates/weapon_parts.json")]
|
||||
public class WeaponPartsExcel : ExcelResource
|
||||
{
|
||||
public uint Genre { get; set; }
|
||||
public uint Detail { get; set; }
|
||||
public uint Particular { get; set; }
|
||||
public uint Level { get; set; }
|
||||
public uint Icon { get; set; }
|
||||
public int AppearID { get; set; }
|
||||
public string I18n { get; set; } = "";
|
||||
public override uint GetId()
|
||||
{
|
||||
return (uint)I18n.GetHashCode();
|
||||
}
|
||||
|
||||
public override void Loaded()
|
||||
{
|
||||
GameData.WeaponPartsData.Add(GetId(), this);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace MikuSB.Data.Excel;
|
||||
|
||||
[ResourceEntity("weapon_skin.json")]
|
||||
[ResourceEntity("item/templates/weapon_skin.json")]
|
||||
public class WeaponSkinExcel : ExcelResource
|
||||
{
|
||||
public uint Genre { get; set; }
|
||||
|
||||
@@ -16,6 +16,9 @@ public static class GameData
|
||||
public static Dictionary<uint, ArItemExcel> ArItemData { get; private set; } = [];
|
||||
public static Dictionary<uint, ManifestationExcel> ManifestationData { get; private set; } = [];
|
||||
public static Dictionary<uint, Rogue3DDifficultExcel> Rogue3DDifficultData { get; private set; } = [];
|
||||
public static Dictionary<uint, Rogue3DSeasonExcel> Rogue3DSeasonData { get; private set; } = [];
|
||||
public static Dictionary<uint, Rogue3DTalentExcel> Rogue3DTalentData { get; private set; } = [];
|
||||
public static Dictionary<uint, Rogue3DDailyBuffExcel> Rogue3DDailyBuffData { get; private set; } = [];
|
||||
public static Dictionary<int, BreakExcel> BreakData { get; private set; } = [];
|
||||
public static Dictionary<uint, SpineExcel> SpineData { get; private set; } = [];
|
||||
public static Dictionary<uint, NodeConditionExcel> NodeConditionData { get; private set; } = [];
|
||||
@@ -23,6 +26,11 @@ public static class GameData
|
||||
public static Dictionary<uint, WeaponSkinExcel> WeaponSkinData { get; private set; } = [];
|
||||
public static Dictionary<uint, DailyLevelExcel> DailyLevelData { get; private set; } = [];
|
||||
public static Dictionary<uint, ProfileExcel> ProfileData { get; private set; } = [];
|
||||
public static Dictionary<uint, CardSkinPartsExcel> CardSkinPartsData { get; private set; } = [];
|
||||
public static Dictionary<uint, CallItemExcel> CallItemData { get; private set; } = [];
|
||||
public static Dictionary<uint, WeaponPartsExcel> WeaponPartsData { get; private set; } = [];
|
||||
public static Dictionary<uint, GuideExcel> GuideData { get; private set; } = [];
|
||||
public static Dictionary<uint, DormGiftExcel> DormGiftData { get; private set; } = [];
|
||||
}
|
||||
|
||||
public static class GameResourceTemplateId
|
||||
|
||||
@@ -46,7 +46,7 @@ public class ResourceManager
|
||||
foreach (var fileName in attribute.FileName)
|
||||
try
|
||||
{
|
||||
var path = ConfigManager.Config.Path.ResourcePath + "/ExcelOutput/" + fileName;
|
||||
var path = ConfigManager.Config.Path.ResourcePath + "/" + fileName;
|
||||
var file = new FileInfo(path);
|
||||
if (!file.Exists)
|
||||
{
|
||||
|
||||
@@ -26,11 +26,14 @@ public class AccountData : BaseDatabaseDataHelper
|
||||
AccountData? result = null;
|
||||
DatabaseHelper.GetAllInstance<AccountData>()?.ForEach(account =>
|
||||
{
|
||||
if (account.Username == username) result = account;
|
||||
if (string.Equals(account.Username, username, StringComparison.OrdinalIgnoreCase)) result = account;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
public static AccountData? GetAccountByEmail(string email)
|
||||
=> GetAccountByUserName(email);
|
||||
|
||||
public static AccountData? GetAccountByUid(int uid, bool force = false)
|
||||
{
|
||||
var result = DatabaseHelper.GetInstance<AccountData>(uid, force);
|
||||
@@ -61,8 +64,15 @@ public class AccountData : BaseDatabaseDataHelper
|
||||
|
||||
#region Account
|
||||
|
||||
public static void CreateAccount(string username, int uid, string password)
|
||||
public static AccountData CreateAccount(string username, int uid, string password)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(username))
|
||||
throw new ArgumentException("Username cannot be empty.", nameof(username));
|
||||
if (GetAccountByUserName(username) != null)
|
||||
throw new InvalidOperationException($"Account '{username}' already exists.");
|
||||
if (uid != 0 && GetAccountByUid(uid) != null)
|
||||
throw new InvalidOperationException($"UID '{uid}' is already in use.");
|
||||
|
||||
var newUid = uid;
|
||||
if (uid == 0)
|
||||
{
|
||||
@@ -84,6 +94,7 @@ public class AccountData : BaseDatabaseDataHelper
|
||||
SetPassword(account, password);
|
||||
|
||||
DatabaseHelper.CreateInstance(account);
|
||||
return account;
|
||||
}
|
||||
|
||||
public static void DeleteAccount(int uid)
|
||||
@@ -178,4 +189,4 @@ public class AccountData : BaseDatabaseDataHelper
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,10 @@ public class DatabaseHelper
|
||||
public static readonly ConcurrentDictionary<int, List<BaseDatabaseDataHelper>> UidInstanceMap = [];
|
||||
public static readonly List<int> ToSaveUidList = [];
|
||||
public static long LastSaveTick = DateTime.UtcNow.Ticks;
|
||||
public static Thread? SaveThread;
|
||||
|
||||
private static int _saving = 0;
|
||||
private static Task? _saveTask;
|
||||
private static CancellationTokenSource? _cts;
|
||||
public static bool LoadAccount;
|
||||
public static bool LoadAllData;
|
||||
|
||||
@@ -77,15 +80,11 @@ public class DatabaseHelper
|
||||
|
||||
while (!res.IsCompleted)
|
||||
{
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
|
||||
LastSaveTick = DateTime.UtcNow.Ticks;
|
||||
|
||||
SaveThread = new Thread(() =>
|
||||
{
|
||||
while (true) CalcSaveDatabase();
|
||||
});
|
||||
SaveThread.Start();
|
||||
_cts = new CancellationTokenSource();
|
||||
_saveTask = RunAutoSave(_cts.Token);
|
||||
|
||||
LoadAllData = true;
|
||||
}
|
||||
@@ -248,6 +247,35 @@ public class DatabaseHelper
|
||||
ToSaveUidList.RemoveAll(x => x == key);
|
||||
}
|
||||
|
||||
public static void Stop()
|
||||
{
|
||||
_cts?.Cancel();
|
||||
}
|
||||
|
||||
public static async Task WaitAsync()
|
||||
{
|
||||
if (_saveTask != null)
|
||||
await _saveTask;
|
||||
}
|
||||
|
||||
private static async Task RunAutoSave(CancellationToken token)
|
||||
{
|
||||
LastSaveTick = DateTime.UtcNow.Ticks;
|
||||
try
|
||||
{
|
||||
while (!token.IsCancellationRequested)
|
||||
{
|
||||
CalcSaveDatabase();
|
||||
await Task.Delay(100, token);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// exit normally
|
||||
// Console.WriteLine($"RunAutoSave exit! - OperationCanceledException");
|
||||
}
|
||||
}
|
||||
|
||||
// Auto save per 5 min
|
||||
public static void CalcSaveDatabase()
|
||||
{
|
||||
@@ -257,6 +285,10 @@ public class DatabaseHelper
|
||||
|
||||
public static void SaveDatabase()
|
||||
{
|
||||
// ensure only one SaveDatabase() runnig
|
||||
if (Interlocked.Exchange(ref _saving, 1) == 1)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
var prev = DateTime.Now;
|
||||
@@ -281,11 +313,18 @@ public class DatabaseHelper
|
||||
Math.Round(t, 2).ToString(CultureInfo.InvariantCulture)));
|
||||
|
||||
ToSaveUidList.Clear();
|
||||
|
||||
// Thread.Sleep(5000); // for test if saving process taking too long
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.Error("An error occurred while saving the database", e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// release lock
|
||||
Volatile.Write(ref _saving, 0);
|
||||
}
|
||||
|
||||
LastSaveTick = DateTime.UtcNow.Ticks;
|
||||
}
|
||||
|
||||
@@ -62,6 +62,7 @@ public abstract class GrowableItemInfo : BaseGameItemInfo
|
||||
|
||||
public class GameWeaponInfo : GrowableItemInfo
|
||||
{
|
||||
[SugarColumn(IsJson = true)] public Dictionary<uint, ulong> PartSlots { get; set; } = [];
|
||||
public override Item ToProto()
|
||||
{
|
||||
var proto = new Item
|
||||
@@ -78,11 +79,13 @@ public class GameWeaponInfo : GrowableItemInfo
|
||||
Evolue = Evolue
|
||||
}
|
||||
};
|
||||
foreach (var (slot, uid) in PartSlots) proto.Slots[slot] = uid;
|
||||
return proto;
|
||||
}
|
||||
}
|
||||
public class GameSkinInfo : BaseGameItemInfo
|
||||
{
|
||||
[SugarColumn(IsJson = true)] public Dictionary<uint, ulong> PartSlots { get; set; } = [];
|
||||
public uint SkinType { get; set; }
|
||||
public override Item ToProto()
|
||||
{
|
||||
@@ -94,6 +97,7 @@ public class GameSkinInfo : BaseGameItemInfo
|
||||
Flag = (uint)Flag,
|
||||
};
|
||||
proto.Slots[(uint)ItemSkinSlotTypeEnum.SLOT_CARD_SKIL_TYPE] = Math.Min(SkinType, 1);
|
||||
foreach (var (slot, uid) in PartSlots) proto.Slots[slot] = uid;
|
||||
return proto;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,6 +35,11 @@ public class ServerTextCHS
|
||||
/// </summary>
|
||||
public class WordTextCHS
|
||||
{
|
||||
public string Furniture => "家具";
|
||||
public string Skin => "皮肤";
|
||||
public string WeaponPart => "武器部件";
|
||||
public string CallItem => "召唤道具";
|
||||
public string SkinPart => "皮肤部件";
|
||||
public string Profile => "个人资料";
|
||||
public string WeaponSkin => "武器皮肤";
|
||||
public string SupportCard => "支援卡";
|
||||
@@ -123,9 +128,11 @@ public class CommandTextCHS
|
||||
{
|
||||
public NoticeTextCHS Notice { get; } = new();
|
||||
public HelpTextCHS Help { get; } = new();
|
||||
public AccountTextCHS Account { get; } = new();
|
||||
public GirlTextCHS Girl { get; } = new();
|
||||
public GiveAllTextCHS GiveAll { get; } = new();
|
||||
public DebugTextCHS Debug { get; } = new();
|
||||
public GameCommandTextCHS Game { get; } = new();
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -212,6 +219,14 @@ public class HelpTextCHS
|
||||
public string CommandAlias => "命令别名: ";
|
||||
}
|
||||
|
||||
public class AccountTextCHS
|
||||
{
|
||||
public string Desc => "管理 SDK 登录使用的账号映射";
|
||||
public string Usage => "用法: /account create <邮箱> <UID>";
|
||||
public string Created => "已创建账号映射: {0} -> UID {1}";
|
||||
public string CreateFailed => "创建账号映射失败: {0}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// path: Game.Command.Girl
|
||||
/// </summary>
|
||||
@@ -224,12 +239,14 @@ public class GirlTextCHS
|
||||
public string Usage =>
|
||||
"用法: /girl add <detail/-1> -p<particular> -l<level> -s<star>\n" +
|
||||
"用法: /girl level <guid/-1> <level>\n" +
|
||||
"用法: /girl neuronic <guid/-1> <level>";
|
||||
"用法: /girl neuronic <guid/-1> <level>\n" +
|
||||
"用法: /girl break <guid/-1> <level>";
|
||||
|
||||
public string NotFound => "角色不存在!";
|
||||
public string Added => "已为玩家添加 {0} 个角色!";
|
||||
public string UpdateLevel => "已将 {1} 个角色等级设置为 {0}!";
|
||||
public string UpdateNeuronicLevel => "已将 {1} 个角色的神经元等级设置为 {0}!";
|
||||
public string UpdateBreakLevel => "已将 {1} 个角色的天启/武格等级设置为 {0}!";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -242,7 +259,10 @@ public class GiveAllTextCHS
|
||||
public string Usage => "用法:/giveall weapon <detail/-1> -p<特定> -l<等級>\n" +
|
||||
"用法:/giveall weaponskin <detail/-1> -p<特定>\n" +
|
||||
"用法:/giveall card <detail/-1> -p<特定> -l<等級>" +
|
||||
"用法:/giveall profile <detail/-1> -g<类型> -p<特定> -l<等级>";
|
||||
"用法:/giveall profile <detail/-1> -g<类型> -p<特定> -l<等级>" +
|
||||
"用法:/giveall skinpart <detail/-1> -g<類型> -p<特定> -l<等級>" +
|
||||
"用法:/giveall weaponpart <detail/-1> -g<類型> -p<特定> -l<等級>" +
|
||||
"用法:/giveall call <detail/-1> -g<類型> -p<特定> -l<等級>";
|
||||
public string NotFound => "未找到 {0}!";
|
||||
public string GiveAllItems => "已向玩家添加 {0} 个 {1}!";
|
||||
}
|
||||
@@ -262,6 +282,14 @@ public class DebugTextCHS
|
||||
public string FileDisabled => "个人调试文件输出已禁用。";
|
||||
}
|
||||
|
||||
public class GameCommandTextCHS
|
||||
{
|
||||
public string Desc => "使用补丁注入启动已配置的游戏";
|
||||
public string Usage => "用法: /game [额外游戏参数]";
|
||||
public string Started => "游戏已启动。PID: {0}";
|
||||
public string Failed => "游戏启动失败: {0}";
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
#endregion
|
||||
|
||||
@@ -35,6 +35,11 @@ public class ServerTextCHT
|
||||
/// </summary>
|
||||
public class WordTextCHT
|
||||
{
|
||||
public string Furniture => "傢俱";
|
||||
public string Skin => "皮膚";
|
||||
public string WeaponPart => "武器部件";
|
||||
public string CallItem => "召喚道具";
|
||||
public string SkinPart => "外觀部件";
|
||||
public string Profile => "個人資料";
|
||||
public string WeaponSkin => "武器外觀";
|
||||
public string SupportCard => "支援卡";
|
||||
@@ -123,9 +128,11 @@ public class CommandTextCHT
|
||||
{
|
||||
public NoticeTextCHT Notice { get; } = new();
|
||||
public HelpTextCHT Help { get; } = new();
|
||||
public AccountTextCHT Account { get; } = new();
|
||||
public GirlTextCHT Girl { get; } = new();
|
||||
public GiveAllTextCHT GiveAll { get; } = new();
|
||||
public DebugTextCHT Debug { get; } = new();
|
||||
public GameCommandTextCHT Game { get; } = new();
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -212,6 +219,14 @@ public class HelpTextCHT
|
||||
public string CommandAlias => "命令別名: ";
|
||||
}
|
||||
|
||||
public class AccountTextCHT
|
||||
{
|
||||
public string Desc => "管理 SDK 登入使用的帳號映射";
|
||||
public string Usage => "用法: /account create <郵箱> <UID>";
|
||||
public string Created => "已建立帳號映射: {0} -> UID {1}";
|
||||
public string CreateFailed => "建立帳號映射失敗: {0}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// path: Game.Command.Girl
|
||||
/// </summary>
|
||||
@@ -224,12 +239,14 @@ public class GirlTextCHT
|
||||
public string Usage =>
|
||||
"用法: /girl add <detail/-1> -p<particular> -l<level> -s<star>\n" +
|
||||
"用法: /girl level <guid/-1> <level>\n" +
|
||||
"用法: /girl neuronic <guid/-1> <level>";
|
||||
"用法: /girl neuronic <guid/-1> <level>\n" +
|
||||
"用法: /girl break <guid/-1> <level>";
|
||||
|
||||
public string NotFound => "角色不存在!";
|
||||
public string Added => "已為玩家新增 {0} 個角色!";
|
||||
public string UpdateLevel => "已將 {1} 個角色等級設為 {0}!";
|
||||
public string UpdateNeuronicLevel => "已將 {1} 個角色的神經元等級設置為 {0}!";
|
||||
public string UpdateBreakLevel => "已将 {1} 个角色的天啟/武格等级设置为 {0}!";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -242,7 +259,10 @@ public class GiveAllTextCHT
|
||||
public string Usage => "用法:/giveall weapon <detail/-1> -p<特定> -l<等級>\n" +
|
||||
"用法:/giveall weaponskin <detail/-1> -p<特定>\n" +
|
||||
"用法:/giveall card <detail/-1> -p<特定> -l<等級>" +
|
||||
"用法:/giveall profile <detail/-1> -g<類型> -p<特定> -l<等級>";
|
||||
"用法:/giveall profile <detail/-1> -g<類型> -p<特定> -l<等級>" +
|
||||
"用法:/giveall skinpart <detail/-1> -g<類型> -p<特定> -l<等級>" +
|
||||
"用法:/giveall weaponpart <detail/-1> -g<類型> -p<特定> -l<等級>" +
|
||||
"用法:/giveall call <detail/-1> -g<類型> -p<特定> -l<等級>";
|
||||
public string NotFound => "未找到 {0}!";
|
||||
public string GiveAllItems => "已向玩家添加 {0} 個 {1}!";
|
||||
}
|
||||
@@ -262,6 +282,14 @@ public class DebugTextCHT
|
||||
public string FileDisabled => "個人調試檔案輸出已停用。";
|
||||
}
|
||||
|
||||
public class GameCommandTextCHT
|
||||
{
|
||||
public string Desc => "使用補丁注入啟動已配置的遊戲";
|
||||
public string Usage => "用法: /game [額外遊戲參數]";
|
||||
public string Started => "遊戲已啟動。PID: {0}";
|
||||
public string Failed => "遊戲啟動失敗: {0}";
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
#endregion
|
||||
|
||||
@@ -35,6 +35,11 @@ public class ServerTextEN
|
||||
/// </summary>
|
||||
public class WordTextEN
|
||||
{
|
||||
public string Furniture => "Furniture";
|
||||
public string Skin => "Skin";
|
||||
public string WeaponPart => "Weapon Part";
|
||||
public string CallItem => "Call Item";
|
||||
public string SkinPart => "Skin Part";
|
||||
public string Profile => "Profile";
|
||||
public string WeaponSkin => "Weapon Skin";
|
||||
public string Valk => "Valkyrie";
|
||||
@@ -82,9 +87,11 @@ public class CommandTextEN
|
||||
{
|
||||
public NoticeTextEN Notice { get; } = new();
|
||||
public HelpTextEN Help { get; } = new();
|
||||
public AccountTextEN Account { get; } = new();
|
||||
public GirlTextEN Girl { get; } = new();
|
||||
public GiveAllTextEN GiveAll { get; } = new();
|
||||
public DebugTextEN Debug { get; } = new();
|
||||
public GameCommandTextEN Game { get; } = new();
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -178,6 +185,14 @@ public class HelpTextEN
|
||||
public string CommandAlias => "Command Alias:";
|
||||
}
|
||||
|
||||
public class AccountTextEN
|
||||
{
|
||||
public string Desc => "Manage account mappings for SDK logins";
|
||||
public string Usage => "Usage: /account create <email> <uid>";
|
||||
public string Created => "Created account mapping: {0} -> UID {1}";
|
||||
public string CreateFailed => "Failed to create account mapping: {0}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// path: Game.Command.Girl
|
||||
/// </summary>
|
||||
@@ -190,12 +205,14 @@ public class GirlTextEN
|
||||
public string Usage =>
|
||||
"Usage: /girl add <detail/-1> -p<particular> -l<level> -s<star>\n" +
|
||||
"Usage: /girl level <guid/-1> <level>\n" +
|
||||
"Usage: /girl neuronic <guid/-1> <level>";
|
||||
"Usage: /girl neuronic <guid/-1> <level>\n" +
|
||||
"Usage: /girl break <guid/-1> <level>";
|
||||
|
||||
public string NotFound => "Character not found!";
|
||||
public string Added => "Granted {0} character(s) to player!";
|
||||
public string UpdateLevel => "Set {1} character(s) to level {0}!";
|
||||
public string UpdateNeuronicLevel => "Set {1} character(s) Neuronic to level {0}!";
|
||||
public string UpdateBreakLevel => "Set {1} character(s) Manifestation to level {0}!";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -208,7 +225,10 @@ public class GiveAllTextEN
|
||||
public string Usage => "Usage: /giveall weapon <detail/-1> -p<particular> -l<level>\n" +
|
||||
"Usage: /giveall weaponskin <detail/-1> -p<particular>\n" +
|
||||
"Usage: /giveall card <detail/-1> -p<particular> -l<level>" +
|
||||
"Usage: /giveall profile <detail/-1> -g<genre> -p<particular> -l<level>";
|
||||
"Usage: /giveall profile <detail/-1> -g<genre> -p<particular> -l<level>" +
|
||||
"Usage: /giveall skinpart <detail/-1> -g<genre> -p<particular> -l<level>" +
|
||||
"Usage: /giveall weaponpart <detail/-1> -g<genre> -p<particular> -l<level>" +
|
||||
"Usage: /giveall call <detail/-1> -g<genre> -p<particular> -l<level>";
|
||||
public string NotFound => "{0} not found!";
|
||||
public string GiveAllItems => "Added {0} {1} to player!";
|
||||
}
|
||||
@@ -228,6 +248,14 @@ public class DebugTextEN
|
||||
public string FileDisabled => "Personal debug file output disabled.";
|
||||
}
|
||||
|
||||
public class GameCommandTextEN
|
||||
{
|
||||
public string Desc => "Launch the configured game with patch injection";
|
||||
public string Usage => "Usage: /game [extra game args]";
|
||||
public string Started => "Game launched. PID: {0}";
|
||||
public string Failed => "Failed to launch game: {0}";
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
#endregion
|
||||
|
||||
@@ -53,7 +53,7 @@ public class IConsole
|
||||
Console.WriteLine();
|
||||
Input = [];
|
||||
CursorIndex = 0;
|
||||
if (InputHistory.Count >= HistoryMaxCount)
|
||||
if (InputHistory.Count >= HistoryMaxCount)
|
||||
InputHistory.RemoveAt(0);
|
||||
InputHistory.Add(input);
|
||||
HistoryIndex = InputHistory.Count;
|
||||
@@ -80,7 +80,7 @@ public class IConsole
|
||||
public static void HandleUpArrow()
|
||||
{
|
||||
if (InputHistory.Count == 0) return;
|
||||
|
||||
|
||||
if (HistoryIndex > 0)
|
||||
{
|
||||
HistoryIndex--;
|
||||
@@ -94,7 +94,7 @@ public class IConsole
|
||||
public static void HandleDownArrow()
|
||||
{
|
||||
if (HistoryIndex >= InputHistory.Count) return;
|
||||
|
||||
|
||||
HistoryIndex++;
|
||||
if (HistoryIndex >= InputHistory.Count)
|
||||
{
|
||||
@@ -102,7 +102,7 @@ public class IConsole
|
||||
Input = [];
|
||||
CursorIndex = 0;
|
||||
}
|
||||
else
|
||||
else
|
||||
{
|
||||
var history = InputHistory[HistoryIndex];
|
||||
Input = [.. history];
|
||||
@@ -114,7 +114,7 @@ public class IConsole
|
||||
public static void HandleLeftArrow()
|
||||
{
|
||||
if (CursorIndex <= 0) return;
|
||||
|
||||
|
||||
var (left, _) = Console.GetCursorPosition();
|
||||
CursorIndex--;
|
||||
Console.SetCursorPosition(left - GetWidth(Input[CursorIndex].ToString()), Console.CursorTop);
|
||||
@@ -123,7 +123,7 @@ public class IConsole
|
||||
public static void HandleRightArrow()
|
||||
{
|
||||
if (CursorIndex >= Input.Count) return;
|
||||
|
||||
|
||||
var (left, _) = Console.GetCursorPosition();
|
||||
CursorIndex++;
|
||||
Console.SetCursorPosition(left + GetWidth(Input[CursorIndex - 1].ToString()), Console.CursorTop);
|
||||
@@ -148,13 +148,29 @@ public class IConsole
|
||||
|
||||
#endregion
|
||||
|
||||
public static string ListenConsole()
|
||||
public static async Task ListenConsole(CancellationToken exitToken)
|
||||
{
|
||||
while (true)
|
||||
while (!exitToken.IsCancellationRequested)
|
||||
{
|
||||
ConsoleKeyInfo keyInfo;
|
||||
try { keyInfo = Console.ReadKey(true); }
|
||||
catch (InvalidOperationException) { continue; }
|
||||
try
|
||||
{
|
||||
if (!Console.KeyAvailable)
|
||||
{
|
||||
await Task.Delay(10, exitToken);
|
||||
continue;
|
||||
}
|
||||
keyInfo = Console.ReadKey(true);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
await Task.Delay(50, exitToken);
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (keyInfo.Key)
|
||||
{
|
||||
|
||||
@@ -38,5 +38,21 @@
|
||||
"DebugMessage": true,
|
||||
"DebugDetailMessage": true,
|
||||
"DebugNoHandlerPacket": true
|
||||
},
|
||||
"Proxy": {
|
||||
"Enabled": true,
|
||||
"Port": 18888
|
||||
},
|
||||
"Loader": {
|
||||
"GamePath": "",
|
||||
"PatchPaths": [
|
||||
"Patch\\MikuSB-Patch.dll"
|
||||
],
|
||||
"Arguments": [
|
||||
"-FeatureLevelES31",
|
||||
"-channelid=seasun",
|
||||
"-NoSplash"
|
||||
],
|
||||
"SetAllProxy": true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
37
GameServer/Command/Commands/CommandAccount.cs
Normal file
37
GameServer/Command/Commands/CommandAccount.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
using MikuSB.Database.Account;
|
||||
using MikuSB.Enums.Player;
|
||||
using MikuSB.Internationalization;
|
||||
|
||||
namespace MikuSB.GameServer.Command.Commands;
|
||||
|
||||
[CommandInfo("account", "Game.Command.Account.Desc", "Game.Command.Account.Usage", [], [PermEnum.Admin, PermEnum.Support])]
|
||||
public class CommandAccount : ICommands
|
||||
{
|
||||
[CommandMethod("create")]
|
||||
public async ValueTask Create(CommandArg arg)
|
||||
{
|
||||
if (!await arg.CheckArgCnt(2))
|
||||
return;
|
||||
|
||||
var email = arg.Args[0].Trim();
|
||||
if (!int.TryParse(arg.Args[1], out var uid) || uid <= 0)
|
||||
{
|
||||
await arg.SendMsg(I18NManager.Translate("Game.Command.Notice.InvalidArguments"));
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var account = AccountData.CreateAccount(email, uid, "");
|
||||
await arg.SendMsg(I18NManager.Translate("Game.Command.Account.Created", account.Username, account.Uid.ToString()));
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
await arg.SendMsg(I18NManager.Translate("Game.Command.Account.CreateFailed", ex.Message));
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
await arg.SendMsg(I18NManager.Translate("Game.Command.Account.CreateFailed", ex.Message));
|
||||
}
|
||||
}
|
||||
}
|
||||
29
GameServer/Command/Commands/CommandGame.cs
Normal file
29
GameServer/Command/Commands/CommandGame.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using MikuSB.Enums.Player;
|
||||
using MikuSB.Internationalization;
|
||||
using MikuSB.Loader;
|
||||
using MikuSB.Util;
|
||||
|
||||
namespace MikuSB.GameServer.Command.Commands;
|
||||
|
||||
[CommandInfo("game", "Game.Command.Game.Desc", "Game.Command.Game.Usage", [], [PermEnum.Admin, PermEnum.Support])]
|
||||
public class CommandGame : ICommands
|
||||
{
|
||||
private static readonly Logger Logger = new("CommandManager");
|
||||
|
||||
[CommandDefault]
|
||||
public async ValueTask Launch(CommandArg arg)
|
||||
{
|
||||
try
|
||||
{
|
||||
var pid = GameLaunchService.Launch(arg.Args.ToArray());
|
||||
var message = I18NManager.Translate("Game.Command.Game.Started", pid.ToString());
|
||||
Logger.Info(message);
|
||||
await arg.SendMsg(message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Error("Failed to launch game.", ex);
|
||||
await arg.SendMsg(I18NManager.Translate("Game.Command.Game.Failed", ex.Message));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,4 +129,41 @@ public class CommandGirl : ICommands
|
||||
level.ToString(),
|
||||
girls.Count.ToString()));
|
||||
}
|
||||
|
||||
[CommandMethod("break")]
|
||||
public async ValueTask UpdateBreakLevel(CommandArg arg)
|
||||
{
|
||||
if (!await arg.CheckOnlineTarget()) return;
|
||||
if (!await arg.CheckArgCnt(2)) return;
|
||||
|
||||
var guid = arg.GetInt(0);
|
||||
var level = Math.Clamp(arg.GetInt(1), 0, 45);
|
||||
var player = arg.Target!.Player!;
|
||||
List<CharacterInfo> girls = [];
|
||||
|
||||
if (guid == -1)
|
||||
{
|
||||
foreach (var girl in player.CharacterManager.CharacterData.Characters)
|
||||
{
|
||||
girl.Break = (uint)level;
|
||||
girls.Add(girl);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var girl = player.CharacterManager.GetCharacterByGUID((uint)guid);
|
||||
if (girl == null)
|
||||
{
|
||||
await arg.SendMsg(I18NManager.Translate("Game.Command.Girl.NotFound"));
|
||||
return;
|
||||
}
|
||||
girl.Break = (uint)level;
|
||||
girls.Add(girl);
|
||||
}
|
||||
|
||||
if (girls.Count > 0) await player.SendPacket(new PacketNtfCallScript(girls));
|
||||
await arg.SendMsg(I18NManager.Translate("Game.Command.Girl.UpdateBreakLevel",
|
||||
level.ToString(),
|
||||
girls.Count.ToString()));
|
||||
}
|
||||
}
|
||||
@@ -150,4 +150,184 @@ public class CommandGiveAll : ICommands
|
||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
||||
I18NManager.Translate("Word.Profile"), profileItems.Count.ToString()));
|
||||
}
|
||||
|
||||
[CommandMethod("skinpart")]
|
||||
public async ValueTask GiveAllSkinPart(CommandArg arg)
|
||||
{
|
||||
if (!await arg.CheckOnlineTarget()) return;
|
||||
if (await arg.GetOption('p') is not int particular) return;
|
||||
if (await arg.GetOption('l') is not int level) return;
|
||||
if (await arg.GetOption('g') is not int genre) return;
|
||||
|
||||
var detail = arg.GetInt(0);
|
||||
var player = arg.Target!.Player!;
|
||||
List<BaseGameItemInfo> skinPartItems = [];
|
||||
if (detail == -1)
|
||||
{
|
||||
// add all
|
||||
foreach (var config in GameData.CardSkinPartsData.Values)
|
||||
{
|
||||
var skinPart = await player.InventoryManager!
|
||||
.AddSkinPartItem((ItemTypeEnum)config.Genre, config.Detail, config.Particular, config.Level, false);
|
||||
if (skinPart != null) skinPartItems.Add(skinPart);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var skinPart = await player.InventoryManager!.AddSkinPartItem((ItemTypeEnum)genre, (uint)detail, (uint)particular, (uint)level, false);
|
||||
if (skinPart == null)
|
||||
{
|
||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.NotFound", I18NManager.Translate("Word.SkinPart")));
|
||||
return;
|
||||
}
|
||||
skinPartItems.Add(skinPart);
|
||||
}
|
||||
if (skinPartItems.Count > 0) await player.SendPacket(new PacketNtfCallScript(skinPartItems));
|
||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
||||
I18NManager.Translate("Word.SkinPart"), skinPartItems.Count.ToString()));
|
||||
}
|
||||
|
||||
[CommandMethod("call")]
|
||||
public async ValueTask GiveAllCallItem(CommandArg arg)
|
||||
{
|
||||
if (!await arg.CheckOnlineTarget()) return;
|
||||
if (await arg.GetOption('p') is not int particular) return;
|
||||
if (await arg.GetOption('l') is not int level) return;
|
||||
if (await arg.GetOption('g') is not int genre) return;
|
||||
|
||||
var detail = arg.GetInt(0);
|
||||
var player = arg.Target!.Player!;
|
||||
List<BaseGameItemInfo> callItems = [];
|
||||
if (detail == -1)
|
||||
{
|
||||
// add all
|
||||
foreach (var config in GameData.CallItemData.Values)
|
||||
{
|
||||
var callItem = await player.InventoryManager!
|
||||
.AddCallItem((ItemTypeEnum)config.Genre, config.Detail, config.Particular, config.Level, false);
|
||||
if (callItem != null) callItems.Add(callItem);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var callItem = await player.InventoryManager!.AddCallItem((ItemTypeEnum)genre, (uint)detail, (uint)particular, (uint)level, false);
|
||||
if (callItem == null)
|
||||
{
|
||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.NotFound", I18NManager.Translate("Word.CallItem")));
|
||||
return;
|
||||
}
|
||||
callItems.Add(callItem);
|
||||
}
|
||||
if (callItems.Count > 0) await player.SendPacket(new PacketNtfCallScript(callItems));
|
||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
||||
I18NManager.Translate("Word.CallItem"), callItems.Count.ToString()));
|
||||
}
|
||||
|
||||
[CommandMethod("weaponpart")]
|
||||
public async ValueTask GiveAllWeaponPart(CommandArg arg)
|
||||
{
|
||||
if (!await arg.CheckOnlineTarget()) return;
|
||||
if (await arg.GetOption('p') is not int particular) return;
|
||||
if (await arg.GetOption('l') is not int level) return;
|
||||
if (await arg.GetOption('g') is not int genre) return;
|
||||
|
||||
var detail = arg.GetInt(0);
|
||||
var player = arg.Target!.Player!;
|
||||
List<BaseGameItemInfo> weaponPartItems = [];
|
||||
if (detail == -1)
|
||||
{
|
||||
// add all
|
||||
foreach (var config in GameData.WeaponPartsData.Values)
|
||||
{
|
||||
var weaponPart = await player.InventoryManager!
|
||||
.AddWeaponPartItem((ItemTypeEnum)config.Genre, config.Detail, config.Particular, config.Level, false);
|
||||
if (weaponPart != null) weaponPartItems.Add(weaponPart);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var weaponPart = await player.InventoryManager!.AddWeaponPartItem((ItemTypeEnum)genre, (uint)detail, (uint)particular, (uint)level, false);
|
||||
if (weaponPart == null)
|
||||
{
|
||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.NotFound", I18NManager.Translate("Word.WeaponPart")));
|
||||
return;
|
||||
}
|
||||
weaponPartItems.Add(weaponPart);
|
||||
}
|
||||
if (weaponPartItems.Count > 0) await player.SendPacket(new PacketNtfCallScript(weaponPartItems));
|
||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
||||
I18NManager.Translate("Word.WeaponPart"), weaponPartItems.Count.ToString()));
|
||||
}
|
||||
|
||||
[CommandMethod("skin")]
|
||||
public async ValueTask GiveAllSkin(CommandArg arg)
|
||||
{
|
||||
if (!await arg.CheckOnlineTarget()) return;
|
||||
if (await arg.GetOption('p') is not int particular) return;
|
||||
if (await arg.GetOption('l') is not int level) return;
|
||||
if (await arg.GetOption('g') is not int genre) return;
|
||||
|
||||
var detail = arg.GetInt(0);
|
||||
var player = arg.Target!.Player!;
|
||||
List<GameSkinInfo> skinItems = [];
|
||||
if (detail == -1)
|
||||
{
|
||||
// add all
|
||||
foreach (var config in GameData.CardSkinData.Values)
|
||||
{
|
||||
var skin = await player.InventoryManager!
|
||||
.AddSkinItem((ItemTypeEnum)config.Genre, config.Detail, config.Particular, config.Level, false);
|
||||
if (skin != null) skinItems.Add(skin);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var skin = await player.InventoryManager!.AddSkinItem((ItemTypeEnum)genre, (uint)detail, (uint)particular, (uint)level, false);
|
||||
if (skin == null)
|
||||
{
|
||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.NotFound", I18NManager.Translate("Word.Skin")));
|
||||
return;
|
||||
}
|
||||
skinItems.Add(skin);
|
||||
}
|
||||
if (skinItems.Count > 0) await player.SendPacket(new PacketNtfCallScript(skinItems));
|
||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
||||
I18NManager.Translate("Word.Skin"), skinItems.Count.ToString()));
|
||||
}
|
||||
|
||||
[CommandMethod("furniture")]
|
||||
public async ValueTask GiveAllHouseFurniture(CommandArg arg)
|
||||
{
|
||||
if (!await arg.CheckOnlineTarget()) return;
|
||||
if (await arg.GetOption('p') is not int particular) return;
|
||||
if (await arg.GetOption('l') is not int level) return;
|
||||
if (await arg.GetOption('g') is not int genre) return;
|
||||
|
||||
var detail = arg.GetInt(0);
|
||||
var player = arg.Target!.Player!;
|
||||
List<BaseGameItemInfo> furnitureItems = [];
|
||||
if (detail == -1)
|
||||
{
|
||||
// add all
|
||||
foreach (var config in GameData.DormGiftData.Values)
|
||||
{
|
||||
var furniture = await player.InventoryManager!
|
||||
.AddHouseFurnitureItem((ItemTypeEnum)config.Genre, config.Detail, config.Particular, config.Level, false);
|
||||
if (furniture != null) furnitureItems.Add(furniture);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var furniture = await player.InventoryManager!.AddHouseFurnitureItem((ItemTypeEnum)genre, (uint)detail, (uint)particular, (uint)level, false);
|
||||
if (furniture == null)
|
||||
{
|
||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.NotFound", I18NManager.Translate("Word.Furniture")));
|
||||
return;
|
||||
}
|
||||
furnitureItems.Add(furniture);
|
||||
}
|
||||
if (furnitureItems.Count > 0) await player.SendPacket(new PacketNtfCallScript(furnitureItems));
|
||||
await arg.SendMsg(I18NManager.Translate("Game.Command.GiveAll.GiveAllItems",
|
||||
I18NManager.Translate("Word.Furniture"), furnitureItems.Count.ToString()));
|
||||
}
|
||||
}
|
||||
@@ -27,11 +27,11 @@ public class CharacterManager(PlayerInstance player) : BasePlayerManager(player)
|
||||
Timestamp = Extensions.GetUnixSec()
|
||||
};
|
||||
|
||||
var weaponInfo = await Player.InventoryManager!.AddWeaponItem((ItemTypeEnum)CharacterExcel.DefaultWeaponGPDL[0], CharacterExcel.DefaultWeaponGPDL[1], CharacterExcel.DefaultWeaponGPDL[2], CharacterExcel.DefaultWeaponGPDL[3],sendPacket:false);
|
||||
var weaponInfo = await Player.InventoryManager!.AddWeaponItem((ItemTypeEnum)CharacterExcel.DefaultWeaponGPDL[0], CharacterExcel.DefaultWeaponGPDL[1], CharacterExcel.DefaultWeaponGPDL[2], CharacterExcel.DefaultWeaponGPDL[3],sendPacket: true);
|
||||
if (weaponInfo != null) character.WeaponUniqueId = weaponInfo.UniqueId;
|
||||
|
||||
var skinInfo = Player.InventoryManager!.GetSkinItemGDPL(ItemTypeEnum.TYPE_CARD_SKIN, detail, particular, level)
|
||||
?? await Player.InventoryManager!.AddSkinItem(ItemTypeEnum.TYPE_CARD_SKIN, detail, particular, level, false);
|
||||
?? await Player.InventoryManager!.AddSkinItem(ItemTypeEnum.TYPE_CARD_SKIN, detail, particular, level, true);
|
||||
if (skinInfo != null) character.SkinId = skinInfo.UniqueId;
|
||||
|
||||
if (sendPacket) await Player.SendPacket(new PacketNtfCallScript([character]));
|
||||
|
||||
@@ -270,4 +270,88 @@ public class InventoryManager(PlayerInstance player) : BasePlayerManager(player)
|
||||
|
||||
return profileInfo;
|
||||
}
|
||||
|
||||
public async ValueTask<BaseGameItemInfo?> AddSkinPartItem(ItemTypeEnum genre, uint detail, uint particular, uint level = 1, bool sendPacket = true)
|
||||
{
|
||||
if (genre != ItemTypeEnum.TYPE_CARD_SKIN_PART) return null;
|
||||
var skinPartData = GameData.CardSkinPartsData.Values.FirstOrDefault(x => x.Genre == (int)genre && x.Detail == detail && x.Particular == particular && x.Level == level);
|
||||
if (skinPartData == null) return null;
|
||||
var templateId = GameResourceTemplateId.FromGdpl((uint)genre, detail, particular, level);
|
||||
if (InventoryData.Items.Values.Any(x => x.TemplateId == templateId)) return null;
|
||||
var skinPartInfo = new BaseGameItemInfo
|
||||
{
|
||||
TemplateId = templateId,
|
||||
UniqueId = InventoryData.NextUniqueUid++,
|
||||
ItemType = genre,
|
||||
ItemCount = 1
|
||||
};
|
||||
InventoryData.Items[skinPartInfo.UniqueId] = skinPartInfo;
|
||||
|
||||
if (sendPacket) await Player.SendPacket(new PacketNtfCallScript([skinPartInfo]));
|
||||
|
||||
return skinPartInfo;
|
||||
}
|
||||
|
||||
public async ValueTask<BaseGameItemInfo?> AddCallItem(ItemTypeEnum genre, uint detail, uint particular, uint level = 1, bool sendPacket = true)
|
||||
{
|
||||
if (genre != ItemTypeEnum.TYPE_CALL) return null;
|
||||
var callData = GameData.CallItemData.Values.FirstOrDefault(x => x.Genre == (int)genre && x.Detail == detail && x.Particular == particular && x.Level == level);
|
||||
if (callData == null) return null;
|
||||
var templateId = GameResourceTemplateId.FromGdpl((uint)genre, detail, particular, level);
|
||||
if (InventoryData.Items.Values.Any(x => x.TemplateId == templateId)) return null;
|
||||
var callInfo = new BaseGameItemInfo
|
||||
{
|
||||
TemplateId = templateId,
|
||||
UniqueId = InventoryData.NextUniqueUid++,
|
||||
ItemType = genre,
|
||||
ItemCount = 1
|
||||
};
|
||||
InventoryData.Items[callInfo.UniqueId] = callInfo;
|
||||
|
||||
if (sendPacket) await Player.SendPacket(new PacketNtfCallScript([callInfo]));
|
||||
|
||||
return callInfo;
|
||||
}
|
||||
|
||||
public async ValueTask<BaseGameItemInfo?> AddWeaponPartItem(ItemTypeEnum genre, uint detail, uint particular, uint level = 1, bool sendPacket = true)
|
||||
{
|
||||
if (genre != ItemTypeEnum.TYPE_WEAPON_PART) return null;
|
||||
var weaponPartData = GameData.WeaponPartsData.Values.FirstOrDefault(x => x.Genre == (int)genre && x.Detail == detail && x.Particular == particular && x.Level == level);
|
||||
if (weaponPartData == null) return null;
|
||||
var templateId = GameResourceTemplateId.FromGdpl((uint)genre, detail, particular, level);
|
||||
if (InventoryData.Items.Values.Any(x => x.TemplateId == templateId)) return null;
|
||||
var weaponPartInfo = new BaseGameItemInfo
|
||||
{
|
||||
TemplateId = templateId,
|
||||
UniqueId = InventoryData.NextUniqueUid++,
|
||||
ItemType = genre,
|
||||
ItemCount = 1
|
||||
};
|
||||
InventoryData.Items[weaponPartInfo.UniqueId] = weaponPartInfo;
|
||||
|
||||
if (sendPacket) await Player.SendPacket(new PacketNtfCallScript([weaponPartInfo]));
|
||||
|
||||
return weaponPartInfo;
|
||||
}
|
||||
|
||||
public async ValueTask<BaseGameItemInfo?> AddHouseFurnitureItem(ItemTypeEnum genre, uint detail, uint particular, uint level = 1, bool sendPacket = true)
|
||||
{
|
||||
if (genre != ItemTypeEnum.TYPE_HOUSE) return null;
|
||||
var houseFurnitureData = GameData.DormGiftData.Values.FirstOrDefault(x => x.Genre == (int)genre && x.Detail == detail && x.Particular == particular && x.Level == level);
|
||||
if (houseFurnitureData == null) return null;
|
||||
var templateId = GameResourceTemplateId.FromGdpl((uint)genre, detail, particular, level);
|
||||
if (InventoryData.Items.Values.Any(x => x.TemplateId == templateId)) return null;
|
||||
var furnitureInfo = new BaseGameItemInfo
|
||||
{
|
||||
TemplateId = templateId,
|
||||
UniqueId = InventoryData.NextUniqueUid++,
|
||||
ItemType = genre,
|
||||
ItemCount = 1
|
||||
};
|
||||
InventoryData.Items[furnitureInfo.UniqueId] = furnitureInfo;
|
||||
|
||||
if (sendPacket) await Player.SendPacket(new PacketNtfCallScript([furnitureInfo]));
|
||||
|
||||
return furnitureInfo;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using Google.Protobuf;
|
||||
using Google.Protobuf;
|
||||
using MikuSB.Data;
|
||||
using MikuSB.Database;
|
||||
using MikuSB.Database.Account;
|
||||
@@ -226,10 +226,17 @@ public class PlayerInstance(PlayerGameData data)
|
||||
continue;
|
||||
}
|
||||
|
||||
proto.Attrs[ToPackedAttrKey(gid, sid)] = val;
|
||||
//ToDo
|
||||
//Temporary fix for login issues(need to handle LoginRsp properly with zlib.)
|
||||
//proto.Attrs[ToPackedAttrKey(gid, sid)] = val;
|
||||
proto.Attrs[ToShiftedAttrKey(gid, sid)] = val;
|
||||
}
|
||||
|
||||
foreach (var x in Data.StrAttrs)
|
||||
{
|
||||
proto.StrAttrs[ToShiftedAttrKey(x.Gid, x.Sid)] = x.Val;
|
||||
}
|
||||
|
||||
proto.ShowItems.AddRange(Data.ShowItems);
|
||||
|
||||
return proto;
|
||||
@@ -251,6 +258,22 @@ public class PlayerInstance(PlayerGameData data)
|
||||
Data.ShowItems[index - 1] = itemId;
|
||||
}
|
||||
|
||||
public void SetStrAttr(uint gid, uint sid, string value)
|
||||
{
|
||||
var attr = Data.StrAttrs.FirstOrDefault(x => x.Gid == gid && x.Sid == sid);
|
||||
if (attr == null)
|
||||
{
|
||||
attr = new PlayerStrAttr
|
||||
{
|
||||
Gid = gid,
|
||||
Sid = sid
|
||||
};
|
||||
Data.StrAttrs.Add(attr);
|
||||
}
|
||||
|
||||
attr.Val = value;
|
||||
}
|
||||
|
||||
public uint ToPackedAttrKey(uint gid, uint sid)
|
||||
{
|
||||
if (gid == 0)
|
||||
@@ -267,9 +290,10 @@ public class PlayerInstance(PlayerGameData data)
|
||||
return (gid << 16) | sid;
|
||||
}
|
||||
|
||||
public void BuildPlayerAttr()
|
||||
public void BuildPlayerAttr(bool additional = false)
|
||||
{
|
||||
var bootstrapAttrs = BuildLobbyBootstrapAttrs();
|
||||
var bootstrapAttrs = BuildLobbyBootstrapAttrs().ToList();
|
||||
if (additional) bootstrapAttrs.AddRange(BuildGirlFurnitureAttrs());
|
||||
var existingAttrs = Data.Attrs
|
||||
.ToDictionary(x => (x.Gid, x.Sid));
|
||||
var seenAttrs = new HashSet<(uint Gid, uint Sid)>();
|
||||
@@ -299,6 +323,24 @@ public class PlayerInstance(PlayerGameData data)
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<(uint Gid, uint Sid, uint Value)> BuildGirlFurnitureAttrs()
|
||||
{
|
||||
// Unlock some furniture slots for every girl
|
||||
// Each furniture attr int stores 10 slots using 3 bits per slot
|
||||
// Value below means slot 0..9 = 1
|
||||
const uint furnitureUnlockedValue = 153391689;
|
||||
|
||||
for (uint girlId = 0; girlId <= 50; girlId++)
|
||||
{
|
||||
// FurnitureStart..FurnitureEnd = 10..19
|
||||
for (uint offset = 10; offset <= 19; offset++)
|
||||
{
|
||||
uint sid = (girlId * 50) + offset;
|
||||
yield return (101, sid, furnitureUnlockedValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<(uint Gid, uint Sid, uint Value)> BuildLobbyBootstrapAttrs()
|
||||
{
|
||||
// GuideLogic uses group 4. Value 999 is safely above every configured step count,
|
||||
@@ -349,6 +391,14 @@ public class PlayerInstance(PlayerGameData data)
|
||||
yield return (22, levelId, 1_700_000_000);
|
||||
}
|
||||
|
||||
foreach (var guide in GameData.GuideData.Values)
|
||||
{
|
||||
yield return (4, guide.ID, 999);
|
||||
}
|
||||
|
||||
for (uint favor = 0; favor <= 50; favor++)
|
||||
yield return (101, favor * 50, 500);
|
||||
|
||||
// Main Scene 0 mean default scene
|
||||
yield return (132, 1, 0);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Library</OutputType>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<CETCompat>false</CETCompat>
|
||||
@@ -20,9 +20,9 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Common\Common.csproj" />
|
||||
<ProjectReference Include="..\MikuSB.Loader\MikuSB.Loader.csproj" />
|
||||
<ProjectReference Include="..\TcpSharp\TcpSharp.csproj" />
|
||||
<ProjectReference Include="..\Proto\Proto.csproj" />
|
||||
<PackageReference Include="System.IO.Pipelines" Version="9.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
using MikuSB.Data;
|
||||
using MikuSB.Database.Inventory;
|
||||
using MikuSB.Proto;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace MikuSB.GameServer.Server.CallGS.Handlers.Girl;
|
||||
|
||||
[CallGSApi("GirlSkinParts_Update")]
|
||||
public class GirlSkinParts_Update : ICallGSHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param, ushort seqNo)
|
||||
{
|
||||
var req = JsonSerializer.Deserialize<GirlSkinPartsUpdateParam>(param);
|
||||
if (req == null)
|
||||
{
|
||||
await CallGSRouter.SendScript(connection, "GirlSkinParts_Update", "{\"sErr\":\"error.BadParam\"}");
|
||||
return;
|
||||
}
|
||||
var player = connection.Player!;
|
||||
var data = new List<GameSkinInfo>();
|
||||
foreach(var partId in req.PartsId)
|
||||
{
|
||||
var partData = player.InventoryManager.GetNormalItem(partId);
|
||||
if (partData == null) continue;
|
||||
|
||||
var partExcel = GameData.CardSkinPartsData.Values.FirstOrDefault(x => x.TemplateId == partData.TemplateId);
|
||||
if (partExcel == null) continue;
|
||||
|
||||
var skinData = player.InventoryManager.GetSkinItem(req.SkinId);
|
||||
if (skinData == null) continue;
|
||||
|
||||
skinData.PartSlots[partExcel.Detail] = partData.UniqueId;
|
||||
data.Add(skinData);
|
||||
}
|
||||
|
||||
var sync = new NtfSyncPlayer
|
||||
{
|
||||
Items = { data.Select(x => x.ToProto()) }
|
||||
};
|
||||
await CallGSRouter.SendScript(connection, "GirlSkinParts_Update", "{}", sync);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class GirlSkinPartsUpdateParam
|
||||
{
|
||||
[JsonPropertyName("tbPartsID")]
|
||||
public List<uint> PartsId { get; set; } = [];
|
||||
|
||||
[JsonPropertyName("nSkinId")]
|
||||
public uint SkinId { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
using MikuSB.Proto;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace MikuSB.GameServer.Server.CallGS.Handlers.House;
|
||||
|
||||
[HouseFunc("ArcadeGameEnterMainUI")]
|
||||
public class ArcadeGameEnterMainUI : IHouseFuncHandler
|
||||
{
|
||||
private static readonly int[] ArcadeUnlockedGirlList = [1, 5, 13, 23, 10];
|
||||
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var unlockGirls = new JsonArray();
|
||||
foreach (var girlId in ArcadeUnlockedGirlList)
|
||||
unlockGirls.Add(girlId);
|
||||
|
||||
var rsp = new JsonObject
|
||||
{
|
||||
["tbUnlockGirlList"] = unlockGirls,
|
||||
["FuncName"] = "ArcadeGameEnterMainUI"
|
||||
};
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Success(rsp));
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("ArcadeGameEnter")]
|
||||
public class ArcadeGameEnter : IHouseFuncHandler
|
||||
{
|
||||
private static readonly Random Random = new();
|
||||
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var rsp = new JsonObject
|
||||
{
|
||||
["FuncName"] = "ArcadeGameEnter",
|
||||
["nSeed"] = Random.Next(1, 1_000_000_000)
|
||||
};
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Success(rsp));
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("ArcadeGameSettlement")]
|
||||
public class ArcadeGameSettlement : IHouseFuncHandler
|
||||
{
|
||||
private const uint HouseArcadeInfoStart = 18000;
|
||||
private const uint ArcadeAttrExpOffset = 2;
|
||||
private const uint ArcadeAttrEndlessScoreOffset = 4;
|
||||
private const uint ArcadeAttrGirlEndlessModeStateOffset = 5;
|
||||
private const uint ArcadeAttrGirlNormalModeStateOffset = 10;
|
||||
private const uint ArcadeAttrGirlNormalModeStateEndOffset = 35;
|
||||
private const uint ArcadeAttrConditionValStartOffset = 36;
|
||||
private const uint ArcadeAttrConditionValEndOffset = 55;
|
||||
private const uint ArcadeAttrPropUseStartOffset = 56;
|
||||
private const uint ArcadeAttrPropUseEndOffset = 250;
|
||||
private const int ArcadeGameModeNormal = 1;
|
||||
private const int ArcadeGameModeEndless = 2;
|
||||
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var root = HouseJson.ParseObject(param);
|
||||
if (root == null) return;
|
||||
|
||||
var player = connection.Player!;
|
||||
var sync = new NtfSyncPlayer();
|
||||
var modeType = HouseJson.NumField(root, "nModeType");
|
||||
var finishRound = Math.Max(0, HouseJson.NumField(root, "nFinishRound"));
|
||||
var maxScore = Math.Max(0, HouseJson.NumField(root, "nMaxScore"));
|
||||
|
||||
if (root["tbConditionVal"] is JsonArray conditions)
|
||||
{
|
||||
foreach (var conditionNode in conditions)
|
||||
{
|
||||
if (conditionNode is not JsonArray condition || condition.Count < 2) continue;
|
||||
var id = HouseJson.ToInt(condition[0]);
|
||||
var value = Math.Max(0, HouseJson.ToInt(condition[1]));
|
||||
if (id < 0) continue;
|
||||
var sid = HouseArcadeInfoStart + ArcadeAttrConditionValStartOffset + (uint)id;
|
||||
if (sid > HouseArcadeInfoStart + ArcadeAttrConditionValEndOffset) continue;
|
||||
var prev = HouseAttr.Read(player, sid);
|
||||
if ((uint)value > prev)
|
||||
await HouseAttr.SetAsync(connection, sid, (uint)value, sync);
|
||||
}
|
||||
}
|
||||
|
||||
if (root["tbPropUse"] is JsonArray propUses)
|
||||
{
|
||||
var slotStart = HouseArcadeInfoStart + ArcadeAttrPropUseStartOffset;
|
||||
var slotEnd = HouseArcadeInfoStart + ArcadeAttrPropUseEndOffset;
|
||||
var slotState = new Dictionary<uint, ArcadePropUseSlot>();
|
||||
var emptySlots = new Queue<uint>();
|
||||
for (uint sid = slotStart; sid <= slotEnd; sid++)
|
||||
{
|
||||
var value = HouseAttr.Read(player, sid);
|
||||
if (value == 0)
|
||||
{
|
||||
emptySlots.Enqueue(sid);
|
||||
continue;
|
||||
}
|
||||
|
||||
slotState[sid] = new ArcadePropUseSlot
|
||||
{
|
||||
Type = (byte)(value & 0xff),
|
||||
Id = (byte)((value >> 8) & 0xff),
|
||||
Count = (ushort)((value >> 16) & 0xffff)
|
||||
};
|
||||
}
|
||||
|
||||
foreach (var propUseNode in propUses)
|
||||
{
|
||||
if (propUseNode is not JsonArray propUse || propUse.Count < 3) continue;
|
||||
var type = HouseJson.ToInt(propUse[0]) & 0xff;
|
||||
var id = HouseJson.ToInt(propUse[1]) & 0xff;
|
||||
var count = HouseJson.ToInt(propUse[2]);
|
||||
if (count <= 0) continue;
|
||||
|
||||
uint? foundSid = null;
|
||||
foreach (var (sid, slot) in slotState)
|
||||
{
|
||||
if (slot.Type == type && slot.Id == id)
|
||||
{
|
||||
foundSid = sid;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (foundSid != null)
|
||||
{
|
||||
var slot = slotState[foundSid.Value];
|
||||
slot.Count = (ushort)Math.Min(0xffff, slot.Count + count);
|
||||
slotState[foundSid.Value] = slot;
|
||||
await HouseAttr.SetAsync(connection, foundSid.Value, HouseAttr.PackArcadePropUse(slot.Type, slot.Id, slot.Count), sync);
|
||||
}
|
||||
else if (emptySlots.Count > 0)
|
||||
{
|
||||
var sid = emptySlots.Dequeue();
|
||||
var packedCount = (ushort)Math.Min(0xffff, count);
|
||||
slotState[sid] = new ArcadePropUseSlot { Type = type, Id = id, Count = packedCount };
|
||||
await HouseAttr.SetAsync(connection, sid, HouseAttr.PackArcadePropUse(type, id, packedCount), sync);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var girlList = root["tbGirlDataList"] as JsonArray;
|
||||
var nAddExp = 0;
|
||||
if (modeType == ArcadeGameModeNormal)
|
||||
{
|
||||
if (girlList != null)
|
||||
{
|
||||
foreach (var girlNode in girlList)
|
||||
{
|
||||
var girlId = HouseJson.ToInt(girlNode);
|
||||
if (girlId <= 0) continue;
|
||||
var sid = HouseArcadeInfoStart + ArcadeAttrGirlNormalModeStateOffset + (uint)girlId;
|
||||
if (sid > HouseArcadeInfoStart + ArcadeAttrGirlNormalModeStateEndOffset) continue;
|
||||
var prev = HouseAttr.Read(player, sid);
|
||||
await HouseAttr.SetAsync(connection, sid, prev + (uint)finishRound, sync);
|
||||
}
|
||||
}
|
||||
nAddExp = finishRound * 10;
|
||||
}
|
||||
else if (modeType == ArcadeGameModeEndless)
|
||||
{
|
||||
var scoreSid = HouseArcadeInfoStart + ArcadeAttrEndlessScoreOffset;
|
||||
var prevScore = HouseAttr.Read(player, scoreSid);
|
||||
if ((uint)maxScore > prevScore)
|
||||
await HouseAttr.SetAsync(connection, scoreSid, (uint)maxScore, sync);
|
||||
|
||||
var bitsSid = HouseArcadeInfoStart + ArcadeAttrGirlEndlessModeStateOffset;
|
||||
var bits = HouseAttr.Read(player, bitsSid);
|
||||
var originalBits = bits;
|
||||
if (girlList != null)
|
||||
{
|
||||
foreach (var girlNode in girlList)
|
||||
{
|
||||
var girlId = HouseJson.ToInt(girlNode);
|
||||
if (girlId is > 0 and < 31)
|
||||
bits |= 1u << girlId;
|
||||
}
|
||||
}
|
||||
if (bits != originalBits)
|
||||
await HouseAttr.SetAsync(connection, bitsSid, bits, sync);
|
||||
|
||||
nAddExp = maxScore / 10;
|
||||
}
|
||||
|
||||
if (nAddExp > 0)
|
||||
{
|
||||
var expSid = HouseArcadeInfoStart + ArcadeAttrExpOffset;
|
||||
var prevExp = HouseAttr.Read(player, expSid);
|
||||
await HouseAttr.SetAsync(connection, expSid, prevExp + (uint)nAddExp, sync);
|
||||
}
|
||||
|
||||
var rsp = new JsonObject
|
||||
{
|
||||
["nAddExp"] = nAddExp,
|
||||
["FuncName"] = "ArcadeGameSettlement"
|
||||
};
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Success(rsp), sync);
|
||||
}
|
||||
|
||||
private struct ArcadePropUseSlot
|
||||
{
|
||||
public int Type { get; set; }
|
||||
public int Id { get; set; }
|
||||
public ushort Count { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("ArcadeGameLogSettlement")]
|
||||
public class ArcadeGameLogSettlement : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var rsp = new JsonObject { ["FuncName"] = "ArcadeGameLogSettlement" };
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Success(rsp));
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("ArcadeGameGetLevelReward")]
|
||||
public class ArcadeGameGetLevelReward : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var rsp = new JsonObject { ["FuncName"] = "ArcadeGameGetLevelReward" };
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Success(rsp));
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("ArcadeGameGetAchReward")]
|
||||
public class ArcadeGameGetAchReward : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var rsp = new JsonObject { ["FuncName"] = "ArcadeGameGetAchReward" };
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Success(rsp));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
using MikuSB.Proto;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace MikuSB.GameServer.Server.CallGS.Handlers.House;
|
||||
|
||||
[HouseFunc("GirlRegister")]
|
||||
public class GirlRegister : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var root = HouseJson.ParseObject(param);
|
||||
if (root == null) return;
|
||||
|
||||
var girlId = HouseJson.NumField(root, "GirlId");
|
||||
var floorId = HouseJson.NumField(root, "FloorId");
|
||||
var sync = new NtfSyncPlayer();
|
||||
if (girlId > 0)
|
||||
{
|
||||
var bedroomSid = HouseAttr.GetNextBedroomSid(connection.Player!, (uint)floorId);
|
||||
await HouseAttr.SetAsync(connection, HouseAttr.GirlRoomNumSid(girlId), HouseAttr.BedroomRegisteredNoRoom, sync);
|
||||
if (bedroomSid != 0) await HouseAttr.SetAsync(connection, bedroomSid, (uint)girlId, sync);
|
||||
}
|
||||
|
||||
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Synthesize(root), sync);
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("SetBedroomGirlId")]
|
||||
public class SetBedroomGirlId : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var root = HouseJson.ParseObject(param);
|
||||
if (root == null) return;
|
||||
|
||||
var bedroomId = HouseJson.NumField(root, "BedroomId");
|
||||
var girlId = HouseJson.NumField(root, "GirlId");
|
||||
var sync = new NtfSyncPlayer();
|
||||
if (bedroomId > 0 && girlId > 0)
|
||||
await HouseAttr.MoveGirlIntoRoomAsync(connection, girlId, bedroomId, sync);
|
||||
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Synthesize(root), sync);
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("GirlRoomChange")]
|
||||
public class GirlRoomChange : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var root = HouseJson.ParseObject(param);
|
||||
if (root == null) return;
|
||||
|
||||
var girlId = HouseJson.NumField(root, "GirlId");
|
||||
var roomId = HouseJson.NumField(root, "RoomId");
|
||||
var oldRoomId = girlId > 0 ? (int)HouseAttr.Read(connection.Player!, HouseAttr.GirlRoomNumSid(girlId)) : 0;
|
||||
var sync = new NtfSyncPlayer();
|
||||
if (girlId > 0 && roomId > 0)
|
||||
await HouseAttr.MoveGirlIntoRoomAsync(connection, girlId, roomId, sync);
|
||||
|
||||
var rsp = new JsonObject
|
||||
{
|
||||
["FuncName"] = "GirlRoomChangeSuccess",
|
||||
["GirlId"] = girlId,
|
||||
["OldRoomId"] = oldRoomId,
|
||||
["NewRoomId"] = roomId
|
||||
};
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Success(rsp), sync);
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("GirlLeaveRoom")]
|
||||
public class GirlLeaveRoom : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var root = HouseJson.ParseObject(param);
|
||||
if (root == null) return;
|
||||
|
||||
var bedroomId = HouseJson.NumField(root, "BedroomId");
|
||||
var girlId = HouseJson.NumField(root, "GirlId");
|
||||
var sync = new NtfSyncPlayer();
|
||||
if (bedroomId > 0 && girlId > 0)
|
||||
{
|
||||
await HouseAttr.SetAsync(connection, HouseAttr.BedroomSlotSid(bedroomId), 0, sync);
|
||||
await HouseAttr.SetAsync(connection, HouseAttr.GirlRoomNumSid(girlId), HouseAttr.BedroomRegisteredNoRoom, sync);
|
||||
}
|
||||
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Synthesize(root), sync);
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("ExchangeRoomGirl")]
|
||||
public class ExchangeRoomGirl : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var root = HouseJson.ParseObject(param);
|
||||
if (root == null) return;
|
||||
|
||||
var roomId1 = HouseJson.NumField(root, "RoomId1");
|
||||
var roomId2 = HouseJson.NumField(root, "RoomId2");
|
||||
var sync = new NtfSyncPlayer();
|
||||
if (roomId1 > 0 && roomId2 > 0 && roomId1 != roomId2)
|
||||
{
|
||||
var slot1 = HouseAttr.BedroomSlotSid(roomId1);
|
||||
var slot2 = HouseAttr.BedroomSlotSid(roomId2);
|
||||
var girl1 = HouseAttr.Read(connection.Player!, slot1);
|
||||
var girl2 = HouseAttr.Read(connection.Player!, slot2);
|
||||
await HouseAttr.SetAsync(connection, slot1, girl2, sync);
|
||||
await HouseAttr.SetAsync(connection, slot2, girl1, sync);
|
||||
if (girl1 > 0) await HouseAttr.SetAsync(connection, HouseAttr.GirlRoomNumSid((int)girl1), (uint)roomId2, sync);
|
||||
if (girl2 > 0) await HouseAttr.SetAsync(connection, HouseAttr.GirlRoomNumSid((int)girl2), (uint)roomId1, sync);
|
||||
}
|
||||
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Synthesize(root), sync);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using MikuSB.Proto;
|
||||
|
||||
namespace MikuSB.GameServer.Server.CallGS.Handlers.House;
|
||||
|
||||
[HouseFunc("SetGroupFurIndex")]
|
||||
public class SetGroupFurIndex : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var root = HouseJson.ParseObject(param);
|
||||
if (root == null) return;
|
||||
|
||||
var areaId = HouseJson.NumField(root, "AreaId");
|
||||
var groupId = HouseJson.NumField(root, "GroupId");
|
||||
var index = HouseJson.NumField(root, "Index");
|
||||
var sync = new NtfSyncPlayer();
|
||||
if (areaId > 0 && groupId is >= 1 and <= 10)
|
||||
{
|
||||
var sid = (uint)(areaId * 50 + 20);
|
||||
var prev = HouseAttr.Read(connection.Player!, sid);
|
||||
var shift = (groupId - 1) * 3;
|
||||
var mask = ~(0b111u << shift);
|
||||
var next = (prev & mask) | (((uint)index & 0b111u) << shift);
|
||||
await HouseAttr.SetAsync(connection, sid, next, sync, sendImmediate: true);
|
||||
}
|
||||
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Synthesize(root), sync);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using MikuSB.Proto;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace MikuSB.GameServer.Server.CallGS.Handlers.House;
|
||||
|
||||
[HouseFunc("SetPlayerRingInfo")]
|
||||
public class SetPlayerRingInfo : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var root = HouseJson.ParseObject(param);
|
||||
if (root == null) return;
|
||||
|
||||
var ringId = HouseJson.NumField(root, "RingId");
|
||||
var ringPos = HouseJson.NumField(root, "RingPos");
|
||||
var ringOffset = HouseJson.NumField(root, "RingOffset");
|
||||
var sync = new NtfSyncPlayer();
|
||||
if (ringPos is >= 1 and <= 10 && ringOffset is >= 0 and <= 2)
|
||||
{
|
||||
var sid = HouseAttr.PlayerRingInfoSidBase + (uint)ringPos;
|
||||
var prev = HouseAttr.Read(connection.Player!, sid);
|
||||
var shift = ringOffset * 10;
|
||||
var mask = ~(0x3ffu << shift);
|
||||
var next = (prev & mask) | (((uint)ringId & 0x3ffu) << shift);
|
||||
await HouseAttr.SetAsync(connection, sid, next, sync, deleteIfZero: true, sendImmediate: true);
|
||||
}
|
||||
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Synthesize(root), sync);
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("ReadGirlLoveStory")]
|
||||
public class ReadGirlLoveStory : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var root = HouseJson.ParseObject(param);
|
||||
if (root == null) return;
|
||||
|
||||
var girlId = HouseJson.NumField(root, "GirlId");
|
||||
var index = HouseJson.NumField(root, "Index");
|
||||
var sync = new NtfSyncPlayer();
|
||||
if (girlId > 0 && index is >= 0 and <= 30)
|
||||
{
|
||||
var sid = (uint)(girlId * 50 + 2);
|
||||
var prev = HouseAttr.Read(connection.Player!, sid);
|
||||
var next = prev | (1u << index);
|
||||
await HouseAttr.SetAsync(connection, sid, next, sync, sendImmediate: true);
|
||||
}
|
||||
|
||||
var rsp = new JsonObject
|
||||
{
|
||||
["GirlId"] = girlId,
|
||||
["Index"] = index,
|
||||
["tbReward"] = new JsonArray(),
|
||||
["FuncName"] = "ReadGirlLoveStorySuccess"
|
||||
};
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Success(rsp), sync);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using MikuSB.Proto;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace MikuSB.GameServer.Server.CallGS.Handlers.House;
|
||||
|
||||
[HouseFunc("UnLockWaterGunGameItem")]
|
||||
public class UnLockWaterGunGameItem : IHouseFuncHandler
|
||||
{
|
||||
private const uint HouseHotSpringInfoStart = 15000;
|
||||
private const uint WaterGunItemCollectBegin = 17;
|
||||
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var root = HouseJson.ParseObject(param);
|
||||
if (root == null) return;
|
||||
|
||||
var sync = new NtfSyncPlayer();
|
||||
if (root["tbItem"] is JsonArray items)
|
||||
{
|
||||
var touched = new Dictionary<uint, uint>();
|
||||
foreach (var node in items)
|
||||
{
|
||||
var itemId = HouseJson.ToInt(node);
|
||||
if (itemId is < 0 or > 60) continue;
|
||||
var offset = itemId / 30;
|
||||
var bit = itemId % 30;
|
||||
var sid = HouseHotSpringInfoStart + WaterGunItemCollectBegin + (uint)offset;
|
||||
var cur = touched.TryGetValue(sid, out var existing)
|
||||
? existing
|
||||
: HouseAttr.Read(connection.Player!, sid);
|
||||
touched[sid] = cur | (1u << bit);
|
||||
}
|
||||
|
||||
foreach (var (sid, value) in touched)
|
||||
await HouseAttr.SetAsync(connection, sid, value, sync);
|
||||
}
|
||||
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Synthesize(root), sync);
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("RouletteEnd")]
|
||||
public class RouletteEnd : IHouseFuncHandler
|
||||
{
|
||||
private const uint HouseHotSpringInfoStart = 15000;
|
||||
private const uint MaxRoundsInWaterGun = 16;
|
||||
private const uint HasCompleteGameGuide = 19;
|
||||
private const uint HotSpringGirlInfoStart = 15100;
|
||||
private const uint HotSpringGirlAttrCount = 10;
|
||||
private const uint HotSpringGirlHasCompleteStory = 1;
|
||||
private const int RoulettePlayModePlot = 1;
|
||||
private const int RoulettePlayModeEndless = 2;
|
||||
private const int RouletteEndReasonSuccess = 0;
|
||||
private const int RouletteTutorialGirlId = 5;
|
||||
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var root = HouseJson.ParseObject(param);
|
||||
if (root == null) return;
|
||||
|
||||
var modeType = HouseJson.NumField(root, "ModeType");
|
||||
var girlId = HouseJson.NumField(root, "GirlId");
|
||||
var isSuccess = HouseJson.NumField(root, "IsSuccess");
|
||||
var rounds = HouseJson.NumField(root, "Rounds");
|
||||
var sync = new NtfSyncPlayer();
|
||||
|
||||
if (isSuccess == RouletteEndReasonSuccess)
|
||||
{
|
||||
if (modeType == RoulettePlayModePlot && girlId > 0)
|
||||
{
|
||||
await HouseAttr.SetAsync(
|
||||
connection,
|
||||
HotSpringGirlInfoStart + (uint)(girlId * (int)HotSpringGirlAttrCount) + HotSpringGirlHasCompleteStory,
|
||||
1,
|
||||
sync);
|
||||
if (girlId == RouletteTutorialGirlId)
|
||||
await HouseAttr.SetAsync(connection, HouseHotSpringInfoStart + HasCompleteGameGuide, 1, sync);
|
||||
}
|
||||
else if (modeType == RoulettePlayModeEndless && rounds > 0)
|
||||
{
|
||||
var sid = HouseHotSpringInfoStart + MaxRoundsInWaterGun;
|
||||
var prev = HouseAttr.Read(connection.Player!, sid);
|
||||
if ((uint)rounds > prev)
|
||||
await HouseAttr.SetAsync(connection, sid, (uint)rounds, sync);
|
||||
}
|
||||
}
|
||||
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Synthesize(root), sync);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
using MikuSB.Proto;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace MikuSB.GameServer.Server.CallGS.Handlers.House;
|
||||
|
||||
[HouseFunc("ChangeNpcSuit")]
|
||||
public class ChangeNpcSuit : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var root = HouseJson.ParseObject(param);
|
||||
if (root == null) return;
|
||||
|
||||
var npcId = HouseJson.NumField(root, "NpcId");
|
||||
var suitId = HouseJson.NumField(root, "SuitId");
|
||||
var sync = new NtfSyncPlayer();
|
||||
await HouseAttr.SetAsync(connection, (uint)(npcId * 50 + 7), (uint)Math.Max(0, suitId), sync, sendImmediate: true);
|
||||
|
||||
var rsp = new JsonObject
|
||||
{
|
||||
["NpcId"] = npcId,
|
||||
["SuitId"] = suitId,
|
||||
["npcSuit"] = new JsonObject
|
||||
{
|
||||
["NpcId"] = npcId,
|
||||
["SuitId"] = suitId
|
||||
},
|
||||
["FuncName"] = "ChangeNpcSuitSuccess"
|
||||
};
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Success(rsp), sync);
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("ChangeNpcSuitByAreaId")]
|
||||
public class ChangeNpcSuitByAreaId : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var root = HouseJson.ParseObject(param);
|
||||
if (root == null) return;
|
||||
|
||||
var npcId = HouseJson.NumField(root, "NpcId");
|
||||
var areaId = HouseJson.NumField(root, "AreaId");
|
||||
var suitId = HouseJson.NumField(root, "SuitId");
|
||||
var sync = new NtfSyncPlayer();
|
||||
|
||||
if (npcId > 0 && areaId > 0)
|
||||
{
|
||||
uint[] slotSids = Enumerable.Range(24, 6).Select(i => (uint)(npcId * 50 + i)).ToArray();
|
||||
uint? chosenSid = null;
|
||||
foreach (var sid in slotSids)
|
||||
{
|
||||
if ((HouseAttr.Read(connection.Player!, sid) & 0xffffu) == (uint)areaId)
|
||||
{
|
||||
chosenSid = sid;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (chosenSid == null)
|
||||
{
|
||||
foreach (var sid in slotSids)
|
||||
{
|
||||
if (HouseAttr.Read(connection.Player!, sid) == 0)
|
||||
{
|
||||
chosenSid = sid;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
chosenSid ??= slotSids[0];
|
||||
var packed = (((uint)suitId & 0xffffu) << 16) | ((uint)areaId & 0xffffu);
|
||||
await HouseAttr.SetAsync(connection, chosenSid.Value, packed, sync, sendImmediate: true);
|
||||
}
|
||||
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Synthesize(root), sync);
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("ChangeGirlBeachSuitId")]
|
||||
public class ChangeGirlBeachSuitId : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var root = HouseJson.ParseObject(param);
|
||||
if (root == null) return;
|
||||
|
||||
var npcId = HouseJson.NumField(root, "NpcId");
|
||||
var suitId = HouseJson.NumField(root, "SuitId");
|
||||
var sync = new NtfSyncPlayer();
|
||||
if (npcId > 0)
|
||||
await HouseAttr.SetAsync(connection, (uint)(npcId * 50 + 8), (uint)Math.Max(0, suitId), sync, sendImmediate: true);
|
||||
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Synthesize(root), sync);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace MikuSB.GameServer.Server.CallGS.Handlers.House;
|
||||
|
||||
// PubGameEnter — returns nSeed for client-side game initialization.
|
||||
[HouseFunc("PubGameEnter")]
|
||||
public class PubGameEnter : IHouseFuncHandler
|
||||
{
|
||||
private static readonly Random Random = new();
|
||||
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var rsp = new JsonObject
|
||||
{
|
||||
["FuncName"] = "PubGameEnter",
|
||||
["nSeed"] = Random.Next(1, 1_000_000_000),
|
||||
["nModeType"] = 1,
|
||||
["bIsGuide"] = false,
|
||||
["bHasTry"] = false
|
||||
};
|
||||
await CallGSRouter.SendScript(connection, "House_Request", rsp.ToJsonString());
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("PubGameMulExit")]
|
||||
public class PubGameMulExit : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var rsp = new JsonObject { ["FuncName"] = "PubGameMulExit" };
|
||||
await CallGSRouter.SendScript(connection, "House_Request", rsp.ToJsonString());
|
||||
}
|
||||
}
|
||||
|
||||
// PubGameSettlement — nAddExp=0 on private server.
|
||||
[HouseFunc("PubGameSettlement")]
|
||||
public class PubGameSettlement : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var rsp = new JsonObject { ["FuncName"] = "PubGameSettlement", ["nAddExp"] = 0 };
|
||||
await CallGSRouter.SendScript(connection, "House_Request", rsp.ToJsonString());
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("PubGameGetReward")]
|
||||
public class PubGameGetReward : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var rsp = new JsonObject { ["FuncName"] = "PubGameGetReward" };
|
||||
await CallGSRouter.SendScript(connection, "House_Request", rsp.ToJsonString());
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("PubGameGetAchReward")]
|
||||
public class PubGameGetAchReward : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var rsp = new JsonObject { ["FuncName"] = "PubGameGetAchReward" };
|
||||
await CallGSRouter.SendScript(connection, "House_Request", rsp.ToJsonString());
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("PubGameAchievementFinish")]
|
||||
public class PubGameAchievementFinish : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var rsp = new JsonObject { ["FuncName"] = "PubGameAchievementFinish" };
|
||||
await CallGSRouter.SendScript(connection, "House_Request", rsp.ToJsonString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
using MikuSB.Database.Player;
|
||||
using MikuSB.GameServer.Game.Player;
|
||||
using MikuSB.Proto;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace MikuSB.GameServer.Server.CallGS.Handlers.House;
|
||||
|
||||
internal static class HouseRequestScript
|
||||
{
|
||||
internal static readonly Dictionary<string, string> FuncNameMap = new()
|
||||
{
|
||||
["ChangeGirlBeachSuitId"] = "ChangeGirlBeachSuitIdSuccess",
|
||||
["ChangeNpcSuitByAreaId"] = "ChangeNpcSuitByAreaIdRsp",
|
||||
["SetGroupFurIndex"] = "SetGroupFurSuccess",
|
||||
["RouletteEnd"] = "RouletteEndRsp",
|
||||
["UnLockWaterGunGameItem"] = "UnLockWaterGunGameItemRsp",
|
||||
["ChangeNpcSuit"] = "ChangeNpcSuitSuccess",
|
||||
["GiveGiftToArea"] = "GiveGiftToAreaSuccess",
|
||||
["BuyRefreshMapTimes"] = "BuyRefreshMapTimesSuccess",
|
||||
["CompleteHousePuzzleTask"] = "CompleteHousePuzzleTaskSuccess",
|
||||
["CompleteStarWishTask"] = "CompleteStarWishTaskSuccess",
|
||||
["SetPlayerRingInfo"] = "SetPlayerRingInfoSuccess",
|
||||
["ReadGirlLoveStory"] = "ReadGirlLoveStorySuccess",
|
||||
["GirlRoomChange"] = "GirlRoomChangeSuccess",
|
||||
["GirlRegister"] = "GirlRegisterSuccess"
|
||||
};
|
||||
|
||||
internal static string Synthesize(JsonObject request)
|
||||
{
|
||||
var funcName = request["FuncName"]?.GetValue<string>();
|
||||
var response = CreateSuccessObject();
|
||||
foreach (var (key, value) in request)
|
||||
{
|
||||
if (key is "FuncName" or "tblog")
|
||||
continue;
|
||||
|
||||
response[key] = value?.DeepClone();
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(funcName))
|
||||
response["FuncName"] = FuncNameMap.TryGetValue(funcName, out var renamed) ? renamed : funcName;
|
||||
|
||||
return response.ToJsonString();
|
||||
}
|
||||
|
||||
internal static string Success(JsonObject? extra = null) => CreateSuccessObject(extra).ToJsonString();
|
||||
|
||||
internal static JsonObject CreateSuccessObject(JsonObject? extra = null)
|
||||
{
|
||||
var response = new JsonObject
|
||||
{
|
||||
["bSuccess"] = true,
|
||||
["nResult"] = 0
|
||||
};
|
||||
|
||||
if (extra != null)
|
||||
{
|
||||
foreach (var (key, value) in extra)
|
||||
response[key] = value?.DeepClone();
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class HouseJson
|
||||
{
|
||||
internal static JsonObject? ParseObject(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonNode.Parse(json) as JsonObject;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
internal static int NumField(JsonObject? obj, string name) => ToInt(obj?[name]);
|
||||
|
||||
internal static int ToInt(JsonNode? node)
|
||||
{
|
||||
if (node == null) return 0;
|
||||
try
|
||||
{
|
||||
if (node is JsonValue value)
|
||||
{
|
||||
if (value.TryGetValue<int>(out var i)) return i;
|
||||
if (value.TryGetValue<uint>(out var u)) return unchecked((int)u);
|
||||
if (value.TryGetValue<long>(out var l)) return unchecked((int)l);
|
||||
if (value.TryGetValue<string>(out var s) && int.TryParse(s, out var parsed)) return parsed;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class HouseAttr
|
||||
{
|
||||
internal const uint Gid = 101;
|
||||
internal const uint BedroomStartSid = 2550;
|
||||
internal const uint BedroomRegisteredNoRoom = 100;
|
||||
internal const uint PlayerRingInfoSidBase = 3174;
|
||||
internal const uint BedroomPerFloor = 8;
|
||||
|
||||
internal static uint Read(PlayerInstance player, uint sid)
|
||||
{
|
||||
var attr = player.Data.Attrs.FirstOrDefault(x => x.Gid == Gid && x.Sid == sid);
|
||||
return attr?.Val ?? 0;
|
||||
}
|
||||
|
||||
internal static async Task SetAsync(
|
||||
Connection connection,
|
||||
uint sid,
|
||||
uint value,
|
||||
NtfSyncPlayer sync,
|
||||
bool deleteIfZero = false,
|
||||
bool sendImmediate = false)
|
||||
{
|
||||
var player = connection.Player!;
|
||||
var attr = player.Data.Attrs.FirstOrDefault(x => x.Gid == Gid && x.Sid == sid);
|
||||
if (value == 0 && deleteIfZero)
|
||||
{
|
||||
if (attr != null)
|
||||
player.Data.Attrs.Remove(attr);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (attr == null)
|
||||
{
|
||||
attr = new PlayerAttr { Gid = Gid, Sid = sid };
|
||||
player.Data.Attrs.Add(attr);
|
||||
}
|
||||
attr.Val = value;
|
||||
}
|
||||
|
||||
sync.Custom[player.ToPackedAttrKey(Gid, sid)] = value;
|
||||
sync.Custom[player.ToShiftedAttrKey(Gid, sid)] = value;
|
||||
if (sendImmediate)
|
||||
await player.SendPacket(CmdIds.NtfSetAttr, new NtfSetAttr { Gid = Gid, Sid = sid, Val = value });
|
||||
}
|
||||
|
||||
internal static uint BedroomSlotSid(int roomId) => BedroomStartSid + (uint)roomId;
|
||||
|
||||
internal static uint GirlRoomNumSid(int girlId) => (uint)(girlId * 50 + 1);
|
||||
|
||||
internal static async Task MoveGirlIntoRoomAsync(Connection connection, int girlId, int roomId, NtfSyncPlayer sync)
|
||||
{
|
||||
var player = connection.Player!;
|
||||
var oldRoom = (int)Read(player, GirlRoomNumSid(girlId));
|
||||
var targetSlotSid = BedroomSlotSid(roomId);
|
||||
var oldSlotSid = oldRoom is >= 1 and < 100 ? BedroomSlotSid(oldRoom) : 0;
|
||||
var occupant = Read(player, targetSlotSid);
|
||||
|
||||
await SetAsync(connection, targetSlotSid, (uint)girlId, sync);
|
||||
await SetAsync(connection, GirlRoomNumSid(girlId), (uint)roomId, sync);
|
||||
|
||||
if (oldRoom is >= 1 and < 100 && oldRoom != roomId)
|
||||
await SetAsync(connection, oldSlotSid, 0, sync);
|
||||
|
||||
if (occupant > 0 && occupant != (uint)girlId)
|
||||
{
|
||||
if (oldRoom is >= 1 and < 100 && oldRoom != roomId)
|
||||
{
|
||||
await SetAsync(connection, oldSlotSid, occupant, sync);
|
||||
await SetAsync(connection, GirlRoomNumSid((int)occupant), (uint)oldRoom, sync);
|
||||
}
|
||||
else
|
||||
{
|
||||
await SetAsync(connection, GirlRoomNumSid((int)occupant), BedroomRegisteredNoRoom, sync);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static uint GetNextBedroomSid(PlayerInstance player, uint floorId)
|
||||
{
|
||||
var floorStartSid = BedroomStartSid + ((floorId - 2) * BedroomPerFloor) + 1;
|
||||
|
||||
for (uint i = 0; i < BedroomPerFloor; i++)
|
||||
{
|
||||
var sid = floorStartSid + i;
|
||||
|
||||
var exists = player.Data.Attrs.Any(x =>
|
||||
x.Gid == Gid &&
|
||||
x.Sid == sid);
|
||||
|
||||
if (!exists)
|
||||
return sid;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal static uint PackArcadePropUse(int type, int id, ushort count) =>
|
||||
(((uint)count & 0xffffu) << 16) | (((uint)id & 0xffu) << 8) | ((uint)type & 0xffu);
|
||||
}
|
||||
117
GameServer/Server/CallGS/Handlers/House/House_Func/HouseThrow.cs
Normal file
117
GameServer/Server/CallGS/Handlers/House/House_Func/HouseThrow.cs
Normal file
@@ -0,0 +1,117 @@
|
||||
using MikuSB.Proto;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace MikuSB.GameServer.Server.CallGS.Handlers.House;
|
||||
|
||||
[HouseFunc("GameEnterMainUI")]
|
||||
public class ThrowGameEnterMainUI : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var rsp = new JsonObject
|
||||
{
|
||||
["FuncName"] = "GameEnterMainUI",
|
||||
["tblockGirlList"] = new JsonArray()
|
||||
};
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Success(rsp));
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("ThrowGameTutorialFinish")]
|
||||
public class ThrowGameTutorialFinish : IHouseFuncHandler
|
||||
{
|
||||
private const uint HouseBeachInfoStart = 17000;
|
||||
private const uint ThrowGameTutorialOffset = 10;
|
||||
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var root = HouseJson.ParseObject(param);
|
||||
if (root == null) return;
|
||||
|
||||
var index = Math.Max(0, HouseJson.NumField(root, "Index"));
|
||||
var sync = new NtfSyncPlayer();
|
||||
await HouseAttr.SetAsync(connection, HouseBeachInfoStart + ThrowGameTutorialOffset + (uint)index, 1, sync);
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Synthesize(root), sync);
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("ThrowGameEnter")]
|
||||
public class ThrowGameEnter : IHouseFuncHandler
|
||||
{
|
||||
private static readonly Random Random = new();
|
||||
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var rsp = new JsonObject
|
||||
{
|
||||
["FuncName"] = "ThrowGameEnter",
|
||||
["nSeed"] = Random.Next(1, 1_000_000_000)
|
||||
};
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Success(rsp));
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("ThrowGameSettlement")]
|
||||
public class ThrowGameSettlement : IHouseFuncHandler
|
||||
{
|
||||
private const uint HouseBeachInfoStart = 17000;
|
||||
private const uint ThrowGameChallengePointsOffset = 2;
|
||||
private const uint ThrowGameUnlockDrinkStartOffset = 50;
|
||||
private const int ThrowGameModeChallenge = 2;
|
||||
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var root = HouseJson.ParseObject(param);
|
||||
if (root == null) return;
|
||||
|
||||
var modeType = HouseJson.NumField(root, "nModeType");
|
||||
var score = Math.Max(0, HouseJson.NumField(root, "nScore"));
|
||||
var sync = new NtfSyncPlayer();
|
||||
if (root["tbUnlockDrink"] is JsonObject unlockDrink && unlockDrink["nDrinkIDs"] is JsonArray drinks)
|
||||
{
|
||||
foreach (var drinkNode in drinks)
|
||||
{
|
||||
var drinkId = HouseJson.ToInt(drinkNode);
|
||||
if (drinkId <= 0) continue;
|
||||
var sid = HouseBeachInfoStart + ThrowGameUnlockDrinkStartOffset + (uint)drinkId;
|
||||
var prev = HouseAttr.Read(connection.Player!, sid);
|
||||
await HouseAttr.SetAsync(connection, sid, prev + 1, sync);
|
||||
}
|
||||
}
|
||||
|
||||
if (modeType == ThrowGameModeChallenge && score > 0)
|
||||
{
|
||||
var sid = HouseBeachInfoStart + ThrowGameChallengePointsOffset;
|
||||
var prev = HouseAttr.Read(connection.Player!, sid);
|
||||
if ((uint)score > prev)
|
||||
await HouseAttr.SetAsync(connection, sid, (uint)score, sync);
|
||||
}
|
||||
|
||||
var rsp = new JsonObject
|
||||
{
|
||||
["nAddExp"] = score,
|
||||
["FuncName"] = "ThrowGameSettlement"
|
||||
};
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Success(rsp), sync);
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("ThrowGameGetLevelReward")]
|
||||
public class ThrowGameGetLevelReward : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var rsp = new JsonObject { ["FuncName"] = "ThrowGameGetLevelReward" };
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Success(rsp));
|
||||
}
|
||||
}
|
||||
|
||||
[HouseFunc("ThrowGameGetAchReward")]
|
||||
public class ThrowGameGetAchReward : IHouseFuncHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param)
|
||||
{
|
||||
var rsp = new JsonObject { ["FuncName"] = "ThrowGameGetAchReward" };
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Success(rsp));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace MikuSB.GameServer.Server.CallGS.Handlers.House;
|
||||
|
||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
|
||||
public class HouseFuncAttribute(string funcName) : Attribute
|
||||
{
|
||||
public string FuncName { get; } = funcName;
|
||||
}
|
||||
|
||||
public interface IHouseFuncHandler
|
||||
{
|
||||
Task Handle(Connection connection, string param);
|
||||
}
|
||||
42
GameServer/Server/CallGS/Handlers/House/House_Request.cs
Normal file
42
GameServer/Server/CallGS/Handlers/House/House_Request.cs
Normal file
@@ -0,0 +1,42 @@
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace MikuSB.GameServer.Server.CallGS.Handlers.House;
|
||||
|
||||
[CallGSApi("House_Request")]
|
||||
public class House_Request : ICallGSHandler
|
||||
{
|
||||
private static readonly Dictionary<string, IHouseFuncHandler> Handlers = [];
|
||||
|
||||
static House_Request()
|
||||
{
|
||||
foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
|
||||
{
|
||||
foreach (var attr in type.GetCustomAttributes<HouseFuncAttribute>())
|
||||
Handlers[attr.FuncName] = (IHouseFuncHandler)Activator.CreateInstance(type)!;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task Handle(Connection connection, string param, ushort seqNo)
|
||||
{
|
||||
var req = JsonSerializer.Deserialize<HouseRequestParam>(param);
|
||||
if (req?.FuncName == null) return;
|
||||
|
||||
if (Handlers.TryGetValue(req.FuncName, out var handler))
|
||||
{
|
||||
await handler.Handle(connection, param);
|
||||
return;
|
||||
}
|
||||
|
||||
var root = HouseJson.ParseObject(param);
|
||||
if (root == null) return;
|
||||
await CallGSRouter.SendScript(connection, "House_Request", HouseRequestScript.Synthesize(root));
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class HouseRequestParam
|
||||
{
|
||||
[JsonPropertyName("FuncName")]
|
||||
public string? FuncName { get; set; }
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using MikuSB.Database;
|
||||
using MikuSB.Enums.Player;
|
||||
using MikuSB.Proto;
|
||||
using System.Text.Json;
|
||||
@@ -22,6 +23,7 @@ public class PlayerSetting_ChangeShowCard : ICallGSHandler
|
||||
return;
|
||||
}
|
||||
player.SetShowItem((int)ProfileShowItemTypeEnum.SHOWITEM_GIRL, card.Guid);
|
||||
DatabaseHelper.SaveDatabaseType(player.Data);
|
||||
var sync = new NtfSyncPlayer();
|
||||
sync.ShowItems.AddRange(player.Data.ShowItems);
|
||||
await CallGSRouter.SendScript(connection, "PlayerSetting_ChangeShowCard", "{}", sync);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using MikuSB.Enums.Player;
|
||||
using MikuSB.Database;
|
||||
using MikuSB.Enums.Player;
|
||||
using MikuSB.Proto;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
@@ -35,7 +36,7 @@ public class PlayerSetting_SetProfileFace : ICallGSHandler
|
||||
}
|
||||
player.SetShowItem((int)ProfileShowItemTypeEnum.SHOWITEM_FRAME, item.UniqueId);
|
||||
}
|
||||
|
||||
DatabaseHelper.SaveDatabaseType(player.Data);
|
||||
var sync = new NtfSyncPlayer();
|
||||
sync.ShowItems.AddRange(player.Data.ShowItems);
|
||||
await CallGSRouter.SendScript(connection, "PlayerSetting_SetProfileFace", "null", sync);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using MikuSB.Enums.Player;
|
||||
using MikuSB.Database;
|
||||
using MikuSB.Enums.Player;
|
||||
using MikuSB.Proto;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
@@ -30,6 +31,8 @@ public class PlayerSetting_SetShowBadge : ICallGSHandler
|
||||
player.SetShowItem((int)slots[i], uniqueId);
|
||||
}
|
||||
|
||||
DatabaseHelper.SaveDatabaseType(player.Data);
|
||||
|
||||
var sync = new NtfSyncPlayer();
|
||||
sync.ShowItems.AddRange(player.Data.ShowItems);
|
||||
await CallGSRouter.SendScript(connection, "PlayerSetting_SetShowBadge", "null", sync);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using MikuSB.Enums.Player;
|
||||
using MikuSB.Database;
|
||||
using MikuSB.Enums.Player;
|
||||
using MikuSB.Proto;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
@@ -23,6 +24,8 @@ public class PlayerSetting_SetShowBubble : ICallGSHandler
|
||||
}
|
||||
|
||||
player.SetShowItem((int)ProfileShowItemTypeEnum.SHOWITEM_BUBBLE, item.UniqueId);
|
||||
DatabaseHelper.SaveDatabaseType(player.Data);
|
||||
|
||||
var sync = new NtfSyncPlayer();
|
||||
sync.ShowItems.AddRange(player.Data.ShowItems);
|
||||
await CallGSRouter.SendScript(connection, "PlayerSetting_SetShowBubble", "null", sync);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using MikuSB.Enums.Player;
|
||||
using MikuSB.Database;
|
||||
using MikuSB.Enums.Player;
|
||||
using MikuSB.Proto;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
@@ -23,6 +24,8 @@ public class PlayerSetting_SetShowCover : ICallGSHandler
|
||||
}
|
||||
|
||||
player.SetShowItem((int)ProfileShowItemTypeEnum.SHOWITEM_COVER, item.UniqueId);
|
||||
DatabaseHelper.SaveDatabaseType(player.Data);
|
||||
|
||||
var sync = new NtfSyncPlayer();
|
||||
sync.ShowItems.AddRange(player.Data.ShowItems);
|
||||
await CallGSRouter.SendScript(connection, "PlayerSetting_SetShowCover", "null", sync);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using MikuSB.Enums.Player;
|
||||
using MikuSB.Database;
|
||||
using MikuSB.Enums.Player;
|
||||
using MikuSB.Proto;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
@@ -23,6 +24,8 @@ public class PlayerSetting_SetShowNameCard : ICallGSHandler
|
||||
}
|
||||
|
||||
player.SetShowItem((int)ProfileShowItemTypeEnum.SHOWITEM_NAMECARD, item.UniqueId);
|
||||
DatabaseHelper.SaveDatabaseType(player.Data);
|
||||
|
||||
var sync = new NtfSyncPlayer();
|
||||
sync.ShowItems.AddRange(player.Data.ShowItems);
|
||||
await CallGSRouter.SendScript(connection, "PlayerSetting_SetShowNameCard", "null", sync);
|
||||
|
||||
39
GameServer/Server/CallGS/Handlers/Misc/SettingChange.cs
Normal file
39
GameServer/Server/CallGS/Handlers/Misc/SettingChange.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using MikuSB.Proto;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace MikuSB.GameServer.Server.CallGS.Handlers.Misc;
|
||||
|
||||
[CallGSApi("SettingChange")]
|
||||
public class SettingChange : ICallGSHandler
|
||||
{
|
||||
private const uint PlayerSettingGid = 44;
|
||||
|
||||
public async Task Handle(Connection connection, string param, ushort seqNo)
|
||||
{
|
||||
var changes = JsonSerializer.Deserialize<List<SettingChangeParam>>(param) ?? [];
|
||||
var player = connection.Player!;
|
||||
var sync = new NtfSyncPlayer();
|
||||
|
||||
foreach (var change in changes)
|
||||
{
|
||||
var value = player.Data.StrAttrs
|
||||
.FirstOrDefault(x => x.Gid == PlayerSettingGid && x.Sid == change.Id)?
|
||||
.Val;
|
||||
|
||||
if (value == null)
|
||||
continue;
|
||||
|
||||
sync.CustomStr[player.ToShiftedAttrKey(PlayerSettingGid, change.Id)] = value;
|
||||
}
|
||||
|
||||
if (sync.CustomStr.Count > 0)
|
||||
await connection.SendPacket(CmdIds.NtfSyncAttr, sync);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class SettingChangeParam
|
||||
{
|
||||
[JsonPropertyName("id")]
|
||||
public uint Id { get; set; }
|
||||
}
|
||||
178
GameServer/Server/CallGS/Handlers/Rogue3D/Rogue3DStateHelper.cs
Normal file
178
GameServer/Server/CallGS/Handlers/Rogue3D/Rogue3DStateHelper.cs
Normal file
@@ -0,0 +1,178 @@
|
||||
using MikuSB.Data;
|
||||
using MikuSB.Database.Player;
|
||||
using MikuSB.GameServer.Game.Player;
|
||||
using MikuSB.Proto;
|
||||
|
||||
namespace MikuSB.GameServer.Server.CallGS.Handlers.Rogue3D;
|
||||
|
||||
internal static class Rogue3DStateHelper
|
||||
{
|
||||
private const uint GroupId = 124;
|
||||
private const uint LevelPassStart = 20;
|
||||
private const uint DailyBuffStart = 51;
|
||||
private const uint DailyBuffEnd = 65;
|
||||
private const int DailyBuffBitCount = 10;
|
||||
private const int DailyBuffBitsPerValue = DailyBuffBitCount + 1;
|
||||
private const uint DailyBuffMask = (1u << DailyBuffBitCount) - 1;
|
||||
private const uint UnlockDiff1Sid = LevelPassStart + 1;
|
||||
private const uint UnlockDiff2Sid = LevelPassStart + 2;
|
||||
private const uint UnlockDiff3Sid = LevelPassStart + 3;
|
||||
private const uint UnlockDiff4Sid = LevelPassStart + 4;
|
||||
private static uint[]? ShuffledDailyBuffIds;
|
||||
|
||||
public static NtfSyncPlayer EnsureUnlockState(PlayerInstance player)
|
||||
{
|
||||
var sync = new NtfSyncPlayer();
|
||||
|
||||
EnsureMinAttr(player, UnlockDiff1Sid, 1, sync);
|
||||
EnsureMinAttr(player, UnlockDiff2Sid, 1, sync);
|
||||
EnsureMinAttr(player, UnlockDiff3Sid, 1, sync);
|
||||
EnsureMinAttr(player, UnlockDiff4Sid, 1, sync);
|
||||
|
||||
foreach (var scienceSid in GetUnlockTalentScienceSids())
|
||||
{
|
||||
EnsureMinAttr(player, scienceSid, 1, sync);
|
||||
}
|
||||
|
||||
EnsureDailyBuffAttrs(player, sync);
|
||||
|
||||
return sync;
|
||||
}
|
||||
|
||||
private static IEnumerable<uint> GetUnlockTalentScienceSids()
|
||||
{
|
||||
return GameData.Rogue3DTalentData.Values
|
||||
.Select(x => x.UnlockCondition)
|
||||
.Where(x => x > 0)
|
||||
.Distinct()
|
||||
.OrderBy(x => x);
|
||||
}
|
||||
|
||||
private static void EnsureDailyBuffAttrs(PlayerInstance player, NtfSyncPlayer sync)
|
||||
{
|
||||
var buffIds = GetOrCreateDailyBuffIds()
|
||||
.Take((int)(DailyBuffEnd - DailyBuffStart + 1) * 3)
|
||||
.ToArray();
|
||||
|
||||
var index = 0;
|
||||
for (var sid = DailyBuffStart; sid <= DailyBuffEnd; sid++)
|
||||
{
|
||||
uint packed = 0;
|
||||
for (var slot = 0; slot < 3 && index < buffIds.Length; slot++, index++)
|
||||
{
|
||||
packed |= (buffIds[index] & DailyBuffMask) << (slot * DailyBuffBitsPerValue);
|
||||
}
|
||||
|
||||
SetAttr(player, sid, packed, sync);
|
||||
}
|
||||
}
|
||||
|
||||
private static uint[] GetOrCreateDailyBuffIds()
|
||||
{
|
||||
if (ShuffledDailyBuffIds != null)
|
||||
{
|
||||
return ShuffledDailyBuffIds;
|
||||
}
|
||||
|
||||
var groupedBuffIds = GameData.Rogue3DDailyBuffData.Values
|
||||
.Where(x => x.ScoreBuffId > 0 && x.ScoreBuffId <= DailyBuffMask)
|
||||
.GroupBy(x => x.GroupId)
|
||||
.OrderBy(x => x.Key)
|
||||
.Select(x => x
|
||||
.OrderBy(y => y.Id)
|
||||
.Select(y => y.ScoreBuffId)
|
||||
.Distinct()
|
||||
.ToList())
|
||||
.ToList();
|
||||
|
||||
var random = new Random();
|
||||
foreach (var group in groupedBuffIds)
|
||||
{
|
||||
Shuffle(group, random);
|
||||
}
|
||||
Shuffle(groupedBuffIds, random);
|
||||
|
||||
var buffIds = new List<uint>();
|
||||
var indexByGroup = new int[groupedBuffIds.Count];
|
||||
var hasRemaining = true;
|
||||
|
||||
while (hasRemaining)
|
||||
{
|
||||
hasRemaining = false;
|
||||
for (var i = 0; i < groupedBuffIds.Count; i++)
|
||||
{
|
||||
var group = groupedBuffIds[i];
|
||||
var index = indexByGroup[i];
|
||||
if (index >= group.Count)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
buffIds.Add(group[index]);
|
||||
indexByGroup[i] = index + 1;
|
||||
hasRemaining = true;
|
||||
}
|
||||
}
|
||||
|
||||
ShuffledDailyBuffIds = buffIds.ToArray();
|
||||
return ShuffledDailyBuffIds;
|
||||
}
|
||||
|
||||
private static IEnumerable<uint> GetDailyBuffIds()
|
||||
{
|
||||
return GetOrCreateDailyBuffIds();
|
||||
}
|
||||
|
||||
private static void Shuffle<T>(IList<T> list, Random random)
|
||||
{
|
||||
for (var i = list.Count - 1; i > 0; i--)
|
||||
{
|
||||
var swapIndex = random.Next(i + 1);
|
||||
(list[i], list[swapIndex]) = (list[swapIndex], list[i]);
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureMinAttr(PlayerInstance player, uint sid, uint value, NtfSyncPlayer sync, bool overwrite = false)
|
||||
{
|
||||
var attr = player.Data.Attrs.FirstOrDefault(x => x.Gid == GroupId && x.Sid == sid);
|
||||
if (attr == null)
|
||||
{
|
||||
attr = new PlayerAttr { Gid = GroupId, Sid = sid, Val = value };
|
||||
player.Data.Attrs.Add(attr);
|
||||
AddSync(player, sync, sid, value);
|
||||
return;
|
||||
}
|
||||
|
||||
if ((!overwrite && attr.Val >= value) || (overwrite && attr.Val == value))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
attr.Val = value;
|
||||
AddSync(player, sync, sid, value);
|
||||
}
|
||||
|
||||
private static void SetAttr(PlayerInstance player, uint sid, uint value, NtfSyncPlayer sync)
|
||||
{
|
||||
var attr = player.Data.Attrs.FirstOrDefault(x => x.Gid == GroupId && x.Sid == sid);
|
||||
if (attr == null)
|
||||
{
|
||||
attr = new PlayerAttr { Gid = GroupId, Sid = sid };
|
||||
player.Data.Attrs.Add(attr);
|
||||
}
|
||||
|
||||
if (attr.Val == value)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
attr.Val = value;
|
||||
AddSync(player, sync, sid, value);
|
||||
}
|
||||
|
||||
private static void AddSync(PlayerInstance player, NtfSyncPlayer sync, uint sid, uint value)
|
||||
{
|
||||
sync.Custom[player.ToPackedAttrKey(GroupId, sid)] = value;
|
||||
sync.Custom[player.ToShiftedAttrKey(GroupId, sid)] = value;
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ public class Rogue3D_CheckOpenAct : ICallGSHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param, ushort seqNo)
|
||||
{
|
||||
await CallGSRouter.SendScript(connection, "Rogue3D_CheckOpenAct", "{\"bOpen\":true}");
|
||||
var sync = Rogue3DStateHelper.EnsureUnlockState(connection.Player!);
|
||||
await CallGSRouter.SendScript(connection, "Rogue3D_CheckOpenAct", "{\"bOpen\":true}", sync);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ public class Rogue3D_SelectMode : ICallGSHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param, ushort seqNo)
|
||||
{
|
||||
await CallGSRouter.SendScript(connection, "Rogue3D_SelectMode", "{}");
|
||||
var sync = Rogue3DStateHelper.EnsureUnlockState(connection.Player!);
|
||||
await CallGSRouter.SendScript(connection, "Rogue3D_SelectMode", "{}", sync);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
using MikuSB.Proto;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace MikuSB.GameServer.Server.CallGS.Handlers.Girl;
|
||||
|
||||
[CallGSApi("Weapon_ReplacePart")]
|
||||
public class Weapon_ReplacePart : ICallGSHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param, ushort seqNo)
|
||||
{
|
||||
var req = JsonSerializer.Deserialize<WeaponPartReplaceParam>(param);
|
||||
if (req == null)
|
||||
{
|
||||
await CallGSRouter.SendScript(connection, "Weapon_ReplacePart", "{\"sErr\":\"error.BadParam\"}");
|
||||
return;
|
||||
}
|
||||
|
||||
var player = connection.Player!;
|
||||
var weaponData = player.InventoryManager.GetWeaponItem(req.Id);
|
||||
if (weaponData == null)
|
||||
{
|
||||
await CallGSRouter.SendScript(connection, "Weapon_ReplacePart", "{}");
|
||||
return;
|
||||
}
|
||||
|
||||
uint partId = 0;
|
||||
if (req.PartId != -1)
|
||||
{
|
||||
var partData = player.InventoryManager.GetNormalItem((uint)req.PartId);
|
||||
if (partData != null) partId = partData.UniqueId;
|
||||
}
|
||||
|
||||
weaponData.PartSlots[req.Type] = partId;
|
||||
var sync = new NtfSyncPlayer
|
||||
{
|
||||
Items = { weaponData.ToProto() }
|
||||
};
|
||||
await CallGSRouter.SendScript(connection, "Weapon_ReplacePart", "null", sync);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class WeaponPartReplaceParam
|
||||
{
|
||||
public int PartId { get; set; }
|
||||
public uint Type { get; set; }
|
||||
public uint Id { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using MikuSB.Enums.Item;
|
||||
using MikuSB.Proto;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace MikuSB.GameServer.Server.CallGS.Handlers.Girl;
|
||||
|
||||
[CallGSApi("Weapon_ShowDefaultPart")]
|
||||
public class Weapon_ShowDefaultPart : ICallGSHandler
|
||||
{
|
||||
public async Task Handle(Connection connection, string param, ushort seqNo)
|
||||
{
|
||||
var req = JsonSerializer.Deserialize<WeaponShowDefaultPartParam>(param);
|
||||
if (req == null)
|
||||
{
|
||||
await CallGSRouter.SendScript(connection, "Weapon_ShowDefaultPart", "{\"sErr\":\"error.BadParam\"}");
|
||||
return;
|
||||
}
|
||||
|
||||
var player = connection.Player!;
|
||||
var weaponData = player.InventoryManager.GetWeaponItem(req.Id);
|
||||
if (weaponData == null)
|
||||
{
|
||||
await CallGSRouter.SendScript(connection, "Weapon_ShowDefaultPart", "{}");
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.Flag == 1) weaponData.Flag = ItemFlagEnum.FLAG_WEAPON_DEFAULT;
|
||||
else weaponData.Flag = ItemFlagEnum.FLAG_READED;
|
||||
|
||||
var sync = new NtfSyncPlayer
|
||||
{
|
||||
Items = { weaponData.ToProto() }
|
||||
};
|
||||
await CallGSRouter.SendScript(connection, "Weapon_ShowDefaultPart", "null", sync);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class WeaponShowDefaultPartParam
|
||||
{
|
||||
[JsonPropertyName("nFlag")] public int Flag { get; set; }
|
||||
public uint Id { get; set; }
|
||||
}
|
||||
@@ -21,11 +21,13 @@ public class HandlerReqLogin : Handler
|
||||
public override async Task OnHandle(Connection connection, byte[] data, ushort seqNo)
|
||||
{
|
||||
var req = ReqLogin.Parser.ParseFrom(data);
|
||||
var account = AccountData.GetAccountByUid(1);
|
||||
var account = AccountData.GetAccountByComboToken(req.Token)
|
||||
?? AccountData.GetAccountByDispatchToken(req.Token)
|
||||
?? AccountData.GetAccountByUid(10001)
|
||||
?? AccountData.GetAccountByUid(1);
|
||||
if (account == null)
|
||||
{
|
||||
AccountData.CreateAccount("MIKU", 0, "");
|
||||
account = AccountData.GetAccountByUid(1);
|
||||
account = AccountData.CreateAccount("default@mikusb.local", 10001, "");
|
||||
if (account == null)
|
||||
{
|
||||
await connection.SendPacket(CmdIds.NtfLogout);
|
||||
@@ -53,6 +55,7 @@ public class HandlerReqLogin : Handler
|
||||
await connection.Player.OnEnterGame();
|
||||
connection.Player.Connection = connection;
|
||||
await connection.SendPacket(new PacketRspLogin(connection.Player!));
|
||||
await connection.SendPacket(new PacketNtfCallScript(connection.Player!));
|
||||
await SendDebugLoginState(connection);
|
||||
|
||||
await connection.Player.OnHeartBeat();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using MikuSB.Database.Player;
|
||||
using MikuSB.Database;
|
||||
using MikuSB.Database.Player;
|
||||
using MikuSB.Proto;
|
||||
|
||||
namespace MikuSB.GameServer.Server.Packet.Recv.Login;
|
||||
@@ -12,7 +13,11 @@ public class HandlerNtfSetAttr : Handler
|
||||
var player = connection.Player!;
|
||||
var attr = player.Data.Attrs
|
||||
.FirstOrDefault(x => x.Gid == req.Gid && x.Sid == req.Sid);
|
||||
if (attr != null) attr.Val = req.Val;
|
||||
|
||||
if (attr != null)
|
||||
{
|
||||
attr.Val = req.Val;
|
||||
}
|
||||
else
|
||||
{
|
||||
player.Data.Attrs.Add(new PlayerAttr
|
||||
@@ -22,6 +27,7 @@ public class HandlerNtfSetAttr : Handler
|
||||
Val = req.Val
|
||||
});
|
||||
}
|
||||
DatabaseHelper.SaveDatabaseType(player.Data);
|
||||
await player.OnHeartBeat();
|
||||
}
|
||||
}
|
||||
|
||||
19
GameServer/Server/Packet/Recv/Player/HandlerNtfSetStrAttr.cs
Normal file
19
GameServer/Server/Packet/Recv/Player/HandlerNtfSetStrAttr.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using MikuSB.Database;
|
||||
using MikuSB.Proto;
|
||||
|
||||
namespace MikuSB.GameServer.Server.Packet.Recv.Login;
|
||||
|
||||
[Opcode(CmdIds.NtfSetStrAttr)]
|
||||
public class HandlerNtfSetStrAttr : Handler
|
||||
{
|
||||
public override async Task OnHandle(Connection connection, byte[] data, ushort seqNo)
|
||||
{
|
||||
var req = NtfSetStrAttr.Parser.ParseFrom(data);
|
||||
var player = connection.Player!;
|
||||
|
||||
player.SetStrAttr(req.Gid, req.Sid, req.Val);
|
||||
DatabaseHelper.SaveDatabaseType(player.Data);
|
||||
|
||||
await player.OnHeartBeat();
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,21 @@ public class PacketNtfCallScript : BasePacket
|
||||
SetData(proto);
|
||||
}
|
||||
|
||||
public PacketNtfCallScript(List<GameSkinInfo> skins) : base(CmdIds.NtfScript)
|
||||
{
|
||||
var proto = new NtfCallScript
|
||||
{
|
||||
Api = "",
|
||||
Arg = "{}",
|
||||
ExtraSync = new NtfSyncPlayer
|
||||
{
|
||||
Items = { skins.Select(x => x.ToProto()) }
|
||||
}
|
||||
};
|
||||
|
||||
SetData(proto);
|
||||
}
|
||||
|
||||
public PacketNtfCallScript(InventoryData inventory) : base(CmdIds.NtfScript)
|
||||
{
|
||||
var proto = new NtfCallScript
|
||||
@@ -87,7 +102,7 @@ public class PacketNtfCallScript : BasePacket
|
||||
|
||||
public PacketNtfCallScript(PlayerInstance Player) : base(CmdIds.NtfScript)
|
||||
{
|
||||
Player.BuildPlayerAttr();
|
||||
Player.BuildPlayerAttr(true);
|
||||
var proto = new NtfCallScript
|
||||
{
|
||||
Api = "",
|
||||
|
||||
357
MikuSB.Loader/GameLaunchService.cs
Normal file
357
MikuSB.Loader/GameLaunchService.cs
Normal file
@@ -0,0 +1,357 @@
|
||||
using System.Collections;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using MikuSB.Util;
|
||||
|
||||
namespace MikuSB.Loader;
|
||||
|
||||
public static class GameLaunchService
|
||||
{
|
||||
public static int Launch(params string[] extraGameArguments)
|
||||
{
|
||||
ConfigManager.LoadConfig();
|
||||
var options = LaunchOptions.FromConfig(extraGameArguments);
|
||||
return Launch(options);
|
||||
}
|
||||
|
||||
public static int Launch(LaunchOptions options)
|
||||
{
|
||||
var startupInfo = new STARTUPINFOW
|
||||
{
|
||||
cb = Marshal.SizeOf<STARTUPINFOW>()
|
||||
};
|
||||
|
||||
var commandLine = BuildCommandLine(options.GamePath, options.GameArguments);
|
||||
var workingDirectory = options.WorkingDirectory ?? Path.GetDirectoryName(options.GamePath)
|
||||
?? throw new InvalidOperationException("Unable to determine working directory.");
|
||||
|
||||
var environment = BuildEnvironmentBlock(options.EnvironmentVariables);
|
||||
try
|
||||
{
|
||||
if (!CreateProcessW(
|
||||
lpApplicationName: options.GamePath,
|
||||
lpCommandLine: commandLine,
|
||||
lpProcessAttributes: IntPtr.Zero,
|
||||
lpThreadAttributes: IntPtr.Zero,
|
||||
bInheritHandles: false,
|
||||
dwCreationFlags: CreationFlags.CREATE_SUSPENDED | CreationFlags.CREATE_UNICODE_ENVIRONMENT,
|
||||
lpEnvironment: environment,
|
||||
lpCurrentDirectory: workingDirectory,
|
||||
lpStartupInfo: ref startupInfo,
|
||||
lpProcessInformation: out var processInfo))
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to create game process.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
foreach (var patchPath in options.PatchPaths)
|
||||
InjectDll(processInfo.hProcess, patchPath);
|
||||
|
||||
if (ResumeThread(processInfo.hThread) == uint.MaxValue)
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to resume game process.");
|
||||
|
||||
return processInfo.dwProcessId;
|
||||
}
|
||||
finally
|
||||
{
|
||||
CloseHandle(processInfo.hThread);
|
||||
CloseHandle(processInfo.hProcess);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (environment != IntPtr.Zero)
|
||||
Marshal.FreeHGlobal(environment);
|
||||
}
|
||||
}
|
||||
|
||||
private static void InjectDll(IntPtr processHandle, string dllPath)
|
||||
{
|
||||
var dllBytes = Encoding.Unicode.GetBytes(dllPath + '\0');
|
||||
var remoteBuffer = VirtualAllocEx(
|
||||
processHandle,
|
||||
IntPtr.Zero,
|
||||
(nuint)dllBytes.Length,
|
||||
AllocationType.Commit | AllocationType.Reserve,
|
||||
MemoryProtection.ReadWrite);
|
||||
|
||||
if (remoteBuffer == IntPtr.Zero)
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error(), "VirtualAllocEx failed.");
|
||||
|
||||
try
|
||||
{
|
||||
if (!WriteProcessMemory(processHandle, remoteBuffer, dllBytes, dllBytes.Length, out var written) ||
|
||||
written.ToInt64() != dllBytes.Length)
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error(), "WriteProcessMemory failed.");
|
||||
}
|
||||
|
||||
var kernel32 = GetModuleHandleW("kernel32.dll");
|
||||
if (kernel32 == IntPtr.Zero)
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error(), "GetModuleHandleW(kernel32.dll) failed.");
|
||||
|
||||
var loadLibrary = GetProcAddress(kernel32, "LoadLibraryW");
|
||||
if (loadLibrary == IntPtr.Zero)
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error(), "GetProcAddress(LoadLibraryW) failed.");
|
||||
|
||||
var remoteThread = CreateRemoteThread(
|
||||
processHandle,
|
||||
IntPtr.Zero,
|
||||
0,
|
||||
loadLibrary,
|
||||
remoteBuffer,
|
||||
0,
|
||||
out _);
|
||||
|
||||
if (remoteThread == IntPtr.Zero)
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error(), "CreateRemoteThread failed.");
|
||||
|
||||
try
|
||||
{
|
||||
var waitResult = WaitForSingleObject(remoteThread, 10_000);
|
||||
if (waitResult != 0)
|
||||
throw new Win32Exception($"Remote LoadLibraryW timed out or failed: {waitResult}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
CloseHandle(remoteThread);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
VirtualFreeEx(processHandle, remoteBuffer, 0, FreeType.Release);
|
||||
}
|
||||
}
|
||||
|
||||
private static string BuildCommandLine(string exePath, IReadOnlyList<string> gameArgs)
|
||||
{
|
||||
var parts = new List<string> { Quote(exePath) };
|
||||
parts.AddRange(gameArgs.Select(Quote));
|
||||
return string.Join(' ', parts);
|
||||
}
|
||||
|
||||
private static IntPtr BuildEnvironmentBlock(IReadOnlyDictionary<string, string> variables)
|
||||
{
|
||||
if (variables.Count == 0)
|
||||
return IntPtr.Zero;
|
||||
|
||||
var merged = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
|
||||
merged[(string)entry.Key] = entry.Value?.ToString() ?? string.Empty;
|
||||
|
||||
foreach (var pair in variables)
|
||||
merged[pair.Key] = pair.Value;
|
||||
|
||||
var payload = string.Join('\0', merged.OrderBy(x => x.Key, StringComparer.OrdinalIgnoreCase)
|
||||
.Select(x => $"{x.Key}={x.Value}")) + "\0\0";
|
||||
|
||||
return Marshal.StringToHGlobalUni(payload);
|
||||
}
|
||||
|
||||
private static string Quote(string value)
|
||||
{
|
||||
if (value.Length == 0)
|
||||
return "\"\"";
|
||||
|
||||
if (!value.Any(char.IsWhiteSpace) && !value.Contains('"'))
|
||||
return value;
|
||||
|
||||
return "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
|
||||
}
|
||||
|
||||
[Flags]
|
||||
private enum CreationFlags : uint
|
||||
{
|
||||
CREATE_SUSPENDED = 0x00000004,
|
||||
CREATE_UNICODE_ENVIRONMENT = 0x00000400
|
||||
}
|
||||
|
||||
[Flags]
|
||||
private enum AllocationType : uint
|
||||
{
|
||||
Commit = 0x1000,
|
||||
Reserve = 0x2000
|
||||
}
|
||||
|
||||
[Flags]
|
||||
private enum MemoryProtection : uint
|
||||
{
|
||||
ReadWrite = 0x04
|
||||
}
|
||||
|
||||
[Flags]
|
||||
private enum FreeType : uint
|
||||
{
|
||||
Release = 0x8000
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
private struct STARTUPINFOW
|
||||
{
|
||||
public int cb;
|
||||
public string? lpReserved;
|
||||
public string? lpDesktop;
|
||||
public string? lpTitle;
|
||||
public int dwX;
|
||||
public int dwY;
|
||||
public int dwXSize;
|
||||
public int dwYSize;
|
||||
public int dwXCountChars;
|
||||
public int dwYCountChars;
|
||||
public int dwFillAttribute;
|
||||
public int dwFlags;
|
||||
public short wShowWindow;
|
||||
public short cbReserved2;
|
||||
public IntPtr lpReserved2;
|
||||
public IntPtr hStdInput;
|
||||
public IntPtr hStdOutput;
|
||||
public IntPtr hStdError;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct PROCESS_INFORMATION
|
||||
{
|
||||
public IntPtr hProcess;
|
||||
public IntPtr hThread;
|
||||
public int dwProcessId;
|
||||
public int dwThreadId;
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern bool CreateProcessW(
|
||||
string? lpApplicationName,
|
||||
string lpCommandLine,
|
||||
IntPtr lpProcessAttributes,
|
||||
IntPtr lpThreadAttributes,
|
||||
bool bInheritHandles,
|
||||
CreationFlags dwCreationFlags,
|
||||
IntPtr lpEnvironment,
|
||||
string? lpCurrentDirectory,
|
||||
ref STARTUPINFOW lpStartupInfo,
|
||||
out PROCESS_INFORMATION lpProcessInformation);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern IntPtr VirtualAllocEx(
|
||||
IntPtr hProcess,
|
||||
IntPtr lpAddress,
|
||||
nuint dwSize,
|
||||
AllocationType flAllocationType,
|
||||
MemoryProtection flProtect);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool VirtualFreeEx(
|
||||
IntPtr hProcess,
|
||||
IntPtr lpAddress,
|
||||
nuint dwSize,
|
||||
FreeType dwFreeType);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool WriteProcessMemory(
|
||||
IntPtr hProcess,
|
||||
IntPtr lpBaseAddress,
|
||||
byte[] lpBuffer,
|
||||
int nSize,
|
||||
out IntPtr lpNumberOfBytesWritten);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern IntPtr GetModuleHandleW(string lpModuleName);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern IntPtr CreateRemoteThread(
|
||||
IntPtr hProcess,
|
||||
IntPtr lpThreadAttributes,
|
||||
nuint dwStackSize,
|
||||
IntPtr lpStartAddress,
|
||||
IntPtr lpParameter,
|
||||
uint dwCreationFlags,
|
||||
out int lpThreadId);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern uint ResumeThread(IntPtr hThread);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool CloseHandle(IntPtr hObject);
|
||||
}
|
||||
|
||||
public sealed class LaunchOptions
|
||||
{
|
||||
public required string GamePath { get; init; }
|
||||
public required IReadOnlyList<string> PatchPaths { get; init; }
|
||||
public string? WorkingDirectory { get; init; }
|
||||
public required IReadOnlyList<string> GameArguments { get; init; }
|
||||
public required IReadOnlyDictionary<string, string> EnvironmentVariables { get; init; }
|
||||
|
||||
public static LaunchOptions FromConfig(IEnumerable<string>? extraGameArguments = null)
|
||||
{
|
||||
var config = ConfigManager.Config;
|
||||
var gamePath = ResolvePath(config.Loader.GamePath, AppContext.BaseDirectory);
|
||||
var patchPaths = ResolvePatchPaths(config.Loader.PatchPaths, AppContext.BaseDirectory);
|
||||
var gameArgs = new List<string>(config.Loader.Arguments ?? []);
|
||||
if (extraGameArguments is not null)
|
||||
gameArgs.AddRange(extraGameArguments.Where(x => !string.IsNullOrWhiteSpace(x)));
|
||||
|
||||
var env = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
if (config.Loader.SetAllProxy && config.Proxy.Enabled)
|
||||
env["ALL_PROXY"] = $"socks5h://127.0.0.1:{config.Proxy.Port}";
|
||||
|
||||
if (string.IsNullOrWhiteSpace(gamePath))
|
||||
throw new InvalidOperationException("Loader.GamePath is not configured.");
|
||||
if (!File.Exists(gamePath))
|
||||
throw new FileNotFoundException("Game executable not found.", gamePath);
|
||||
if (patchPaths.Count == 0)
|
||||
throw new InvalidOperationException("At least one patch path is required.");
|
||||
|
||||
foreach (var patchPath in patchPaths)
|
||||
{
|
||||
if (!File.Exists(patchPath))
|
||||
throw new FileNotFoundException("Patch DLL not found.", patchPath);
|
||||
}
|
||||
|
||||
var workingDirectory = Path.GetDirectoryName(gamePath);
|
||||
if (string.IsNullOrWhiteSpace(workingDirectory) || !Directory.Exists(workingDirectory))
|
||||
throw new DirectoryNotFoundException($"Working directory not found: {workingDirectory}");
|
||||
|
||||
return new LaunchOptions
|
||||
{
|
||||
GamePath = Path.GetFullPath(gamePath),
|
||||
PatchPaths = patchPaths,
|
||||
WorkingDirectory = Path.GetFullPath(workingDirectory),
|
||||
GameArguments = gameArgs,
|
||||
EnvironmentVariables = env
|
||||
};
|
||||
}
|
||||
|
||||
private static string? ResolvePath(string? value, string baseDirectory)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
return null;
|
||||
|
||||
return Path.IsPathRooted(value)
|
||||
? value
|
||||
: Path.GetFullPath(Path.Combine(baseDirectory, value));
|
||||
}
|
||||
|
||||
private static List<string> ResolvePatchPaths(IEnumerable<string>? values, string baseDirectory)
|
||||
{
|
||||
var result = new List<string>();
|
||||
if (values is null)
|
||||
return result;
|
||||
|
||||
foreach (var value in values)
|
||||
{
|
||||
var resolved = ResolvePath(value, baseDirectory);
|
||||
if (!string.IsNullOrWhiteSpace(resolved))
|
||||
result.Add(resolved);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
16
MikuSB.Loader/MikuSB.Loader.csproj
Normal file
16
MikuSB.Loader/MikuSB.Loader.csproj
Normal file
@@ -0,0 +1,16 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Library</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyName>MikuSB.Loader</AssemblyName>
|
||||
<RootNamespace>MikuSB.Loader</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Common\Common.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RuntimeIdentifiers>win-x64</RuntimeIdentifiers>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
@@ -102,11 +102,6 @@ static void UpdateResources(string resourcePackagePath, string resourceTargetDir
|
||||
ZipFile.ExtractToDirectory(resourcePackagePath, resourceStagingDirectory, overwriteFiles: true);
|
||||
|
||||
var extractedRoot = Directory.GetDirectories(resourceStagingDirectory).FirstOrDefault() ?? resourceStagingDirectory;
|
||||
var excelOutputSource = Path.Combine(extractedRoot, "ExcelOutput");
|
||||
if (!Directory.Exists(excelOutputSource))
|
||||
throw new DirectoryNotFoundException($"ExcelOutput directory was not found in resource package: {excelOutputSource}");
|
||||
|
||||
var excelOutputTarget = Path.Combine(resourceTargetDirectory, "ExcelOutput");
|
||||
Directory.CreateDirectory(excelOutputTarget);
|
||||
CopyDirectory(excelOutputSource, excelOutputTarget);
|
||||
Directory.CreateDirectory(resourceTargetDirectory);
|
||||
CopyDirectory(extractedRoot, resourceTargetDirectory);
|
||||
}
|
||||
|
||||
@@ -24,6 +24,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Proxy", "Proxy\Proxy.csproj
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MikuSB.Updater", "MikuSB.Updater\MikuSB.Updater.csproj", "{CE0F3A4B-8C55-4A31-A1B5-A0CB1C7F0A11}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MikuSB.Loader", "MikuSB.Loader\MikuSB.Loader.csproj", "{B7AE1E7E-6A42-4E64-B2B1-2EB522F9E3A1}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -62,6 +64,10 @@ Global
|
||||
{CE0F3A4B-8C55-4A31-A1B5-A0CB1C7F0A11}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{CE0F3A4B-8C55-4A31-A1B5-A0CB1C7F0A11}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{CE0F3A4B-8C55-4A31-A1B5-A0CB1C7F0A11}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{B7AE1E7E-6A42-4E64-B2B1-2EB522F9E3A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B7AE1E7E-6A42-4E64-B2B1-2EB522F9E3A1}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B7AE1E7E-6A42-4E64-B2B1-2EB522F9E3A1}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B7AE1E7E-6A42-4E64-B2B1-2EB522F9E3A1}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<CETCompat>false</CETCompat>
|
||||
@@ -50,7 +50,6 @@
|
||||
Targets="Restore;Publish"
|
||||
RemoveProperties="PublishProfile"
|
||||
Properties="Configuration=$(Configuration);RuntimeIdentifier=$(RuntimeIdentifier);SelfContained=false;PublishSingleFile=true;PublishDir=$(_UpdaterPublishDir)" />
|
||||
|
||||
<Copy
|
||||
SourceFiles="$(_UpdaterPublishDir)MikuSB.Updater.exe"
|
||||
DestinationFiles="$(PublishDir)MikuSB.Updater.exe"
|
||||
|
||||
@@ -160,7 +160,7 @@ public class LoaderManager : MikuSB
|
||||
}
|
||||
}
|
||||
|
||||
public static void InitCommand()
|
||||
public static async Task InitCommand(CancellationToken exitToken)
|
||||
{
|
||||
// Register the command handlers
|
||||
try
|
||||
@@ -178,6 +178,6 @@ public class LoaderManager : MikuSB
|
||||
IConsole.OnConsoleExcuteCommand += CommandExecutor.ConsoleExcuteCommand;
|
||||
CommandExecutor.OnRunCommand += (sender, e) => { CommandManager.HandleCommand(e, sender); };
|
||||
|
||||
IConsole.ListenConsole();
|
||||
await IConsole.ListenConsole(exitToken);
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,10 @@ public class MikuSB
|
||||
public static readonly Listener Listener = new();
|
||||
public static readonly CommandManager CommandManager = new();
|
||||
|
||||
// for exit signal
|
||||
private static readonly CancellationTokenSource _cts = new();
|
||||
private static int _exitCode = 0;
|
||||
|
||||
public static async Task Main()
|
||||
{
|
||||
var time = DateTime.Now;
|
||||
@@ -50,44 +54,58 @@ public class MikuSB
|
||||
ResourceManager.IsLoaded = true;
|
||||
|
||||
HandbookGenerator.GenerateAll();
|
||||
LoaderManager.InitCommand();
|
||||
var consoleTask = Task.Run(() => LoaderManager.InitCommand(_cts.Token), _cts.Token);
|
||||
|
||||
var elapsed = DateTime.Now - time;
|
||||
Logger.Info(I18NManager.Translate("Server.ServerInfo.ServerStarted",
|
||||
Math.Round(elapsed.TotalSeconds, 2).ToString(CultureInfo.InvariantCulture)));
|
||||
|
||||
await consoleTask;
|
||||
|
||||
await ProcessExit(Volatile.Read(ref _exitCode));
|
||||
}
|
||||
|
||||
# region Exit
|
||||
#region Exit
|
||||
|
||||
private static void RegisterExitEvent()
|
||||
{
|
||||
AppDomain.CurrentDomain.ProcessExit += (_, _) =>
|
||||
{
|
||||
Logger.Info(I18NManager.Translate("Server.ServerInfo.Shutdown"));
|
||||
ProcessExit();
|
||||
RequestShutdown(0);
|
||||
};
|
||||
AppDomain.CurrentDomain.UnhandledException += (obj, arg) =>
|
||||
{
|
||||
Logger.Error(I18NManager.Translate("Server.ServerInfo.UnhandledException", obj.GetType().Name),
|
||||
(Exception)arg.ExceptionObject);
|
||||
Logger.Info(I18NManager.Translate("Server.ServerInfo.Shutdown"));
|
||||
ProcessExit();
|
||||
Environment.Exit(1);
|
||||
RequestShutdown(1);
|
||||
};
|
||||
|
||||
Console.CancelKeyPress += (_, eventArgs) =>
|
||||
{
|
||||
Logger.Info(I18NManager.Translate("Server.ServerInfo.CancelKeyPressed"));
|
||||
eventArgs.Cancel = true;
|
||||
Environment.Exit(0);
|
||||
RequestShutdown(0);
|
||||
};
|
||||
}
|
||||
|
||||
private static void ProcessExit()
|
||||
private static void RequestShutdown(int exitCode)
|
||||
{
|
||||
Interlocked.Exchange(ref _exitCode, exitCode);
|
||||
_cts.Cancel();
|
||||
}
|
||||
|
||||
private static async Task ProcessExit(int exitCode)
|
||||
{
|
||||
SocketListener.Connections.Values.ToList().ForEach(x => x.Stop(true));
|
||||
DatabaseHelper.SaveThread?.Interrupt();
|
||||
DatabaseHelper.SaveDatabase();
|
||||
|
||||
DatabaseHelper.Stop(); // notify stop
|
||||
await DatabaseHelper.WaitAsync(); // wait AutoSave thread exit
|
||||
|
||||
DatabaseHelper.SaveDatabase(); // final flush
|
||||
|
||||
Environment.Exit(exitCode);
|
||||
}
|
||||
|
||||
# endregion
|
||||
|
||||
@@ -9,7 +9,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
|
||||
<PublishDir>bin\MikuSB-Win64-Debug</PublishDir>
|
||||
<PublishProtocol>FileSystem</PublishProtocol>
|
||||
<_TargetId>Folder</_TargetId>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
<SelfContained>false</SelfContained>
|
||||
<PublishSingleFile>false</PublishSingleFile>
|
||||
|
||||
@@ -9,7 +9,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
|
||||
<PublishDir>bin\MikuSB-MultiFile\</PublishDir>
|
||||
<PublishProtocol>FileSystem</PublishProtocol>
|
||||
<_TargetId>Folder</_TargetId>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
<SelfContained>false</SelfContained>
|
||||
<PublishSingleFile>false</PublishSingleFile>
|
||||
|
||||
@@ -9,7 +9,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
|
||||
<PublishDir>bin\MikuSB-OneFile\</PublishDir>
|
||||
<PublishProtocol>FileSystem</PublishProtocol>
|
||||
<_TargetId>Folder</_TargetId>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
<SelfContained>true</SelfContained>
|
||||
<PublishSingleFile>true</PublishSingleFile>
|
||||
|
||||
@@ -24,8 +24,8 @@ public static class UpdateService
|
||||
"https://github.com/Kei-Luna/MikuSB-Resource/archive/refs/heads/main.zip";
|
||||
private static readonly string[] RequiredResourceFiles =
|
||||
[
|
||||
"card.json",
|
||||
"weapon.json"
|
||||
"item/templates/card.json",
|
||||
"item/templates/weapon.json"
|
||||
];
|
||||
|
||||
public static async Task<bool> TryStartSelfUpdateAsync()
|
||||
@@ -160,11 +160,11 @@ public static class UpdateService
|
||||
|
||||
private static bool AreRequiredResourcesPresent()
|
||||
{
|
||||
var excelOutputPath = Path.Combine(AppContext.BaseDirectory, ConfigManager.Config.Path.ResourcePath, "ExcelOutput");
|
||||
if (!Directory.Exists(excelOutputPath))
|
||||
var resourcePath = Path.Combine(AppContext.BaseDirectory, ConfigManager.Config.Path.ResourcePath);
|
||||
if (!Directory.Exists(resourcePath))
|
||||
return false;
|
||||
|
||||
return RequiredResourceFiles.All(fileName => File.Exists(Path.Combine(excelOutputPath, fileName)));
|
||||
return RequiredResourceFiles.All(fileName => File.Exists(Path.Combine(resourcePath, fileName)));
|
||||
}
|
||||
|
||||
private static async Task DownloadAndInstallResourcesAsync()
|
||||
@@ -187,13 +187,8 @@ public static class UpdateService
|
||||
ZipFile.ExtractToDirectory(resourcePackagePath, resourceStagingDirectory, overwriteFiles: true);
|
||||
|
||||
var extractedRoot = Directory.GetDirectories(resourceStagingDirectory).FirstOrDefault() ?? resourceStagingDirectory;
|
||||
var excelOutputSource = Path.Combine(extractedRoot, "ExcelOutput");
|
||||
if (!Directory.Exists(excelOutputSource))
|
||||
throw new DirectoryNotFoundException($"ExcelOutput directory was not found in resource package: {excelOutputSource}");
|
||||
|
||||
var excelOutputTarget = Path.Combine(resourceTargetDirectory, "ExcelOutput");
|
||||
Directory.CreateDirectory(excelOutputTarget);
|
||||
CopyDirectory(excelOutputSource, excelOutputTarget);
|
||||
Directory.CreateDirectory(resourceTargetDirectory);
|
||||
CopyDirectory(extractedRoot, resourceTargetDirectory);
|
||||
}
|
||||
|
||||
private static bool ConfirmUpdate(string latestVersion)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<CETCompat>false</CETCompat>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>MikuSB.Proxy</RootNamespace>
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using MikuSB.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace MikuSB.Proxy;
|
||||
|
||||
public sealed class ProxyCertificateAuthority
|
||||
{
|
||||
private const string Password = "MikuSB.Proxy.LocalCA";
|
||||
private readonly ConcurrentDictionary<string, X509Certificate2> _serverCertificates = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly ILogger<ProxyCertificateAuthority> _logger;
|
||||
private readonly ProxyOptions _options;
|
||||
private readonly X509Certificate2 _rootCertificate;
|
||||
|
||||
public ProxyCertificateAuthority(IOptions<ProxyOptions> options, ILogger<ProxyCertificateAuthority> logger)
|
||||
{
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
_rootCertificate = LoadOrCreateRootCertificate();
|
||||
|
||||
if (_options.InstallRootCertificate)
|
||||
InstallRootCertificate();
|
||||
else
|
||||
_logger.LogWarning(
|
||||
"MikuSB proxy root certificate is not installed automatically. Import {CertificatePath} into CurrentUser Root to enable HTTPS interception.",
|
||||
RootCerPath);
|
||||
}
|
||||
|
||||
public string RootCerPath => Path.Combine(CertificateDirectory, "MikuSB.Proxy.Root.cer");
|
||||
|
||||
private static string CertificateDirectory => Path.Combine(AppContext.BaseDirectory, "proxy-certs");
|
||||
|
||||
public X509Certificate2 GetServerCertificate(string host)
|
||||
{
|
||||
host = host.Trim().TrimEnd('.').ToLowerInvariant();
|
||||
return _serverCertificates.GetOrAdd(host, CreateServerCertificate);
|
||||
}
|
||||
|
||||
private X509Certificate2 LoadOrCreateRootCertificate()
|
||||
{
|
||||
Directory.CreateDirectory(CertificateDirectory);
|
||||
var pfxPath = Path.Combine(CertificateDirectory, "MikuSB.Proxy.Root.pfx");
|
||||
|
||||
if (File.Exists(pfxPath))
|
||||
{
|
||||
var existing = X509CertificateLoader.LoadPkcs12(
|
||||
File.ReadAllBytes(pfxPath),
|
||||
Password,
|
||||
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserKeySet);
|
||||
|
||||
if (!File.Exists(RootCerPath))
|
||||
File.WriteAllBytes(RootCerPath, existing.Export(X509ContentType.Cert));
|
||||
|
||||
return existing;
|
||||
}
|
||||
|
||||
using var rsa = RSA.Create(4096);
|
||||
var request = new CertificateRequest(
|
||||
"CN=MikuSB Proxy Root CA",
|
||||
rsa,
|
||||
HashAlgorithmName.SHA256,
|
||||
RSASignaturePadding.Pkcs1);
|
||||
|
||||
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
|
||||
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign | X509KeyUsageFlags.DigitalSignature, true));
|
||||
request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, false));
|
||||
|
||||
var root = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(10));
|
||||
var exportable = X509CertificateLoader.LoadPkcs12(
|
||||
root.Export(X509ContentType.Pfx, Password),
|
||||
Password,
|
||||
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserKeySet);
|
||||
|
||||
File.WriteAllBytes(pfxPath, exportable.Export(X509ContentType.Pfx, Password));
|
||||
File.WriteAllBytes(RootCerPath, exportable.Export(X509ContentType.Cert));
|
||||
_logger.LogInformation("Created MikuSB proxy root certificate at {CertificatePath}", RootCerPath);
|
||||
return exportable;
|
||||
}
|
||||
|
||||
private X509Certificate2 CreateServerCertificate(string host)
|
||||
{
|
||||
using var rsa = RSA.Create(2048);
|
||||
var request = new CertificateRequest($"CN={host}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
|
||||
var san = new SubjectAlternativeNameBuilder();
|
||||
if (IPAddress.TryParse(host, out var address))
|
||||
san.AddIpAddress(address);
|
||||
else
|
||||
san.AddDnsName(host);
|
||||
|
||||
request.CertificateExtensions.Add(san.Build());
|
||||
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));
|
||||
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, true));
|
||||
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension([new Oid("1.3.6.1.5.5.7.3.1")], false));
|
||||
|
||||
var serial = RandomNumberGenerator.GetBytes(16);
|
||||
using var certificate = request.Create(
|
||||
_rootCertificate,
|
||||
DateTimeOffset.UtcNow.AddDays(-1),
|
||||
DateTimeOffset.UtcNow.AddYears(2),
|
||||
serial);
|
||||
|
||||
return X509CertificateLoader.LoadPkcs12(
|
||||
certificate.CopyWithPrivateKey(rsa).Export(X509ContentType.Pfx),
|
||||
null,
|
||||
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserKeySet);
|
||||
}
|
||||
|
||||
private void InstallRootCertificate()
|
||||
{
|
||||
using var store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
|
||||
store.Open(OpenFlags.ReadWrite);
|
||||
var existing = store.Certificates.Find(X509FindType.FindByThumbprint, _rootCertificate.Thumbprint, false);
|
||||
if (existing.Count > 0)
|
||||
return;
|
||||
|
||||
store.Add(_rootCertificate);
|
||||
_logger.LogWarning("Installed MikuSB proxy root certificate into CurrentUser Root store. Thumbprint={Thumbprint}", _rootCertificate.Thumbprint);
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,20 @@
|
||||
using System.Buffers;
|
||||
using System.Net;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Authentication;
|
||||
using System.Text;
|
||||
using MikuSB.Configuration;
|
||||
using MikuSB.Util;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace MikuSB.Proxy;
|
||||
|
||||
public sealed class ProxyServer(
|
||||
IOptions<ProxyOptions> options,
|
||||
ProxyCertificateAuthority certificateAuthority,
|
||||
HttpClient httpClient,
|
||||
ILogger<ProxyServer> logger) : BackgroundService
|
||||
Logger logger) : BackgroundService
|
||||
{
|
||||
private const string ListenAddress = "127.0.0.1";
|
||||
private const string ServerHost = "127.0.0.1";
|
||||
private const int DefaultSocksPort = 18888;
|
||||
|
||||
private static readonly string[] TargetDomains =
|
||||
[
|
||||
"amazingseasuncdn.com",
|
||||
@@ -28,411 +24,272 @@ public sealed class ProxyServer(
|
||||
"xoyo.games",
|
||||
"yo.games",
|
||||
"qcloud.com",
|
||||
"xgsdk.xoyo.games",
|
||||
"xqdata.xoyo.games",
|
||||
"tencentcs.com"
|
||||
];
|
||||
|
||||
private static readonly HashSet<string> HopByHopHeaders = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"Connection",
|
||||
"Proxy-Connection",
|
||||
"Keep-Alive",
|
||||
"Proxy-Authenticate",
|
||||
"Proxy-Authorization",
|
||||
"TE",
|
||||
"Trailer",
|
||||
"Transfer-Encoding",
|
||||
"Upgrade"
|
||||
};
|
||||
|
||||
private readonly ProxyOptions _options = options.Value;
|
||||
private TcpListener? _listener;
|
||||
private readonly List<TcpListener> _listeners = [];
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
if (!_options.Enabled)
|
||||
{
|
||||
logger.LogInformation("MikuSB proxy is disabled");
|
||||
logger.Info("MikuSB proxy is disabled");
|
||||
return;
|
||||
}
|
||||
|
||||
var address = IPAddress.Parse(ListenAddress);
|
||||
_listener = new TcpListener(address, _options.Port);
|
||||
_listener.Start();
|
||||
logger.LogInformation("MikuSB proxy listening on {Address}:{Port}", ListenAddress, _options.Port);
|
||||
foreach (var port in GetListenPorts())
|
||||
{
|
||||
var listener = new TcpListener(IPAddress.Parse(ListenAddress), port);
|
||||
listener.Start();
|
||||
_listeners.Add(listener);
|
||||
logger.Info($"MikuSB SOCKS5 proxy listening on {ListenAddress}:{port}");
|
||||
_ = Task.Run(() => AcceptLoopAsync(listener, port, stoppingToken), stoppingToken);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
var client = await _listener.AcceptTcpClientAsync(stoppingToken);
|
||||
_ = Task.Run(() => HandleClientAsync(client, stoppingToken), stoppingToken);
|
||||
}
|
||||
await Task.Delay(Timeout.Infinite, stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public override Task StopAsync(CancellationToken cancellationToken)
|
||||
public override async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_listener?.Stop();
|
||||
return base.StopAsync(cancellationToken);
|
||||
var stopTask = base.StopAsync(cancellationToken);
|
||||
foreach (var listener in _listeners)
|
||||
listener.Stop();
|
||||
await stopTask;
|
||||
}
|
||||
|
||||
private async Task HandleClientAsync(TcpClient client, CancellationToken cancellationToken)
|
||||
private IEnumerable<int> GetListenPorts()
|
||||
{
|
||||
yield return DefaultSocksPort;
|
||||
|
||||
if (_options.Port > 0 && _options.Port != DefaultSocksPort)
|
||||
yield return _options.Port;
|
||||
}
|
||||
|
||||
private async Task AcceptLoopAsync(TcpListener listener, int port, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
var client = await listener.AcceptTcpClientAsync(cancellationToken);
|
||||
_ = Task.Run(() => HandleClientAsync(client, port, cancellationToken), cancellationToken);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (SocketException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (ObjectDisposedException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleClientAsync(TcpClient client, int listenPort, CancellationToken cancellationToken)
|
||||
{
|
||||
using (client)
|
||||
{
|
||||
using var clientStream = client.GetStream();
|
||||
|
||||
try
|
||||
{
|
||||
await HandleClientCoreAsync(client, cancellationToken);
|
||||
await NegotiateAsync(clientStream, cancellationToken);
|
||||
var request = await ReadConnectRequestAsync(clientStream, cancellationToken);
|
||||
if (request is null)
|
||||
return;
|
||||
|
||||
using var upstream = new TcpClient();
|
||||
var destination = ResolveDestination(request, listenPort);
|
||||
|
||||
await upstream.ConnectAsync(destination.Host, destination.Port, cancellationToken);
|
||||
await SendConnectReplyAsync(clientStream, success: true, cancellationToken);
|
||||
|
||||
if (ConfigManager.Config.HttpServer.EnableLog)
|
||||
logger.Info($"SOCKS: {request.Host}:{request.Port} -> {destination.Host}:{destination.Port}");
|
||||
|
||||
using var upstreamStream = upstream.GetStream();
|
||||
await TunnelAsync(clientStream, upstreamStream, cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (IOException)
|
||||
catch (Exception ex) when (ex is IOException or SocketException)
|
||||
{
|
||||
}
|
||||
catch (SocketException)
|
||||
{
|
||||
}
|
||||
catch (AuthenticationException ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Proxy TLS authentication failed");
|
||||
if (ConfigManager.Config.HttpServer.EnableLog)
|
||||
logger.Warn($"SOCKS client failed: {ex.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Proxy client failed");
|
||||
logger.Warn($"SOCKS client failed: {ex}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleClientCoreAsync(TcpClient client, CancellationToken cancellationToken)
|
||||
private async Task NegotiateAsync(NetworkStream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var stream = client.GetStream();
|
||||
var request = await ProxyHttpRequest.ReadAsync(stream, cancellationToken);
|
||||
if (request is null)
|
||||
return;
|
||||
var header = new byte[2];
|
||||
await ReadExactAsync(stream, header, cancellationToken);
|
||||
|
||||
if (request.Method.Equals("CONNECT", StringComparison.OrdinalIgnoreCase))
|
||||
if (header[0] != 0x05)
|
||||
throw new IOException("Unsupported SOCKS version");
|
||||
|
||||
var methods = new byte[header[1]];
|
||||
if (methods.Length > 0)
|
||||
await ReadExactAsync(stream, methods, cancellationToken);
|
||||
|
||||
await stream.WriteAsync(new byte[] { 0x05, 0x00 }, cancellationToken);
|
||||
}
|
||||
|
||||
private async Task<SocksRequest?> ReadConnectRequestAsync(NetworkStream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
var header = new byte[4];
|
||||
await ReadExactAsync(stream, header, cancellationToken);
|
||||
|
||||
if (header[0] != 0x05)
|
||||
throw new IOException("Invalid SOCKS request");
|
||||
|
||||
if (header[1] != 0x01)
|
||||
{
|
||||
var (host, port) = SplitHostPort(request.Target, 443);
|
||||
if (ShouldRedirect(host))
|
||||
{
|
||||
await WriteAsciiAsync(stream, "HTTP/1.1 200 Connection Established\r\nProxy-Agent: MikuSB.Proxy\r\n\r\n", cancellationToken);
|
||||
using var tlsStream = new SslStream(stream, false);
|
||||
await tlsStream.AuthenticateAsServerAsync(new SslServerAuthenticationOptions
|
||||
{
|
||||
ServerCertificate = certificateAuthority.GetServerCertificate(host),
|
||||
EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13
|
||||
}, cancellationToken);
|
||||
|
||||
await HandleRedirectedHttpLoopAsync(tlsStream, host, cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
await TunnelAsync(stream, host, port, cancellationToken);
|
||||
return;
|
||||
await SendConnectReplyAsync(stream, success: false, cancellationToken);
|
||||
return null;
|
||||
}
|
||||
|
||||
await HandlePlainHttpLoopAsync(stream, request, cancellationToken);
|
||||
}
|
||||
|
||||
private async Task HandlePlainHttpLoopAsync(Stream clientStream, ProxyHttpRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
while (true)
|
||||
var host = header[3] switch
|
||||
{
|
||||
var host = request.Host;
|
||||
if (string.IsNullOrWhiteSpace(host))
|
||||
{
|
||||
await WriteSimpleResponseAsync(clientStream, HttpStatusCode.BadRequest, "Missing Host header", cancellationToken);
|
||||
return;
|
||||
}
|
||||
0x01 => new IPAddress(await ReadBytesAsync(stream, 4, cancellationToken)).ToString(),
|
||||
0x03 => await ReadDomainAsync(stream, cancellationToken),
|
||||
0x04 => new IPAddress(await ReadBytesAsync(stream, 16, cancellationToken)).ToString(),
|
||||
_ => throw new IOException("Unsupported address type")
|
||||
};
|
||||
|
||||
if (ShouldRedirect(SplitHostPort(host, 80).Host))
|
||||
await ForwardToServerAsync(clientStream, request, cancellationToken);
|
||||
else
|
||||
await ForwardToOriginAsync(clientStream, request, cancellationToken);
|
||||
|
||||
if (request.ShouldClose)
|
||||
return;
|
||||
|
||||
var nextRequest = await ProxyHttpRequest.ReadAsync(clientStream, cancellationToken);
|
||||
if (nextRequest is null)
|
||||
return;
|
||||
|
||||
request = nextRequest;
|
||||
}
|
||||
var portBytes = await ReadBytesAsync(stream, 2, cancellationToken);
|
||||
var port = (portBytes[0] << 8) | portBytes[1];
|
||||
return new SocksRequest(host, port);
|
||||
}
|
||||
|
||||
private async Task HandleRedirectedHttpLoopAsync(Stream tlsStream, string originalHost, CancellationToken cancellationToken)
|
||||
private static async Task<string> ReadDomainAsync(NetworkStream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
var length = await ReadBytesAsync(stream, 1, cancellationToken);
|
||||
var domain = await ReadBytesAsync(stream, length[0], cancellationToken);
|
||||
return System.Text.Encoding.ASCII.GetString(domain);
|
||||
}
|
||||
|
||||
private (string Host, int Port) ResolveDestination(SocksRequest request, int listenPort)
|
||||
{
|
||||
if (IsSelfReference(request.Host, request.Port, listenPort))
|
||||
throw new IOException("Proxy self-reference detected");
|
||||
|
||||
if (!ShouldRedirect(request.Host))
|
||||
return (request.Host, request.Port);
|
||||
|
||||
return ("127.0.0.1", request.Port switch
|
||||
{
|
||||
var request = await ProxyHttpRequest.ReadAsync(tlsStream, cancellationToken);
|
||||
if (request is null)
|
||||
return;
|
||||
|
||||
request.HostOverride = originalHost;
|
||||
await ForwardToServerAsync(tlsStream, request, cancellationToken);
|
||||
|
||||
if (request.ShouldClose)
|
||||
return;
|
||||
}
|
||||
80 => ConfigManager.Config.HttpServer.Port,
|
||||
893 => 31443,
|
||||
13443 => 13443,
|
||||
18443 => 18443,
|
||||
31443 => 31443,
|
||||
_ => 13443
|
||||
});
|
||||
}
|
||||
|
||||
private async Task ForwardToServerAsync(Stream clientStream, ProxyHttpRequest request, CancellationToken cancellationToken)
|
||||
private static bool ShouldRedirect(string host)
|
||||
{
|
||||
var pathAndQuery = request.GetPathAndQuery();
|
||||
var uri = new Uri($"http://{ServerHost}:{_options.ServerHttpPort}{pathAndQuery}");
|
||||
logger.LogInformation("[Proxy] Redirect: {Method} {Host}{Path} -> {Uri}", request.Method, request.HostOverride ?? request.Host, pathAndQuery, uri);
|
||||
await SendHttpRequestAsync(clientStream, request, uri, true, cancellationToken);
|
||||
}
|
||||
|
||||
private async Task ForwardToOriginAsync(Stream clientStream, ProxyHttpRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var uri = request.GetAbsoluteUri();
|
||||
if (uri is null)
|
||||
foreach (var domain in TargetDomains)
|
||||
{
|
||||
await WriteSimpleResponseAsync(clientStream, HttpStatusCode.BadRequest, "Only absolute-form proxy requests are supported for non-target HTTP", cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
if (IsSelfReference(uri))
|
||||
{
|
||||
logger.LogWarning("[Proxy] Self-reference blocked: {Method} {Uri}", request.Method, uri);
|
||||
await WriteSimpleResponseAsync(clientStream, HttpStatusCode.LoopDetected, "Proxy self-reference detected", cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
await SendHttpRequestAsync(clientStream, request, uri, false, cancellationToken);
|
||||
}
|
||||
|
||||
private bool IsSelfReference(Uri uri)
|
||||
{
|
||||
if (uri.Port != _options.Port)
|
||||
return false;
|
||||
|
||||
return uri.Host is "127.0.0.1" or "localhost" or "::1"
|
||||
|| uri.Host.Equals(ListenAddress, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private async Task SendHttpRequestAsync(Stream clientStream, ProxyHttpRequest request, Uri uri, bool addCors, CancellationToken cancellationToken)
|
||||
{
|
||||
using var outgoing = new HttpRequestMessage(new HttpMethod(request.Method), uri);
|
||||
if (request.Body.Length > 0)
|
||||
outgoing.Content = new ByteArrayContent(request.Body);
|
||||
|
||||
foreach (var (name, value) in request.Headers)
|
||||
{
|
||||
if (HopByHopHeaders.Contains(name) || name.Equals("Host", StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
|
||||
if (!outgoing.Headers.TryAddWithoutValidation(name, value))
|
||||
{
|
||||
outgoing.Content ??= new ByteArrayContent(request.Body);
|
||||
outgoing.Content.Headers.TryAddWithoutValidation(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
using var response = await httpClient.SendAsync(outgoing, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||
var body = await response.Content.ReadAsByteArrayAsync(cancellationToken);
|
||||
|
||||
var builder = new StringBuilder();
|
||||
builder.Append("HTTP/1.1 ")
|
||||
.Append((int)response.StatusCode)
|
||||
.Append(' ')
|
||||
.Append(response.ReasonPhrase ?? response.StatusCode.ToString())
|
||||
.Append("\r\n");
|
||||
|
||||
foreach (var header in response.Headers)
|
||||
AppendHeader(builder, header.Key, header.Value);
|
||||
|
||||
foreach (var header in response.Content.Headers)
|
||||
{
|
||||
if (!header.Key.Equals("Content-Length", StringComparison.OrdinalIgnoreCase))
|
||||
AppendHeader(builder, header.Key, header.Value);
|
||||
}
|
||||
|
||||
if (addCors)
|
||||
builder.Append("Access-Control-Allow-Origin: *\r\n");
|
||||
|
||||
builder.Append("Content-Length: ").Append(body.Length).Append("\r\n");
|
||||
builder.Append("Connection: keep-alive\r\n\r\n");
|
||||
|
||||
await WriteAsciiAsync(clientStream, builder.ToString(), cancellationToken);
|
||||
if (body.Length > 0)
|
||||
await clientStream.WriteAsync(body, cancellationToken);
|
||||
}
|
||||
|
||||
private async Task TunnelAsync(Stream clientStream, string host, int port, CancellationToken cancellationToken)
|
||||
{
|
||||
using var upstream = new TcpClient();
|
||||
await upstream.ConnectAsync(host, port, cancellationToken);
|
||||
await WriteAsciiAsync(clientStream, "HTTP/1.1 200 Connection Established\r\nProxy-Agent: MikuSB.Proxy\r\n\r\n", cancellationToken);
|
||||
|
||||
await using var upstreamStream = upstream.GetStream();
|
||||
var clientToServer = clientStream.CopyToAsync(upstreamStream, cancellationToken);
|
||||
var serverToClient = upstreamStream.CopyToAsync(clientStream, cancellationToken);
|
||||
await Task.WhenAny(clientToServer, serverToClient);
|
||||
}
|
||||
|
||||
private bool ShouldRedirect(string host)
|
||||
{
|
||||
host = host.Trim().TrimEnd('.').ToLowerInvariant();
|
||||
foreach (var target in TargetDomains)
|
||||
{
|
||||
var normalized = target.Trim().TrimEnd('.').ToLowerInvariant();
|
||||
if (host == normalized || host.EndsWith($".{normalized}", StringComparison.OrdinalIgnoreCase))
|
||||
if (host.Equals(domain, StringComparison.OrdinalIgnoreCase) ||
|
||||
host.EndsWith("." + domain, StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void AppendHeader(StringBuilder builder, string name, IEnumerable<string> values)
|
||||
private bool IsSelfReference(string host, int port, int listenPort)
|
||||
{
|
||||
if (HopByHopHeaders.Contains(name))
|
||||
return;
|
||||
if (port != listenPort && port != _options.Port && port != DefaultSocksPort)
|
||||
return false;
|
||||
|
||||
foreach (var value in values)
|
||||
builder.Append(name).Append(": ").Append(value).Append("\r\n");
|
||||
return host is "127.0.0.1" or "localhost" or "::1";
|
||||
}
|
||||
|
||||
private static async Task WriteSimpleResponseAsync(Stream stream, HttpStatusCode statusCode, string message, CancellationToken cancellationToken)
|
||||
private static async Task SendConnectReplyAsync(NetworkStream stream, bool success, CancellationToken cancellationToken)
|
||||
{
|
||||
var body = Encoding.UTF8.GetBytes(message);
|
||||
await WriteAsciiAsync(
|
||||
stream,
|
||||
$"HTTP/1.1 {(int)statusCode} {statusCode}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n",
|
||||
cancellationToken);
|
||||
await stream.WriteAsync(body, cancellationToken);
|
||||
var reply = success
|
||||
? new byte[] { 0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
|
||||
: new byte[] { 0x05, 0x05, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
|
||||
await stream.WriteAsync(reply, cancellationToken);
|
||||
}
|
||||
|
||||
private static Task WriteAsciiAsync(Stream stream, string value, CancellationToken cancellationToken) =>
|
||||
stream.WriteAsync(Encoding.ASCII.GetBytes(value), cancellationToken).AsTask();
|
||||
|
||||
private static (string Host, int Port) SplitHostPort(string hostPort, int defaultPort)
|
||||
private static async Task TunnelAsync(NetworkStream clientStream, NetworkStream upstreamStream, CancellationToken cancellationToken)
|
||||
{
|
||||
if (hostPort.StartsWith('['))
|
||||
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
var upstreamToClient = CopyAsync(upstreamStream, clientStream, linkedCts.Token);
|
||||
var clientToUpstream = CopyAsync(clientStream, upstreamStream, linkedCts.Token);
|
||||
|
||||
await Task.WhenAny(upstreamToClient, clientToUpstream);
|
||||
linkedCts.Cancel();
|
||||
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(upstreamToClient, clientToUpstream);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
var end = hostPort.IndexOf(']');
|
||||
if (end > 0 && hostPort.Length > end + 2 && hostPort[end + 1] == ':' && int.TryParse(hostPort[(end + 2)..], out var ipv6Port))
|
||||
return (hostPort[1..end], ipv6Port);
|
||||
|
||||
return (hostPort.Trim('[', ']'), defaultPort);
|
||||
}
|
||||
|
||||
var colon = hostPort.LastIndexOf(':');
|
||||
if (colon > 0 && int.TryParse(hostPort[(colon + 1)..], out var port))
|
||||
return (hostPort[..colon], port);
|
||||
|
||||
return (hostPort, defaultPort);
|
||||
}
|
||||
|
||||
private sealed class ProxyHttpRequest
|
||||
private static async Task CopyAsync(Stream source, Stream destination, CancellationToken cancellationToken)
|
||||
{
|
||||
public required string Method { get; init; }
|
||||
public required string Target { get; init; }
|
||||
public required string Version { get; init; }
|
||||
public required List<KeyValuePair<string, string>> Headers { get; init; }
|
||||
public required byte[] Body { get; init; }
|
||||
public string? HostOverride { get; set; }
|
||||
|
||||
public string? Host => HostOverride ?? Headers.FirstOrDefault(x => x.Key.Equals("Host", StringComparison.OrdinalIgnoreCase)).Value;
|
||||
|
||||
public bool ShouldClose =>
|
||||
Headers.Any(x => x.Key.Equals("Connection", StringComparison.OrdinalIgnoreCase)
|
||||
&& x.Value.Contains("close", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
public Uri? GetAbsoluteUri() => Uri.TryCreate(Target, UriKind.Absolute, out var uri) ? uri : null;
|
||||
|
||||
public string GetPathAndQuery()
|
||||
var buffer = ArrayPool<byte>.Shared.Rent(16 * 1024);
|
||||
try
|
||||
{
|
||||
if (Uri.TryCreate(Target, UriKind.Absolute, out var uri))
|
||||
return uri.PathAndQuery;
|
||||
|
||||
if (string.IsNullOrEmpty(Target))
|
||||
return "/";
|
||||
|
||||
return Target[0] == '/' ? Target : $"/{Target}";
|
||||
}
|
||||
|
||||
public static async Task<ProxyHttpRequest?> ReadAsync(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
var rented = ArrayPool<byte>.Shared.Rent(64 * 1024);
|
||||
try
|
||||
while (true)
|
||||
{
|
||||
var length = 0;
|
||||
while (true)
|
||||
{
|
||||
var read = await stream.ReadAsync(rented.AsMemory(length, 1), cancellationToken);
|
||||
if (read == 0)
|
||||
return null;
|
||||
var bytesRead = await source.ReadAsync(buffer, cancellationToken);
|
||||
if (bytesRead <= 0)
|
||||
break;
|
||||
|
||||
length += read;
|
||||
if (length >= 4
|
||||
&& rented[length - 4] == '\r'
|
||||
&& rented[length - 3] == '\n'
|
||||
&& rented[length - 2] == '\r'
|
||||
&& rented[length - 1] == '\n')
|
||||
break;
|
||||
|
||||
if (length == rented.Length)
|
||||
throw new InvalidDataException("HTTP proxy request header is too large");
|
||||
}
|
||||
|
||||
var headerText = Encoding.ASCII.GetString(rented, 0, length);
|
||||
var lines = headerText.Split("\r\n", StringSplitOptions.None);
|
||||
var requestLine = lines[0].Split(' ', 3, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (requestLine.Length != 3)
|
||||
throw new InvalidDataException("Invalid HTTP proxy request line");
|
||||
|
||||
var headers = new List<KeyValuePair<string, string>>();
|
||||
var contentLength = 0;
|
||||
for (var i = 1; i < lines.Length; i++)
|
||||
{
|
||||
var line = lines[i];
|
||||
if (string.IsNullOrEmpty(line))
|
||||
break;
|
||||
|
||||
var colon = line.IndexOf(':');
|
||||
if (colon <= 0)
|
||||
continue;
|
||||
|
||||
var name = line[..colon].Trim();
|
||||
var value = line[(colon + 1)..].Trim();
|
||||
headers.Add(new KeyValuePair<string, string>(name, value));
|
||||
if (name.Equals("Content-Length", StringComparison.OrdinalIgnoreCase) && int.TryParse(value, out var parsedLength))
|
||||
contentLength = parsedLength;
|
||||
}
|
||||
|
||||
var body = new byte[contentLength];
|
||||
var offset = 0;
|
||||
while (offset < body.Length)
|
||||
{
|
||||
var read = await stream.ReadAsync(body.AsMemory(offset), cancellationToken);
|
||||
if (read == 0)
|
||||
throw new EndOfStreamException("HTTP proxy request body ended early");
|
||||
|
||||
offset += read;
|
||||
}
|
||||
|
||||
return new ProxyHttpRequest
|
||||
{
|
||||
Method = requestLine[0],
|
||||
Target = requestLine[1],
|
||||
Version = requestLine[2],
|
||||
Headers = headers,
|
||||
Body = body
|
||||
};
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(rented);
|
||||
await destination.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken);
|
||||
await destination.FlushAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<byte[]> ReadBytesAsync(Stream stream, int length, CancellationToken cancellationToken)
|
||||
{
|
||||
var buffer = new byte[length];
|
||||
await ReadExactAsync(stream, buffer, cancellationToken);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
private static async Task ReadExactAsync(Stream stream, byte[] buffer, CancellationToken cancellationToken)
|
||||
{
|
||||
var offset = 0;
|
||||
while (offset < buffer.Length)
|
||||
{
|
||||
var bytesRead = await stream.ReadAsync(buffer.AsMemory(offset), cancellationToken);
|
||||
if (bytesRead <= 0)
|
||||
throw new IOException("Unexpected EOF");
|
||||
offset += bytesRead;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record SocksRequest(string Host, int Port);
|
||||
}
|
||||
|
||||
@@ -9,17 +9,8 @@ public static class ProxyServiceCollectionExtensions
|
||||
public static IServiceCollection AddMikuSbProxy(this IServiceCollection services, ProxyOptions options)
|
||||
{
|
||||
services.AddSingleton<IOptions<ProxyOptions>>(Microsoft.Extensions.Options.Options.Create(options));
|
||||
services.AddSingleton<ProxyCertificateAuthority>();
|
||||
services.AddSingleton(new HttpClient(new SocketsHttpHandler
|
||||
{
|
||||
AllowAutoRedirect = false,
|
||||
AutomaticDecompression = System.Net.DecompressionMethods.None,
|
||||
UseCookies = false,
|
||||
UseProxy = false
|
||||
}));
|
||||
services.AddSingleton<ProxyServer>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<ProxyServer>());
|
||||
services.AddHostedService<WindowsSystemProxyService>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using MikuSB.Configuration;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace MikuSB.Proxy;
|
||||
|
||||
public sealed class WindowsSystemProxyService(
|
||||
IOptions<ProxyOptions> options,
|
||||
ILogger<WindowsSystemProxyService> logger) : IHostedService, IDisposable
|
||||
{
|
||||
private const string InternetSettingsPath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
|
||||
private readonly ProxyOptions _options = options.Value;
|
||||
private ConsoleCtrlHandler? _consoleCtrlHandler;
|
||||
private int _proxyDisabled;
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!_options.Enabled || !_options.ManageSystemProxy)
|
||||
return Task.CompletedTask;
|
||||
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
logger.LogWarning("System proxy management is only supported on Windows");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
using var key = Registry.CurrentUser.OpenSubKey(InternetSettingsPath, writable: true);
|
||||
if (key is null)
|
||||
{
|
||||
logger.LogWarning("Unable to open Windows Internet Settings registry key");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
var proxyServer = $"http=127.0.0.1:{_options.Port};https=127.0.0.1:{_options.Port}";
|
||||
|
||||
key.SetValue("ProxyEnable", 1, RegistryValueKind.DWord);
|
||||
key.SetValue("ProxyServer", proxyServer, RegistryValueKind.String);
|
||||
key.SetValue("ProxyOverride", _options.ProxyOverride, RegistryValueKind.String);
|
||||
NotifyProxySettingsChanged();
|
||||
AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
|
||||
RegisterConsoleCtrlHandler();
|
||||
|
||||
logger.LogWarning("Windows system proxy enabled for MikuSB: {ProxyServer}", proxyServer);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!_options.Enabled || !_options.ManageSystemProxy || !_options.RestoreSystemProxyOnStop)
|
||||
return Task.CompletedTask;
|
||||
|
||||
DisableSystemProxy();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
AppDomain.CurrentDomain.ProcessExit -= OnProcessExit;
|
||||
UnregisterConsoleCtrlHandler();
|
||||
|
||||
if (_options.Enabled && _options.ManageSystemProxy && _options.RestoreSystemProxyOnStop)
|
||||
DisableSystemProxy();
|
||||
}
|
||||
|
||||
private void OnProcessExit(object? sender, EventArgs e)
|
||||
{
|
||||
if (_options.Enabled && _options.ManageSystemProxy && _options.RestoreSystemProxyOnStop)
|
||||
DisableSystemProxy();
|
||||
}
|
||||
|
||||
private void DisableSystemProxy()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
return;
|
||||
|
||||
if (Interlocked.Exchange(ref _proxyDisabled, 1) == 1)
|
||||
return;
|
||||
|
||||
using var key = Registry.CurrentUser.OpenSubKey(InternetSettingsPath, writable: true);
|
||||
if (key is null)
|
||||
return;
|
||||
|
||||
key.SetValue("ProxyEnable", 0, RegistryValueKind.DWord);
|
||||
key.DeleteValue("ProxyServer", throwOnMissingValue: false);
|
||||
key.DeleteValue("ProxyOverride", throwOnMissingValue: false);
|
||||
NotifyProxySettingsChanged();
|
||||
logger.LogWarning("Windows system proxy disabled for MikuSB shutdown");
|
||||
}
|
||||
|
||||
private void RegisterConsoleCtrlHandler()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
return;
|
||||
|
||||
_consoleCtrlHandler = OnConsoleCtrl;
|
||||
SetConsoleCtrlHandler(_consoleCtrlHandler, add: true);
|
||||
}
|
||||
|
||||
private void UnregisterConsoleCtrlHandler()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows() || _consoleCtrlHandler is null)
|
||||
return;
|
||||
|
||||
SetConsoleCtrlHandler(_consoleCtrlHandler, add: false);
|
||||
_consoleCtrlHandler = null;
|
||||
}
|
||||
|
||||
private bool OnConsoleCtrl(int signal)
|
||||
{
|
||||
if (_options.Enabled && _options.ManageSystemProxy && _options.RestoreSystemProxyOnStop)
|
||||
DisableSystemProxy();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void NotifyProxySettingsChanged()
|
||||
{
|
||||
InternetSetOption(IntPtr.Zero, 39, IntPtr.Zero, 0);
|
||||
InternetSetOption(IntPtr.Zero, 37, IntPtr.Zero, 0);
|
||||
}
|
||||
|
||||
private delegate bool ConsoleCtrlHandler(int signal);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool SetConsoleCtrlHandler(ConsoleCtrlHandler handler, bool add);
|
||||
|
||||
[DllImport("wininet.dll", SetLastError = true)]
|
||||
private static extern bool InternetSetOption(IntPtr internet, int option, IntPtr buffer, int bufferLength);
|
||||
}
|
||||
10
README.md
10
README.md
@@ -32,17 +32,17 @@
|
||||
|
||||
## Requirements
|
||||
|
||||
- [.NET SDK 9.0](https://dotnet.microsoft.com/en-us/download/dotnet/9.0)
|
||||
- [.NET SDK 10.0](https://dotnet.microsoft.com/en-us/download/dotnet/10.0)
|
||||
|
||||
## Running
|
||||
|
||||
1. Restore dependencies and build.
|
||||
|
||||
```powershell
|
||||
dotnet build
|
||||
```
|
||||
|
||||
2. Enjoy.
|
||||
2. Set `GamePath` in `Config.json` to the path of your game executable.
|
||||
3. Start the server and run the `game` command.
|
||||
4. Enjoy.
|
||||
|
||||
## Feature List
|
||||
|
||||
@@ -90,4 +90,4 @@ MikuSB was developed for educational and research purposes.
|
||||
- This repository does not include any copyrighted game assets, binaries, or master data.
|
||||
- Use this software at your own risk. The authors assume no responsibility for any damages or legal consequences resulting from its use.
|
||||
|
||||
If you are a rights holder and have any concerns regarding this software, please contact `devilpromt` or `kei_luna` on Discord.
|
||||
If you are a rights holder and have any concerns regarding this software, please contact `devilpromt` or `kei_luna` on Discord.
|
||||
|
||||
@@ -32,17 +32,17 @@ English documentation is available in [README.md](README.md).
|
||||
|
||||
## 要件
|
||||
|
||||
- [.NET SDK 9.0](https://dotnet.microsoft.com/ja-jp/download/dotnet/9.0)
|
||||
- [.NET SDK 10.0](https://dotnet.microsoft.com/ja-jp/download/dotnet/10.0)
|
||||
|
||||
## 起動方法
|
||||
|
||||
1. 依存を復元してビルドします。
|
||||
|
||||
```powershell
|
||||
dotnet build
|
||||
```
|
||||
|
||||
2. 楽しんで
|
||||
2. Config.json の`GamePath`にあなたのゲームの実行ファイルのパスを書き込みます
|
||||
3. サーバーを起動し`game`コマンドを入力します
|
||||
4. 楽しむ
|
||||
|
||||
## 機能一覧
|
||||
|
||||
|
||||
66
README_linux.md
Normal file
66
README_linux.md
Normal file
@@ -0,0 +1,66 @@
|
||||
# MikuSB on Linux
|
||||
|
||||
|
||||
## Config
|
||||
|
||||
### setup steam launch options as following
|
||||
|
||||
`HTTP_PROXY="http://127.0.0.1:8888" HTTPS_PROXY="http://127.0.0.1:8888" ALL_PROXY="http://127.0.0.1:8888" %command%`
|
||||
|
||||
### start local server and keep it running
|
||||
|
||||
```
|
||||
./MikuSB
|
||||
```
|
||||
|
||||
### find root CA cert, and create ca bundle
|
||||
|
||||
root CA cert, should in the path: `proxy-certs/MikuSB.Proxy.Root.pem`
|
||||
|
||||
|
||||
### setup root CA for proton/wine
|
||||
|
||||
not sure, even I remove Proton PFX (Wine prefix) folder, without redo this step, still no cert issue.
|
||||
|
||||
`Proton Hotfix` is the proton version which selected in steam `Force the use of a specific Steam Play compatibility tool`
|
||||
|
||||
```bash
|
||||
APPID=<THE-APP-ID-OF-THE-GAME>
|
||||
STEAM_COMPAT_DATA_PATH=~/.steam/steam/steamapps/compatdata/$APPID/pfx
|
||||
STEAM_WINE_PATH="$HOME/.steam/steam/steamapps/common/Proton Hotfix/files/bin/wine"
|
||||
WINEPREFIX=$STEAM_COMPAT_DATA_PATH $STEAM_WINE_PATH certutil -addstore -f Root proxy-certs/MikuSB.Proxy.Root.pem
|
||||
```
|
||||
|
||||
### start the game and enjoy
|
||||
|
||||
|
||||
## development
|
||||
|
||||
1. Restore dependencies and build.
|
||||
|
||||
```bash
|
||||
dotnet build
|
||||
```
|
||||
|
||||
2. run it
|
||||
|
||||
```bash
|
||||
dotnet run --project ./MikuSB
|
||||
```
|
||||
|
||||
## release build
|
||||
|
||||
```bash
|
||||
DOTNET_CLI_UI_LANGUAGE=en time dotnet publish ./MikuSB/MikuSB.csproj -c Release -r linux-x64 --self-contained true -p:PublishSingleFile=true --property:PublishDir=../publish
|
||||
|
||||
# output will in ./publish/*
|
||||
cd ./publish
|
||||
|
||||
# start server
|
||||
./MikuSB
|
||||
```
|
||||
|
||||
## TODO:
|
||||
|
||||
* [ ] tool/script for CA cert create and install to proton/wine
|
||||
* [ ] automatic done in main program
|
||||
@@ -1,5 +1,6 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using MikuSB.Configuration;
|
||||
using MikuSB.Database.Account;
|
||||
using MikuSB.SdkServer.Models;
|
||||
using MikuSB.Util;
|
||||
using System.Text;
|
||||
@@ -12,6 +13,8 @@ public class RouteController : ControllerBase
|
||||
{
|
||||
public static ConfigContainer Config = ConfigManager.Config;
|
||||
|
||||
private const int DefaultAccountUid = 10001;
|
||||
|
||||
public static object BuildServerList(string version = "")
|
||||
{
|
||||
return new
|
||||
@@ -107,21 +110,70 @@ public class RouteController : ControllerBase
|
||||
code = 0,
|
||||
data = new
|
||||
{
|
||||
agreementUpdateTime = "1728552600000",
|
||||
appDownLoadUrl = "",
|
||||
enableReportDataToDouyin = false,
|
||||
loginType = new[] { "channel" },
|
||||
openActivationCode = false,
|
||||
qqGroup = (string?)null,
|
||||
privacyUpdateTime = "1728552600000",
|
||||
realNameAuth = false
|
||||
platformPrivacyAgreement = "https://www.amazingseasun.com/privacy.html?lang=zh-Hant&gamecode=200001086",
|
||||
payType = new[] { "mycard" },
|
||||
loginType = new[] { "mail", "google", "twitter", "guest", "steam" },
|
||||
closeGeetest = false,
|
||||
userAgreement = "https://www.amazingseasun.com/user.html?lang=zh-Hant&gamecode=111111680",
|
||||
privacyAgreement = "https://www.amazingseasun.com/privacy.html?lang=zh-Hant&gamecode=111111680",
|
||||
initPrivacyUpdateTime = 0,
|
||||
platformUserAgreement = "https://www.amazingseasun.com/user.html?lang=zh-Hant&gamecode=200001086",
|
||||
accountPublicKey = "",
|
||||
payChannel = (string[]?)null,
|
||||
registerPrivacyUrl = "https://xgsdk.xoyo.games:13443/seasun/privacy-agreement/200001086/register/privacy.html?language=zh-Hant",
|
||||
loginPrivacyUrl = "https://xgsdk.xoyo.games:13443/seasun/privacy-agreement/111111680/login/privacy.html?language=zh-Hant"
|
||||
},
|
||||
msg = "success"
|
||||
msg = "操作成功"
|
||||
};
|
||||
|
||||
return Ok(rsp);
|
||||
}
|
||||
|
||||
private static AccountData EnsureDefaultAccount()
|
||||
{
|
||||
var account = AccountData.GetAccountByUid(DefaultAccountUid)
|
||||
?? AccountData.GetAccountByEmail("default@mikusb.local");
|
||||
if (account != null)
|
||||
return account;
|
||||
|
||||
return AccountData.CreateAccount("default@mikusb.local", DefaultAccountUid, "");
|
||||
}
|
||||
|
||||
private static AccountData ResolveAccountByUid(string? uid)
|
||||
{
|
||||
if (int.TryParse(uid, out var parsedUid))
|
||||
{
|
||||
var accountByUid = AccountData.GetAccountByUid(parsedUid);
|
||||
if (accountByUid != null)
|
||||
return accountByUid;
|
||||
}
|
||||
|
||||
return EnsureDefaultAccount();
|
||||
}
|
||||
|
||||
private static AccountData ResolveAccountForSdkLogin(string? email, string? uid, string? token)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(token))
|
||||
{
|
||||
var accountByComboToken = AccountData.GetAccountByComboToken(token);
|
||||
if (accountByComboToken != null)
|
||||
return accountByComboToken;
|
||||
|
||||
var accountByDispatchToken = AccountData.GetAccountByDispatchToken(token);
|
||||
if (accountByDispatchToken != null)
|
||||
return accountByDispatchToken;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(email))
|
||||
{
|
||||
var accountByEmail = AccountData.GetAccountByEmail(email);
|
||||
if (accountByEmail != null)
|
||||
return accountByEmail;
|
||||
}
|
||||
|
||||
return ResolveAccountByUid(uid);
|
||||
}
|
||||
|
||||
[HttpGet("/seasun/loginByToken")]
|
||||
[HttpPost("/seasun/loginByToken")]
|
||||
public IActionResult LoginByToken(
|
||||
@@ -131,33 +183,67 @@ public class RouteController : ControllerBase
|
||||
[FromForm] string? form_token
|
||||
)
|
||||
{
|
||||
string finalUid = uid ?? form_uid ?? "10001";
|
||||
string finalToken = token ?? form_token ?? Guid.NewGuid().ToString("N");
|
||||
var account = ResolveAccountForSdkLogin(null, uid ?? form_uid, token ?? form_token);
|
||||
var finalUid = account.Uid.ToString();
|
||||
var finalToken = account.GenerateComboToken();
|
||||
|
||||
object rsp = new
|
||||
{
|
||||
code = 0,
|
||||
data = new
|
||||
{
|
||||
associatedAccounts = new[]
|
||||
{
|
||||
new { bindStatus = false, nickname = "", thirdPartyType = "mail" },
|
||||
new { bindStatus = true, nickname = Config.GameServer.GameServerName, thirdPartyType = "google" },
|
||||
new { bindStatus = false, nickname = "", thirdPartyType = "twitter" },
|
||||
new { bindStatus = false, nickname = "", thirdPartyType = "guest" },
|
||||
new { bindStatus = false, nickname = "", thirdPartyType = "steam" }
|
||||
},
|
||||
associatedAccounts = Array.Empty<string>(),
|
||||
isFirstLogin = false,
|
||||
isNeedKoreaSciAuth = false,
|
||||
ksOpenId = $"ks_{finalUid}",
|
||||
nickname = Config.GameServer.GameServerName,
|
||||
passportId = finalUid.Length > 10 ? finalUid[^10..] : finalUid,
|
||||
nickname = account.Username,
|
||||
passportId = finalUid,
|
||||
playerFillAgeUrl = "",
|
||||
status = 0,
|
||||
thirdPartyUid = "",
|
||||
token = finalToken,
|
||||
type = "google",
|
||||
uid = finalUid
|
||||
type = "guest",
|
||||
uid = account.Uid
|
||||
},
|
||||
msg = "操作成功"
|
||||
};
|
||||
|
||||
return Ok(rsp);
|
||||
}
|
||||
|
||||
[HttpGet("/seasun/login")]
|
||||
[HttpPost("/seasun/login")]
|
||||
public IActionResult Login(
|
||||
[FromQuery] string? uid,
|
||||
[FromQuery] string? token,
|
||||
[FromQuery] string? email,
|
||||
[FromForm] string? form_uid,
|
||||
[FromForm] string? form_token,
|
||||
[FromForm] string? form_email
|
||||
)
|
||||
{
|
||||
var finalEmail = email ?? form_email;
|
||||
var account = ResolveAccountForSdkLogin(finalEmail, uid ?? form_uid, token ?? form_token);
|
||||
var finalUid = account.Uid.ToString();
|
||||
var finalToken = account.GenerateComboToken();
|
||||
|
||||
object rsp = new
|
||||
{
|
||||
code = 0,
|
||||
data = new
|
||||
{
|
||||
associatedAccounts = Array.Empty<string>(),
|
||||
isFirstLogin = false,
|
||||
isNeedKoreaSciAuth = false,
|
||||
ksOpenId = $"ks_{finalUid}",
|
||||
nickname = account.Username,
|
||||
passportId = finalUid,
|
||||
playerFillAgeUrl = "",
|
||||
status = 0,
|
||||
thirdPartyUid = "",
|
||||
token = finalToken,
|
||||
type = "guest",
|
||||
uid = account.Uid
|
||||
},
|
||||
msg = "操作成功"
|
||||
};
|
||||
@@ -172,8 +258,8 @@ public class RouteController : ControllerBase
|
||||
[FromForm] string? form_uid
|
||||
)
|
||||
{
|
||||
string uidString = uid ?? form_uid ?? "10001";
|
||||
var finalUid = int.TryParse(uidString, out int parsedUid) ? parsedUid : 10001;
|
||||
var account = ResolveAccountByUid(uid ?? form_uid);
|
||||
var uidString = account.Uid.ToString();
|
||||
|
||||
object rsp = new
|
||||
{
|
||||
@@ -183,9 +269,9 @@ public class RouteController : ControllerBase
|
||||
bindAccountTypes = new[] { "google" },
|
||||
channelUid = uidString,
|
||||
loginAccountType = "google",
|
||||
nickName = Config.GameServer.GameServerName,
|
||||
passportId = uidString.Length > 10 ? uidString[^10..] : uidString,
|
||||
uid = $"seasun__{uid}"
|
||||
nickName = account.Username,
|
||||
passportId = uidString,
|
||||
uid = $"seasun__{uidString}"
|
||||
},
|
||||
msg = "操作成功"
|
||||
};
|
||||
@@ -252,7 +338,7 @@ public class RouteController : ControllerBase
|
||||
[HttpGet("/account/query-uid/{appId}")]
|
||||
public IActionResult QueryUid(string appId, [FromQuery] string authInfo)
|
||||
{
|
||||
var uid = ExtractUid(authInfo) ?? "10001";
|
||||
var uid = ResolveAccountByUid(ExtractUid(authInfo)).Uid.ToString();
|
||||
|
||||
object rsp = new
|
||||
{
|
||||
|
||||
@@ -17,17 +17,34 @@ public static class SdkServer
|
||||
{
|
||||
public static void Start(string[] args)
|
||||
{
|
||||
BuildWebHost(args).RunAsync();
|
||||
}
|
||||
var builder = Host.CreateDefaultBuilder(args)
|
||||
.ConfigureWebHostDefaults(webBuilder =>
|
||||
{
|
||||
webBuilder
|
||||
.UseStartup<Startup>()
|
||||
.ConfigureLogging((_, logging) => { logging.ClearProviders(); })
|
||||
.ConfigureKestrel(serverOptions =>
|
||||
{
|
||||
// Pre-warm cert before first TLS handshake
|
||||
_ = Utils.CertHelper.GetOrCreate(null);
|
||||
|
||||
private static IWebHost BuildWebHost(string[] args)
|
||||
{
|
||||
var builder = WebHost.CreateDefaultBuilder(args)
|
||||
.UseStartup<Startup>()
|
||||
.ConfigureLogging((_, logging) => { logging.ClearProviders(); })
|
||||
.UseUrls(ConfigManager.Config.HttpServer.GetDisplayAddress());
|
||||
var bindAddr = System.Net.IPAddress.Parse(ConfigManager.Config.HttpServer.BindAddress);
|
||||
foreach (var port in new[] { ConfigManager.Config.HttpServer.Port, 13443, 18443, 31443 })
|
||||
{
|
||||
serverOptions.Listen(bindAddr, port, o =>
|
||||
{
|
||||
o.UseHttps(https =>
|
||||
{
|
||||
https.ServerCertificateSelector = (_, sni) =>
|
||||
Utils.CertHelper.GetOrCreate(sni);
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return builder.Build();
|
||||
var host = builder.Build();
|
||||
host.RunAsync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,7 +108,7 @@ public class Startup
|
||||
{
|
||||
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower;
|
||||
});
|
||||
services.AddSingleton<Logger>(_ => new Logger("HttpServer"));
|
||||
services.AddSingleton<Logger>(_ => new Logger("Proxy"));
|
||||
services.AddMikuSbProxy(ConfigManager.Config.Proxy);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>MikuSB.SdkServer</RootNamespace>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user