DCS/ruiyiweiUX/Assets/GeneralTools/Editor/ResourcesDwonload.cs

405 lines
16 KiB
C#
Raw Permalink Normal View History

2026-06-09 13:59:11 +08:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Xml;
using UnityEditor;
using UnityEngine.Networking;
using System.Text;
using System;
using System.Media;
namespace GeneralTools
{
public class ResourcesDwonload : EditorWindow
{
private static ResourcesDwonload window;
private static string downloadRootUrl;
private static string downloadGetUrl;
private static string webVideoUrl;
private static string webAudioUrl;
private static string dataPath;
private List<DownloadXML> xmlList;
private List<string> titleList;
private int nowIndex = 0;
private string tempSaveDir;
private string saveFilePath;
private DateTime downloadBeginTime;
private bool httpGetFinished = false;
DownloadXML nowChooseXml;
bool autoopen = false;
bool autoimport = false;
string importdir = "";
string folderMode = "";
bool allowDownload = true;
Vector2 infopos = Vector2.zero;
Vector2 btnpos = Vector2.zero;
bool isShowBar = false;
float downPragrass = 0;
Thread downLoadThread = null;
Stream st;
Stream so;
[MenuItem("GeneralTools/资源下载/外网环境", false, 1)]
static void OpenWindow()
{
downloadRootUrl = "http://UnityResources.fyzdev.com";
downloadGetUrl = "http://UnityResources.fyzdev.com/download.php";
webVideoUrl = "http://UnityResources.fyzdev.com/video.php?url=";
webAudioUrl = "http://UnityResources.fyzdev.com/audio.php?url=";
//获取窗口并打开
window = GetWindow<ResourcesDwonload>("下载页Beta");
window.Show();//显示窗口
}
[MenuItem("GeneralTools/资源下载/风语筑局域网", false, 2)]
static void OpenWindowLocal()
{
downloadRootUrl = "http://192.168.21.136:1212";
downloadGetUrl = "http://192.168.21.136:1212/download.php";
webVideoUrl = "http://192.168.21.136:1212/video.php?url=";
webAudioUrl = "http://192.168.21.136:1212/audio.php?url=";
//获取窗口并打开
window = GetWindow<ResourcesDwonload>("下载页Beta");
window.Show();//显示窗口
}
private void Awake()
{
dataPath = Application.dataPath + "/";
httpGetFinished = false;
string xmlStr = HttpGet(downloadGetUrl, "");
xmlList = HandleXML(xmlStr);
titleList = xmlList.Select(m => m.rootName).ToList();
ChangeIndex(0);
httpGetFinished = true;
}
void ChangeIndex(int index)
{
nowIndex = index;
nowChooseXml = xmlList[nowIndex];
autoopen = nowChooseXml.autoOpen;
autoimport = nowChooseXml.autoImport;
importdir = nowChooseXml.importPath;
folderMode = nowChooseXml.folderMode;
allowDownload = nowChooseXml.allowDownload;
}
private void OnGUI()
{
if (!httpGetFinished)
return;
///自动生成
///
///生成最顶端按钮
///
btnpos = EditorGUILayout.BeginScrollView(btnpos, GUILayout.Height(40));
EditorGUILayout.BeginHorizontal();
for (int i = 0; i < titleList.Count; i++)
{
int index = i;
if (GUILayout.Button(titleList[index], GUILayout.Width(100)))
{
ChangeIndex(index);
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndScrollView();
//下方的东西会刷新
//临时路径
tempSaveDir = GetTempSavePath(nowChooseXml.rootName);
EditorGUILayout.BeginHorizontal();
GUILayout.Label("下载临时文件保存路径(电脑的绝对路径,无法更改)");
autoopen = EditorGUILayout.Toggle("下载完自动打开", autoopen);
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.TextField(tempSaveDir);
//自动导入
autoimport = EditorGUILayout.BeginToggleGroup("下载完自动导入", autoimport);
GUILayout.Label("导入工程路径(Asset/下的相对路径)");
importdir = EditorGUILayout.TextField(importdir);
EditorGUILayout.EndToggleGroup();
EditorGUILayout.Space();
//子文件
infopos = EditorGUILayout.BeginScrollView(infopos);
for (int i = 0; i < nowChooseXml.itemList.Count; i++)
{
EditorGUILayout.Space();
DownloadXMLItem tempItep = nowChooseXml.itemList[i];
EditorGUILayout.BeginHorizontal();
GUILayout.Label((i + 1).ToString(), GUILayout.Width(20));
GUILayout.TextField(tempItep.fileName, GUILayout.Width(300));
GUILayout.TextArea(tempItep.info);
GUILayout.TextField(tempItep.size, GUILayout.Width(100));
if (allowDownload && GUILayout.Button("下载", GUILayout.Width(100)))
{
object[] objee = new object[6] { downloadRootUrl + "/" + tempItep.url, Path.Combine(tempSaveDir, tempItep.fileName), Path.Combine(importdir, tempItep.fileName), autoopen, autoimport, tempItep.size };
GoDownload(objee);
window.RemoveNotification();
window.ShowNotification(new GUIContent("开始下载" + tempItep.fileName + "\r\n" + "文件大小:" + tempItep.size));
}
if (folderMode == "Audio")
{
if (GUILayout.Button("试听(网页)", GUILayout.Width(100)))
{
System.Diagnostics.Process.Start(webAudioUrl + "/" + tempItep.url);
}
}
else if (folderMode == "Photo")
{
if (GUILayout.Button("浏览(网页)", GUILayout.Width(100)))
{
System.Diagnostics.Process.Start(downloadRootUrl + "/" + tempItep.url);
}
}
else if (folderMode == "Video")
{
if (GUILayout.Button("观看(网页)", GUILayout.Width(100)))
{
System.Diagnostics.Process.Start(webVideoUrl + "/" + tempItep.url);
}
}
else if (folderMode == "General")
{
if (GUILayout.Button("下载(网页)", GUILayout.Width(100)))
{
System.Diagnostics.Process.Start(downloadRootUrl + "/" + tempItep.url);
}
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndScrollView();
}
private void Update()
{
if (!isShowBar)
{
EditorUtility.ClearProgressBar();
return;
}
bool isCancel = EditorUtility.DisplayCancelableProgressBar("下载中...", (downPragrass * 100).ToString("F2") + "%", downPragrass);
if (isCancel)
{
window.RemoveNotification();
window.ShowNotification(new GUIContent("取消下载:" + Path.GetFileName(saveFilePath)));
CloseAll();
isShowBar = false;
string ts = (DateTime.Now - downloadBeginTime).TotalSeconds.ToString("F2");
Debug.Log("下载取消用时:" + ts + "秒,");
Debug.Log("---------------------------------------------------------");
}
if (downPragrass >= 1)
{
window.RemoveNotification();
window.ShowNotification(new GUIContent("下载成功,详情在Console窗口"));
isShowBar = false;
}
}
void CloseAll()
{
if (downLoadThread != null)
{
downLoadThread.Interrupt();
downLoadThread.Abort();
downLoadThread = null;
}
if (so != null)
{
so.Close();
so.Dispose();
so = null;
}
if (st != null)
{
st.Close();
st.Dispose();
st = null;
}
if (!string.IsNullOrEmpty(saveFilePath))
{
File.Delete(saveFilePath);
saveFilePath = "";
}
}
void GoDownload(object path)
{
downloadBeginTime = DateTime.Now;
downPragrass = 0;
isShowBar = true;
CloseAll();
downLoadThread = new Thread(Download);
downLoadThread.IsBackground = true;
downLoadThread.Start(path);
}
private void Download(object obj)
{
string URL = ((object[])obj)[0].ToString();
saveFilePath = ((object[])obj)[1].ToString();
string fileCopyToPath = Path.Combine(dataPath, ((object[])obj)[2].ToString());
bool _autoopen = (bool)((object[])obj)[3];
bool _autoimport = (bool)((object[])obj)[4];
string _fileSize = ((object[])obj)[5].ToString();
string dir = Path.GetDirectoryName(saveFilePath);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
downPragrass = 0;
isShowBar = true;
HttpWebRequest Myrq = (HttpWebRequest)WebRequest.Create(URL);
HttpWebResponse myrp = (HttpWebResponse)Myrq.GetResponse();
long fileLength = myrp.ContentLength;
Debug.Log("开始下载");
st = myrp.GetResponseStream();
so = new FileStream(saveFilePath, FileMode.Create);
long totalDownloadedByte = 0;
byte[] by = new byte[1024];
int osize = st.Read(by, 0, by.Length);
while (osize > 0)
{
totalDownloadedByte = osize + totalDownloadedByte;
so.Write(by, 0, osize);
osize = st.Read(by, 0, by.Length);
downPragrass = totalDownloadedByte / (float)fileLength;
}
so.Close();
so.Dispose();
st.Close();
st.Dispose();
downPragrass = 1;
if (_autoopen)
{
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
info.FileName = saveFilePath;
info.Arguments = "";
try
{
System.Diagnostics.Process pro = System.Diagnostics.Process.Start(info);
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
}
Debug.Log("临时文件保存成功,路径:" + saveFilePath);
if (_autoimport)
{
try
{
string fileCopyDir = Path.GetDirectoryName(fileCopyToPath);
if (!Directory.Exists(fileCopyDir))
Directory.CreateDirectory(fileCopyDir);
File.Copy(saveFilePath, fileCopyToPath, true);
Debug.Log("导入工程,路径:" + fileCopyToPath);
}
catch (Exception)
{
}
}
string ts = (DateTime.Now - downloadBeginTime).TotalSeconds.ToString("F2");
Debug.Log("下载结束,文件大小:" + _fileSize + ",用时:" + ts + "秒,");
Debug.Log("---------------------------------------------------------");
saveFilePath = "";
}
public string HttpGet(string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
private List<DownloadXML> HandleXML(string xml)
{
List<DownloadXML> xmlList = new List<DownloadXML>();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
XmlNode resources = xmlDoc.SelectSingleNode("UnityResources");
foreach (XmlElement res in resources)
{
DownloadXML newXml = new DownloadXML();
newXml.rootName = res.GetAttribute("floder_name");
newXml.autoOpen = (res.GetAttribute("auto_open") == "false") ? false : true;
newXml.autoImport = (res.GetAttribute("auto_import") == "false") ? false : true;
newXml.importPath = res.GetAttribute("import_path");
newXml.folderMode = res.GetAttribute("folder_mode");
newXml.allowDownload = (res.GetAttribute("allow_download") == "false") ? false : true;
foreach (XmlElement item in res.ChildNodes)
{
DownloadXMLItem newItem = new DownloadXMLItem();
newItem.fileName = item.GetAttribute("filename");
newItem.url = item.GetAttribute("url");
string info = item.GetAttribute("info");
newItem.info = info;
long sizeL = long.Parse(item.GetAttribute("size"));
newItem.size = ConvertFileSize(sizeL);
newXml.itemList.Add(newItem);
}
xmlList.Add(newXml);
}
return xmlList;
}
public string GetTempSavePath(string floder)
{
return Application.temporaryCachePath + "/PackageCache/" + floder + "/";
}
public static string ConvertFileSize(long size)
{
string result = "0KB";
int filelength = size.ToString().Length;
if (filelength < 4)
result = size + "byte";
else if (filelength < 7)
result = Math.Round(Convert.ToDouble(size / 1024d), 2) + "KB";
else if (filelength < 10)
result = Math.Round(Convert.ToDouble(size / 1024d / 1024), 2) + "MB";
else if (filelength < 13)
result = Math.Round(Convert.ToDouble(size / 1024d / 1024 / 1024), 2) + "GB";
else
result = Math.Round(Convert.ToDouble(size / 1024d / 1024 / 1024 / 1024), 2) + "TB";
return result;
}
}
public class DownloadXML
{
public string rootName;
public bool autoOpen;
public bool autoImport;
public string importPath;
public string folderMode;
public bool allowDownload;
public List<DownloadXMLItem> itemList;
public DownloadXML()
{
itemList = new List<DownloadXMLItem>();
}
}
public class DownloadXMLItem
{
public string fileName;
public string url;
public string info;
public string size;
}
}