WebTranslateHelper.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using MiniWebApi.Utilities;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using Vinno.IUS.Common.Configuration;
  7. using Vinno.vCloud.Disk;
  8. namespace Vinno.vCloud.Disk.Language
  9. {
  10. public class WebTranslateHelper
  11. {
  12. public const string ChineseLanguageKey = "Chinese";
  13. public const string EnglishLanguageKey = "English";
  14. private static readonly Dictionary<string, string> DefaultNls = new Dictionary<string, string>
  15. {
  16. {ChineseLanguageKey, "Chinese"},
  17. {EnglishLanguageKey, "English"},
  18. };
  19. private static readonly Dictionary<string, string> _cultureToLanguage = new Dictionary<string, string>();
  20. private static readonly Dictionary<string, ConfigManager> _configManagers = new Dictionary<string, ConfigManager>();
  21. private static readonly ViewEngine _viewEngine = new ViewEngine();
  22. public static string[] SupportedLanguages => DefaultNls.Keys.ToArray();
  23. static WebTranslateHelper()
  24. {
  25. foreach (KeyValuePair<string, string> keyValuePair in DefaultNls)
  26. {
  27. _cultureToLanguage[keyValuePair.Value.ToLower()] = keyValuePair.Key;
  28. var languagePath = $"Language/{keyValuePair.Key}.json";
  29. using (var languageStream = _viewEngine.GetResourceFile(languagePath))
  30. {
  31. using (var reader = new StreamReader(languageStream))
  32. {
  33. var content = reader.ReadToEnd();
  34. WebTranslateHelper.AddLanguageResource(keyValuePair.Key, content);
  35. Vinno.IUS.Common.Utilities.TranslateHelper.AddLanguageResource(keyValuePair.Key, content);
  36. }
  37. }
  38. }
  39. }
  40. private static void AddLanguageResource(string language, string resource)
  41. {
  42. if (!_configManagers.ContainsKey(language))
  43. {
  44. _configManagers.Add(language, new ConfigManager(resource));
  45. }
  46. }
  47. /// <summary>
  48. /// Translate to target Language with specified key.
  49. /// </summary>
  50. /// <param name="key"></param>
  51. /// <param name="language"></param>
  52. /// <returns></returns>
  53. public static string Translate(string key, string language = null)
  54. {
  55. var currentLanguage = language ?? ContextBase.Current?.Context.Request.Cookies["lang"]?.Value ?? "English";
  56. ConfigManager languageManager = null;
  57. if (_configManagers.ContainsKey(currentLanguage))
  58. {
  59. languageManager = _configManagers[currentLanguage];
  60. }
  61. if (string.IsNullOrEmpty(key))
  62. {
  63. return string.Empty;
  64. }
  65. var translatedValue = languageManager?.GetValue("Languages", key, string.Empty);
  66. if (string.IsNullOrEmpty(translatedValue))
  67. {
  68. return key;
  69. }
  70. return translatedValue.Replace("\\r\\n", Environment.NewLine);
  71. }
  72. }
  73. }