using System;
using System.IO;
using UnityEngine.Networking;
using XRTool.Util;
namespace MRStore.Util
{
///
/// 断点下载的辅助器
///
public class DownInfoHandler : DownloadHandlerScript
{
///
/// 文件流
///
private FileStream stream;
///
/// 下载资源的结构体
///
public DownInfo info { get; private set; }
public UnityWebRequest webRequest { get; private set; }
public void SetWebRequest(UnityWebRequest req, long contentLength)
{
webRequest = req;
ReadLocalData();
if (info != null)
{
info.ActiveTotalLength((long)contentLength);
}
}
///
/// 读取本地的数据
/// 读取临时数据缓存区tmppath
///
private void ReadLocalData()
{
if (stream == null)
{
try
{
FileMode model = FileMode.Append;
if (!File.Exists(info.tmpFilePath))
{
model = FileMode.OpenOrCreate;
}
stream = new FileStream(info.tmpFilePath, model, FileAccess.Write, FileShare.Write);
}
catch (Exception ex)
{
UnityLog.LogError(info.tmpFilePath + "File Stream Error" + ex.ToString());
if (stream != null)
{
stream.Dispose();
}
stream = null;
}
}
}
///
/// 构造函数
///
///
public DownInfoHandler(DownInfo info) : base(new byte[1024*256])
{
this.info = info;
this.info.SetDownHandler(this);
}
///
/// 服务器返回此文件的剩余大小
///
///
protected override void ReceiveContentLengthHeader(ulong contentLength)
{
if (contentLength == 0)
{
CompleteContent();
}
base.ReceiveContentLengthHeader(contentLength);
}
///
/// 从服务器接收到数据
///
///
///
///
protected override bool ReceiveData(byte[] data, int dataLength)
{
WriteFile(data, dataLength);
return base.ReceiveData(data, dataLength);
}
///
/// 下载,写入文件
///
///
///
public void WriteFile(byte[] data, int dataLength)
{
if (data != null && data.Length > 0)
{
if (stream != null)
{
stream.Write(data, 0, dataLength);
info.ActiveProcess(GetProgress());
}
}
}
protected override float GetProgress()
{
return info.downloadedFileLen*1.0f / info.totalSize;
}
///
/// 下载完成
/// 网络停止时也有可能会调用此方法
///
protected override void CompleteContent()
{
if (stream != null)
{
stream.Flush();
stream.Dispose();
}
stream = null;
info.ActiveComplete();
base.CompleteContent();
Dispose();
}
///
/// 下载错误,程序异常退出,网络停止时等异常情况下,停止此资源
///
public void ErrorDispose(string error)
{
if (stream != null)
{
stream.Flush();
stream.Dispose();
}
if (info != null && !string.IsNullOrEmpty(error))
{
info.ActiveError(error);
}
stream = null;
webRequest = null;
Dispose();
}
}
}