using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using LitJson;
using System.IO;
using System.Net;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.GZip;
using System;
using UnityEngine.UI;
using System.Text;
//直接使用 将byte转换为Stream,省去先保存到本地在解压的过程
public class DownloadUpdates : MonoBehaviour
{
public Text text;
private string str = "";
public string m_Username = "rendadev";
public string m_Password = "12345678";
private string downUrl = "";//下载压缩包的地址
//请求地址,写自己的请求地址就行//rendadev:12345678@
private string url = "http://update.bbtjoy.com/auto-update/api/v1/device/1000000/program/check-update?machineType=FuDaiJi&machineLayout=Single&programVersion=NormalVer&programVersionNumber=19700101.00";
//声明 JsonData,LitJson 提供的方法
JsonData itemdata;
private void Start()
{
OnDownload();
}
/// <summary>
/// 下载app
/// </summary>
public void OnDownload()
{
JsonData data = JsonMapper.ToObject(DoQuery());
downUrl = (string)data["info"]["url"];
Debug.Log(downUrl);
StartCoroutine(Wait_LoadDown("myzip",downUrl));
}
//IEnumerator GetDown()
//{
// WWW getData = new WWW(url);
// yield return getData;
// if (getData.error != null)
// {
// text.text += "错误:" + getData.error;
// Debug.Log(getData.error);
// }
// else
// {
// text.text += getData.text;
// Debug.Log(getData.text);
// }
// //把请求到的数据转换成 JsonData array 类型,并存储到itemdata里
// itemdata = JsonMapper.ToObject(getData.text);
// downUrl = (string)itemdata["info"]["url"];
// Debug.Log(downUrl);
// if (downUrl != "")
// {
// text.text += "开始下载zip";
// //下载此地址的压缩包
// StartCoroutine(Wait_LoadDown("myzip", downUrl));
// }
//}
/// <summary>
/// 下载
/// </summary>
/// <param name="ZipID"></param>
/// <param name="url"></param>
/// <returns></returns>
IEnumerator Wait_LoadDown(string ZipID, string url)
{
WWW www = new WWW(url);
yield return www;
if (www.isDone)
{
if (www.error == null)
{
text.text += "下载成功";
Debug.Log("下载成功");
string dir = Application.persistentDataPath;
Debug.Log(dir);
text.text += dir;
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
yield return new WaitForEndOfFrame();
//直接使用 将byte转换为Stream,省去先保存到本地在解压的过程
bool isSuccessLoad = SaveZip(ZipID, url, www.bytes);
if (isSuccessLoad)
{
//
}
else
{
}
}
else
{
text.text += www.error;
Debug.Log(www.error);
}
}
}
/// <summary>
/// 解压
/// </summary>
/// <param name="ZipID"></param>
/// <param name="url"></param>
/// <param name="ZipByte"></param>
/// <param name="password"></param>
/// <returns></returns>
public bool SaveZip(string ZipID, string url, byte[] ZipByte, string password = null)
{
bool result = true;
FileStream fs = null;
ZipInputStream zipStream = null;
ZipEntry ent = null;
string fileName_1 = "";
ZipID = Application.persistentDataPath + "/" + ZipID;
Debug.Log(ZipID);
if (!Directory.Exists(ZipID))
{
Directory.CreateDirectory(ZipID);
}
try
{
//直接使用 将byte转换为Stream,省去先保存到本地在解压的过程
Stream stream = new MemoryStream(ZipByte);
zipStream = new ZipInputStream(stream);
if (!string.IsNullOrEmpty(password))
{
zipStream.Password = password;
}
while ((ent = zipStream.GetNextEntry()) != null)
{
if (!string.IsNullOrEmpty(ent.Name))
{
fileName_1 = Path.Combine(ZipID, ent.Name);
#region
string fileName = fileName_1.Replace('\\', '/');
if (fileName.EndsWith("/"))
{
Directory.CreateDirectory(fileName);
continue;
}
#endregion
fs = File.Create(fileName);
int size = 2048;
byte[] data = new byte[size];
while (true)
{
size = zipStream.Read(data, 0, data.Length);
if (size > 0)
{
//fs.Write(data, 0, data.Length);
fs.Write(data, 0, size);//解决读取不完整情况
}
else break;
}
}
}
}
catch (Exception e)
{
Debug.Log(e.ToString());
text.text += e.ToString();
result = false;
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
if (zipStream != null)
{
zipStream.Close();
zipStream.Dispose();
}
if (ent != null)
{
ent = null;
}
GC.Collect();
GC.Collect(1);
}
return result;
}
public string DoQuery(string argument = null, string data = null, string method = "GET")
{
//string url = "http://update.bbtjoy.com/auto-update/api/v1/device/1000000/program/check-update?machineType=FuDaiJi&machineLayout=Single&programVersion=NormalVer&programVersionNumber=19700101.00";//string.Format("{0}{1}/", Config.BaseURL, resource.ToString());
if (argument != null)
{
url = string.Format("{0}{1}/", url, argument);
}
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/json";
request.Method = method;
if (data != null)
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(data);
}
}
string base64Credentials = GetEncodedCredentials();
request.Headers.Add("Authorization", "Basic " + base64Credentials);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
text.text = result;
return result;
}
private string GetEncodedCredentials()
{
string mergedCredentials = string.Format("{0}:{1}", m_Username, m_Password);
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
Debug.Log(Convert.ToBase64String(byteCredentials));
return Convert.ToBase64String(byteCredentials);
}
}