Skip to content
Open
15 changes: 15 additions & 0 deletions AscNet.GameServer/Game/PurchaseCatalog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,21 @@ private static Dictionary<dynamic, dynamic> ToComboInfo(JObject combo)

private static bool HasEnded(long end, long now) => end > 0 && end <= now;

/// <summary>The client region's Name for a package id (Configs/purchase_names.json), else <paramref name="fallback"/>.</summary>
public static string LocalName(uint id, string? region, string fallback) =>
RegionText.Overlay(region, "purchase_names.json")[id.ToString()] is JObject entry && entry.Value<string>("Name") is { Length: > 0 } name ? name : fallback;

/// <summary>Replaces Name/Desc of a purchase info with the client region's text (Configs/purchase_names.json), if it has one.</summary>
public static void Localize(Dictionary<dynamic, dynamic> info, string? region)
{
if (!info.TryGetValue("Id", out dynamic? id)
|| RegionText.Overlay(region, "purchase_names.json")[Convert.ToString(id)] is not JObject text)
return;
foreach (string field in new[] { "Name", "Desc" })
if (text.Value<string>(field) is { Length: > 0 } value)
info[field] = value;
}

private static Dictionary<dynamic, dynamic> ToPurchaseInfo(JObject entry)
{
// A fresh recursive copy prevents a player's state from leaking into the catalog.
Expand Down
33 changes: 33 additions & 0 deletions AscNet.GameServer/Game/RegionText.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using AscNet.Common.Util;
using AscNet.Logging;
using Newtonsoft.Json.Linq;
using System.Collections.Concurrent;

namespace AscNet.GameServer.Game;

/// <summary>
/// Texts the server itself sends (shop and package names) come from EN-only snapshots. A region's replacements live in
/// Resources/regions/&lt;region&gt;/Configs/&lt;file&gt;; EN, a region without the file and an id missing from it keep the snapshot text.
/// </summary>
internal static class RegionText
{
private static readonly JObject Empty = new();
private static readonly ConcurrentDictionary<(string Region, string File), JObject> Overlays = new();
private static readonly Logger log = new(typeof(RegionText), LogLevel.DEBUG, LogLevel.DEBUG);

public static JObject Overlay(string? region, string file) =>
string.IsNullOrEmpty(region) || region == ClientRegions.Default || !ClientRegions.GateRegions.Contains(region)
? Empty
: Overlays.GetOrAdd((region, file), Load);

// A broken overlay must not break the request that reads it: log once and keep the snapshot (EN) text.
private static JObject Load((string Region, string File) key)
{
try { return JsonSnapshot.LoadObject(Path.Combine("regions", key.Region, "Configs", key.File)); }
catch (Exception error) when (error is Newtonsoft.Json.JsonException or IOException)
{
log.Error($"Ignoring region text {key.Region}/{key.File}: {error.Message}");
return new JObject();
}
}
}
44 changes: 44 additions & 0 deletions AscNet.GameServer/Game/ServerText.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@

namespace AscNet.GameServer.Game;

/// <summary>
/// Fixed texts the server itself writes into pushes and mails, per client region (JP/TW/KR/CN translations; any other region keeps EN).
/// Names of shops and packages are data and live in Resources/regions/&lt;region&gt;/Configs (<see cref="RegionText"/>).
/// </summary>
internal static class ServerText
{
private static string Pick(string? region, string en, string jp, string tw, string kr, string cn) => region switch
{
"jp" => jp, "tw" => tw, "kr" => kr, "cn" => cn, _ => en
};

public static string Lucia(string? region) =>
Pick(region, "System - Lucia", "システム - ルシア", "系統 - 露西亞", "시스템 - 루시아", "系统 - 露西亚");

public static string LoginGreeting(string? region, string player, string freeNotice) => Pick(region,
$"Hello {player}! {freeNotice}\n\nTry '/help' to get started",
$"こんにちは、{player}さん!{freeNotice}\n\n「/help」で始めましょう",
$"你好,{player}!{freeNotice}\n\n輸入「/help」開始使用",
$"안녕하세요, {player}님! {freeNotice}\n\n'/help'를 입력해 시작하세요",
$"你好,{player}!{freeNotice}\n\n输入“/help”开始使用");

public static string StrongholdSender(string? region) =>
Pick(region, "Norman Revival Plan", "ノルマン復興戦", "諾曼復興戰", "노르만 부흥전", "诺曼复兴战");

public static string StrongholdResultTitle(string? region) => Pick(region,
"Norman Revival Plan results", "ノルマン復興戦 結果", "諾曼復興戰 結算", "노르만 부흥전 결과", "诺曼复兴战 结算");

public static string StrongholdUnclaimedTitle(string? region) => Pick(region,
"Norman Revival Plan unclaimed rewards", "ノルマン復興戦 未受取の報酬", "諾曼復興戰 未領取獎勵",
"노르만 부흥전 미수령 보상", "诺曼复兴战 未领取奖励");

public static string StrongholdUnclaimedReward(string? region, string desc) => Pick(region,
$"Unclaimed reward: {desc}", $"未受取の報酬:{desc}", $"未領取的獎勵:{desc}", $"미수령 보상: {desc}", $"未领取的奖励:{desc}");

public static string StrongholdCycleResult(string? region, int cycle, int finished, int ore) => Pick(region,
$"Cycle {cycle} complete. Stages cleared: {finished}. Ore earned: {ore}.",
$"サイクル{cycle}が完了しました。クリアしたステージ:{finished}。獲得した鉱石:{ore}。",
$"第{cycle}週期已完成。通關關卡數:{finished}。獲得礦石:{ore}。",
$"사이클 {cycle} 완료. 클리어한 스테이지: {finished}. 획득한 광석: {ore}.",
$"第{cycle}周期已完成。通关关卡数:{finished}。获得矿石:{ore}。");
}
13 changes: 7 additions & 6 deletions AscNet.GameServer/Handlers/AccountModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1020,19 +1020,19 @@ private static NotifyFunctionalEntranceData BuildFunctionalEntranceData(Player p
return new() { RedPointDatas = new(player.FunctionalEntranceRedPoints) };
}

private static PurchaseDailyNotify BuildPurchaseDailyNotify()
private static PurchaseDailyNotify BuildPurchaseDailyNotify(string? region)
{
PurchaseDailyNotify notify = new();
notify.FreeRewardInfoList.Add(new()
{
Id = 90943,
Name = "Serum Daily Supply",
Name = PurchaseCatalog.LocalName(90943, region, "Serum Daily Supply"),
UiType = 6
});
notify.FreeRewardInfoList.Add(new()
{
Id = 90944,
Name = "Weekly Limited Pack",
Name = PurchaseCatalog.LocalName(90944, region, "Weekly Limited Pack"),
UiType = 6
});

Expand Down Expand Up @@ -1404,7 +1404,7 @@ static void DoLogin(Session session, bool updateLoginAccounting)
NotifyMails notifyMails = MailModule.BuildNotifyMails(session.player, mailNow);
requireCheckedSave |= mailStateChanged;
NotifyFunctionalEntranceData notifyFunctionalEntranceData = BuildFunctionalEntranceData(session.player);
PurchaseDailyNotify purchaseDailyNotify = BuildPurchaseDailyNotify();
PurchaseDailyNotify purchaseDailyNotify = BuildPurchaseDailyNotify(FreeNotice.RegionOf(session.player));
PayModule.AddSignInNotifications(purchaseDailyNotify, session.player);
foreach (uint id in session.player.PurchaseDailyPasses.Keys)
if (PayModule.RemainingDays(session.player, id) > 0
Expand Down Expand Up @@ -1608,9 +1608,10 @@ internal static NotifyWorldChat BuildLoginWorldChat(Session session)
{
string region = FreeNotice.RegionOf(session.player);
NotifyWorldChat loginWorldChat = new();
loginWorldChat.ChatMessages.Add(ChatModule.MakeLuciaWorldMessage($"Hello {session.player.PlayerData.Name}! {FreeNotice.FreeText(region)}\n\nTry '/help' to get started"));
loginWorldChat.ChatMessages.Add(ChatModule.MakeLuciaWorldMessage(
ServerText.LoginGreeting(region, session.player.PlayerData.Name, FreeNotice.FreeText(region)), region));
if (session.IsHosted)
loginWorldChat.ChatMessages.Add(ChatModule.MakeLuciaWorldMessage(FreeNotice.HostedText(region)));
loginWorldChat.ChatMessages.Add(ChatModule.MakeLuciaWorldMessage(FreeNotice.HostedText(region), region));
return loginWorldChat;
}

Expand Down
14 changes: 7 additions & 7 deletions AscNet.GameServer/Handlers/ChatModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ public static void SendChatRequestHandler(Session session, Packet.Request packet
else session.SendPush(notifyChatMessage);
session.SendResponse(new SendChatResponse { Code = 0, RefreshTime = 0 }, packet.Id);
if (commandFeedback is not null)
session.SendPush(BuildCommandFeedback(request.ChatData.ChannelType, commandFeedback));
session.SendPush(BuildCommandFeedback(request.ChatData.ChannelType, commandFeedback, FreeNotice.RegionOf(session.player)));
session.SendPush(notifyWorldChat);
}

Expand Down Expand Up @@ -398,7 +398,7 @@ internal static NotifyChatMessage BuildNotifyChatMessage(Session session, ChatDa
};
}

private static NotifyChatMessage BuildCommandFeedback(ChatChannelType channelType, string content)
private static NotifyChatMessage BuildCommandFeedback(ChatChannelType channelType, string content, string? region)
{
return new()
{
Expand All @@ -408,7 +408,7 @@ private static NotifyChatMessage BuildCommandFeedback(ChatChannelType channelTyp
SenderId = 88_001,
Icon = 9_010_102,
CreateTime = DateTimeOffset.Now.ToUnixTimeSeconds(),
NickName = "System - Lucia",
NickName = AscNet.GameServer.Game.ServerText.Lucia(region),
Content = content
};
}
Expand Down Expand Up @@ -440,7 +440,7 @@ public static void SelectChatChannelRequestHandler(Session session, Packet.Reque
session.SendResponse(new SelectChatChannelResponse { Code = 0 }, packet.Id);
}

public static ChatData MakeLuciaMessage(string content)
public static ChatData MakeLuciaMessage(string content, string? region = null)
{
return new ChatData()
{
Expand All @@ -450,14 +450,14 @@ public static ChatData MakeLuciaMessage(string content)
ChannelType = ChatChannelType.World,
MsgType = ChatMsgType.Normal,
SenderId = 0,
NickName = "System - Lucia",
NickName = AscNet.GameServer.Game.ServerText.Lucia(region),
CreateTime = DateTimeOffset.Now.ToUnixTimeSeconds()
};
}

public static ChatData MakeLuciaWorldMessage(string content)
public static ChatData MakeLuciaWorldMessage(string content, string? region = null)
{
ChatData message = MakeLuciaMessage(content);
ChatData message = MakeLuciaMessage(content, region);
message.SenderId = 88001;
return message;
}
Expand Down
1 change: 1 addition & 0 deletions AscNet.GameServer/Handlers/PayModule.Store.cs
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ internal static void GrantMailDailyRewards(Session session, bool sendPush = true
if (pass.LastClaimDay >= day) continue;
long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var rewards = ReadPurchaseRewards(new() { ["RewardGoodsList"] = info!["DailyRewardGoodsList"] }, 1);
AscNet.GameServer.Game.PurchaseCatalog.Localize(info, FreeNotice.RegionOf(session.player));
PlayerMail mail = new()
{
Id = $"purchase-daily:{session.player.PlayerData.Id}:{id}:{day}",
Expand Down
1 change: 1 addition & 0 deletions AscNet.GameServer/Handlers/PayModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ private static void ApplyPurchaseState(List<dynamic> purchaseInfoList, Player? p
if (purchaseInfo is not Dictionary<dynamic, dynamic> data)
continue;
uint id = ReadDynamicUInt(data, "Id");
PurchaseCatalog.Localize(data, player is null ? null : FreeNotice.RegionOf(player));
data["BuyTimes"] = player is null ? 0 : CurrentBuyTimes(player, data);
data["LastBuyTime"] = player?.PurchaseLastBuyTimes.GetValueOrDefault(id) ?? 0L;
if (player?.PurchaseBuyTimes.GetValueOrDefault(id) > 0)
Expand Down
31 changes: 26 additions & 5 deletions AscNet.GameServer/Handlers/ShopModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ public static void GetFixedShopAllInfoRequestHandler(Session session, Packet.Req
session.SendResponse(new GetFixedShopAllInfoResponse
{
Code = code,
ShopBaseInfoList = BuildShopBaseInfoList(shopIds.ToHashSet()),
ShopBaseInfoList = BuildShopBaseInfoList(FreeNotice.RegionOf(session.player), shopIds.ToHashSet()),
ShopValidInfos = shopIds.Select(shopId => BuildShopValidInfo(session, shopId)).ToList(),
ClientShopList = clientShopList
}, packet.Id);
Expand Down Expand Up @@ -399,15 +399,32 @@ public static void BuyRequestHandler(Session session, Packet.Request packet)
[RequestPacketHandler("GetShopBaseInfoRequest")]
public static void GetShopBaseInfoRequestHandler(Session session, Packet.Request packet)
{
session.SendResponse(BuildShopBaseInfoResponse(), packet.Id);
session.SendResponse(BuildShopBaseInfoResponse(FreeNotice.RegionOf(session.player)), packet.Id);
}

private static GetShopBaseInfoResponse BuildShopBaseInfoResponse() => new()
private static GetShopBaseInfoResponse BuildShopBaseInfoResponse(string? region) => new()
{
ShopBaseInfoList = BuildShopBaseInfoList()
ShopBaseInfoList = BuildShopBaseInfoList(region)
};

private static List<dynamic> BuildShopBaseInfoList(HashSet<uint>? filterIds = null)
/// <summary>
/// Shop names the shared EN snapshots carry, replaced per client region from Resources/regions/&lt;region&gt;/Configs/shop_names.json
/// ({"shops": {"&lt;shopId&gt;": name}, "baseInfos": {"&lt;shopId&gt;": name}}); a region without that file, or an id missing from it, keeps the EN name.
/// </summary>
internal static class ShopNames
{
private static string Lookup(string? region, string section, uint shopId, string fallback)
{
string? name = RegionText.Overlay(region, "shop_names.json")[section]?[shopId.ToString()]?.Value<string>();
return string.IsNullOrEmpty(name) ? fallback : name;
}

public static string Shop(string? region, uint shopId, string fallback) => Lookup(region, "shops", shopId, fallback);

public static string BaseInfo(string? region, uint shopId, string fallback) => Lookup(region, "baseInfos", shopId, fallback);
}

private static List<dynamic> BuildShopBaseInfoList(string? region, HashSet<uint>? filterIds = null)
{
JObject snapshot = JsonSnapshot.LoadObject(ShopBaseInfoSnapshotPath);
// Dorm's Type=101 tabs are usable only when their static catalog exists.
Expand All @@ -418,6 +435,9 @@ private static List<dynamic> BuildShopBaseInfoList(HashSet<uint>? filterIds = nu
|| ShopCatalog(ReadUInt(row, "Id")) is { GoodsList.Count: > 0 });
if (filterIds is not null)
rows = rows.Where(row => filterIds.Contains(ReadUInt(row, "Id")));
rows = rows.ToList();
foreach (JObject row in rows)
row["Name"] = ShopNames.BaseInfo(region, ReadUInt(row, "Id"), row.Value<string>("Name") ?? string.Empty);
return JsonSnapshot.ReadDynamicList(new JArray(rows));
}

Expand Down Expand Up @@ -465,6 +485,7 @@ private static ClientShop BuildClientShop(uint shopId, Player player)
if (ShopCatalog(shopId) is { } snapshot)
{
ClientShop shop = CloneClientShop(snapshot);
shop.Name = ShopNames.Shop(FreeNotice.RegionOf(player), shopId, shop.Name);
if (IsTheatre6Shop(shopId))
shop.ClosedTime = checked((int)Theatre6ShopWindow(shopId).EndTime);
if (ReconcileManualShopRefresh(player, shopId, DateTimeOffset.UtcNow))
Expand Down
8 changes: 4 additions & 4 deletions AscNet.GameServer/Handlers/StrongholdModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ private static void SettleExpiredCycle(Player player, long now)
throw new InvalidDataException($"Empty Stronghold settlement reward {reward.RewardId}.");
AddSettlementMail(player, Config("UnGetRewardMail"), reward.Id, now, goods,
RewardKey(player, reward.Id),
$"Unclaimed reward: {reward.Desc}");
ServerText.StrongholdUnclaimedReward(FreeNotice.RegionOf(player), reward.Desc));
state.RewardIds.Add(reward.Id);
state.ClaimedRewardIds.Add(reward.Id);
}
Expand All @@ -381,7 +381,7 @@ private static void SettleExpiredCycle(Player player, long now)
result.MinerCount = state.MineRecords[^1].MinerCount;
state.LastResultRecord = result;
AddSettlementMail(player, Config("ResultMail"), 0, now, null, null,
$"Cycle {result.Id} complete. Stages cleared: {result.FinishCount}. Ore earned: {result.MineralCount}.");
ServerText.StrongholdCycleResult(FreeNotice.RegionOf(player), result.Id, result.FinishCount, result.MineralCount));
}

private static void AddSettlementMail(Player player, int templateId, int rewardId, long now,
Expand All @@ -396,8 +396,8 @@ private static void AddSettlementMail(Player player, int templateId, int rewardI
{
Id = id,
GroupId = templateId,
SendName = "Norman Revival Plan",
Title = goods is null ? "Norman Revival Plan results" : "Norman Revival Plan unclaimed rewards",
SendName = ServerText.StrongholdSender(FreeNotice.RegionOf(player)),
Title = goods is null ? ServerText.StrongholdResultTitle(FreeNotice.RegionOf(player)) : ServerText.StrongholdUnclaimedTitle(FreeNotice.RegionOf(player)),
Content = content,
CreateTime = now,
SendTime = now,
Expand Down
Loading
Loading