Forest_Client/Forest/Assets/Scripts/Framework/AppNetConfig.cs

361 lines
13 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using BestHTTP;
using UnityEngine;
using System.Linq;
using System.Text;
using Framework.Event;
using LC.Newtonsoft.Json;
using LC.Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Security.Cryptography;
public enum NetRequestStatus
{
None = 0,
Start,
Wait,
Success,
}
public class AppNetConfig : MonoBehaviour
{
/// <summary>
/// 请求服务器返回信息类
/// </summary>
private class ServerResponseInfo
{
public int code = -1;
public string message;
public string data;
}
/// <summary>
/// 请求获取数据类
/// </summary>
private class PostData
{
public string action;
public string time;
public string sign;
public string client_id;
public string client_type;
public string game_data;
}
/// <summary>
/// 请求上传数据类
/// </summary>
private class UploadPostData
{
public string action;
public string time;
public string sign;
public string client_id;
public string third_id;
public string game_data;
}
public static NetRequestStatus State = NetRequestStatus.None;
//private static readonly string URL = "http://192.168.3.90:8000/web_api/server_update.php";
private static readonly string URL = "http://170.106.198.9/web_api/server_update.php";
private static readonly string Sign = "oxZsw7oTruE7wAWFZxzk6M3CUCAi3m6b";
private static string _createSign;
private static string _myTime;
private static string _getData;
private static string _saveData;
private bool _upload;
private static ServerResponseInfo _serverData;
private PostData _postData;
private UploadPostData _uploadPostData;
private static bool _thirdLoginSuccess;
private static bool _deviceLoginSuccess;
private bool _isNewUser;
void Start()
{
_postData = new PostData();
_serverData = new ServerResponseInfo();
_uploadPostData = new UploadPostData();
EventManager.Instance.Register<string>(EventManager.EventName.UploadToRemote, StartUpload);
EventManager.Instance.Register(EventManager.EventName.NewUserLogin, SaveNewUserData);
}
private void OnDestroy()
{
EventManager.Instance.Unregister<string>(EventManager.EventName.UploadToRemote, StartUpload);
EventManager.Instance.Unregister(EventManager.EventName.NewUserLogin, SaveNewUserData);
}
private void StartUpload(string jsonData)
{
_saveData = jsonData;
_upload = true;
}
private void SaveNewUserData()
{
DebugUtil.LogWarning("新玩家");
var jsonData = JsonConvert.SerializeObject(AppInfoManager.Instance.RemoteAppUserInfo);
UploadDataToServer(jsonData);
}
private void BindThirdID()
{
var jsonData = JsonConvert.SerializeObject(AppInfoManager.Instance.AppUserInfo);
UploadDataToServer(jsonData);
}
private void Update()
{
if (State == NetRequestStatus.Start)
{
State = NetRequestStatus.Wait;
GetDataFromServer();
}
if (_upload && !string.IsNullOrEmpty(_saveData))
{
_upload = false;
UploadDataToServer(_saveData);
}
}
private void GetDataFromServer()
{
try
{
var uniqueID = AppInfoManager.Instance.GetUniqueID();
var uniqueType = AppInfoManager.Instance.GetUniqueType();
DebugUtil.Log("使用{0}获取数据, ID:{1}", AppInfoManager.Instance.CurLoginState, uniqueID);
HTTPRequest request = new HTTPRequest(new Uri(URL), HTTPMethods.Post, OnGetFinished);
request.SetHeader("Content-Type", "application/json");
_createSign = GenerateHash("get_data", uniqueID);
_postData = new PostData
{
action = "get_data",
time = _myTime,
sign = _createSign,
client_id = uniqueID,
client_type = uniqueType,
game_data = "None"
};
var jsonData = JsonConvert.SerializeObject(_postData);
if (string.IsNullOrEmpty(jsonData))
DebugUtil.LogError("Json转化后postDataJson为空");
var bytes = Encoding.UTF8.GetBytes(jsonData);
request.RawData = bytes;
request.Send();
}
catch (Exception e)
{
DebugUtil.LogError("AppNetConfig.GetDataFromServer Error: {0}", e);
}
}
private void OnGetFinished(HTTPRequest request, HTTPResponse response)
{
try
{
var loginIDState = AppInfoManager.Instance.CurLoginState;
switch (request.State)
{
case HTTPRequestStates.Finished:
{
var jsonData = response.DataAsText;
JObject jObj = JObject.Parse(jsonData);
_serverData.code = (int)jObj["code"];
_serverData.message = jObj["message"]?.ToString();
//找不到用户信息
if (_serverData.code == 1)
{
//查不到第三方信息 但是本地有 绑定
if (loginIDState == AppInfoManager.NetConfigID.ThirdID && _deviceLoginSuccess)
{
DebugUtil.Log("查不到第三方信息 但是本地有, 保存数据, 服务器返回消息:{0}", jsonData);
BindThirdID();
_thirdLoginSuccess = true;
}
//其余情况以设备id注册新玩家
else
{
DebugUtil.Log("无设备ID和第三方ID, 新玩家, 先保存数据");
_isNewUser = true;
EventManager.Instance.Send(EventManager.EventName.NewUserLogin);
}
}
else if (_serverData.code == 0)
{
var data = jObj["data"];
if (data != null)
{
_serverData.data = data["game_data"]?.ToString();
if (!string.IsNullOrEmpty(_serverData.data))
{
if (loginIDState == AppInfoManager.NetConfigID.ThirdID && !_deviceLoginSuccess)
{
_thirdLoginSuccess = true;
AppInfoManager.Instance.ThirdIdGetSuccess(_serverData.data);
DebugUtil.Log("第一次使用第三方id获取成功设备id无登录");
}
//后续登录 和 设备id获取得到第三方id的情况
else if (loginIDState == AppInfoManager.NetConfigID.ThirdID && _deviceLoginSuccess)
{
_thirdLoginSuccess = true;
AppInfoManager.Instance.ThirdIdGetSuccessWithDevice(_serverData.data);
DebugUtil.Log("使用第三方id获取成功");
}
//本地有设备id缓存 并且没登录过第三方
else if (loginIDState == AppInfoManager.NetConfigID.DeviceID && !_thirdLoginSuccess)
{
_deviceLoginSuccess = true;
AppInfoManager.Instance.DeviceIdGetSuccess(_serverData.data);
DebugUtil.Log("使用设备id获取成功进行有无第三方id判断");
}
else
{
DebugUtil.Log("设备id获取成功但是第三方也成功登录的情况");
}
}
}
}
else
{
DebugUtil.LogError("Sever Get Error, code: {0}, message: {1}", _serverData.code,
_serverData.message);
}
break;
}
default:
string text = "Request Finished with Error! " + (request.Exception != null
? (request.Exception.Message + "\n" + request.Exception.StackTrace)
: "No Exception");
DebugUtil.LogError(text);
break;
}
}
catch (JsonReaderException jsonEx)
{
DebugUtil.LogError("GetData JSON parsing error: {0}\nRaw response: {1}", jsonEx.Message,
response.DataAsText);
}
catch (Exception e)
{
DebugUtil.LogError("AppNetConfig.GetDataFromBestHttp Error: {0}", e);
}
}
private void UploadDataToServer(string data)
{
try
{
var clientID = AppInfoManager.Instance.AppUserInfo.UserInfo.UserID;
var thirdID = AppInfoManager.Instance.AppUserInfo.UserInfo.ThirdId;
DebugUtil.Log("上传的玩家数据, clientID:{0}, thirdID: {1}gameData:{2}", clientID, thirdID, data);
var request = new HTTPRequest(new Uri(URL), HTTPMethods.Post, NewOnUploadFinished);
request.SetHeader("Content-Type", "application/json");
_createSign = GenerateHash("save_third_data", clientID);
_uploadPostData = new UploadPostData
{
action = "save_third_data",
time = _myTime,
sign = _createSign,
client_id = clientID,
third_id = thirdID,
game_data = data,
};
string jsonData = JsonConvert.SerializeObject(_uploadPostData);
if (string.IsNullOrEmpty(jsonData))
DebugUtil.LogError("Json转化后, uploadPostDat为空");
DebugUtil.Log("UploadData.Post信息{0}", jsonData);
var bytes = Encoding.UTF8.GetBytes(jsonData);
request.RawData = bytes;
request.Send();
}
catch (Exception e)
{
DebugUtil.LogError("AppNetConfig.UploadDataToServer Error: {0}", e);
}
}
private void NewOnUploadFinished(HTTPRequest request, HTTPResponse response)
{
try
{
switch (request.State)
{
case HTTPRequestStates.Finished:
{
var jsonData = response.DataAsText;
DebugUtil.Log("Upload从服务器获取到的数据{0}", jsonData);
JObject jObj = JObject.Parse(jsonData);
_serverData.code = (int)jObj["code"];
_serverData.message = jObj["message"]?.ToString();
if (_serverData.code == 0)
{
DebugUtil.Log("服务器保存数据成功 !!!!");
if (_isNewUser)
GetDataFromServer();
}
else
{
DebugUtil.LogError("Sever Save Error, code: {0}, message: {1}", _serverData.code,
_serverData.message);
}
break;
}
default:
string text = "Request Finished with Error! " + (request.Exception != null
? (request.Exception.Message + "\n" + request.Exception.StackTrace)
: "No Exception");
DebugUtil.LogError(text);
break;
}
}
catch (JsonReaderException jsonEx)
{
DebugUtil.LogError("Upload JSON parsing error: {0}\nRaw response: {1}", jsonEx.Message,
response.DataAsText);
}
catch (Exception e)
{
DebugUtil.LogError("AppNetConfig.OnUploadFinished Error: {0}", e);
}
}
private static string GenerateHash(string action, string uniqueID)
{
DateTime currentTimeUtc = DateTime.UtcNow;
var timeStamp = ((DateTimeOffset)currentTimeUtc).ToUnixTimeSeconds();
_myTime = timeStamp.ToString();
Dictionary<string, string> signData = new Dictionary<string, string>
{
{ "time", _myTime },
{ "action", action },
{ "client_id", uniqueID }
};
SortedDictionary<string, string> sortedData = new SortedDictionary<string, string>(signData);
string concatenatedData =
string.Join("&", sortedData.Select(kv => $"{kv.Key}={Uri.EscapeDataString(kv.Value)}"));
byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes(Sign);
byte[] dataBytes = System.Text.Encoding.UTF8.GetBytes(concatenatedData);
using (HMACSHA256 hmac = new HMACSHA256(keyBytes))
{
byte[] hashBytes = hmac.ComputeHash(dataBytes);
string hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
return hash;
}
}
}