You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

564 lines
23 KiB

using Container.Common;
using Container.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace Container.Business
{
public class DownLoadMethod
{
private Class_Log log = new Class_Log();
private App app = ((App)Application.Current);
//public bool DownLoadZip(string url, string downloadFolder, string md5, out string errorMsg, bool isback = true, bool isupdate = true)
//{
// bool flag = false;
// errorMsg = string.Empty;
// try
// {
// if (!Directory.Exists(downloadFolder))
// {
// Directory.CreateDirectory(downloadFolder);
// }
// WebClientPro webClient = new WebClientPro(30 * 60 * 1000);
// string fileName = url.Substring(url.Replace("\\", "/").Replace(@"\", "/").LastIndexOf('/') + 1);
// if (fileName.Contains("?"))
// {
// fileName = fileName.Substring(0, fileName.IndexOf('?'));
// }
// string downUrl = downloadFolder + @"\" + fileName;
// //下载更新包
// webClient.DownloadFile(url, downUrl);
// string localMD5 = GetMD5HashFromFile(downUrl);
// if (!string.IsNullOrEmpty(md5) && md5 != localMD5)
// {
// errorMsg = "MD5校验不合格";
// File.Delete(downUrl);
// return flag;
// }
// string UpdateReleasePath = downloadFolder + @"/temp/";
// //解压更新包至指定路径
// if (Directory.Exists(UpdateReleasePath))
// {
// DeleteDir(UpdateReleasePath, 1);
// Directory.CreateDirectory(UpdateReleasePath);
// }
// ZipFile.ExtractToDirectory(downUrl, UpdateReleasePath);
// string mainpropath = downloadFolder + @"\Main";
// DirectoryInfo di = new DirectoryInfo(mainpropath);//正式包路径
// DirectoryInfo di2 = new DirectoryInfo(UpdateReleasePath);//更新包解压路径
// if (isback)
// {
// DirectoryInfo source = new DirectoryInfo(downloadFolder);
// DirectoryInfo[] dirs = source.GetDirectories();
// foreach (DirectoryInfo dir in dirs)
// {
// log.WriteLogFile(mainpropath + "----" + dir.Name.Length + "----" + mainpropath.Length, "更新");
// if (dir.Name.Contains("Main") && dir.Name.Length > 4)
// {
// DeleteDir(dir.FullName, 1);
// }
// }
// DirectoryInfo diback = new DirectoryInfo(mainpropath + DateTime.Now.ToString("yyyyMMddHHmmss"));//正式包路径
// MoveDirectory(di, diback, true); //复制子目录
// }
// if (isupdate)
// {
// MoveDirectory(di2, di, true); //复制子目录
// }
// flag = true;
// }
// catch (Exception e)
// {
// flag = false;
// errorMsg = e.Message;
// log.WriteLogFile(e.ToString(), "DownLoadZipError");
// }
// return flag;
//}
/// <summary>
/// 获取文件MD5 哈希码
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public string GetMD5HashFromFile(string fileName)
{
try
{
FileStream file = new FileStream(fileName, FileMode.Open);
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(file);
file.Close();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
catch (Exception ex)
{
log.WriteLogFile("GetMD5HashFromFile() fail, error:" + ex.ToString(), "downloaderror");
return "";
}
}
public static string ReadContext(string path)
{
try
{
if (File.Exists(path))
{
FileStream fs = new FileStream(path, FileMode.Open);
StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8);
string context = sr.ReadToEnd();
fs.Close();
sr.Close();
sr.Dispose();
fs.Dispose();
return context;
}
else
{
return "";
}
}
catch (Exception ex)
{
Class_Log log = new Class_Log();
log.WriteLogFile(ex.ToString(), "Temp113");
ReadContext(path);
return "";
}
}
public void DeleteDir(string srcPath, int isSelf = 0)
{
try
{
if (!Directory.Exists(srcPath))
{
return;
}
DirectoryInfo dir = new DirectoryInfo(srcPath);
FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //返回目录中所有文件和子目录
foreach (FileSystemInfo i in fileinfo)
{
try
{
if (i is DirectoryInfo) //判断是否文件夹
{
DirectoryInfo subdir = new DirectoryInfo(i.FullName);
subdir.Delete(true); //删除子目录和文件
}
else
{
//如果 使用了 streamreader 在删除前 必须先关闭流 ,否则无法删除 sr.close();
File.Delete(i.FullName); //删除指定文件
}
}
catch (Exception)
{
}
}
if (isSelf == 1)
{
dir.Delete();
}
}
catch (Exception e)
{
log.WriteLogFile("DeleteDir:" + e.Message, "downloaderror");
}
}
/// <summary>
/// 拷贝目录内容
/// </summary>
/// <param name="source">源目录</param>
/// <param name="destination">目的目录</param>
/// <param name="copySubDirs">是否拷贝子目录</param>
public void CopyDirectory(DirectoryInfo source, DirectoryInfo destination, bool copySubDirs)
{
if (!destination.Exists)
{
destination.Create(); //目标目录若不存在就创建
}
FileInfo[] files = source.GetFiles();
foreach (FileInfo file in files)
{
file.CopyTo(Path.Combine(destination.FullName, file.Name), true); //复制目录中所有文件,替换相同文件
}
if (copySubDirs)
{
DirectoryInfo[] dirs = source.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
string destinationDir = Path.Combine(destination.FullName, dir.Name);
CopyDirectory(dir, new DirectoryInfo(destinationDir), copySubDirs); //复制子目录
}
}
}
/// <summary>
/// 拷贝目录内容,删除本身
/// </summary>
/// <param name="source">源目录</param>
/// <param name="destination">目的目录</param>
/// <param name="copySubDirs">是否拷贝子目录</param>
public void MoveDirectory(DirectoryInfo source, DirectoryInfo destination, bool copySubDirs)
{
if (!destination.Exists)
{
destination.Create(); //目标目录若不存在就创建
}
FileInfo[] files = source.GetFiles();
foreach (FileInfo file in files)
{
file.CopyTo(Path.Combine(destination.FullName, file.Name), true); //复制目录中所有文件,替换相同文件
file.Delete();
}
if (copySubDirs)
{
DirectoryInfo[] dirs = source.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
string destinationDir = Path.Combine(destination.FullName, dir.Name);
MoveDirectory(dir, new DirectoryInfo(destinationDir), copySubDirs); //复制子目录
}
if (source.GetDirectories().Length == 0)
source.Delete();
}
}
bool done = false;
private string outLinePath = AppDomain.CurrentDomain.BaseDirectory + "/OutlineFiles";
public bool DownLoadScreenConfig(List<ScheduleModel> ScheduleList, string configStr)
{
if (!done)
{
done = true;
log.WriteLogFile("开始下载", "exelog");
try
{
int downerrorCount = 0;
foreach (var resource in ScheduleList)
{
if (resource == null || resource.schedule == null || resource.schedule.Count == 0)
{
continue;
}
foreach (var item in resource.schedule)
{
if (item != null && item.programs != null)
{
foreach (var itemprogram in item.programs)
{
if (itemprogram.backgroundMaterialInfo != null)
{
var localFileName = string.Empty;
if (localFileName.Contains('?'))
{
localFileName = itemprogram.backgroundMaterialInfo.fileHash + itemprogram.backgroundMaterialInfo.filePath.Substring(itemprogram.backgroundMaterialInfo.filePath.LastIndexOf("."), itemprogram.backgroundMaterialInfo.filePath.LastIndexOf("?") - itemprogram.backgroundMaterialInfo.filePath.LastIndexOf("."));
}
else
{
localFileName = itemprogram.backgroundMaterialInfo.fileHash + itemprogram.backgroundMaterialInfo.filePath.Substring(itemprogram.backgroundMaterialInfo.filePath.LastIndexOf("."));
}
bool flag = DownLoadFile(itemprogram.backgroundMaterialInfo.filePath, localFileName, itemprogram.backgroundMaterialInfo.fileHash);
if (!flag)
{
downerrorCount += 1;
}
}
foreach (var itemcomponent in itemprogram.components)
{
if (itemcomponent.materials != null)
{
foreach (var material in itemcomponent.materials)
{
if (string.IsNullOrEmpty(material.fileUrl))
{
continue;
}
var localFileName = string.Empty;
if (localFileName.Contains('?'))
{
localFileName = material.fileHash + material.fileUrl.Substring(material.fileUrl.LastIndexOf("."), material.fileUrl.LastIndexOf("?") - material.fileUrl.LastIndexOf("."));
}
else
{
localFileName = material.fileHash + material.fileUrl.Substring(material.fileUrl.LastIndexOf("."));
}
bool flag = DownLoadFile(material.fileUrl, localFileName, material.fileHash);
if (!flag)
{
downerrorCount += 1;
}
}
}
}
}
}
}
}
if (downerrorCount > 0)
{
done = false;
return false;
}
else
{
bool flag = Write(outLinePath + "/temp/screenconfig.txt", configStr);
if (flag)
{
//DeleteDir(outLinePath + "/Main", 0);
DirectoryInfo di = new DirectoryInfo(outLinePath + "/Main");//正式包路径
DirectoryInfo di2 = new DirectoryInfo(outLinePath + "/temp");//更新包解压路径
MergeDirectory(di2, di, true);
done = false;
return true;
}
else
{
done = false;
return false;
}
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "OutLineLog");
done = false;
return false;
}
finally
{
done = false;
}
}
else
{
return false;
}
}
private bool DownLoadFile(string filePath, string localFileName, string hash)
{
try
{
filePath = app.FileServerPath + filePath;
filePath = filePath.Replace(@"\", @"/");
var tempFolder = outLinePath + "/temp";
var mainFolder = outLinePath + "/Main";
if (!Directory.Exists(tempFolder))
{
Directory.CreateDirectory(tempFolder);
}
if (!File.Exists(tempFolder + "/" + localFileName))
{
if (!File.Exists(mainFolder + "/" + localFileName))
{
if (File.Exists(tempFolder + "/" + localFileName))
{
return true;
}
if (File.Exists(tempFolder + "/" + localFileName + ".temp"))
File.Delete(tempFolder + "/" + localFileName + ".temp");
using (Stream fileStream = new FileStream(tempFolder + "/" + localFileName + ".temp", FileMode.OpenOrCreate))
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(filePath);
request.AddRange(fileStream.Length);
HttpWebResponse respone = (HttpWebResponse)request.GetResponse();
using (Stream netStream = respone.GetResponseStream())
{
long totalDownloadedByte = 0;
byte[] read = new byte[1024];
int realReadLen = netStream.Read(read, 0, read.Length);
while (realReadLen > 0)
{
totalDownloadedByte = realReadLen + totalDownloadedByte;
fileStream.Write(read, 0, realReadLen);
realReadLen = netStream.Read(read, 0, read.Length);
System.Windows.Forms.Application.DoEvents();
}
netStream.Close();
}
if (fileStream.Length != respone.ContentLength)
{
log.WriteLogFile("文件未下载完毕", "文件");
}
fileStream.Close();
log.WriteLogFile("下载完成" + tempFolder + "/" + localFileName, "exelog");
File.Move(tempFolder + "/" + localFileName + ".temp", tempFolder + "/" + localFileName);
var fileHash = GetMD5HashFromFile(tempFolder + "/" + localFileName);
if (fileHash != hash)
{
log.WriteLogFile("localFile " + fileHash + " getHash:" + hash, "exelog");
File.Delete(tempFolder + "/" + localFileName);
log.WriteLogFile("FileHash对比不一致,须删除重新下载" + tempFolder + "/" + localFileName, "exelog");
return false;
}
}
catch (Exception ex)
{
fileStream.Close();
log.WriteLogFile("下载失败" + tempFolder + "/" + localFileName + ex.ToString(), "exelog");
File.Delete(tempFolder + "/" + localFileName + ".temp");
log.WriteLogFile(ex.ToString(), "OutLineLog");
return false;
}
}
}
else
{
File.Copy(mainFolder + "/" + localFileName, tempFolder + "/" + localFileName);
}
}
return true;
}
catch (Exception e)
{
log.WriteLogFile(e.ToString(), "OutLineLog");
return false;
}
}
public bool Write(string path, string configStr)
{
try
{
if (!Directory.Exists(outLinePath + "/temp"))
{
Directory.CreateDirectory(outLinePath + "/temp");
}
FileStream fs = new FileStream(path, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//开始写入
sw.Write(configStr);
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 拷贝目录内容,删除本身
/// </summary>
/// <param name="source">源目录</param>
/// <param name="destination">目的目录</param>
/// <param name="copySubDirs">是否拷贝子目录</param>
public void MergeDirectory(DirectoryInfo source, DirectoryInfo destination, bool copySubDirs)
{
if (!destination.Exists)
{
destination.Create(); //目标目录若不存在就创建
}
if (!source.Exists)
{
source.Create(); //目标目录若不存在就创建
}
FileInfo[] sourceFiles = source.GetFiles();
FileInfo[] destinationFiles = destination.GetFiles();
foreach (var item in sourceFiles)
{
if (item.Extension.Contains("txt"))
{
item.CopyTo(Path.Combine(destination.FullName, item.Name), true);
}
else if ((!File.Exists(Path.Combine(destination.FullName, item.Name))))
{
CopyTo(item, Path.Combine(destination.FullName, item.Name));
//item.CopyTo(Path.Combine(destination.FullName, item.Name),true);
}
}
foreach (var item in destinationFiles)
{
if (!File.Exists(Path.Combine(source.FullName, item.Name)))
{
try
{
item.Delete();
}
catch (Exception)
{
}
}
}
DeleteDir(source.FullName, 1);
}
private void CopyTo(FileInfo tempFile, string mainFilePath)
{
try
{
string fileTempMD5 = GetMD5HashFromFile(tempFile.FullName);
tempFile.CopyTo(mainFilePath, true);
string fileMainMD5 = GetMD5HashFromFile(mainFilePath);
if (fileTempMD5 != fileMainMD5)
{
File.Delete(mainFilePath);
CopyTo(tempFile, mainFilePath);
}
else
{
File.Delete(tempFile.FullName);
}
}
catch (Exception e)
{
log.WriteLogFile(e.ToString(), "copyError");
if (File.Exists(mainFilePath))
{
File.Delete(mainFilePath);
}
CopyTo(tempFile, mainFilePath);
}
}
}
}