JsonFileManager.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text.Json;
  5. using Microsoft.Extensions.Configuration;
  6. namespace BubbleSocketCore.Library
  7. {
  8. public class JsonFileManager
  9. {
  10. private readonly SHA256HashGenerator sha256HashGenerator;
  11. private readonly IConfiguration Configuration;
  12. public JsonFileManager(IConfiguration configuration)
  13. {
  14. sha256HashGenerator = SHA256HashGenerator.GetInstance();
  15. Configuration = configuration;
  16. }
  17. public string GetAccountFilePath(string username)
  18. {
  19. var filename = sha256HashGenerator.Get(username + Configuration.GetValue<string>("ServerSalt")) + ".json";
  20. string accountFilePath = Configuration["AccountFilePath"];
  21. return Path.Combine(accountFilePath, filename);
  22. }
  23. public JsonElement ReadAccountFile(string username)
  24. {
  25. var json = System.IO.File.ReadAllText(GetAccountFilePath(username));
  26. return JsonSerializer.Deserialize<dynamic>(json);
  27. }
  28. public void WriteAccountFile(string username, dynamic data)
  29. {
  30. var json = JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true });
  31. System.IO.File.WriteAllText(GetAccountFilePath(username), json);
  32. }
  33. public bool DoesAccountAlreadyExist(string username)
  34. {
  35. return System.IO.File.Exists(GetAccountFilePath(username));
  36. }
  37. public string GetCharacterListFilePath(string accountId)
  38. {
  39. var filename = sha256HashGenerator.Get(accountId) + ".json";
  40. string accountFilePath = Configuration["DataStoreFilePath"];
  41. return Path.Combine(accountFilePath, "characters" ,filename);
  42. }
  43. public List<Character> GetCharacterList(string accountId)
  44. {
  45. var characterListFilePath = GetCharacterListFilePath(accountId);
  46. if (!System.IO.File.Exists(characterListFilePath))
  47. {
  48. var newCharacterData = new List<Character>() { new Character("demo", "default") };
  49. var newCharacterJson = JsonSerializer.Serialize(newCharacterData, new JsonSerializerOptions { WriteIndented = true });
  50. System.IO.File.WriteAllText(characterListFilePath, newCharacterJson);
  51. }
  52. var json = System.IO.File.ReadAllText(characterListFilePath);
  53. return JsonSerializer.Deserialize<List<Character>>(json);
  54. }
  55. }
  56. public class Character
  57. {
  58. public string Name { get; }
  59. public string Channel { get; }
  60. public Character(string name, string channel)
  61. {
  62. Name = name;
  63. Channel = channel;
  64. }
  65. }
  66. }