Files
PrinceOfGlory/Assets/代码/资源下载/UploadInfoToWeb.cs
kridoo ac041525cc 1
2026-01-12 09:39:28 +08:00

342 lines
12 KiB
C#
Raw Permalink 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 Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
public class UploadInfoToWeb : MonoBehaviour
{
[Header("秒")]
public int uploadTime = 120;//上传时间。要求apk包名和平台上一致
bool isUpload;
DateTime dateTime, begin_at;
string padModel;//修改“设备型号.txt”内容为平板的型号和后台分组中一致
Assets assets = new();
void Start()
{
if (File.Exists(Config.DeviceModel))
{
padModel = File.ReadAllText(Config.DeviceModel);
}
else
{
padModel = PicoAPI._Instance.PicoSN();
File.WriteAllText(Config.DeviceModel, padModel);
}
GameTools.CreateDirectory(Config.UseRecordPath);
begin_at = DateTime.Now;
dateTime = DateTime.Now.AddSeconds(-10);
//StartCoroutine(check());
InvokeRepeating("UploadEQ", 1f, 60f);
}
private void Update()
{
if (DateTime.Now >= dateTime.AddSeconds(10))
{
dateTime = DateTime.Now;
UploadLocalWatchInfo();
}
if (Time.time > uploadTime && !isUpload)
{
UploadPlayInfo();
isUpload = true;
}
}
#region
IEnumerator check()
{
using (UnityWebRequest request = UnityWebRequest.Get("http://www.baidu.com"))
{
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.Log("网络不可用,退出游戏");
Application.Quit();
yield break;
}
else
{
Debug.Log("网络可用");
}
}
yield return new WaitForSeconds(1);
//获取设备SN和剩下的播放次数
WWWForm devicesForm = new WWWForm();
WebNet.Encrypt(padModel);
devicesForm.AddField("tabletSN", padModel);
using (UnityWebRequest req = UnityWebRequest.Post(WebNet.getDeviceList, devicesForm))
{
req.SetRequestHeader("Authorization", WebNet.Authorization);
req.SetRequestHeader("Post-Time", WebNet.Post_Time);
yield return req.SendWebRequest();
JObject jsonData = JsonConvert.DeserializeObject<JObject>(req.downloadHandler.text);
//Debug.Log(jsonData["code"]);
//Debug.Log(jsonData["msg"]);
if (jsonData["code"].ToString() == "200")
{
JToken data = jsonData["data"];
if (data.Count() > 0)
{
bool hasSn = false;
for (int i = 0; i < data.Count(); i++)
{
int.TryParse(data[i]["play_time"].ToString(), out int play_time);
if (play_time <= 0)
{
Debug.Log("次数用完,退出游戏");
Application.Quit();
}
if (string.Equals(data[i]["deviceSN"].ToString(), Config.SN))
{
hasSn = true;
break;
}
}
if (hasSn)
{
Debug.Log("包含");
}
else
{
Debug.Log("不含此SN退出游戏");
Application.Quit();
}
}
else
{
Debug.Log("没有此平板型号的分组");
Application.Quit();
}
}
else
{
Debug.Log("请求失败");
Application.Quit();
}
}
yield return new WaitForSeconds(1);
WWWForm assetsForm = new WWWForm();
WebNet.Encrypt(Config.SN);
//Debug.Log(WebNet.s);//加密前字符串
//Debug.Log(WebNet.Authorization);//加密后token
assetsForm.AddField("deviceSN", Config.SN);
assetsForm.AddField("password", WebNet.password);
using (UnityWebRequest req = UnityWebRequest.Post(WebNet.assetsUrl, assetsForm))
{
yield return req.SendWebRequest();
if (req.result != UnityWebRequest.Result.Success)
{
Debug.Log($"获取资源失败:{req.error}");
yield break;
}
else
{
JObject jsonData = JsonConvert.DeserializeObject<JObject>(req.downloadHandler.text);
if (jsonData["code"].ToString() != "200")
{
Debug.Log($"获取资源失败:{jsonData["msg"]}");
yield break;
}
JToken data = jsonData["data"];
JToken host = data["host"];//资源主地址
WebNet.DownAssetsUrl = host.ToString();
JToken video = data["video"];
for (int i = 0; i < video.Count(); i++)
{
string packageName = video[i]["sequence"].ToString();
if (string.Equals(Application.identifier, packageName))
{
assets.resource_id = int.Parse(video[i]["resource_id"].ToString());
assets.resource_name = video[i]["resource_name"].ToString();
assets.sequence = video[i]["sequence"].ToString();
assets.url = video[i]["url"].ToString();
assets.brief = video[i]["brief"].ToString();
assets.icon = video[i]["icon"].ToString();
assets.file_size = int.Parse(video[i]["file_size"].ToString());
assets.group_id = int.Parse(video[i]["group_id"].ToString());
assets.group_name = video[i]["group_name"].ToString();
assets.device_id = int.Parse(video[i]["device_id"].ToString());
assets.play_time = int.Parse(video[i]["play_time"].ToString());
assets.province = video[i]["province"].ToString();
assets.city = video[i]["city"].ToString();
assets.updated_at = video[i]["updated_at"].ToString();
assets.type = int.Parse(video[i]["type"].ToString());
break;
}
}
}
}
}
#endregion
#region 使
/// <summary>
/// 向平台上传视频播放信息
/// </summary>
public void UploadPlayInfo()
{
DateTime end_at = DateTime.Now;
TimeSpan timeSpan = end_at - begin_at;
int duration = (int)timeSpan.TotalSeconds;
WatchInfoRecordLocal(Config.SN, assets, begin_at.ToString(), end_at.ToString(), duration, 1);
}
/// <summary>
/// 本地记录观看信息,并更新剩余播放次数
/// </summary>
void WatchInfoRecordLocal(string deviceSN, Assets videoData, string begin_at, string end_at, int duration, int times)
{
string file = $"{deviceSN}{videoData.resource_name}{end_at}.json".Replace("/", "").Replace(":", "").Trim();
string fileName = Path.Combine(Config.UseRecordPath, file);
WatchVideoInfo watchVideoInfo = new WatchVideoInfo();
watchVideoInfo.deviceSN = Config.SN;
watchVideoInfo.group_id = videoData.group_id;
watchVideoInfo.resource_id = videoData.resource_id;
watchVideoInfo.device_id = videoData.device_id;
watchVideoInfo.begin_at = begin_at;
watchVideoInfo.end_at = end_at;
watchVideoInfo.duration = duration;
watchVideoInfo.times = times;
string json = JsonUtility.ToJson(watchVideoInfo);
byte[] bytes = Encoding.UTF8.GetBytes(json);
GameTools.WriteFile(fileName, bytes);
//Debug.Log("记录观看信息成功");
}
/// <summary>
/// 上传本地观看信息
/// </summary>
void UploadLocalWatchInfo()
{
StartCoroutine(UploadLocalInfo());
}
IEnumerator UploadLocalInfo()
{
using (UnityWebRequest request = UnityWebRequest.Get("http://www.baidu.com"))
{
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
//Debug.Log("网络不可用,无法上传使用信息");
yield break;
}
else
{
//Debug.Log("网络可用,上传使用信息中");
}
}
//上传本地播放信息
List<string> WatchInfoNames = Directory.GetFiles(Config.UseRecordPath).Select(Path.GetFileName).ToList();
if (WatchInfoNames.Count > 0)
{
foreach (var item in WatchInfoNames)
{
string path = Path.Combine(Config.UseRecordPath, item);
byte[] bytes = GameTools.ReadFile(path);
string fileContents = Encoding.UTF8.GetString(bytes);
WatchVideoInfo watchVideoInfo = JsonUtility.FromJson<WatchVideoInfo>(fileContents);
WWWForm form1 = new WWWForm();
WebNet.Encrypt(watchVideoInfo.deviceSN);
form1.AddField("deviceSN", watchVideoInfo.deviceSN);
form1.AddField("group_id", watchVideoInfo.group_id);
form1.AddField("resource_id", watchVideoInfo.resource_id);
form1.AddField("device_id", watchVideoInfo.device_id);
form1.AddField("begin_at", watchVideoInfo.begin_at);
form1.AddField("end_at", watchVideoInfo.end_at);
form1.AddField("duration", watchVideoInfo.duration);
form1.AddField("times", watchVideoInfo.times);
using (UnityWebRequest req = UnityWebRequest.Post(WebNet.UploadInfoUrl, form1))
{
req.SetRequestHeader("Authorization", WebNet.Authorization);
req.SetRequestHeader("Post-Time", WebNet.Post_Time);
yield return req.SendWebRequest();
if (req.result == UnityWebRequest.Result.Success)
{
//Debug.Log("上传本地观看信息成功");
File.Delete(path);//删除本地记录
}
else
{
//Debug.Log($"上传本地观看失败!");
//Debug.Log($"请求失败:{req.result}\r\n错误:{req.error}\r\ncode:{req.responseCode}\r\ntext:{req.downloadHandler?.text}");
}
}
}
}
}
#endregion
#region
/// <summary>
/// 向平台上传设备电量信息
/// </summary>
void UploadEQ()
{
StartCoroutine(UploadEQInfo());
}
IEnumerator UploadEQInfo()
{
using (UnityWebRequest request = UnityWebRequest.Get("http://www.baidu.com"))
{
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.Log("网络不可用");
yield break;
}
else
{
Debug.Log("网络可用");
}
}
WWWForm form1 = new WWWForm();
WebNet.Encrypt(Config.SN);
form1.AddField("deviceId", Config.SN);
int.TryParse(PicoAPI._Instance.PicoPower(), out int power);
form1.AddField("elecQuantity", power);
//form1.AddField("elecQuantity", 100);
using (UnityWebRequest req = UnityWebRequest.Post(WebNet.uploadEQ, form1))
{
req.SetRequestHeader("Authorization", WebNet.Authorization);
req.SetRequestHeader("Post-Time", WebNet.Post_Time);
yield return req.SendWebRequest();
if (req.result == UnityWebRequest.Result.Success)
{
Debug.Log("上传设备电量成功");
}
else
{
Debug.Log(req.downloadHandler.text);
JToken jsonData = JsonConvert.DeserializeObject<JObject>(req.downloadHandler.text);
Debug.Log($"上传设备电量失败!");
//Debug.Log($"<color=red>上传信息失败!{jsonData["code"]}</color>");
//Debug.Log($"<color=red>上传信息失败!{jsonData["msg"]}</color>");
}
}
}
#endregion
}