From 3932b2025d40e7507a84ee6f2c21132525715829 Mon Sep 17 00:00:00 2001 From: zggsong Date: Sun, 14 Jan 2024 14:28:26 +0800 Subject: [PATCH] chore: Organize your code --- .csharpierrc.json | 2 +- STranslate/ViewModels/InputViewModel.cs | 119 ++++-------------- .../History/HistoryContentViewModel.cs | 4 + STranslate/ViewModels/ServiceHandler.cs | 101 +++++++++++++++ 4 files changed, 129 insertions(+), 97 deletions(-) create mode 100644 STranslate/ViewModels/ServiceHandler.cs diff --git a/.csharpierrc.json b/.csharpierrc.json index e7740ff1..a45130a6 100644 --- a/.csharpierrc.json +++ b/.csharpierrc.json @@ -1,3 +1,3 @@ { - "printWidth": 140 + "printWidth": 180 } \ No newline at end of file diff --git a/STranslate/ViewModels/InputViewModel.cs b/STranslate/ViewModels/InputViewModel.cs index 1badde1b..298fd0b6 100644 --- a/STranslate/ViewModels/InputViewModel.cs +++ b/STranslate/ViewModels/InputViewModel.cs @@ -123,14 +123,7 @@ private async Task HandleHistoryAsync(object obj, HistoryModel? history, string } } - private async Task TranslateServiceAsync( - object obj, - string source, - string dbTarget, - string target, - long size, - CancellationToken token - ) + private async Task TranslateServiceAsync(object obj, string source, string dbTarget, string target, long size, CancellationToken token) { var services = Singleton.Instance.CurTransServiceList; HistoryModel? history = null; @@ -166,13 +159,10 @@ await Parallel.ForEachAsync( try { - Task response; - if (translatorList != null) { IdentifyLanguage = "缓存"; - service.Data = - translatorList?.FirstOrDefault(x => x.Identify == service.Identify)?.Data ?? "该服务未获取到缓存Ctrl+Enter更新"; + service.Data = translatorList?.FirstOrDefault(x => x.Identify == service.Identify)?.Data ?? "该服务未获取到缓存Ctrl+Enter更新"; return; } @@ -184,73 +174,18 @@ await Parallel.ForEachAsync( target = autoRet.Item2; } + var sourceStr = LangDict[source].ToString(); + var targetStr = LangDict[target].ToString(); + //根据不同服务类型区分 //TODO: 新接口需要适配 - switch (service.Type) + service.Data = service.Type switch { - case ServiceType.ApiService: - { - response = - (Task) - await service.TranslateAsync( - new RequestApi() - { - Text = InputContent, - SourceLang = LangDict[source].ToString(), - TargetLang = LangDict[target].ToString() - }, - token - ); - service.Data = (response.Result as ResponseApi)!.Data; - break; - } - - case ServiceType.BaiduService: - { - string salt = new Random().Next(100000).ToString(); - string sign = StringUtil.EncryptString(service.AppID + InputContent + salt + service.AppKey); - response = - (Task) - await service.TranslateAsync( - new RequestBaidu() - { - Text = InputContent, - From = LangDict[source].ToString(), - TO = LangDict[target].ToString(), - AppId = service.AppID, - Salt = salt, - Sign = sign - }, - token - ); - var ret = (response.Result as ResponseBaidu)?.TransResult ?? []; - service.Data = - ret.Length == 0 - ? string.Empty - : string.Join( - Environment.NewLine, - ret.Where(trans => !string.IsNullOrEmpty(trans.Dst)).Select(trans => trans.Dst) - ); - break; - } - - case ServiceType.BingService: - { - var req = new RequestBing - { - From = LangDict[source].ToString(), - To = LangDict[target].ToString(), - Req = [new TextData { Text = InputContent }], - }; - response = (Task)await service.TranslateAsync(req, token); - var ret = (response.Result as ResponseBing[])!.FirstOrDefault()?.Translations?.FirstOrDefault()?.Text; - service.Data = string.IsNullOrEmpty(ret) ? string.Empty : ret; - break; - } - - default: - break; - } + ServiceType.ApiService => await ServiceHandler.ApiHandler(service, InputContent, sourceStr, targetStr, token), + ServiceType.BaiduService => await ServiceHandler.BaiduHandler(service, InputContent, sourceStr, targetStr, token), + ServiceType.BingService => await ServiceHandler.BingHandler(service, InputContent, sourceStr, targetStr, token), + _ => throw new NotImplementedException() + }; } catch (TaskCanceledException ex) { @@ -286,13 +221,9 @@ private void HandleTranslationException(ITranslator service, string errorMessage service.Data = errorMessage; if (isDebug) - LogService.Logger.Debug( - $"[{service.Name}({service.Identify})] {errorMessage}, 请求API: {service.Url}, 异常信息: {exception?.Message}" - ); + LogService.Logger.Debug($"[{service.Name}({service.Identify})] {errorMessage}, 请求API: {service.Url}, 异常信息: {exception?.Message}"); else - LogService.Logger.Error( - $"[{service.Name}({service.Identify})] {errorMessage}, 请求API: {service.Url}, 异常信息: {exception?.Message}" - ); + LogService.Logger.Error($"[{service.Name}({service.Identify})] {errorMessage}, 请求API: {service.Url}, 异常信息: {exception?.Message}"); } #endregion Translatehandle @@ -433,17 +364,11 @@ protected override IList CreateProperties(Type type, MemberSeriali } /// - /// 获取当前翻译服务 + /// 获取当前翻译服务的缓存结果 /// public class CurrentTranslatorConverter : JsonConverter { - public override ITranslator? ReadJson( - JsonReader reader, - Type objectType, - ITranslator? existingValue, - bool hasExistingValue, - JsonSerializer serializer - ) + public override ITranslator? ReadJson(JsonReader reader, Type objectType, ITranslator? existingValue, bool hasExistingValue, JsonSerializer serializer) { // 从 JSON 数据中加载一个 JObject JObject jsonObject = JObject.Load(reader); @@ -458,12 +383,14 @@ JsonSerializer serializer // 根据 Identify 查找匹配的翻译服务 //TODO: 新接口需要适配 - translator = translators.FirstOrDefault(x => x.Identify.ToString() == identify) ?? type switch - { - (int)ServiceType.BaiduService => new TranslatorBaidu(), - (int)ServiceType.BingService => new TranslatorBing(), - _ => new TranslatorApi(), - }; + translator = + translators.FirstOrDefault(x => x.Identify.ToString() == identify) + ?? type switch + { + (int)ServiceType.BaiduService => new TranslatorBaidu(), + (int)ServiceType.BingService => new TranslatorBing(), + _ => new TranslatorApi(), + }; // 从 JSON 中提取 Data 字段的值,设置到 translator 的 Data 属性中 translator.Data = jsonObject["Data"]!.Value()!; diff --git a/STranslate/ViewModels/Preference/History/HistoryContentViewModel.cs b/STranslate/ViewModels/Preference/History/HistoryContentViewModel.cs index 0253d2a7..20571d21 100644 --- a/STranslate/ViewModels/Preference/History/HistoryContentViewModel.cs +++ b/STranslate/ViewModels/Preference/History/HistoryContentViewModel.cs @@ -38,6 +38,8 @@ public HistoryContentViewModel(HistoryModel? history) private void Delete() { Singleton.Instance.DeleteHistoryCommand.Execute(null); + + ToastHelper.Show("删除成功", WindowType.Preference); } [RelayCommand] @@ -46,6 +48,8 @@ private void CopyResult(object obj) if (obj is string str && !string.IsNullOrEmpty(str)) { Clipboard.SetDataObject(str); + + ToastHelper.Show("复制成功", WindowType.Preference); } } diff --git a/STranslate/ViewModels/ServiceHandler.cs b/STranslate/ViewModels/ServiceHandler.cs new file mode 100644 index 00000000..bed14c79 --- /dev/null +++ b/STranslate/ViewModels/ServiceHandler.cs @@ -0,0 +1,101 @@ +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using STranslate.Model; +using STranslate.Util; + +namespace STranslate.ViewModels +{ + /// + /// 不同服务处理类 + /// TODO: 新接口需要适配 + /// + public class ServiceHandler + { + /// + /// API + /// + /// + /// + /// + /// + /// + /// + public static async Task ApiHandler(ITranslator service, string content, string source, string target, CancellationToken token) + { + var response = + (Task) + await service.TranslateAsync( + new RequestApi() + { + Text = content, + SourceLang = source, + TargetLang = target + }, + token + ); + var ret = (response.Result as ResponseApi)!.Data?.ToString() ?? ""; + + return ret; + } + + /// + /// Baidu + /// + /// + /// + /// + /// + /// + /// + public static async Task BaiduHandler(ITranslator service, string content, string source, string target, CancellationToken token) + { + string salt = new Random().Next(100000).ToString(); + string sign = StringUtil.EncryptString(service.AppID + content + salt + service.AppKey); + var response = + (Task) + await service.TranslateAsync( + new RequestBaidu() + { + Text = content, + From = source, + TO = target, + AppId = service.AppID, + Salt = salt, + Sign = sign + }, + token + ); + var transResults = (response.Result as ResponseBaidu)?.TransResult ?? []; + var ret = + transResults.Length == 0 + ? string.Empty + : string.Join(Environment.NewLine, transResults.Where(trans => !string.IsNullOrEmpty(trans.Dst)).Select(trans => trans.Dst)); + return ret; + } + + /// + /// Bing + /// + /// + /// + /// + /// + /// + /// + public static async Task BingHandler(ITranslator service, string content, string source, string target, CancellationToken token) + { + var req = new RequestBing + { + From = source, + To = target, + Req = [new TextData { Text = content }], + }; + var response = (Task)await service.TranslateAsync(req, token); + var ret = (response.Result as ResponseBing[])!.FirstOrDefault()?.Translations?.FirstOrDefault()?.Text; + + return ret ?? ""; + } + } +}