CultivationOfBrewing-2/Assets/Scripts/Project/Manager/NetManager.cs

431 lines
15 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Cysharp.Threading.Tasks;
using LitJson;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Utilities.Encoders;
using SecretUtils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
public class NetManager : BaseManager<NetManager>
{
private NetManager() { }
public Dictionary<string, string> webURLDic = new Dictionary<string, string>();
public ExamData currentExamData = new ExamData();
public TaskListData taskListData = new TaskListData();
/// <summary>
/// 网络访问的token
/// </summary>
public string token = "";
public string url;
public int appId = 0;
public string examId = "1";//试卷id
public string examinationId = "1";//考场id
public string stuId = "1";//用户id
public string groupId = "1";//所在分组id
public string operationType = "1";//用户操作类型
public string machineId;//机器码
public string batchId = "1";//学习批次id
public string userName = "";
public int schemeID = 0;//课程id
public int totalTime = 0;
public D_SerData getSerData = new D_SerData();
public D_SerData sendSerData = new D_SerData();
private Action<IEnumerator> DoStartCoroutine;
public async UniTask<T> Get<T>(string endpoint)
{
var getRequest = CreateRequest(endpoint);
await getRequest.SendWebRequest();
#if UNITY_EDITOR
Debug.Log("async req : " + getRequest.downloadHandler.text);
#endif
//T result = JsonConvert.DeserializeObject<T>(getRequest.downloadHandler.text);
var s = Encrypt.DecryptECB(getRequest.downloadHandler.text);
T result = JsonConvert.DeserializeObject<T>(s);
getRequest.Dispose();
return result;
}
public async UniTask Get(string endpoint)
{
var getRequest = CreateRequest(endpoint);
await getRequest.SendWebRequest();
getRequest.Dispose();
}
public async UniTask<T> Post<T>(string endpoint, object payload)
{
var postRequest = CreateRequest(endpoint, RequestType.POST, payload);
//Debug.Log(postRequest);
await postRequest.SendWebRequest();
#if UNITY_EDITOR
//Debug.Log("async req : " + postRequest.downloadHandler.text);
//Debug.Log("endpoint : " + endpoint);
#endif
T result = JsonConvert.DeserializeObject<T>(postRequest.downloadHandler.text);
postRequest.Dispose();
return result;
}
private UnityWebRequest CreateRequest(string path, RequestType type = RequestType.GET, object data = null)
{
var request = new UnityWebRequest(path, type.ToString());
if (data != null)
{
//string reqJson = JsonConvert.SerializeObject(data);
var json_str = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
var json_byte = Sm4Base.EncryptECB(json_str, Encrypt._key);
string reqJson = Hex.ToHexString(json_byte);
#if UNITY_EDITOR
//Debug.Log($"async req json : {reqJson}");
#endif
var bodyRaw = Encoding.UTF8.GetBytes(reqJson);
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
}
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("Authorization", token);
return request;
}
public static IEnumerator PoststringByRaw(string url, string json)
{
UnityWebRequest request = new UnityWebRequest(url, "POST");
byte[] bodyData = Encoding.UTF8.GetBytes(json);
request.SetRequestHeader("Content-Type", "application/json");
request.uploadHandler = new UploadHandlerRaw(bodyData);
request.downloadHandler = new DownloadHandlerBuffer();
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Error: " + request.error);
}
else
{
Debug.Log("Response: " + request.downloadHandler.text);
}
request.Dispose();
}
/// <summary>
/// 请求类型
/// </summary>
public enum RequestType
{
GET = 0,
POST = 1
}
public void Init(Action<IEnumerator> _DoStartCoroutine)
{
DoStartCoroutine = _DoStartCoroutine;
machineId = UnityEngine.SystemInfo.deviceUniqueIdentifier;//机器码
}
private long lastTime;
//增加保存数据
public void SendResult(string resultData)
{
JsonData jsonData = new JsonData();
jsonData["id"] = "";
jsonData["appId"] = GameManager.Instance.systemId.ToString();
jsonData["courseId"] = schemeID;
jsonData["examId"] = examId;
jsonData["examinationId"] = examinationId;
jsonData["stuId"] = stuId;
jsonData["groupId"] = groupId;
jsonData["machineId"] = machineId;
jsonData["batchId"] = batchId;
jsonData["recordContent"] = resultData;//记录文本id
jsonData["operationType"] = operationType;
jsonData["isComp"] = sendSerData.isComp;//是否完成 0:未完成 1:已完成
jsonData["currentProcess"] = sendSerData.currentProcess;//当前步骤点
jsonData["sumProcess"] = sendSerData.sumProcess;//总步骤点
jsonData["score"] = sendSerData.score;//步骤分
jsonData["preScore"] = "";
jsonData["inTimes"] = (DateTime.Now - GameManager.RunModelMgr.startTime).TotalSeconds.ToString();
jsonData["remark"] = sendSerData.remark;//备注
jsonData["stepName"] = "";
jsonData["testPoint"] = "";
jsonData["defaultScore"] = "";
var _post_json = Sm4Base.EncryptECB(Encoding.UTF8.GetBytes(jsonData.ToJson()), Encrypt._key);
var _header = Encrypt.Header(GameManager.NetMgr.token);
//DoStartCoroutine?.Invoke(sendPost(webURLDic["练习学习"], jsonData, result =>
DoStartCoroutine?.Invoke(PostRequest(url + webURLDic["练习学习"], Hex.ToHexString(_post_json), _header, result =>
{
try
{
result = Encrypt.DecryptECB(result);
Debug.Log(result);
JObject jo = JObject.Parse(result);
if (jo["code"].ToObject<int>() == 200)
{
//TipPanel.ShowTip("上传分数成功");
}
else
{
//TipPanel.ShowTip("上传分数失败;" + jo["msg"].ToString());
}
}
catch (Exception e)
{
Debug.Log($"<Color=red>{e.Message}\n ResultJosn{result}</Color>");
}
}));
}
public IEnumerator sendPost(string itf, JsonData jsonData, Action<string> action)
{
string ds = jsonData.ToJson();
byte[] postBytes = Encoding.Default.GetBytes(ds);
using (UnityWebRequest request = new UnityWebRequest(url + itf, "POST"))
{
request.uploadHandler = new UploadHandlerRaw(postBytes);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
if (GameManager.NetMgr.token != "")
{
request.SetRequestHeader("Authorization", GameManager.NetMgr.token);
}
yield return request.SendWebRequest();//发送请求
if (request.responseCode == 200)//检验是否成功
{
string text = request.downloadHandler.text;
Debug.Log(text);
action?.Invoke(text);
}
else
{
Debug.Log("请求失败:" + request.responseCode);
}
}//method传输方式默认为Get
}
/// <summary>
/// 获取本地配置文件
/// </summary>
/// <param name="action"></param>
public async void GetConfig(UnityAction<bool> action)
{
string path = Application.streamingAssetsPath + "/info.ini";
if (File.Exists(path))
{
string str = File.ReadAllText(path);
if (str.Contains("ycjl"))
{
string text = str.Split("://")[1].Split("\'|")[0];
Debug.Log($"text=={text}");
if (text != "" && !string.IsNullOrEmpty(text))
{
string[] arr = text.Split(',');
//appld = arr[0];
examId = arr[0];//试卷id/任务ID
examinationId = arr[1];//考场id
stuId = arr[2];//用户id
groupId = arr[3];//所在分组id
operationType = arr[4];//用户操作类型 1.学习任务 2.练习 3.考试
batchId = arr[5];//学习批次id
token = arr[6];
userName = UserName(arr[7]); //用户名
schemeID = int.Parse(arr[8]);//科目ID
url = $"http://{arr[9]}";//Ip地址
totalTime = int.Parse(arr[10]);//总时间
// foreach (var item in arr)
// {
// Debug.Log(item);
// }
}
}
else
{
Debug.Log($"text==是空得");
}
string pathJson = Application.streamingAssetsPath + "/Config/URLConfig.txt";
if (File.Exists(pathJson))
{
string[] info = File.ReadAllLines(pathJson);
for (int i = 0; i < info.Length; i++)
{
int index = i;
if (info[index] != "")
{
webURLDic.Add(info[index].Split(",")[0], info[index].Split(",")[1]);
Debug.Log(info[index]);
}
}
if (operationType == "3")
{
var _cipher = Sm4Base.EncryptECB(Encoding.UTF8.GetBytes(examId), Encrypt._key);
string _id = Hex.ToHexString((Sm4Base.EncryptECB(Encoding.UTF8.GetBytes(examId), Encrypt._key)));
string examUrl = url + webURLDic["试卷"] + _id;
//string examUrl = url + webURLDic["试卷"] + examId;
currentExamData = await Get<ExamData>(examUrl);
taskListData = JsonConvert.DeserializeObject<TaskListData>(currentExamData.data.backJson);
action?.Invoke(true);
}
else
{
action?.Invoke(true);
}
}
else
{
Debug.LogError("没有对应的文件Config/URLConfig.txt");
action?.Invoke(false);
}
}
else
{
Debug.LogError("没有对应的文件info.ini");
Debug.LogError("没有对应的文件Config/URLConfig.txt");
action?.Invoke(false);
}
}
public string GetTokenURL()
{
return url + webURLDic["GetToken"];
}
/// <summary>
/// 写入本地文件给前端调用
/// </summary>
/// <param name="info"></param>
public void SaveInfo(string info)
{
string path = Application.streamingAssetsPath + "/start.ini";
File.WriteAllText(path, info);
}
public string UserName(string userNameInfo)
{
string encodedString = RemoveSlashAfterAmpersand(userNameInfo);
StringBuilder sb = new StringBuilder();
bool collectingDigits = false;
int currentNumber = 0;
foreach (char c in encodedString)
{
if (char.IsDigit(c))
{
currentNumber = currentNumber * 10 + (c - '0');
collectingDigits = true;
}
else
{
if (collectingDigits && currentNumber <= 0xFFFF) // Unicode码点范围是0x0000到0xFFFF对于基本多语言平面
{
char character = (char)currentNumber;
sb.Append(character);
currentNumber = 0;
collectingDigits = false;
}
}
}
if (collectingDigits && currentNumber <= 0xFFFF)
{
sb.Append((char)currentNumber);
}
return ParseUnicodeEscapes(sb.ToString());
}
private string ParseUnicodeEscapes(string input)
{
return Regex.Replace(
input,
@"\\u([0-9a-fA-F]{4})",
match => ((char)int.Parse(match.Groups[1].Value, System.Globalization.NumberStyles.HexNumber)).ToString()
);
}
private string RemoveSlashAfterAmpersand(string input)
{
// 查找 & 的位置
int ampersandIndex = input.IndexOf('&');
// 如果没有 & 或者 & 后面没有 /,直接返回原字符串
if (ampersandIndex == -1 || ampersandIndex + 1 >= input.Length || input[ampersandIndex + 1] != '/')
{
return input;
}
// 查找第一个 / 的位置
int slashIndex = input.IndexOf('/', ampersandIndex);
// 如果 & 后面存在 /,移除 & 到 / 之间的部分
if (slashIndex >= 0)
{
// 返回 & 后面的部分,去掉 /
return input.Remove(ampersandIndex + 1, slashIndex - ampersandIndex);
}
return input;
}
public IEnumerator PostRequest(string _url, string _post_json, Dictionary<string, string> _header = null, Action<string> _callback = null)
{
using (UnityWebRequest request = new UnityWebRequest(_url, "POST"))
{
var data = Encoding.UTF8.GetBytes(_post_json);
request.uploadHandler = new UploadHandlerRaw(data);
request.downloadHandler = new DownloadHandlerBuffer();
if (_header != null)
{
foreach (var item in _header)
{
request.SetRequestHeader(item.Key, item.Value);
}
}
yield return request.SendWebRequest();
if (request.error != null)
{
Debug.Log(request.error);
_callback?.Invoke(null);
}
else
{
if (request.responseCode == 200)
{
_callback?.Invoke(request.downloadHandler.text);
}
}
}
}
}
public class Login
{
public string msg;
public string code;
public string data;
public string token;
}