Files
WebviewSdk_Unity_IOS/Assets/Scripts/NetworkKit_sdk.cs
T

571 lines
18 KiB
C#
Raw Normal View History

2026-07-09 10:28:18 +08:00
using System.Text;
using UnityEngine;
using System.Collections;
using UnityEngine.Events;
using UnityEngine.Networking;
using System.Collections.Generic;
using Newtonsoft.Json;
using BingoBrain;
using System;
using DontConfuse;
using System.Linq;
using System.Security.Cryptography;
public class NetworkKit_sdk
{
2026-07-09 13:43:19 +08:00
public const string JarvisToken = "JarvisToken";
2026-07-09 10:28:18 +08:00
public static string CDNUrl;
public static string GetCacheToken()
{
string token = null;
if (PlayerPrefs.HasKey(JarvisToken))
{
token = PlayerPrefs.GetString(JarvisToken, string.Empty);
}
return token;
}
public static void SetCacheToken(string token)
{
PlayerPrefs.SetString(JarvisToken, token);
}
public const string DomainDebugUrl = @"https://sdkapi.jsoncompare.online/api/";
public static readonly string DomainReleaseUrl = $"https://bingotornado.top/api/";
private static IEnumerator PostInternal<T>(string url, object requestData, UnityAction<bool, T> onCompleted,
Dictionary<string, string> header = null)
{
string requestJson = JsonConvert.SerializeObject(requestData);
string url2 = url;
#if BingoBrainRelease
url2 = Base64Kit_sdk.Encode(url);
requestJson = Base64Kit_sdk.Encode(requestJson);
#endif
byte[] bytes = Encoding.UTF8.GetBytes(requestJson);
string url1 = DomainDebugUrl + url2;
//Debug.Log($"Url: {url1}");
UnityWebRequest loginRequest = new UnityWebRequest(url1, UnityWebRequest.kHttpVerbPOST)
{
uploadHandler = new UploadHandlerRaw(bytes),
downloadHandler = new DownloadHandlerBuffer()
};
if (header != null)
{
foreach (var keyValuePair in header)
{
loginRequest.SetRequestHeader(keyValuePair.Key, keyValuePair.Value);
}
}
SetRequestContentType(loginRequest);
yield return loginRequest.SendWebRequest();
if (loginRequest.result is not UnityWebRequest.Result.Success)
{
onCompleted?.Invoke(false, default);
}
else
{
string receiveContent = loginRequest.downloadHandler.text;
#if BingoBrainRelease
if (!receiveContent.IsNullOrWhiteSpace())
{
receiveContent = receiveContent.Substring(0, receiveContent.Length - 1);
receiveContent = receiveContent.Substring(1);
receiveContent = Base64Kit_sdk.Decode(receiveContent);
}
#endif
// Debug.Log(url + "--------" + loginRequest.downloadHandler.text);
2026-07-09 18:12:27 +08:00
// Debug.Log(url + "--------" + receiveContent);
2026-07-09 13:43:19 +08:00
var response = JsonConvert.DeserializeObject<ResponseData_sdk>(receiveContent);
2026-07-09 10:28:18 +08:00
if (response?.code == 0)
{
var responseData = JsonConvert.DeserializeObject<T>(response.data.ToString());
onCompleted?.Invoke(true, responseData);
}
else
{
if (response?.code == 1005)
{
ReLoginGetToken();
}
onCompleted?.Invoke(false, default);
}
}
loginRequest.Dispose();
}
public static void SetRequestContentType(UnityWebRequest request)
{
request.SetRequestHeader("Content-Type", "application/json;charset=utf-8");
}
public static void Post<T>(string url, object requestData, UnityAction<bool, T> onCompleted)
{
SdkManager.Instance.StartCoroutine(PostInternal(url, requestData, onCompleted));
}
public static void Post(string url, object requestData, UnityAction<bool, object> onCompleted = null)
{
SdkManager.Instance.StartCoroutine(PostInternal(url, requestData, onCompleted));
}
public static void PostWithHeader<T>(string url, object requestData = null,
UnityAction<bool, T> onCompleted = null)
{
ReSetToken();
var headers = new Dictionary<string, string> { { "x-token", GetCacheToken() } };
SdkManager.Instance.StartCoroutine(PostInternal(url, requestData, onCompleted, headers));
}
public static void PostWithHeader<T>(string url, UnityAction<bool, T> onCompleted)
{
if (onCompleted != null)
{
PostWithHeader<T>(url, null, (isSuccess, obj) => { onCompleted.Invoke(isSuccess, obj); });
}
else
{
PostWithHeader<T>(url);
}
}
public static void PostWithHeader(string url, object requestData = null, UnityAction<bool> onCompleted = null)
{
if (onCompleted != null)
{
PostWithHeader<object>(url, requestData, (isSuccess, obj) => { onCompleted?.Invoke(isSuccess); });
}
else
{
PostWithHeader<object>(url, requestData);
}
}
public static void Get(string url, UnityAction<string> onCompleted)
{
SdkManager.Instance.StartCoroutine(GetInternal(url, onCompleted));
}
public static IEnumerator GetInternal(string url, UnityAction<string> onCompleted)
{
var request = UnityWebRequest.Get(url);
yield return request.SendWebRequest();
if (request.result is not UnityWebRequest.Result.Success)
{
onCompleted?.Invoke(default);
}
else
{
var receiveContent = request.downloadHandler.text;
var json = Json_StringFormat(receiveContent);
onCompleted?.Invoke(receiveContent);
}
request.Dispose();
}
public static string Json_StringFormat(string sourceJson)
{
sourceJson += " ";
var index = 0;
var newJson = new StringBuilder();
for (int i = 0; i < sourceJson.Length - 1; i++)
{
if (sourceJson[i] == '{' || sourceJson[i] == '[')
{
index++;
newJson.Append(sourceJson[i]);
newJson.Append("\n");
for (var a = 0; a < index; a++)
{
newJson.Append("\t");
}
}
else if ((sourceJson[i] == '}' || sourceJson[i] == ']'))
{
index--;
newJson.Append("\n");
for (var a = 0; a < index; a++)
{
newJson.Append("\t");
}
newJson.Append(sourceJson[i]);
newJson.Append(sourceJson[i + 1] == ',' ? "," : "");
newJson.Append("\n");
if (sourceJson[i + 1] == ',') i++;
for (int a = 0; a < index; a++)
{
newJson.Append("\t");
}
}
else if (sourceJson[i] != '}' && sourceJson[i] != ']' && sourceJson[i + 1] == ',')
{
newJson.Append(sourceJson[i]);
newJson.Append(sourceJson[i + 1]);
newJson.Append("\n");
i++;
for (var a = 0; a < index; a++)
{
newJson.Append("\t");
}
}
else
{
newJson.Append(sourceJson[i]);
}
}
return newJson.ToString();
}
// public static void BuriedPoint(string eventname, string eventproperty, int integer)
// {
// if (eventname == BuriedPointEvent.Apple_AD_event || eventname == BuriedPointEvent.Apple_pay_event)
// {
// eventname = GameHelper.IsAdModelOfPay() ? BuriedPointEvent.Apple_AD_event : BuriedPointEvent.Apple_pay_event;
// }
// buriedPointObject.@event = eventname;
// buriedPointObject.property = eventproperty;
// buriedPointObject.n = integer;
// PostWithHeader<BuriedPointObject>("/event/incrN", buriedPointObject, (isSuccess, obj) =>
// {
// // Debug.Log(isSuccess);
// // Debug.Log(eventproperty);
// //Debug.Log(JsonUtility.ToJson(obj));
// });
// }
2026-07-09 13:43:19 +08:00
// public static BuriedPointObject buriedPointObject = new BuriedPointObject();
2026-07-09 10:28:18 +08:00
// public static string GetNetworkType()
// {
// switch (Application.internetReachability)
// {
// case NetworkReachability.ReachableViaCarrierDataNetwork:
// return NetworkType.mobile;
// case NetworkReachability.ReachableViaLocalAreaNetwork:
// return NetworkType.wifi;
// case NetworkReachability.NotReachable:
// return NetworkType.notConnected;
// default:
// return NetworkType.notConnected;
// }
// }
private static bool isReqToken = false;
public static void ReSetToken()
{
if (isReqToken) return;
// var nowTimes = GameHelper.GetNowTime();
// var passtime = GameHelper.GetLoginModel().expires_at;
// // Debug.Log($"ReSetToken nowTimes:{nowTimes} passtime:{passtime}");
// if (passtime == 0 || passtime - nowTimes > 3600) return;
// isReqToken = true;
// var headers = new Dictionary<string, string> { { "x-token", GetCacheToken() } };
// IsfvKit.StartCoroutine(PostInternal<ResquestTokenData>("tokenRefresh", null, (isSuccess, tokenData) =>
// {
// if (isSuccess)
// {
// LoginModel loginModel = GameHelper.GetLoginModel();
// loginModel.token = tokenData.token;
// loginModel.expires_at = tokenData.expires_at;
// SetCacheToken(tokenData.token);
// }
// isReqToken = false;
// }, headers));
}
private static bool isReqToken1 = false;
public static void ReLoginGetToken()
{
// if (isReqToken1) return;
// var requestLoginData = new RequestLoginData
// {
// device_id = SystemInfo.deviceUniqueIdentifier,
// pack_name = NetworkMsg.Identifier,
// app_version = Application.version,
// channel = BingoBea.Instance.attribution,
// sim = WebviewManager.haveSimCard
// };
// isReqToken1 = true;
// Post<LoginModel>("login", requestLoginData, (isSuccess, loginData) =>
// {
// if (isSuccess)
// {
// LoginModel loginModel = GameHelper.GetLoginModel();
// loginModel.token = loginData.token;
// loginModel.expires_at = loginData.expires_at;
// SetCacheToken(loginData.token);
// }
// isReqToken1 = false;
// });
}
}
public class Base64Kit_sdk
{
// public static string Base64Encode(string source)
// {
// byte[] bytes = Encoding.UTF8.GetBytes(source);
// string encode = Convert.ToBase64String(bytes);
// return encode;
// }
// public static string Encode(string data, bool is_apple_pay = false)
// {
// var key = BingoBrain.Network.DomainRelease;
// //if (is_apple_pay) key = "com.leisuregames.crazygourmet";
// var keyMD5 = MD5Kit.MD5String1(key);
// //UnityEngine.Debug.Log("Base64 Encode Key: " + keyMD5);
// var str = Base64EncodeUtil.Base64Encode(data + keyMD5);
// var bytes = Encoding.UTF8.GetBytes(str);
// for (int i = 0, j = bytes.Length - 1; i < j; i += 1, j -= 1)
// {
// if (i % 2 == 0)
// {
// (bytes[i], bytes[j]) = (bytes[j], bytes[i]);
// }
// }
// var loginData = Encoding.UTF8.GetString(bytes);
// return loginData;
// }
// public static string Decode(string data)
// {
// var bytes = Encoding.UTF8.GetBytes(data);
// for (int i = 0, j = bytes.Length - 1; i < j; i += 1, j -= 1)
// {
// if (i % 2 == 0)
// {
// (bytes[i], bytes[j]) = (bytes[j], bytes[i]);
// }
// }
// var str = Encoding.UTF8.GetString(bytes);
// var str1 = Base64EncodeUtil.Base64Decode(str);
// var key = BingoBrain.Network.DomainRelease;
// var keyMD5 = MD5Kit.MD5String1(key);
// // Debug.Log("Base64 Decode Key: " + keyMD5);
// // Debug.Log("Base64 Decode str1: " + str1);
// var result = str1.Replace(keyMD5, string.Empty);
// return result;
// }
// public static string Decode(string data, string key)
// {
// var bytes = Encoding.UTF8.GetBytes(data);
// for (int i = 0, j = bytes.Length - 1; i < j; i += 1, j -= 1)
// {
// if (i % 2 == 0)
// {
// (bytes[i], bytes[j]) = (bytes[j], bytes[i]);
// }
// }
// var str = Encoding.UTF8.GetString(bytes);
// var str1 = Base64EncodeUtil.Base64Decode(str);
// // var key = NetworkManager.DomainRelease;
// var keyMD5 = MD5Kit.MD5String1(key);
// var result = str1.Replace(keyMD5, string.Empty);
// return result;
// }
private static byte[] GenerateKey(string secret)
{
using var sha256 = SHA256.Create();
return sha256.ComputeHash(Encoding.UTF8.GetBytes(secret));
}
internal static byte[] Encrypt(byte[] plainText, string secret)
{
if (plainText == null || plainText.Length == 0) return plainText;
var key = GenerateKey(secret);
using var aes = Aes.Create();
aes.Key = key;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.None;
aes.GenerateIV();
var iv = aes.IV;
var blockSize = aes.BlockSize / 8;
var padding = blockSize - plainText.Length % blockSize;
var padded = new byte[plainText.Length + padding];
Buffer.BlockCopy(plainText, 0, padded, 0, plainText.Length);
for (var i = plainText.Length; i < padded.Length; i++) padded[i] = (byte)padding;
using var encryptor = aes.CreateEncryptor();
var encrypted = encryptor.TransformFinalBlock(padded, 0, padded.Length);
var result = new byte[iv.Length + encrypted.Length];
Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
Buffer.BlockCopy(encrypted, 0, result, iv.Length, encrypted.Length);
return ToUrlSafeBase64(result);
}
internal static byte[] Decrypt(byte[] encryptedBase64, string secret)
{
if (encryptedBase64 == null || encryptedBase64.Length == 0) return encryptedBase64;
var key = GenerateKey(secret);
var fullCipher = FromUrlSafeBase64(encryptedBase64);
if (fullCipher.Length < 16) throw new Exception("Invalid cipher data");
var iv = fullCipher.Take(16).ToArray();
var cipherText = fullCipher.Skip(16).ToArray();
using var aes = Aes.Create();
aes.Key = key;
aes.IV = iv;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.None;
using var decryptor = aes.CreateDecryptor();
var decrypted = decryptor.TransformFinalBlock(cipherText, 0, cipherText.Length);
int pad = decrypted[^1];
if (pad <= 0 || pad > decrypted.Length) throw new Exception("Invalid padding");
var result = decrypted.Take(decrypted.Length - pad).ToArray();
return result;
}
// 用双引号包裹字节数组
private static byte[] QuoteBytes(byte[] input)
{
var result = new byte[input.Length + 2];
result[0] = (byte)'"';
Buffer.BlockCopy(input, 0, result, 1, input.Length);
result[result.Length - 1] = (byte)'"';
return result;
}
// 去除双引号(如果存在)
internal static byte[] UnquoteBytes(byte[] input)
{
if (input.Length >= 2 && input[0] == (byte)'"' && input[input.Length - 1] == (byte)'"')
{
var result = new byte[input.Length - 2];
Buffer.BlockCopy(input, 1, result, 0, result.Length);
return result;
}
return input;
}
private static byte[] ToUrlSafeBase64(byte[] data)
{
var base64 = Convert.ToBase64String(data);
var urlSafe = base64.Replace('+', '-').Replace('/', '_');
return Encoding.UTF8.GetBytes(urlSafe);
}
private static byte[] FromUrlSafeBase64(byte[] urlSafe)
{
var base64 = Encoding.UTF8.GetString(urlSafe).Replace('-', '+').Replace('_', '/');
return Convert.FromBase64String(base64);
}
}
public class ResquestTokenData_sdk
{
public string token;
public long expires_at;
}
public class NetworkType_sdk
{
public static string mobile = "Mobile Data";
public static string wifi = "Wi-Fi";
public static string notConnected = "Not Connected";
}
public static class Base64EncodeUtil_sdk
{
public static string Base64Encode(string source)
{
return Base64Encode(Encoding.UTF8, source);
}
public static string Base64Decode(string result)
{
return Base64Decode(Encoding.UTF8, result);
}
public static string Base64Encode(Encoding encoding, string source)
{
byte[] bytes = encoding.GetBytes(source);
string encode = Convert.ToBase64String(bytes);
return encode;
}
public static string Base64Decode(Encoding encoding, string result)
{
byte[] bytes = Convert.FromBase64String(result);
string decode = encoding.GetString(bytes);
return decode;
}
public static string Base64EncodeString(byte[] source)
{
return Convert.ToBase64String(source);
}
public static byte[] Base64DecodeBytes(string result)
{
return Convert.FromBase64String(result);
}
}
public class ResponseData_sdk
{
public int code;
public string msg;
public object data;
}
public class BuriedPointObject_sdk
{
public string @event;
public string property;
public int n;
}
2026-07-09 13:43:19 +08:00
public class H5sendClass
{
public string link;
public string type;
}
2026-07-09 18:12:27 +08:00