ServerPreferencesManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. using System.Diagnostics.CodeAnalysis;
  2. using System.Linq;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using Content.Server.Database;
  6. using Content.Shared.CCVar;
  7. using Content.Shared.Preferences;
  8. using Robust.Server.Player;
  9. using Robust.Shared.Configuration;
  10. using Robust.Shared.Network;
  11. using Robust.Shared.Player;
  12. using Robust.Shared.Utility;
  13. namespace Content.Server.Preferences.Managers
  14. {
  15. /// <summary>
  16. /// Sends <see cref="MsgPreferencesAndSettings"/> before the client joins the lobby.
  17. /// Receives <see cref="MsgSelectCharacter"/> and <see cref="MsgUpdateCharacter"/> at any time.
  18. /// </summary>
  19. public sealed class ServerPreferencesManager : IServerPreferencesManager, IPostInjectInit
  20. {
  21. [Dependency] private readonly IServerNetManager _netManager = default!;
  22. [Dependency] private readonly IConfigurationManager _cfg = default!;
  23. [Dependency] private readonly IServerDbManager _db = default!;
  24. [Dependency] private readonly IPlayerManager _playerManager = default!;
  25. [Dependency] private readonly IDependencyCollection _dependencies = default!;
  26. [Dependency] private readonly ILogManager _log = default!;
  27. [Dependency] private readonly UserDbDataManager _userDb = default!;
  28. // Cache player prefs on the server so we don't need as much async hell related to them.
  29. private readonly Dictionary<NetUserId, PlayerPrefData> _cachedPlayerPrefs =
  30. new();
  31. private ISawmill _sawmill = default!;
  32. private int MaxCharacterSlots => _cfg.GetCVar(CCVars.GameMaxCharacterSlots);
  33. public void Init()
  34. {
  35. _netManager.RegisterNetMessage<MsgPreferencesAndSettings>();
  36. _netManager.RegisterNetMessage<MsgSelectCharacter>(HandleSelectCharacterMessage);
  37. _netManager.RegisterNetMessage<MsgUpdateCharacter>(HandleUpdateCharacterMessage);
  38. _netManager.RegisterNetMessage<MsgDeleteCharacter>(HandleDeleteCharacterMessage);
  39. _sawmill = _log.GetSawmill("prefs");
  40. }
  41. private async void HandleSelectCharacterMessage(MsgSelectCharacter message)
  42. {
  43. var index = message.SelectedCharacterIndex;
  44. var userId = message.MsgChannel.UserId;
  45. if (!_cachedPlayerPrefs.TryGetValue(userId, out var prefsData) || !prefsData.PrefsLoaded)
  46. {
  47. Logger.WarningS("prefs", $"User {userId} tried to modify preferences before they loaded.");
  48. return;
  49. }
  50. if (index < 0 || index >= MaxCharacterSlots)
  51. {
  52. return;
  53. }
  54. var curPrefs = prefsData.Prefs!;
  55. if (!curPrefs.Characters.ContainsKey(index))
  56. {
  57. // Non-existent slot.
  58. return;
  59. }
  60. prefsData.Prefs = new PlayerPreferences(curPrefs.Characters, index, curPrefs.AdminOOCColor);
  61. if (ShouldStorePrefs(message.MsgChannel.AuthType))
  62. {
  63. await _db.SaveSelectedCharacterIndexAsync(message.MsgChannel.UserId, message.SelectedCharacterIndex);
  64. }
  65. }
  66. private async void HandleUpdateCharacterMessage(MsgUpdateCharacter message)
  67. {
  68. var userId = message.MsgChannel.UserId;
  69. // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
  70. if (message.Profile == null)
  71. _sawmill.Error($"User {userId} sent a {nameof(MsgUpdateCharacter)} with a null profile in slot {message.Slot}.");
  72. else
  73. await SetProfile(userId, message.Slot, message.Profile);
  74. }
  75. public async Task SetProfile(NetUserId userId, int slot, ICharacterProfile profile)
  76. {
  77. if (!_cachedPlayerPrefs.TryGetValue(userId, out var prefsData) || !prefsData.PrefsLoaded)
  78. {
  79. _sawmill.Error($"Tried to modify user {userId} preferences before they loaded.");
  80. return;
  81. }
  82. if (slot < 0 || slot >= MaxCharacterSlots)
  83. return;
  84. var curPrefs = prefsData.Prefs!;
  85. var session = _playerManager.GetSessionById(userId);
  86. profile.EnsureValid(session, _dependencies);
  87. var profiles = new Dictionary<int, ICharacterProfile>(curPrefs.Characters)
  88. {
  89. [slot] = profile
  90. };
  91. prefsData.Prefs = new PlayerPreferences(profiles, slot, curPrefs.AdminOOCColor);
  92. if (ShouldStorePrefs(session.Channel.AuthType))
  93. await _db.SaveCharacterSlotAsync(userId, profile, slot);
  94. }
  95. private async void HandleDeleteCharacterMessage(MsgDeleteCharacter message)
  96. {
  97. var slot = message.Slot;
  98. var userId = message.MsgChannel.UserId;
  99. if (!_cachedPlayerPrefs.TryGetValue(userId, out var prefsData) || !prefsData.PrefsLoaded)
  100. {
  101. Logger.WarningS("prefs", $"User {userId} tried to modify preferences before they loaded.");
  102. return;
  103. }
  104. if (slot < 0 || slot >= MaxCharacterSlots)
  105. {
  106. return;
  107. }
  108. var curPrefs = prefsData.Prefs!;
  109. // If they try to delete the slot they have selected then we switch to another one.
  110. // Of course, that's only if they HAVE another slot.
  111. int? nextSlot = null;
  112. if (curPrefs.SelectedCharacterIndex == slot)
  113. {
  114. // That ! on the end is because Rider doesn't like .NET 5.
  115. var (ns, profile) = curPrefs.Characters.FirstOrDefault(p => p.Key != message.Slot)!;
  116. if (profile == null)
  117. {
  118. // Only slot left, can't delete.
  119. return;
  120. }
  121. nextSlot = ns;
  122. }
  123. var arr = new Dictionary<int, ICharacterProfile>(curPrefs.Characters);
  124. arr.Remove(slot);
  125. prefsData.Prefs = new PlayerPreferences(arr, nextSlot ?? curPrefs.SelectedCharacterIndex, curPrefs.AdminOOCColor);
  126. if (ShouldStorePrefs(message.MsgChannel.AuthType))
  127. {
  128. if (nextSlot != null)
  129. {
  130. await _db.DeleteSlotAndSetSelectedIndex(userId, slot, nextSlot.Value);
  131. }
  132. else
  133. {
  134. await _db.SaveCharacterSlotAsync(userId, null, slot);
  135. }
  136. }
  137. }
  138. // Should only be called via UserDbDataManager.
  139. public async Task LoadData(ICommonSession session, CancellationToken cancel)
  140. {
  141. if (!ShouldStorePrefs(session.Channel.AuthType))
  142. {
  143. // Don't store data for guests.
  144. var prefsData = new PlayerPrefData
  145. {
  146. PrefsLoaded = true,
  147. Prefs = new PlayerPreferences(
  148. new[] {new KeyValuePair<int, ICharacterProfile>(0, HumanoidCharacterProfile.Random())},
  149. 0, Color.Transparent)
  150. };
  151. _cachedPlayerPrefs[session.UserId] = prefsData;
  152. }
  153. else
  154. {
  155. var prefsData = new PlayerPrefData();
  156. var loadTask = LoadPrefs();
  157. _cachedPlayerPrefs[session.UserId] = prefsData;
  158. await loadTask;
  159. async Task LoadPrefs()
  160. {
  161. var prefs = await GetOrCreatePreferencesAsync(session.UserId, cancel);
  162. prefsData.Prefs = prefs;
  163. }
  164. }
  165. }
  166. public void FinishLoad(ICommonSession session)
  167. {
  168. // This is a separate step from the actual database load.
  169. // Sanitizing preferences requires play time info due to loadouts.
  170. // And play time info is loaded concurrently from the DB with preferences.
  171. var prefsData = _cachedPlayerPrefs[session.UserId];
  172. DebugTools.Assert(prefsData.Prefs != null);
  173. prefsData.Prefs = SanitizePreferences(session, prefsData.Prefs, _dependencies);
  174. prefsData.PrefsLoaded = true;
  175. var msg = new MsgPreferencesAndSettings();
  176. msg.Preferences = prefsData.Prefs;
  177. msg.Settings = new GameSettings
  178. {
  179. MaxCharacterSlots = MaxCharacterSlots
  180. };
  181. _netManager.ServerSendMessage(msg, session.Channel);
  182. }
  183. public void OnClientDisconnected(ICommonSession session)
  184. {
  185. _cachedPlayerPrefs.Remove(session.UserId);
  186. }
  187. public bool HavePreferencesLoaded(ICommonSession session)
  188. {
  189. return _cachedPlayerPrefs.ContainsKey(session.UserId);
  190. }
  191. /// <summary>
  192. /// Tries to get the preferences from the cache
  193. /// </summary>
  194. /// <param name="userId">User Id to get preferences for</param>
  195. /// <param name="playerPreferences">The user preferences if true, otherwise null</param>
  196. /// <returns>If preferences are not null</returns>
  197. public bool TryGetCachedPreferences(NetUserId userId,
  198. [NotNullWhen(true)] out PlayerPreferences? playerPreferences)
  199. {
  200. if (_cachedPlayerPrefs.TryGetValue(userId, out var prefs))
  201. {
  202. playerPreferences = prefs.Prefs;
  203. return prefs.Prefs != null;
  204. }
  205. playerPreferences = null;
  206. return false;
  207. }
  208. /// <summary>
  209. /// Retrieves preferences for the given username from storage.
  210. /// </summary>
  211. public PlayerPreferences GetPreferences(NetUserId userId)
  212. {
  213. var prefs = _cachedPlayerPrefs[userId].Prefs;
  214. if (prefs == null)
  215. {
  216. throw new InvalidOperationException("Preferences for this player have not loaded yet.");
  217. }
  218. return prefs;
  219. }
  220. /// <summary>
  221. /// Retrieves preferences for the given username from storage or returns null.
  222. /// </summary>
  223. public PlayerPreferences? GetPreferencesOrNull(NetUserId? userId)
  224. {
  225. if (userId == null)
  226. return null;
  227. if (_cachedPlayerPrefs.TryGetValue(userId.Value, out var pref))
  228. return pref.Prefs;
  229. return null;
  230. }
  231. private async Task<PlayerPreferences> GetOrCreatePreferencesAsync(NetUserId userId, CancellationToken cancel)
  232. {
  233. var prefs = await _db.GetPlayerPreferencesAsync(userId, cancel);
  234. if (prefs is null)
  235. {
  236. return await _db.InitPrefsAsync(userId, HumanoidCharacterProfile.Random(), cancel);
  237. }
  238. return prefs;
  239. }
  240. private PlayerPreferences SanitizePreferences(ICommonSession session, PlayerPreferences prefs, IDependencyCollection collection)
  241. {
  242. // Clean up preferences in case of changes to the game,
  243. // such as removed jobs still being selected.
  244. return new PlayerPreferences(prefs.Characters.Select(p =>
  245. {
  246. return new KeyValuePair<int, ICharacterProfile>(p.Key, p.Value.Validated(session, collection));
  247. }), prefs.SelectedCharacterIndex, prefs.AdminOOCColor);
  248. }
  249. public IEnumerable<KeyValuePair<NetUserId, ICharacterProfile>> GetSelectedProfilesForPlayers(
  250. List<NetUserId> usernames)
  251. {
  252. return usernames
  253. .Select(p => (_cachedPlayerPrefs[p].Prefs, p))
  254. .Where(p => p.Prefs != null)
  255. .Select(p => new KeyValuePair<NetUserId, ICharacterProfile>(p.p, p.Prefs!.SelectedCharacter));
  256. }
  257. internal static bool ShouldStorePrefs(LoginType loginType)
  258. {
  259. return loginType.HasStaticUserId();
  260. }
  261. private sealed class PlayerPrefData
  262. {
  263. public bool PrefsLoaded;
  264. public PlayerPreferences? Prefs;
  265. }
  266. void IPostInjectInit.PostInject()
  267. {
  268. _userDb.AddOnLoadPlayer(LoadData);
  269. _userDb.AddOnFinishLoad(FinishLoad);
  270. _userDb.AddOnPlayerDisconnect(OnClientDisconnected);
  271. }
  272. }
  273. }