123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- using MiniWebApi.Utilities;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using Vinno.IUS.Common.Configuration;
- using Vinno.vCloud.Disk;
- namespace Vinno.vCloud.Disk.Language
- {
- public class WebTranslateHelper
- {
- public const string ChineseLanguageKey = "Chinese";
- public const string EnglishLanguageKey = "English";
- private static readonly Dictionary<string, string> DefaultNls = new Dictionary<string, string>
- {
- {ChineseLanguageKey, "Chinese"},
- {EnglishLanguageKey, "English"},
- };
- private static readonly Dictionary<string, string> _cultureToLanguage = new Dictionary<string, string>();
- private static readonly Dictionary<string, ConfigManager> _configManagers = new Dictionary<string, ConfigManager>();
- private static readonly ViewEngine _viewEngine = new ViewEngine();
- public static string[] SupportedLanguages => DefaultNls.Keys.ToArray();
- static WebTranslateHelper()
- {
- foreach (KeyValuePair<string, string> keyValuePair in DefaultNls)
- {
- _cultureToLanguage[keyValuePair.Value.ToLower()] = keyValuePair.Key;
- var languagePath = $"Language/{keyValuePair.Key}.json";
- using (var languageStream = _viewEngine.GetResourceFile(languagePath))
- {
- using (var reader = new StreamReader(languageStream))
- {
- var content = reader.ReadToEnd();
- WebTranslateHelper.AddLanguageResource(keyValuePair.Key, content);
- Vinno.IUS.Common.Utilities.TranslateHelper.AddLanguageResource(keyValuePair.Key, content);
- }
- }
- }
- }
- private static void AddLanguageResource(string language, string resource)
- {
- if (!_configManagers.ContainsKey(language))
- {
- _configManagers.Add(language, new ConfigManager(resource));
- }
- }
- /// <summary>
- /// Translate to target Language with specified key.
- /// </summary>
- /// <param name="key"></param>
- /// <param name="language"></param>
- /// <returns></returns>
- public static string Translate(string key, string language = null)
- {
- var currentLanguage = language ?? ContextBase.Current?.Context.Request.Cookies["lang"]?.Value ?? "English";
- ConfigManager languageManager = null;
- if (_configManagers.ContainsKey(currentLanguage))
- {
- languageManager = _configManagers[currentLanguage];
- }
- if (string.IsNullOrEmpty(key))
- {
- return string.Empty;
- }
- var translatedValue = languageManager?.GetValue("Languages", key, string.Empty);
- if (string.IsNullOrEmpty(translatedValue))
- {
- return key;
- }
- return translatedValue.Replace("\\r\\n", Environment.NewLine);
- }
- }
- }
|