Skip to content

Commit

Permalink
chore: Organize your code
Browse files Browse the repository at this point in the history
  • Loading branch information
ZGGSONG committed Jan 14, 2024
1 parent e9c06c1 commit 3932b20
Show file tree
Hide file tree
Showing 4 changed files with 129 additions and 97 deletions.
2 changes: 1 addition & 1 deletion .csharpierrc.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"printWidth": 140
"printWidth": 180
}
119 changes: 23 additions & 96 deletions STranslate/ViewModels/InputViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,14 +123,7 @@ private async Task HandleHistoryAsync(object obj, HistoryModel? history, string
}
}

private async Task<HistoryModel?> TranslateServiceAsync(
object obj,
string source,
string dbTarget,
string target,
long size,
CancellationToken token
)
private async Task<HistoryModel?> TranslateServiceAsync(object obj, string source, string dbTarget, string target, long size, CancellationToken token)
{
var services = Singleton<ServiceViewModel>.Instance.CurTransServiceList;
HistoryModel? history = null;
Expand Down Expand Up @@ -166,13 +159,10 @@ await Parallel.ForEachAsync(

try
{
Task<object> 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;
}

Expand All @@ -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<object>)
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<object>)
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<object>)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)
{
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -433,17 +364,11 @@ protected override IList<JsonProperty> CreateProperties(Type type, MemberSeriali
}

/// <summary>
/// 获取当前翻译服务
/// 获取当前翻译服务的缓存结果
/// </summary>
public class CurrentTranslatorConverter : JsonConverter<ITranslator>
{
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);
Expand All @@ -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<string>()!;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ public HistoryContentViewModel(HistoryModel? history)
private void Delete()
{
Singleton<HistoryViewModel>.Instance.DeleteHistoryCommand.Execute(null);

ToastHelper.Show("删除成功", WindowType.Preference);
}

[RelayCommand]
Expand All @@ -46,6 +48,8 @@ private void CopyResult(object obj)
if (obj is string str && !string.IsNullOrEmpty(str))
{
Clipboard.SetDataObject(str);

ToastHelper.Show("复制成功", WindowType.Preference);
}
}

Expand Down
101 changes: 101 additions & 0 deletions STranslate/ViewModels/ServiceHandler.cs
Original file line number Diff line number Diff line change
@@ -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
{
/// <summary>
/// 不同服务处理类
/// TODO: 新接口需要适配
/// </summary>
public class ServiceHandler
{
/// <summary>
/// API
/// </summary>
/// <param name="service"></param>
/// <param name="content"></param>
/// <param name="source"></param>
/// <param name="target"></param>
/// <param name="token"></param>
/// <returns></returns>
public static async Task<string> ApiHandler(ITranslator service, string content, string source, string target, CancellationToken token)
{
var response =
(Task<object>)
await service.TranslateAsync(
new RequestApi()
{
Text = content,
SourceLang = source,
TargetLang = target
},
token
);
var ret = (response.Result as ResponseApi)!.Data?.ToString() ?? "";

return ret;
}

/// <summary>
/// Baidu
/// </summary>
/// <param name="service"></param>
/// <param name="content"></param>
/// <param name="source"></param>
/// <param name="target"></param>
/// <param name="token"></param>
/// <returns></returns>
public static async Task<string> 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<object>)
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;
}

/// <summary>
/// Bing
/// </summary>
/// <param name="service"></param>
/// <param name="content"></param>
/// <param name="source"></param>
/// <param name="target"></param>
/// <param name="token"></param>
/// <returns></returns>
public static async Task<string> 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<object>)await service.TranslateAsync(req, token);
var ret = (response.Result as ResponseBing[])!.FirstOrDefault()?.Translations?.FirstOrDefault()?.Text;

return ret ?? "";
}
}
}

0 comments on commit 3932b20

Please sign in to comment.