using System;
using System.ComponentModel;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;
using Gameplay;
using UnityEngine;
using UnityEngine.Networking;
public partial class SROptions
{
///
/// 成功时的最大间隔
///
private const float Success_MAX_INTERVALS = 300f; // 5分钟
///
/// 失败时的最大间隔
///
private const float FAIL_MAX_INTERVALS = 15f; // 15 秒
///
/// 超时时间
///
private readonly double timeOutTick = 10f; // 10秒没下完超时
///
/// 当前下载间隔
///
private float intervals = Success_MAX_INTERVALS;
///
/// 下载计时
///
private float timer = 0f;
///
/// 减少最大间隔时间次数
///
private int count = 0;
///
/// 总下载次数
///
private int total;
private StreamWriter writerUnityWebRequest;
private StreamWriter writerHttpClient;
///
/// 是否下载中
///
private bool isDownloading = false;
///
/// 下载地址1
///
private const string DOWNLOAD_URL_1 = "http://1.14.62.163/Build/TapTapDev/Android/0.1.0/_ExtBuildInfo.json";
///
/// 下载地址2
///
private const string DOWNLOAD_URL_2 = "http://1.14.62.163/Build/TapTapDev/Android/0.1.0/OutputCache.manifest";
//[Category("下载测试"), DisplayName("开始下载")] 25/2/20 关闭DEBUGGER功能
// public async void BeginDownload()
// {
// Screen.sleepTimeout = SleepTimeout.NeverSleep;
//#if UNITY_EDITOR
// string fileUnityWebRequestPath = Path.Combine(Application.streamingAssetsPath, "UnityWebRequestTest.txt");
// string fileHttpClientPath = Path.Combine(Application.streamingAssetsPath, "HttpClientTest.txt");
//#else
// string fileUnityWebRequestPath = Path.Combine(Application.persistentDataPath, "UnityWebRequestTest.txt");
// string fileHttpClientPath = Path.Combine(Application.persistentDataPath, "HttpClientTest.txt");
//#endif
// writerUnityWebRequest = File.CreateText(fileUnityWebRequestPath);
// writerHttpClient = File.CreateText(fileHttpClientPath);
//
// timer = intervals;
// total = 0;
// isDownloading = true;
//
// while (isDownloading)
// {
// if (timer >= intervals)
// {
// timer -= intervals;
// ++total;
// string downLoadUrl = ((total / 2) & 1) == 1 ? DOWNLOAD_URL_1 : DOWNLOAD_URL_2;
// string networdType = Application.internetReachability switch
// {
// NetworkReachability.ReachableViaCarrierDataNetwork => "流量",
// NetworkReachability.ReachableViaLocalAreaNetwork => "Wifi",
// _ => "没有网络"
// };
// if ((total & 1) == 1)
// DownloadByUnityWebRequest(downLoadUrl, networdType);
// else
// DownloadByHttpClient(downLoadUrl, networdType);
// }
// await UniTask.DelayFrame(1);
// timer += Time.deltaTime;
// }
// }
//[Category("下载测试"), DisplayName("停止下载")] 25/2/20 关闭DEBUGGER功能
//public void StopDownload()
//{
// Screen.sleepTimeout = SleepTimeout.SystemSetting;
// isDownloading = false;
//
// writerUnityWebRequest.Flush();
// writerUnityWebRequest.Close();
//
// writerHttpClient.Flush();
// writerHttpClient.Close();
//}
///
/// 发送企业微信通知
///
public async void SendWechatMessage(string content)
{
string url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=bf89f555-f710-48c4-87d0-7a8182dec13e";
string message = "{\r\n" +
"\"msgtype\":\"text\",\r\n" +
"\"text\":{\r\n" +
$"\"content\":\"{content}\",\r\n" +
$"\"mentioned_list\":[\"@all\"]" +
"}\r\n" + "}";
UnityWebRequest request = UnityWebRequest.Post(url, message, "application/json");
await request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
Debug.LogError($"Error: {request.error}");
else
Debug.Log($"Response: {request.downloadHandler.text}"); // 请求成功,输出响应数据
request.Dispose();
}
///
/// 通过WebRequest下载
///
private async void DownloadByUnityWebRequest(string url, string netword)
{
string log = string.Empty;
DateTime startTime = CommonUtils.GetCurTime(CommonUtils.E_TimeType.Local);
DateTime endTime;
using UnityWebRequest request = UnityWebRequest.Get(url);
UnityWebRequestAsyncOperation asyncOperation = request.SendWebRequest();
while (!asyncOperation.isDone)
{
await UniTask.DelayFrame(1);
endTime = CommonUtils.GetCurTime(CommonUtils.E_TimeType.Local);
TimeSpan timeSpan = endTime - startTime;
if (timeSpan.TotalSeconds > timeOutTick)
{
request.Abort();
log = $"第{total}次下载,类型:{nameof(UnityWebRequest)}, 网络:{netword}, {timeOutTick}s超时,URL:{url}";
Debug.LogWarning(log);
writerUnityWebRequest.WriteLine(log);
writerUnityWebRequest.Flush();
intervals = FAIL_MAX_INTERVALS;
count = 6;
SendWechatMessage(log);
return;
}
}
endTime = CommonUtils.GetCurTime(CommonUtils.E_TimeType.Local);
if (request.result != UnityWebRequest.Result.Success)
{
log = $"第{total}次下载,类型:{nameof(UnityWebRequest)}, 网络:{netword}, 开始时间:{startTime},完成时间:{endTime},间隔:{(endTime - startTime).TotalSeconds}秒,下载失败,URL:{url}";
Debug.LogError(log);
writerUnityWebRequest.WriteLine(log);
writerUnityWebRequest.Flush();
intervals = FAIL_MAX_INTERVALS;
count = 6;
SendWechatMessage(log);
return;
}
log = $"第{total}次下载,类型:{nameof(UnityWebRequest)}, 网络:{netword}, 开始时间:{startTime},完成时间:{endTime},间隔:{(endTime - startTime).TotalSeconds}秒,下载成功,URL:{url}";
Debug.Log(log);
writerUnityWebRequest.WriteLine(log);
writerUnityWebRequest.Flush();
--count;
if (count <= 0)
intervals = Success_MAX_INTERVALS;
}
///
/// 通过HttpClient下载
///
private async void DownloadByHttpClient(string url, string netword)
{
string log = string.Empty;
DateTime startTime = CommonUtils.GetCurTime(CommonUtils.E_TimeType.Local);
DateTime endTime;
CancellationTokenSource cancellationTokenSource = new();
using HttpClient client = new();
Task response = client.GetAsync(url, cancellationTokenSource.Token);
while (!response.IsCompleted)
{
await UniTask.DelayFrame(1);
endTime = CommonUtils.GetCurTime(CommonUtils.E_TimeType.Local);
TimeSpan timeSpan = endTime - startTime;
if (timeSpan.TotalSeconds > timeOutTick)
{
cancellationTokenSource.Cancel();
log = $"第{total}次下载,类型:{nameof(HttpClient)}, 网络:{netword}, {timeOutTick}s超时,URL:{url}";
Debug.LogWarning(log);
writerHttpClient.WriteLine(log);
writerHttpClient.Flush();
intervals = FAIL_MAX_INTERVALS;
count = 6;
SendWechatMessage(log);
return;
}
}
endTime = CommonUtils.GetCurTime(CommonUtils.E_TimeType.Local);
if (!response.IsCompletedSuccessfully || !response.Result.IsSuccessStatusCode)
{
log = $"第{total}次下载,类型:{nameof(HttpClient)}, 网络:{netword}, 开始时间:{startTime},完成时间:{endTime},间隔:{(endTime - startTime).TotalSeconds}秒,下载失败,URL:{url}";
Debug.LogError(log);
writerHttpClient.WriteLine(log);
writerHttpClient.Flush();
intervals = FAIL_MAX_INTERVALS;
count = 6;
SendWechatMessage(log);
return;
}
log = $"第{total}次下载,类型:{nameof(HttpClient)}, 网络:{netword}, 开始时间:{startTime},完成时间:{endTime},间隔:{(endTime - startTime).TotalSeconds}秒,下载成功,URL:{url}";
Debug.Log(log);
writerHttpClient.WriteLine(log);
writerHttpClient.Flush();
--count;
if (count <= 0)
intervals = Success_MAX_INTERVALS;
}
}