RoomEncrypter.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using MafiaTelegramBot.Resources;
  5. namespace MafiaTelegramBot.Game
  6. {
  7. public static class RoomEncrypter
  8. {
  9. private static readonly Dictionary<string, string> ShortName = new();
  10. private static readonly Dictionary<string, string> FullName = new();
  11. public static string GetCode(string roomName)
  12. {
  13. if (ShortName.ContainsKey(roomName)) return ShortName[roomName];
  14. var shortName = RandomString();
  15. while (ShortName.ContainsKey(shortName)) shortName = RandomString();
  16. ShortName.Add(roomName, shortName);
  17. FullName.Add(shortName, roomName);
  18. return shortName;
  19. }
  20. public static string GetName(string roomKey)
  21. {
  22. return FullName[roomKey];
  23. }
  24. public static void RemoveCode(string roomName)
  25. {
  26. FullName.Remove(GetCode(roomName));
  27. ShortName.Remove(roomName);
  28. }
  29. private static readonly Random Random = new();
  30. private static string RandomString(int length = Constants.ROOM_CODE_LENGTH)
  31. {
  32. const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  33. return new string(Enumerable.Repeat(chars, length)
  34. .Select(s => s[Random.Next(s.Length)]).ToArray());
  35. }
  36. }
  37. }