csharp-sdk-upm/Common/AppRouter/LCAppRouter.cs

82 lines
3.0 KiB
C#
Raw Normal View History

using System;
2020-03-09 12:31:25 +08:00
using System.Threading.Tasks;
using System.Net.Http;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace LeanCloud.Common {
2020-03-10 16:54:50 +08:00
public class LCAppRouter {
2020-03-09 12:31:25 +08:00
private readonly string appId;
2020-03-09 12:31:25 +08:00
private readonly string server;
2020-03-10 16:54:50 +08:00
private LCAppServer appServer;
2020-03-10 16:54:50 +08:00
public LCAppRouter(string appId, string server) {
2020-03-09 12:31:25 +08:00
if (!IsInternalApp(appId) && string.IsNullOrEmpty(server)) {
// 国内节点必须配置自定义域名
throw new Exception("Please init with your server url.");
}
this.appId = appId;
this.server = server;
}
2020-03-09 12:31:25 +08:00
public async Task<string> GetApiServer() {
// 优先返回用户自定义域名
if (!string.IsNullOrEmpty(server)) {
return server;
}
2020-03-10 16:54:50 +08:00
LCAppServer appServ = await FetchAppServer();
return appServ.ApiServer;
}
public async Task<string> GetRealtimeServer() {
if (!string.IsNullOrEmpty(server)) {
return server;
}
LCAppServer appServ = await FetchAppServer();
return appServ.PushServer;
}
async Task<LCAppServer> FetchAppServer() {
2020-03-09 12:31:25 +08:00
// 判断节点地区
if (!IsInternalApp(appId)) {
// 国内节点必须配置自定义域名
throw new Exception("Please init with your server url.");
}
// 向 App Router 请求地址
2020-03-10 16:54:50 +08:00
if (appServer == null || !appServer.IsValid) {
2020-03-09 12:31:25 +08:00
try {
HttpRequestMessage request = new HttpRequestMessage {
RequestUri = new Uri($"https://app-router.com/2/route?appId={appId}"),
Method = HttpMethod.Get
};
HttpClient client = new HttpClient();
2020-03-10 16:54:50 +08:00
LCHttpUtils.PrintRequest(client, request);
2020-03-09 12:31:25 +08:00
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
request.Dispose();
2020-03-09 12:31:25 +08:00
string resultString = await response.Content.ReadAsStringAsync();
response.Dispose();
2020-03-10 16:54:50 +08:00
LCHttpUtils.PrintResponse(response, resultString);
2020-03-09 12:31:25 +08:00
Dictionary<string, object> data = JsonConvert.DeserializeObject<Dictionary<string, object>>(resultString);
2020-03-10 16:54:50 +08:00
appServer = new LCAppServer(data);
2020-03-09 12:31:25 +08:00
} catch (Exception e) {
LCLogger.Error(e);
2020-03-09 12:31:25 +08:00
// 拉取服务地址失败后,使用国际节点的默认服务地址
2020-03-10 16:54:50 +08:00
appServer = LCAppServer.GetInternalFallbackAppServer(appId);
}
}
2020-03-10 16:54:50 +08:00
return appServer;
}
2020-03-09 12:31:25 +08:00
private static bool IsInternalApp(string appId) {
if (appId.Length < 9) {
return false;
}
2020-03-09 12:31:25 +08:00
string suffix = appId.Substring(appId.Length - 9);
return suffix == "-MdYXbMMI";
}
}
}