542 lines
20 KiB
C#
542 lines
20 KiB
C#
using System.IO;
|
||
using UnityEngine;
|
||
using UnityEngine.Events;
|
||
using LitJson;
|
||
using Newtonsoft.Json;
|
||
using System;
|
||
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using UnityEditor;
|
||
using UnityEngine.Networking;
|
||
using Unity.VisualScripting.FullSerializer;
|
||
using System.Runtime.InteropServices.ComTypes;
|
||
using System.Text;
|
||
using UnityEngine.Networking.Types;
|
||
using Unity.VisualScripting;
|
||
using Newtonsoft.Json.Linq;
|
||
using Cysharp.Threading.Tasks;
|
||
using System.Text.RegularExpressions;
|
||
|
||
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 string appId = "10007";
|
||
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 int schemeID = 7002;//课程id
|
||
public int totalTime = 0;
|
||
public string[] stepStrArr;
|
||
public string userName = "";
|
||
public D_SerData getSerData = new D_SerData();
|
||
public D_SerData sendSerData = new D_SerData();
|
||
private Action<IEnumerator> DoStartCoroutine;
|
||
private Action getSerDataCompleteHandler;
|
||
|
||
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);
|
||
getRequest.Dispose();
|
||
return result;
|
||
}
|
||
public async UniTask Get(string endpoint)
|
||
{
|
||
var getRequest = CreateRequest(endpoint);
|
||
await getRequest.SendWebRequest();
|
||
getRequest.Dispose();
|
||
}
|
||
/// <summary>
|
||
/// 请求类型
|
||
/// </summary>
|
||
public enum RequestType
|
||
{
|
||
GET = 0,
|
||
POST = 1
|
||
}
|
||
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);
|
||
#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 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 string GetTokenURL()
|
||
{
|
||
return url + webURLDic["GetToken"];
|
||
}
|
||
//==========================================================移植结束 HQB
|
||
public void Init(Action<IEnumerator> _DoStartCoroutine)
|
||
{
|
||
DoStartCoroutine = _DoStartCoroutine;
|
||
machineId = UnityEngine.SystemInfo.deviceUniqueIdentifier;//机器码
|
||
schemeID = 7002;//课程id
|
||
}
|
||
public void init_getSerData(Action _getSerDataCompleteHandler)
|
||
{
|
||
getSerDataCompleteHandler = _getSerDataCompleteHandler;
|
||
|
||
getSerDataCompleteHandler?.Invoke();
|
||
|
||
}
|
||
private void backHandler1(string text)
|
||
{
|
||
Login login = JsonUtility.FromJson<Login>(text);
|
||
token = login.token;
|
||
getNewRecord();
|
||
}
|
||
|
||
//获取上次保存的数据
|
||
private void getNewRecord()
|
||
{
|
||
string url = "member/pro/simulationStepRecord/getNewRecord?";
|
||
url += "appId=" + GameManager.NetMgr.appId + "&";
|
||
url += "examId=" + GameManager.NetMgr.examId + "&";
|
||
url += "examinationId=" + GameManager.NetMgr.examinationId + "&";
|
||
url += "stuId=" + GameManager.NetMgr.stuId + "&";
|
||
url += "groupId=" + GameManager.NetMgr.groupId + "&";
|
||
url += "operationType=" + GameManager.NetMgr.operationType + "&";
|
||
url += "machineId=" + GameManager.NetMgr.machineId + "&";
|
||
url += "batchId=" + GameManager.NetMgr.batchId + "&";
|
||
url += "courseId=" + GameManager.NetMgr.schemeID;
|
||
DoStartCoroutine?.Invoke(GameManager.NetMgr.sendGet(url, backHandler));
|
||
//DoStartCoroutine?.Invoke(GameManager.NetMgr.sendPost("member/pro/simulationStepRecord/getNewRecord", jsonData, backHandler1, "GET"));//发起请求
|
||
}
|
||
private void backHandler(string text)
|
||
{
|
||
string[] arr = text.Split("\"data\":null");
|
||
if (arr.Length == 1)
|
||
{
|
||
D_SerDataParent d_SerDataParent = JsonUtility.FromJson<D_SerDataParent>(text);
|
||
GameManager.NetMgr.getSerData = d_SerDataParent.data;
|
||
}
|
||
getSerDataCompleteHandler?.Invoke();
|
||
//{"msg":"操作成功","code":200,
|
||
//"data":{"createBy":"106","createTime":"2024-10-17 18:37:22","updateBy":null,"updateTime":null,"remark":null,"pageNum":null,"pageSize":null,"id":"1296542589557669888","appId":"1","examId":"1","examinationId":"1","stuId":"1","groupId":"1","recordContentId":"1","operationType":"1","isComp":"1","currentProcess":"1","sumProcess":"1","score":"1","inTimes":"1"}}
|
||
}
|
||
|
||
private long lastTime;
|
||
//增加保存数据
|
||
public void add()
|
||
{
|
||
JsonData jsonData = new JsonData();
|
||
jsonData["appId"] = GameManager.NetMgr.appId;
|
||
jsonData["examId"] = GameManager.NetMgr.examId;
|
||
jsonData["examinationId"] = GameManager.NetMgr.examinationId;
|
||
jsonData["stuId"] = GameManager.NetMgr.stuId;
|
||
jsonData["groupId"] = GameManager.NetMgr.groupId;
|
||
jsonData["operationType"] = GameManager.NetMgr.operationType;
|
||
jsonData["machineId"] = GameManager.NetMgr.machineId;
|
||
|
||
jsonData["batchId"] = GameManager.NetMgr.batchId;
|
||
jsonData["courseId"] = GameManager.NetMgr.schemeID;
|
||
jsonData["recordContent"] = stepStrArr[int.Parse(GameManager.NetMgr.sendSerData.currentProcess)];//GameManager.NetMgr.sendSerData.recordContent;//记录文本id
|
||
jsonData["isComp"] = GameManager.NetMgr.sendSerData.isComp;//是否完成 0:未完成 1:已完成
|
||
jsonData["currentProcess"] = GameManager.NetMgr.sendSerData.currentProcess;//当前步骤点
|
||
jsonData["sumProcess"] = GameManager.NetMgr.sendSerData.sumProcess;//总步骤点
|
||
jsonData["score"] = GameManager.NetMgr.sendSerData.score;//步骤分
|
||
|
||
DateTime unixStartTime = new DateTime(1970, 1, 1);
|
||
DateTime now = DateTime.UtcNow;
|
||
TimeSpan timeSpan = now - unixStartTime;
|
||
long timestamp = (long)timeSpan.TotalMilliseconds;
|
||
jsonData["inTimes"] = ((GetCurrentUnixTimestampMillis() - lastTime) / 1000.0f).ToString("F2");
|
||
setTime();
|
||
|
||
jsonData["remark"] = GameManager.NetMgr.sendSerData.remark;//备注
|
||
DoStartCoroutine?.Invoke(GameManager.NetMgr.sendPost("member/pro/simulationStepRecord/add", jsonData, null));
|
||
}
|
||
public void setTime()
|
||
{
|
||
lastTime = GetCurrentUnixTimestampMillis();
|
||
}
|
||
private long GetCurrentUnixTimestampMillis()
|
||
{
|
||
// Unix时间戳是从1970年1月1日开始计算
|
||
DateTime unixStartTime = new DateTime(1970, 1, 1);
|
||
// 当前时间
|
||
DateTime now = DateTime.UtcNow;
|
||
// 当前时间与Unix时间戳的时间间隔
|
||
TimeSpan timeSpan = now - unixStartTime;
|
||
// 将时间间隔转换为毫秒数
|
||
long timestamp = (long)timeSpan.TotalMilliseconds;
|
||
|
||
return timestamp;
|
||
}
|
||
|
||
//HQB 1203 移植
|
||
//增加保存数据
|
||
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"] = "";
|
||
|
||
DoStartCoroutine?.Invoke(sendPost(webURLDic["练习学习"], jsonData, result =>
|
||
{
|
||
JObject jo = JObject.Parse(result);
|
||
if (jo["code"].ToObject<int>() == 200)
|
||
{
|
||
//TipPanel.ShowTip("上传分数成功");
|
||
}
|
||
else
|
||
{
|
||
//TipPanel.ShowTip("上传分数失败;" + jo["msg"].ToString());
|
||
}
|
||
}));
|
||
}
|
||
|
||
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;
|
||
}
|
||
|
||
public IEnumerator sendGet(string itf, Action<string> action)
|
||
{
|
||
//string ds = jsonData.ToJson();
|
||
//byte[] postBytes = Encoding.Default.GetBytes(ds);
|
||
UnityWebRequest request = new UnityWebRequest(url + "/" + itf, "GET");//method传输方式,默认为Get;
|
||
|
||
//request.uploadHandler = new UploadHandlerRaw(postBytes);
|
||
request.downloadHandler = new DownloadHandlerBuffer();
|
||
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);
|
||
}
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// 获取本地配置文件
|
||
/// </summary>
|
||
/// <param name="action"></param>
|
||
/*public void GetConfig(UnityAction<bool> action)
|
||
{
|
||
string path = Application.streamingAssetsPath + "/info.ini";
|
||
if (File.Exists(path))
|
||
{
|
||
try//HQB 1127
|
||
{
|
||
string str = File.ReadAllText(path);
|
||
string text = str.Split("cdzxcjc://")[1].Split("\'|")[0];
|
||
string[] arr = text.Split('&');
|
||
//appld = arr[0];
|
||
examId = arr[0];//试卷id
|
||
examinationId = arr[1];//考场id
|
||
stuId = arr[2];//用户id
|
||
groupId = arr[3];//所在分组id
|
||
operationType = arr[4];//用户操作类型
|
||
batchId = arr[5];//学习批次id
|
||
token = arr[6];
|
||
url = arr[7];
|
||
//action?.Invoke(true);
|
||
string pathJson = Application.streamingAssetsPath + "/Config/Config.txt";
|
||
if (File.Exists(pathJson))
|
||
{
|
||
string json = File.ReadAllText(pathJson);
|
||
stepStrArr = json.Split('@');
|
||
//sendSerData.recordContent = json;
|
||
Debug.LogError(json);
|
||
action?.Invoke(true);
|
||
}
|
||
else
|
||
{
|
||
Debug.Log("没有对应的文件Config/Config.txt");
|
||
action?.Invoke(false);
|
||
//UIManager.Instance.ShowPanel<UI_MessagePanel>(E_UI_Layer.System, (panel) =>
|
||
//{
|
||
// panel.Init("没有读取到正确的Ip地址文件,请检查项目StreamingAssets文件夹下Config文件是否正常配置地址端口后再试!", E_MessageType.Error, Const.E_QuitApp);
|
||
//});
|
||
}
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
Debug.Log("HQB——读取失败,先读默认info");
|
||
string path2 = Application.streamingAssetsPath + "/info_1.ini";
|
||
if (File.Exists(path2))
|
||
{
|
||
string str = File.ReadAllText(path2);
|
||
string text = str.Split("cdzxcjc://")[1].Split("\'|")[0];
|
||
string[] arr = text.Split('&');
|
||
//appld = arr[0];
|
||
examId = arr[0];//试卷id
|
||
examinationId = arr[1];//考场id
|
||
stuId = arr[2];//用户id
|
||
groupId = arr[3];//所在分组id
|
||
operationType = arr[4];//用户操作类型
|
||
batchId = arr[5];//学习批次id
|
||
token = arr[6];
|
||
url = arr[7];
|
||
string pathJson = Application.streamingAssetsPath + "/Config/Config.txt";
|
||
if (File.Exists(pathJson))
|
||
{
|
||
string json = File.ReadAllText(pathJson);
|
||
stepStrArr = json.Split('@');
|
||
//sendSerData.recordContent = json;
|
||
Debug.LogError(json);
|
||
action?.Invoke(true);
|
||
}
|
||
else
|
||
{
|
||
Debug.Log("二次读取失败——HQB");
|
||
action?.Invoke(false);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
else
|
||
{
|
||
Debug.Log("没有对应的文件info.ini");
|
||
action?.Invoke(false);
|
||
//UIManager.Instance.ShowPanel<UI_MessagePanel>(E_UI_Layer.System, (panel) =>
|
||
//{
|
||
// panel.Init("没有读取到正确的Ip地址文件,请检查项目StreamingAssets文件夹下Config文件是否正常配置地址端口后再试!", E_MessageType.Error, Const.E_QuitApp);
|
||
//});
|
||
}
|
||
|
||
}*/
|
||
|
||
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")
|
||
{
|
||
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);
|
||
}
|
||
|
||
}
|
||
|
||
/// <summary>
|
||
///
|
||
/// </summary>
|
||
/// <param name="info"></param>
|
||
public void SaveInfo(string info)
|
||
{
|
||
string path = Application.streamingAssetsPath + "/Config/info.txt";
|
||
Debug.Log(path);
|
||
File.WriteAllText(path, info);
|
||
}
|
||
}
|
||
public class Login
|
||
{
|
||
public string msg;
|
||
public string code;
|
||
public string data;
|
||
public string token;
|
||
}
|
||
|