using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Collections;
using System.Diagnostics;
using Dare.DN.Services.EntityServices;
using Dare.DN.Components;
using Dare.DN.Components.Entities;
using Dare.DN.Components.Entities.Media;
using System.Net;
using System.IO;
using System.Web;
using Dare.Utilities.Model;
using Dare.Utilities;
using Dare.Utilities.IO;
using SevenZip;
using System.Xml;
using Dare.Utilities.Net.Ftp;
namespace DareTrayTool
{
/// <summary>
/// 网络多媒体导入导出工具
/// </summary>
public partial class MainFrm : Form
{
#region 初始化变量
UriBuilder uribuilder = null;
Dare.DN.Services.Application app;
Dare.DN.Services.EntityServices.TerminalGroupInfoService groupService;
Dare.DN.Services.EntityServices.MediaInfoService mediaService;
Dare.DN.Services.EntityServices.MediaFolderInfoService folderService;
Dare.DN.Services.EntityServices.PlaybillScheduleService scheduleService;
//--------------------计划单导出----------------------//
private const bool USE_FILE_ENCRYPT = false; //是否使用加密
private const bool CHANGE_PLAY_FILE_NAME = true; //是否改变文件名和路径
private bool isAbort = false;//是否终止导出计划单任务
//--------------------节目单导出----------------------//
private string tabName = string.Empty;
private string desPath = string.Empty;
private string pmTolProcess = string.Empty;
private string exTolProcess = string.Empty;
//-------------------------节目单导入--------------------//
OpenFileDialog ofd = null;
#endregion

#region 初始化方法
private void IntPublic()
{
app = Dare.DN.Services.Application.Instance;
groupService = app.GetDbService<TerminalGroupInfoService>();
mediaService = app.GetDbService<MediaInfoService>();
folderService = app.GetDbService<MediaFolderInfoService>();
scheduleService = app.GetDbService<PlaybillScheduleService>();

uribuilder = new UriBuilder();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Path.Combine(Application.StartupPath, "sysfig.xml"));
XmlNode xn = null;
xn = xmlDoc.SelectSingleNode("sys/host");
uribuilder.Host = DES.Decode(xn.InnerText.Trim(), "da@^@re");
xn = xmlDoc.SelectSingleNode("sys/user");
uribuilder.UserName = DES.Decode(xn.InnerText.Trim(), "da@^@re");
xn = xmlDoc.SelectSingleNode("sys/pwd");
uribuilder.Password = DES.Decode(xn.InnerText.Trim(), "da@^@re");
}
#endregion

#region 终端组与计划单UI绑定
/// <summary>
/// 计划单终端数绑定
/// </summary>
private void PlayTrViewInt()
{
this.PlayTrView.Nodes.Clear();
this.PlayTrView.ImageList = this.imageList1;
this.PlayTrView.ImageIndex = 0;
this.PlayTrView.SelectedImageIndex = 0;
TerminalGroupDataInit();
//展开父节点
this.PlayTrView.Nodes[0].Expand();
//默认选中父节点
//this.PlayTrView.SelectedNode = this.TrView.Nodes[0];
this.PlayTrView.Select();

//初始化节目单列表排序
this.lvPlayFile.ListViewItemSorter = new ListViewSort();
}
/// <summary>
/// 终端关联计划单列表绑定
/// </summary>
private void TerminalGroupDataInit()
{
List<TerminalGroupInfo> groups;
if (AppContext.Current.CurrentUser.HasPrivilegeOf(Dare.DN.Components.Entities.PrivilegeType.AllPrivileges))
{
groups = groupService.GetAll();
}
else
{
groups = groupService.GetAllByUserId(true, true, AppContext.Current.CurrentUser.Id);
}

TreeNode terminalroot = new TreeNode("所有节目终端");
PlayTrView.Nodes.Add(terminalroot);

bool top = true;
foreach (TerminalGroupInfo group in groups)
{
if (group.ParentId == null)
{
break;
}
top = false;
}

if (top == false)
{
foreach (TerminalGroupInfo group in groups)
{
bool b = false;
foreach (TerminalGroupInfo sgroup in groups)
{
if (sgroup.Id == group.ParentId)
{
b = true;
break;
}
}
if (b == false)group.ParentId = null;
}
}
TerminalGroupTreeDataBind(terminalroot.Nodes, null, groups);
}
private void TerminalGroupTreeDataBind(TreeNodeCollection nodes, int? parentId, List<TerminalGroupInfo> groups)
{
foreach (TerminalGroupInfo group in groups)
{
if (group.ParentId == parentId)
{
TreeNode tn = new TreeNode();
tn.Text = group.Name;
tn.Tag = group.Id;
nodes.Add(tn);
if (group.HasChildren != false)
{
TerminalGroupTreeDataBind(tn.Nodes, group.Id, groups);
}
}
}
}
private void TemTrView_AfterSelect(object sender, TreeViewEventArgs e)
{
if (e.Node.Tag != null)
{
int terminalId=0;
int.TryParse(e.Node.Tag.ToString(), out terminalId);
ScheduleDataInit(terminalId);
}
}
private void ScheduleDataInit(int?groupId)
{
List<PlaybillScheduleInfo> scheduleList=null;
int totalCount = 0;
if (groupId == null && !AppContext.Current.CurrentUser.HasPrivilegeOf(PrivilegeType.AllPrivileges))
{
scheduleList = scheduleService.Search(null, AppContext.Current.CurrentUser.Id, true, false, null, null, -1, -1, out totalCount);
}
else
{
scheduleList = scheduleService.Search(groupId, null, true, false, null, null, -1, -1, out totalCount);
}

lvPlayFile.Items.Clear();
lvPlayFile.View = View.Details;
lvPlayFile.GridLines = true;
lvPlayFile.FullRowSelect = true;
lvPlayFile.CheckBoxes = true;
lvPlayFile.ShowItemToolTips = true;

if (scheduleList.Count!=0)
{
LoadingFrm.StartLoading(this, "正在加载播放列表...");
foreach (PlaybillScheduleInfo schedule in scheduleList)
{
ListViewItem li = new ListViewItem();
li.Tag = schedule.Id;
li.SubItems[0].Text = schedule.Name;
li.SubItems.Add(new FileSizeData(GetPlayContentLength(schedule.Playbills)).ToString());
li.SubItems.Add(FormatPlayType(schedule.PriorityIndex));
li.SubItems.Add(schedule.ValidDate.ToString());
li.SubItems.Add(schedule.ExpiredDate.ToString());
li.SubItems.Add(FormatPlayState((int)schedule.AuditState));
li.SubItems.Add(string.IsNullOrEmpty(schedule.CreatorUserName) ? "匿名" : schedule.CreatorUserName);
li.SubItems.Add(schedule.CreateDate.Value.ToString("yyyy-MM-dd HH:MM"));
//li.SubItems.Add(schedule.CreateDate.Value.ToString("y-M-d H:M"));
lvPlayFile.Items.Add(li);
}

LoadingFrm.CloseLoading();
}
}
/// <summary>
/// 节目容量
/// </summary>
/// <param name="playId"></param>
/// <returns></returns>
private long GetPlayContentLength(List<PlaybillInfo> playbills)
{
long plContentLength = 0;
foreach (PlaybillInfo playbill in playbills)
{
foreach (TemplateArea area in playbill.Program.Areas)
{
foreach (TemplateAreaPlayList playlist in area.PlayLists)
{
foreach (MediaInfo media in playlist)
{
MediaInfo md = mediaService.Get(media.Id);
plContentLength += md.ContentLength;
}
}
}
}
return plContentLength;
}
private string FormatPlayType(int playtype)
{
string play = string.Empty;
switch (playtype)
{
case 1:
play = "常规播放";
break;
case 128:
play = "紧急插播";
break;
case 0:
play = "默认垫片";
break;
default:
break;
}
return play;
}

private string FormatPlayState(int state)
{
string lvText = "审核";
switch (state)
{
case 0:
lvText = "待" + lvText;
break;
case 1:
lvText = lvText + "通过";
break;
case 2:
lvText = lvText + "驳回";
break;
default:
break;
}
return lvText;
}

private void ckbxAll_CheckStateChanged(object sender, EventArgs e)
{
if (this.lvPlayFile.Items.Count > 0)
{
foreach (ListViewItem lv in this.lvPlayFile.Items)
{
lv.Checked = (sender as CheckBox).Checked;
}
}
}

private void lvPlayFile_ItemCheck(object sender, ItemCheckEventArgs e)
{
//if ((e.CurrentValue == CheckState.Checked))
//{
// this.ckbxAll.Checked = false;
//}
}
#endregion

#region 计划单处理
private bool DownPlayFile(string rootPath, MediaFileInfo mediaFile)
{
string srcPath = string.Empty;
long fileLength = 0;
string saveToPath = string.Empty;
string localPath = string.Empty;
bool resavel=false;

srcPath = mediaFile.SourcePath;
fileLength = mediaFile.Length;

if (CHANGE_PLAY_FILE_NAME)
{
localPath = Path.Combine(rootPath, "resource");
mediaFile.Name = Dare.Utilities.IO.StreamHash.ComputeMD5(Encoding.Default.GetBytes(mediaFile.SourcePath)).ToString("N") + Path.GetExtension(mediaFile.Name).ToLower();
mediaFile.Path = "resource";
}
else
{
localPath = Path.Combine(rootPath, mediaFile.Path);
}

if (!Directory.Exists(localPath))
Directory.CreateDirectory(localPath);

saveToPath = Path.Combine(localPath, mediaFile.Name);
if (File.Exists(saveToPath))
{
FileInfo file = new FileInfo(saveToPath);
if (file.Length != mediaFile.Length || mediaFile.Length != 0)
{
File.Delete(saveToPath);
}
}
else
{
resavel=DownloadFile(srcPath, saveToPath, fileLength, plPBar, lblplPercent, lblplTolProcess, lblplCurrentFile);
}
return resavel;
}
private void ExportPlaybill(int[]arrPlay, string savePath)
{
//创建目录
DirectoryInfo exportRootDir = new DirectoryInfo(savePath);
if (!exportRootDir.Exists)
exportRootDir.Create();

FileSystemInfo[] filesysteminfos = exportRootDir.GetFileSystemInfos();
if (filesysteminfos.Length > 0)
{
Program.ThreadSafe(this, delegate
{
if (MessageBox.Show(this, "计划单导出目录\"" + exportRootDir.FullName + "\"下已存在内容文件,是否立即清理?", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
foreach (FileSystemInfo dirinfo in filesysteminfos)
{
if (dirinfo is DirectoryInfo)
{
(dirinfo as DirectoryInfo).Delete(true);
}
else if (dirinfo is FileInfo)
{
(dirinfo as FileInfo).Delete();
}
}
}
});
}

Dictionary<int, MediaFileInfo> readyDownloadFiles = new Dictionary<int, MediaFileInfo>();
Dictionary<string, MediaFileInfo> readyDownloadFontFiles = new Dictionary<string, MediaFileInfo>();
Dictionary<int, ProgramMediaInfo> programs = new Dictionary<int, ProgramMediaInfo>();

//获得计划单列表
PlaybillScheduleList playlist = GetScheduleInfo(arrPlay, PlaybillScheduleType.Normal);
PlaybillScheduleList emergencyPlaylist = GetScheduleInfo(arrPlay, PlaybillScheduleType.Emergency);

//处理计划单列表
ProcessScheduleList(playlist, programs, readyDownloadFiles, readyDownloadFontFiles);
ProcessScheduleList(emergencyPlaylist, programs, readyDownloadFiles, readyDownloadFontFiles);

//下载节目文件
int downloadCount = 0;
int totalDownloadCount = readyDownloadFiles.Count + readyDownloadFontFiles.Count;
try
{
Program.ThreadSafe(lblplTolProcess, delegate
{
lblplTolProcess.Text = "(" + downloadCount + "/" + totalDownloadCount + ")";
});

foreach (MediaFileInfo file in readyDownloadFiles.Values)
{
string fname = Path.GetFileNameWithoutExtension(file.Name);
string fextion = Path.GetExtension(file.Name);
downloadCount++;
Program.ThreadSafe(lblplCurrentFile, delegate
{
lblplCurrentFile.Text = fname.Length > 15 ? fname.Substring(0, 15) + "..." + fextion + "(" + new FileSizeData(file.Length) + ")" : file.Name + "(" + new FileSizeData(file.Length) + ")";
});
Program.ThreadSafe(lblplTolProcess, delegate
{
lblplTolProcess.Text = "(" + downloadCount + "/" + totalDownloadCount + ")";
});

//下载播放文件
if (!DownPlayFile(savePath, file))
continue;
}

foreach (MediaFileInfo file in readyDownloadFontFiles.Values)
{
string tname = Path.GetFileNameWithoutExtension(file.Name);
string textion = Path.GetExtension(file.Name);
downloadCount++;
Program.ThreadSafe(lblplCurrentFile, delegate
{
lblplCurrentFile.Text = tname.Length > 15 ? tname.Substring(0, 15) + "..." + textion + "(" + new FileSizeData(file.Length) + ")" : file.Name + "(" + new FileSizeData(file.Length) + ")";
});
Program.ThreadSafe(lblplTolProcess, delegate
{
lblplTolProcess.Text = "(" + downloadCount + "/" + totalDownloadCount + ")";
});
//下载字体文件
if (!DownPlayFile(savePath, file))
continue;
}

//创建节目单计划单导出目录
string plPath = Path.Combine(exportRootDir.FullName, "playlist");
if (!Directory.Exists(plPath))
{
Directory.CreateDirectory(plPath);
}
string tmpPath = Path.Combine(exportRootDir.FullName, "template");
if (!Directory.Exists(tmpPath))
{
Directory.CreateDirectory(tmpPath);
}

//写入模板文件
byte[] xmlData;
int CorpId = 0;
DareMD5 md5 = new DareMD5(DareMD5.DEFAULT_SPECIAL_CODE + (uint)CorpId);
foreach (ProgramMediaInfo program in programs.Values)
{
xmlData = Encoding.UTF8.GetBytes(program.SupportTerminalXmlSerializerInstance.ToXml(false, false));
File.WriteAllBytes(Path.Combine(tmpPath, program.Id + ".xml"), xmlData);
program.Checksum = md5.ComputeGuid(xmlData).ToString("N");
}

//写入计划单文件
File.WriteAllText(Path.Combine(plPath, "playlist.xml"), playlist.SupportTerminalXmlSerializerInstance.ToXml(false, false), Encoding.UTF8);
File.WriteAllText(Path.Combine(plPath, "playliste.xml"), emergencyPlaylist.SupportTerminalXmlSerializerInstance.ToXml(false, false), Encoding.UTF8);

//删除之前的导出反馈文件(终端会在根目录存放export.ok文件)
string exportOkFile = Path.Combine(exportRootDir.Root.FullName, "export.ok");
if (File.Exists(exportOkFile))
{
File.Delete(exportOkFile);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

private PlaybillScheduleList GetScheduleInfo(int[] arrPlay, PlaybillScheduleType scheduleType)
{
PlaybillScheduleList scheduleList = scheduleService.GetScheduleList(scheduleType, arrPlay);
return scheduleList;
}

private void ProcessScheduleList(PlaybillScheduleList scheduleList, Dictionary<int, ProgramMediaInfo> programs, Dictionary<int, MediaFileInfo> readyDownloadFiles, Dictionary<string, MediaFileInfo> readyDownloadFontFiles)
{
foreach (PlaybillScheduleInfo schedule in scheduleList)
{
foreach (PlaybillInfo playbill in schedule.Playbills)
{
if (programs.ContainsKey(playbill.ProgramId))
{
playbill.Program = programs[playbill.ProgramId];
}
else
{
if (playbill.Program == null) playbill.Program = mediaService.Get(playbill.ProgramId) as ProgramMediaInfo;
programs.Add(playbill.ProgramId, playbill.Program);
}

foreach (TemplateArea area in playbill.Program.Areas)
{
if (area is ClockArea)
{
ClockArea clockArea = area as ClockArea;
string fontFile = clockArea.FontFile;
if (!String.IsNullOrEmpty(fontFile))
{
if (!readyDownloadFontFiles.ContainsKey(fontFile))
{
MediaFileInfo fontMediaFile = app.ResService.GetFileInfo(fontFile);
fontMediaFile.Id = -readyDownloadFontFiles.Count - 1;
fontMediaFile.Type = MediaFileType.Other;
fontMediaFile.Format = MediaFileFormat.Unkown;
readyDownloadFontFiles.Add(fontFile, fontMediaFile);
}
clockArea.FontFileInfo = readyDownloadFontFiles[fontFile];
}
}
else
{
foreach (TemplateAreaPlayList areaplaylist in area.PlayLists)
{
foreach (MediaInfo media in areaplaylist)
{
if (media is ResourceMediaInfo)
{
ResourceMediaInfo rectrivedMedia = mediaService.Get(media.Id) as ResourceMediaInfo;
ResourceMediaInfo realMedia = media as ResourceMediaInfo;
realMedia.Resources.Clear();
foreach (IMediaResSource res in rectrivedMedia.Resources)
{
if (res is MediaFileInfo)
{
MediaFileInfo file = res as MediaFileInfo;
if (!readyDownloadFiles.ContainsKey(file.Id))
{
readyDownloadFiles.Add(file.Id, file);
}
realMedia.Resources.Add(readyDownloadFiles[file.Id]);
}
else
{
realMedia.Resources.Add(res);
}
}

if (media is TextMediaInfo)
{
TextMediaInfo textMedia = media as TextMediaInfo;
string fontFile = textMedia.FontFile;
if (!String.IsNullOrEmpty(fontFile))
{
if (!readyDownloadFontFiles.ContainsKey(fontFile))
{
MediaFileInfo fontMediaFile = app.ResService.GetFileInfo(fontFile);
fontMediaFile.Id = -readyDownloadFontFiles.Count - 1;
fontMediaFile.Type = MediaFileType.Other;
fontMediaFile.Format = MediaFileFormat.Unkown;
readyDownloadFontFiles.Add(fontFile, fontMediaFile);
}
textMedia.FontFileInfo = readyDownloadFontFiles[fontFile];
}
}
}
}
}
}
}
}
}
}
#endregion

#region 计划单导出
/// <summary>
/// 计划单导出
/// </summary>
private void btnPlayExport_Click(object sender, EventArgs e)
{
string savePath = string.Empty;
long pltolDownLength = 0;
int pCount = this.lvPlayFile.CheckedItems.Count;
if (pCount == 0)
{
MessageBox.Show(this, "请选择要导出的计划单!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}

FolderBrowserDialog pDialog = new FolderBrowserDialog();
if (pDialog.ShowDialog(this) == DialogResult.OK)
{
savePath = pDialog.SelectedPath;

DriveInfo drive = new DriveInfo(savePath);
int[] arrPlay = new int[pCount];
for (int i = 0; i < pCount; i++)
{
if (this.lvPlayFile.CheckedItems[i].Checked)
{
arrPlay[i] = (int)this.lvPlayFile.CheckedItems[i].Tag;
pltolDownLength += FileSizeData.Parse(this.lvPlayFile.CheckedItems[i].SubItems[1].Text);
}
}

if (drive.AvailableFreeSpace < pltolDownLength + 1024 * 1024)
{
MessageBox.Show(this, "对不起,当前磁盘空间不足,请清理出至少 " + new FileSizeData(pltolDownLength + 1024 * 1024 - drive.AvailableFreeSpace) + " 磁盘空间!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}

this.btnPlayExport.Enabled = false;
this.btnplCancel.Enabled = true;
Thread plThread = new Thread(() =>
{
try
{
isAbort = false;
ExportPlaybill(arrPlay, savePath);
}
catch (Exception ex)
{
Program.ThreadSafe(this, delegate
{
MessageBox.Show(this, "计划单导出失败!原因:" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
});
}
finally
{
Program.ThreadSafe(btnPlayExport, delegate
{
this.btnPlayExport.Enabled = true;
});
if (!isAbort)
{
Program.ThreadSafe(btnplCancel, delegate
{
this.btnplCancel.Enabled = false;
});
Program.ThreadSafe(this, delegate
{
MessageBox.Show(this, "计划单导出完毕!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
});
}
}
});
plThread.IsBackground = true;
plThread.Start();
}
}
private void btnplCancel_Click(object sender, EventArgs e)
{
if (MessageBox.Show("确定要取消计划单导出任务吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
isAbort = true;
this.btnplCancel.Enabled = false;
}
}
private void btnRefresh_Click(object sender, EventArgs e)
{
PlayTrViewInt();
}
#endregion

#region 列表排序
private class ListViewSort : IComparer
{
/// <summary>
/// 指定按照哪个列排序
/// </summary>
private int columntosort;
//// <summary>
/// 指定排序的方式
/// </summary>
private SortOrder sortorder;
//// <summary>
/// 声明CaseInsensitiveComparer类对象,
/// </summary>
private CaseInsensitiveComparer objectcompare;

/// <summary>
/// 获取或设置按照哪一列排序.
/// </summary>
public int SortColumn
{
set
{
columntosort = value;
}
get
{
return columntosort;
}
}
/// <summary>
/// 获取或设置排序方式.
/// </summary>
public SortOrder Order
{
set
{
sortorder = value;
}
get
{
return sortorder;
}
}
/// <summary>
/// 构造函数
/// </summary>
public ListViewSort()
{
// 默认按第一列排序
columntosort = 0;
// 排序方式为不排序
sortorder = SortOrder.None;
// 初始化CaseInsensitiveComparer类对象
objectcompare = new CaseInsensitiveComparer();
}
/// <summary>
/// 重写IComparer接口.
/// </summary>
/// <param name="x">要比较的第一个对象</param>
/// <param name="y">要比较的第二个对象</param>
/// <returns>比较的结果.如果相等返回0,如果x大于y返回1,如果x小于y返回-1</returns>
public int Compare(object x, object y)
{
int compareResult;
ListViewItem listviewX, listviewY;

// 将比较对象转换为ListViewItem对象
listviewX = (ListViewItem)x;
listviewY = (ListViewItem)y;

// 比较
compareResult = objectcompare.Compare(listviewX.SubItems[columntosort].Text, listviewY.SubItems[columntosort].Text);

// 根据上面的比较结果返回正确的比较结果
switch (sortorder)
{
case SortOrder.Ascending:
// 因为是正序排序,所以直接返回结果
return compareResult;
case SortOrder.Descending:
// 如果是反序排序,所以要取负值再返回
return (-compareResult);
default:
// 如果相等返回0
return 0;
}
}
}

private void lvPlayFile_ColumnClick(object sender, ColumnClickEventArgs e)
{
ListView lv = sender as ListView;
ListViewSort ls = lv.ListViewItemSorter as ListViewSort;
// 检查点击的列是不是现在的排序列.
if (e.Column == ls.SortColumn)
{
// 重新设置此列的排序方法.
if (ls.Order == SortOrder.Ascending)
{
ls.Order = SortOrder.Descending;
}
else
{
ls.Order = SortOrder.Ascending;
}
}
else
{
// 设置排序列,默认为正向排序
ls.SortColumn = e.Column;
ls.Order = SortOrder.Ascending;
}
// 用新的排序方法对ListView排序
((ListView)sender).Sort();
}

private void lvMediaFile_ColumnClick(object sender, ColumnClickEventArgs e)
{
ListView lv = sender as ListView;
ListViewSort ls = lv.ListViewItemSorter as ListViewSort;
// 检查点击的列是不是现在的排序列.
if (e.Column == ls.SortColumn)
{
// 重新设置此列的排序方法.
if (ls.Order == SortOrder.Ascending)
{
ls.Order = SortOrder.Descending;
}
else
{
ls.Order = SortOrder.Ascending;
}
}
else
{
// 设置排序列,默认为正向排序
ls.SortColumn = e.Column;
ls.Order = SortOrder.Ascending;
}
// 用新的排序方法对ListView排序
((ListView)sender).Sort();
}
#endregion

#region FTP常规方法
/// <summary>
/// FTP下载方法
/// </summary>
/// <param name="remote"></param>
/// <param name="local"></param>
/// <param name="length"></param>
/// <param name="ub"></param>
/// <returns></returns>
private bool DownloadFile(string remote, string local, long length, ProgressBar pbar, Label lblpercent, Label lbltolprocess, Label lblcurrentfile)
{
bool result = false;
int downlength = 0;//当前下载大小

//-------------------建立连接----------------//
string url = string.Empty;
url = (uribuilder.Host.ToLower().StartsWith("ftp://") ? uribuilder.Host : "ftp://" + uribuilder.Host) + ((uribuilder.Host.ToLower().StartsWith("ftp://") ? uribuilder.Host : "ftp://" + uribuilder.Host).EndsWith("/") ? "" : "/") + remote;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.Credentials = new NetworkCredential(uribuilder.UserName, uribuilder.Password);
request.Proxy = null;
//命令执行完毕之后关闭连接
request.KeepAlive = false;
request.UseBinary = true;
request.UsePassive = true;
request.EnableSsl = false;
request.Method = WebRequestMethods.Ftp.DownloadFile;
//-------------------建立连接----------------//

//创建或打开本地文件
using (FileStream fileStream = new FileStream(local, FileMode.OpenOrCreate))
{
//request.ContentOffset = fileStream.Length;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Stream stream = response.GetResponseStream();
//fileStream.Position = fileStream.Length;
int bufferLength = 256 * 1024;//256K
byte[] buffer = new byte[bufferLength];
int readCount = 0;
while ((readCount = stream.Read(buffer, 0, bufferLength) )> 0)
{
//是否终止任务
if (isAbort)
{
fileStream.Dispose();
Program.ThreadSafe(pbar, delegate
{
pbar.Value = 0;
});
Program.ThreadSafe(lblpercent, delegate
{
lblpercent.Text = "[0%]";
});
Program.ThreadSafe(lbltolprocess, delegate
{
lbltolprocess.Text = "(0/0)";
});
Program.ThreadSafe(lblcurrentfile, delegate
{
lblcurrentfile.Text = "------";
});
break;
}
downlength += readCount;//已经下载大小
fileStream.Write(buffer, 0, readCount);
int tolpercent = (int)((float)(downlength / (float)length * 100));
Program.ThreadSafe(pbar, delegate
{
pbar.Value = tolpercent;
});
Program.ThreadSafe(lblpercent, delegate
{
lblpercent.Text = "[" + tolpercent.ToString() + "%]";
});
//readCount = stream.Read(buffer, 0, bufferLength);
}
response.GetResponseStream().Close();
}
result = true;
}
return result;
}
private bool DownloadFile(string remote, string local)
{
//-------------------建立连接----------------//
bool result = false;
string url = string.Empty;
url = (uribuilder.Host.ToLower().StartsWith("ftp://") ? uribuilder.Host : "ftp://" + uribuilder.Host) + ((uribuilder.Host.ToLower().StartsWith("ftp://") ? uribuilder.Host : "ftp://" + uribuilder.Host).EndsWith("/") ? "" : "/") + remote;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.Credentials = new NetworkCredential(uribuilder.UserName, uribuilder.Password);
request.Proxy = null;
//命令执行完毕之后关闭连接
request.KeepAlive = false;
request.UseBinary = true;
request.UsePassive = true;
request.EnableSsl = false;
request.Method = WebRequestMethods.Ftp.DownloadFile;
//-------------------建立连接----------------//

//创建或打开本地文件
using (FileStream fileStream = new FileStream(local, FileMode.OpenOrCreate))
{
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Stream stream = response.GetResponseStream();
int bufferLength = 256 * 1024;//256K
byte[] buffer = new byte[bufferLength];
int readCount = 0;
while ((readCount = stream.Read(buffer, 0, buffer.Length)) > 0)
{
//是否终止任务
if (isAbort)
{
fileStream.Dispose();
Program.ThreadSafe(pdPBar, delegate
{
pdPBar.Value = 0;
});
Program.ThreadSafe(lblpdPercent, delegate
{
lblpdPercent.Text = "[0%]";
});
Program.ThreadSafe(lblpdTolProcess, delegate
{
lblpdTolProcess.Text = "(0/0)";
});
Program.ThreadSafe(lblpdCurrenFile, delegate
{
lblpdCurrenFile.Text = "------";
});
break;
}
fileStream.Write(buffer, 0, readCount);
}
response.GetResponseStream().Close();
}
result = true;
}
return result;
}
//private bool DownloadFile(string remote, string local)
//{
// FtpClient ftpClient = new FtpClient(uribuilder);
// return ftpClient.DownloadFile(remote, local);
//}
//private byte[] DownloadData(string remote)
//{
// FtpClient ftpClient = new FtpClient(uribuilder);
// return ftpClient.DownloadData(remote);
//}
private bool? IsDirExists(string dir)
{
FtpClient ftpClient = new FtpClient(uribuilder);
return ftpClient.DirExists(dir);
}
private bool? IsFileExists(string fName)
{
FtpClient ftpClient = new FtpClient(uribuilder);
return ftpClient.FileExists(fName);
}
private bool CreateDir(string dir)
{
FtpClient ftpClient = new FtpClient(uribuilder);
return ftpClient.MakeDir(dir);
}

private bool UploadFile(string remote, string local)
{
bool result = false;
int uploadlength = 0;//当前上载大小

if (File.Exists(local))
{
FileInfo fileInfo = new FileInfo(local);
long length = fileInfo.Length;
//-------------------建立连接----------------//
string url = string.Empty;
url = (uribuilder.Host.ToLower().StartsWith("ftp://") ? uribuilder.Host : "ftp://" + uribuilder.Host) + ((uribuilder.Host.ToLower().StartsWith("ftp://") ? uribuilder.Host : "ftp://" + uribuilder.Host).EndsWith("/") ? "" : "/") + remote;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.Credentials = new NetworkCredential(uribuilder.UserName, uribuilder.Password);
request.Proxy = null;
//命令执行完毕之后关闭连接
request.KeepAlive = false;
request.UseBinary = true;
request.UsePassive = true;
request.EnableSsl = false;
request.ContentLength = length;
request.Method = WebRequestMethods.Ftp.UploadFile;
//-------------------建立连接----------------//

//创建或打开本地文件
using (FileStream fileStream = fileInfo.OpenRead())
{
using (Stream stream = request.GetRequestStream())
{
int bufferLength = 256 * 1024;//256K
byte[] buffer = new byte[bufferLength];
int readCount = 0;
while ((readCount=stream.Read(buffer, 0, bufferLength))> 0)
{
uploadlength += readCount;//已经上载大小
stream.Write(buffer, 0, readCount);
int tolpercent = (int)((float)(uploadlength / (float)length * 100));
}
}
result = true;
}
}
else
{
result = false;
}
return result;
}
private bool UploadFile(string remote, string local, ProgressBar pbar, Label lblpercent, Label lbltolprocess, Label lblcurrentfile)
{
bool result = false;
int upLength = 0;//当前上载大小

if (File.Exists(local))
{
FileInfo fileInfo = new FileInfo(local);
if (!fileInfo.Exists) throw new FileNotFoundException("待上传的本地文件不存在!", local);
long length = fileInfo.Length;
//-------------------建立连接----------------//
string url = string.Empty;
url = (uribuilder.Host.ToLower().StartsWith("ftp://") ? uribuilder.Host : "ftp://" + uribuilder.Host) + ((uribuilder.Host.ToLower().StartsWith("ftp://") ? uribuilder.Host : "ftp://" + uribuilder.Host).EndsWith("/") ? "" : "/") + remote;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.Credentials = new NetworkCredential(uribuilder.UserName, uribuilder.Password);
request.Proxy = null;
//命令执行完毕之后关闭连接
request.KeepAlive = false;
request.UseBinary = true;
request.UsePassive = true;
request.EnableSsl = false;
request.ContentLength = length;
request.Method = WebRequestMethods.Ftp.UploadFile;
//-------------------建立连接----------------//

//创建或打开本地文件
using (Stream stream = request.GetRequestStream())
{
int bufferLength = 256 * 1024;//256K
byte[] buffer = new byte[bufferLength];
int readCount = 0;
using (FileStream fileStream = fileInfo.OpenRead())
{
while ((readCount = fileStream.Read(buffer, 0, bufferLength)) > 0)
{
upLength += readCount;//已经上载大小
stream.Write(buffer, 0, readCount);
int tolpercent = (int)((float)(upLength / (float)length * 100));
Program.ThreadSafe(pbar, delegate
{
pbar.Value = tolpercent;
});
Program.ThreadSafe(lblpercent, delegate
{
lblpercent.Text = "[" + tolpercent.ToString() + "%]";
});
}
}
result = true;
}
}
else
{
result = false;
}
return result;
}
#endregion

#region 用户组与节目单UI绑定
/// <summary>
/// 节目用户组树绑定
/// </summary>
private void MediaTrViewInt()
{
this.MediaTrView.Nodes.Clear();
this.MediaTrView.ImageList = this.imageList1;
this.MediaTrView.ImageIndex = 1;
this.MediaTrView.SelectedImageIndex = 1;

List<MediaFolderInfo> programGroups;
if (AppContext.Current.CurrentUser.HasPrivilegeOf(Dare.DN.Components.Entities.PrivilegeType.AllPrivileges))
{
programGroups = folderService.GetUserRootFolder(-1,true);
}
else
{
programGroups = folderService.GetUserRootFolder(AppContext.Current.CurrentUser.Id,false);
}

if (programGroups != null)
{
TreeNode programroot = new TreeNode("所有节目用户");
MediaTrView.Nodes.Add(programroot);
ProgramGroupTreeDataBind(programroot.Nodes, programGroups);
}

//展开父节点
this.MediaTrView.Nodes[0].Expand();
//默认选中父节点
//this.MediaTrView.SelectedNode = this.TrView.Nodes[0];
this.MediaTrView.Select();

//初始化列表排序
this.lvMediaFile.ListViewItemSorter = new ListViewSort();
}

private void ProgramGroupTreeDataBind(TreeNodeCollection nodes,List<MediaFolderInfo> groups)
{
foreach (MediaFolderInfo group in groups)
{
TreeNode tn = new TreeNode();
tn.Text = group.Name;
tn.Tag = group.Id;
nodes.Add(tn);
}
}

private void MediaTrView_AfterSelect(object sender, TreeViewEventArgs e)
{
this.mediackbxAll.Checked = false;
if (e.Node.Tag != null)
{
int pmFolderId = (int)e.Node.Tag;
ProgrambillDataInit(pmFolderId);
}
}

/// <summary>
/// 用户关联节目列表绑定
/// </summary>
private void ProgrambillDataInit(int folderId)
{
List<MediaInfo> mediaList = null;
//int totalCount = 0;
//mediaList = mediaService.SearchByType(folderId > 0 ? new int[] { folderId } : null, false, null, null, MediaAuditState.Passed, null, true, -1, -1, out totalCount, MediaType.Program);
mediaList = mediaService.GetByFolderId(folderId, MediaType.Program);

lvMediaFile.Items.Clear();
lvMediaFile.View = View.Details;
lvMediaFile.GridLines = true;
lvMediaFile.FullRowSelect = true;
lvMediaFile.CheckBoxes = true;
lvMediaFile.ShowItemToolTips = true;
if (mediaList.Count != 0)
{
LoadingFrm.StartLoading(this, "正在加载节目列表...");
foreach (MediaInfo md in mediaList)
{
ListViewItem li = new ListViewItem();
li.Tag = md.Id;
li.SubItems[0].Text = md.Name;
li.SubItems.Add(new FileSizeData(GetPgmContentLength(md)).ToString());
li.SubItems.Add(md.Width.Value.ToString());
li.SubItems.Add(md.Height.Value.ToString());
li.SubItems.Add(md.RefCount.Value.ToString());
li.SubItems.Add(md.Revision.ToString());
//li.SubItems.Add(md.CreateDate.Value.ToString("y-M-d H:M"));
li.SubItems.Add(md.CreateDate.Value.ToString("yyyy-MM-dd HH:MM"));
lvMediaFile.Items.Add(li);
}
LoadingFrm.CloseLoading();
}
}
/// <summary>
/// 节目单容量
/// </summary>
/// <param name="playId"></param>
/// <returns></returns>
private long GetPgmContentLength(MediaInfo mediaInfo)
{
long pmContentLength = 0;
ProgramMediaInfo program = null;

program = mediaInfo as ProgramMediaInfo;
foreach (TemplateArea area in program.Areas)
{
foreach (TemplateAreaPlayList playlist in area.PlayLists)
{
foreach (MediaInfo media in playlist)
{
MediaInfo md = mediaService.Get(media.Id);
pmContentLength += md.ContentLength;
}
}
}
return pmContentLength;
}
private void mediackbxAll_CheckStateChanged(object sender, EventArgs e)
{
foreach (ListViewItem lv in this.lvMediaFile.Items)
{
lv.Checked = (sender as CheckBox).Checked;
}
}
private void lvMediaFile_ItemChecked(object sender, ItemCheckedEventArgs e)
{
//foreach (ListViewItem lv in this.lvMediaFile.Items)
//{
// if (!lv.Checked)
// {
// mediackbxAll.Checked = false;
// break;
// }
//}
}
#endregion

#region 节目单导出
private int GetMdCount(List<MediaInfo> mediaList)
{
int i = 0;
foreach (MediaInfo md in mediaList)
{
switch(md.Type)
{
case MediaType.Rss://.rss
case MediaType.NetworkImage://.url
case MediaType.BroadcastVideo://.bdv
case MediaType.DVBChannel://.dvb
case MediaType.NetworkFinanceImage://.fimg.url
case MediaType.NetworkFinanceText://.ftxt.url
case MediaType.WebSnapImage://.web.url
case MediaType.Template:
case MediaType.Program:
i++;
break;
default:
break;
}
}
return i;
}
private void btnPdRefresh_Click(object sender, EventArgs e)
{
MediaTrViewInt();
}

/// <summary>
/// 节目单导出
/// </summary>
private void btnpmExport_Click(object sender, EventArgs e)
{
string outPath = string.Empty;
int mCount = 0;
long pmtolDownLength = 0;
string dllPath = string.Empty;

SevenZipCompressor zip7 =new SevenZipCompressor();
dllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "7z.dll");
SevenZipCompressor.SetLibraryPath(dllPath);
zip7.ArchiveFormat = OutArchiveFormat.SevenZip;
zip7.CompressionLevel = CompressionLevel.Fast;

mCount = this.lvMediaFile.CheckedItems.Count;
if (mCount == 0)
{
MessageBox.Show(this, "请选择要导出的节目单,", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}

FolderBrowserDialog fDialog = new FolderBrowserDialog();
if (fDialog.ShowDialog(this) == DialogResult.OK)
{
outPath = fDialog.SelectedPath;
DriveInfo drive = new DriveInfo(outPath);

//节目单集合
Dictionary<int, string> dicProram = new Dictionary<int, string>();
for (int i = 0; i < mCount; i++)
{
if (this.lvMediaFile.CheckedItems[i].Checked)
{
int id = 0;
string fileName = string.Empty;
string perLength = string.Empty;

id = (int)this.lvMediaFile.CheckedItems[i].Tag;
fileName = this.lvMediaFile.CheckedItems[i].SubItems[0].Text;
perLength = this.lvMediaFile.CheckedItems[i].SubItems[1].Text;

dicProram.Add(id, fileName + " [" + perLength + "]");
pmtolDownLength += FileSizeData.Parse(perLength);
}
}

long tmpLength = pmtolDownLength * 2 + 1024 * 1024;
if (drive.AvailableFreeSpace < tmpLength)
{
MessageBox.Show(this, "对不起,当前磁盘空间不足,请清理出至少 " + new FileSizeData(tmpLength - drive.AvailableFreeSpace) + " 磁盘空间!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}

this.btnpmExport.Enabled = false;
this.btnpmCancel.Enabled = true;
LoadingFrm.StartLoading(this, "请稍等,正在导出节目...");
Thread pmThread = new Thread(() =>
{
try
{
isAbort = false;
int j = 0;
//遍历Dictionary<int, string> dicProram
foreach (KeyValuePair<int, string> mdDic in dicProram)
{
j++;
//当前处理条目
pmTolProcess = "(" + j + "/" + mCount + ")";
//当前节目
Program.ThreadSafe(lblpmCurrenFile, delegate
{
this.lblpmCurrenFile.Text = mdDic.Value;
});

string zFile = string.Empty;
zFile = mdDic.Value.Substring(0, mdDic.Value.IndexOf('[')).Trim();
//desPath = Path.Combine(outPath, mdDic.Key.ToString());
desPath = Path.Combine(outPath, zFile);
//using (FileStream outStream = new FileStream(Path.Combine(outPath, mdDic.Key + ".7z"), FileMode.Create, FileAccess.Write))
using (FileStream outStream = new FileStream(Path.Combine(outPath, zFile + ".7z"), FileMode.Create, FileAccess.Write))
{
string srcPath = string.Empty;
string fileDir = string.Empty;
string extFolder = string.Empty;
List<MediaInfo> mediaList = null;
int nCount = 0;
int k = 0;

StringBuilder sb = new StringBuilder();
sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sb.AppendLine("<medias>");

//获取节目关联媒体文件
mediaList = mediaService.GetRelationMediaLst(mdDic.Key);
if (mediaList == null) throw new Exception("节目关联媒体文件不存在!");
//获取下载媒体数量
nCount = mediaList.Count - GetMdCount(mediaList);
foreach (MediaInfo md in mediaList)
{
MediaFolderInfo folder = null;
string tmpFolder = string.Empty;
string srcFolder = string.Empty;
//是否终止任务
if (isAbort) break;
folder = folderService.Get(md.FolderId);
if (folder == null) throw new Exception(string.Format("找不到文件夹[NAME={0}],文件夹可能已被删除!", folder.Name));
if (md.Type == MediaType.Video || md.Type == MediaType.Audio || md.Type == MediaType.Image || md.Type == MediaType.Text)
{
k++;
Program.ThreadSafe(this, delegate
{
//当前处理媒体条目
this.lblpdTolProcess.Text = "(" + k + "/" + nCount + ")";
});
string fname = Path.GetFileNameWithoutExtension(md.Name);
string fextion = Path.GetExtension(md.Name);
Program.ThreadSafe(this, delegate
{
//当前媒体
lblpdCurrenFile.Text = fname.Length > 15 ? fname.Substring(0, 15) + "..." + fextion + "(" + new FileSizeData(md.FileLength) + ")" : md.Name + "(" + new FileSizeData(md.FileLength) + ")";
});

//获取主媒体文件
srcFolder = folder.PhysicalPath;
srcPath = Path.Combine(srcFolder, md.Name);
if (!Directory.Exists(Path.Combine(desPath, srcFolder)))
{
Directory.CreateDirectory(Path.Combine(desPath, srcFolder));
}
if (!DownloadFile(srcPath.Replace(@"\", "/"), Path.Combine(desPath, srcPath), md.FileLength, pdPBar, lblpdPercent, lblpdTolProcess, lblpdCurrenFile))
continue;
sb.AppendLine(string.Format(" <md mediaid=\"{0}\">", md.Id));
CreateMediaXml(md, sb);
sb.AppendLine(" </md>");
}

switch (md.Type)
{
case MediaType.Rss://.rss
case MediaType.NetworkImage://.url
case MediaType.BroadcastVideo://.bdv
case MediaType.DVBChannel://.dvb
case MediaType.NetworkFinanceImage://.fimg.url
case MediaType.NetworkFinanceText://.ftxt.url
case MediaType.WebSnapImage://.web.url
//获取文件记录
sb.AppendLine(string.Format(" <md mediaid=\"{0}\">", md.Id));
CreateMediaXml(md, sb);
sb.AppendLine(" </md>");
break;
case MediaType.Template://.tpl
case MediaType.Program://.pgm
//获取缩略图文件
srcPath = md.ThumbnailFile;
fileDir = Path.GetDirectoryName(srcPath);
extFolder = Path.Combine(desPath, fileDir);
if (!Directory.Exists(extFolder))
{
Directory.CreateDirectory(extFolder);
}
if (!DownloadFile(srcPath.Replace(@"\", "/"), Path.Combine(desPath, srcPath)))
continue;

//获取XML记录文件
sb.AppendLine(string.Format(" <md id=\"{0}\">", md.Id));
CreateMediaXml(md, sb);
sb.AppendLine(" </md>");
break;
default:
break;
}
}
sb.AppendLine("</medias>");

//是否终止任务
if (isAbort) break;

//输出节目媒体关联XML记录
//File.WriteAllText(Path.Combine(desPath, mdDic.Key + ".xml"), sb.ToString(), Encoding.UTF8);
File.WriteAllText(Path.Combine(desPath, zFile + ".xml"), sb.ToString(), Encoding.UTF8);
//------------------------------获取节目关联媒体列表---------------------------------//

//------------------------------进行节目媒体文件压缩---------------------------------//
zip7.Compressing += new EventHandler<ProgressEventArgs>(zip7_Compressing);
zip7.CompressionFinished += new EventHandler(zip7_CompressionFinished);
zip7.CompressDirectory(desPath, outStream, "Da@^@re");
//zip7.CompressDirectory(desPath, outStream);
}
}
}
catch (Exception ex)
{
Program.ThreadSafe(this, delegate
{
LoadingFrm.CloseLoading();
MessageBox.Show(this, "节目单导出失败!原因:" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
});
}
finally
{
LoadingFrm.CloseLoading();
if (!isAbort)
{
Program.ThreadSafe(btnpmCancel, delegate
{
this.btnpmCancel.Enabled = false;
});
Program.ThreadSafe(this, delegate
{
MessageBox.Show(this, "节目单导出完毕!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
});
}
else
{
Program.ThreadSafe(lblpmCurrenFile, delegate
{
this.lblpmCurrenFile.Text = "------";
});
}
Program.ThreadSafe(btnpmExport, delegate
{
this.btnpmExport.Enabled = true;
});
}
});
pmThread.IsBackground = true;
pmThread.Start();
}
}
/// <summary>
/// 节目下载取消事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnpmCancel_Click(object sender, EventArgs e)
{
if (TopMessageBox.Show("确定要取消节目单导出任务吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
isAbort = true;
this.btnpmCancel.Enabled = false;
}
}
/// <summary>
/// 创建媒体XML记录
/// </summary>
/// <param name="md"></param>
/// <param name="sb"></param>
private void CreateMediaXml(MediaInfo md, StringBuilder sb)
{
MediaFolderInfo srcFolder = folderService.Get(md.FolderId);
if (srcFolder == null) throw new Exception(md.FolderId+",目录不存在!");
sb.AppendLine(string.Format(" <physical_path>{0}</physical_path>", srcFolder.PhysicalPath));
sb.AppendLine(string.Format(" <name>{0}</name>", md.Name));
sb.AppendLine(string.Format(" <type>{0}</type>", (int)md.Type));
sb.AppendLine(string.Format(" <xml>{0}</xml>", md.Xml));
}
/// <summary>
/// 节目压缩结束事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void zip7_CompressionFinished(object sender, EventArgs e)
{
if (Directory.Exists(desPath))
{
Directory.Delete(desPath, true);
}
}
/// <summary>
/// 节目压缩进行事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void zip7_Compressing(object sender, ProgressEventArgs e)
{
Program.ThreadSafe(lblpmTolProcess, delegate
{
this.lblpmTolProcess.Text = pmTolProcess;
});
Program.ThreadSafe(pmPBar, delegate
{
this.pmPBar.Value = e.PercentDone;
});
Program.ThreadSafe(lblpmPercent, delegate
{
this.lblpmPercent.Text = "[" + e.PercentDone + "%]";
});
}
#endregion

#region 节目包导入
private void btnpmSelect_Click(object sender, EventArgs e)
{
ofd = new OpenFileDialog();
ofd.Title = "选择压缩文件";
ofd.Filter = "压缩文件|*.7z";
ofd.Multiselect = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
if (ofd.FileNames.Length != 0)
{
ofd.Tag = ofd.FileNames;

lvImport.Items.Clear();
lvImport.View = View.Details;
lvImport.GridLines = true;
lvImport.FullRowSelect = true;
lvImport.ShowItemToolTips = true;
lvImport.CheckBoxes = true;
lvImport.SmallImageList = this.imageList2;
foreach (string file in ofd.FileNames)
{
ListViewItem li = new ListViewItem();
li.SubItems[0].Text = file;
FileInfo fileInfo = new FileInfo(file);
li.SubItems.Add(new FileSizeData(fileInfo.Length).ToString());
li.ImageIndex = 1;
li.SubItems.Add("准备导入");
lvImport.Items.Add(li);
}
this.btnImport.Enabled = true;
this.btnimDelete.Enabled = true;
}
}
}
private void LstViewBind(List<ImportMd> lst)
{
lvImport.Items.Clear();
lvImport.View = View.Details;
lvImport.GridLines = true;
lvImport.FullRowSelect = true;
lvImport.ShowItemToolTips = true;
lvImport.CheckBoxes = true;
lvImport.SmallImageList = this.imageList2;
foreach (ImportMd md in lst)
{
ListViewItem li = new ListViewItem();
li.SubItems[0].Text = md.FilePath;
FileInfo fileInfo = new FileInfo(md.FilePath);
li.SubItems.Add(new FileSizeData(fileInfo.Length).ToString());
switch (md.State)
{
case 0://成功
li.ImageIndex = 0;
break;
case 1://准备
li.ImageIndex = 1;
break;
case 2://失败
li.ImageIndex = 2;
break;
default:
break;
}
li.SubItems.Add(md.Message);
lvImport.Items.Add(li);
}
}
/// <summary>
/// 节目包导入
/// </summary>
private void btnImport_Click(object sender, EventArgs e)
{
int wCount = 0;
if (ofd == null)
{
MessageBox.Show(this, "请选择节目包!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
string[] fArray = (string[])ofd.Tag;
wCount = fArray.Length;
this.btnImport.Enabled = false;
this.btnimDelete.Enabled = false;
Thread imThread = new Thread(() =>
{
isAbort = false;
int m = 0;
List<ImportMd> importList = new List<ImportMd>();
foreach (string file in fArray)
{
string extFolder = string.Empty;
try
{
m++;
//当前处理条目
exTolProcess = "(" + m + "/" + wCount + ")";
//当前节目
Program.ThreadSafe(lblexCurrenFile, delegate
{
this.lblexCurrenFile.Text = file;
});

//-------------------解压节目----------------------//
extFolder = Path.GetFileNameWithoutExtension(file);
using (SevenZipExtractor uzip7 = new SevenZipExtractor(file, "Da@^@re"))
{
uzip7.FileExtractionStarted += new EventHandler<FileInfoEventArgs>(uzip7_FileExtractionStarted);
uzip7.ExtractArchive(extFolder);
}

//----------------------导入节目---------------------------//
string xmlPath = string.Empty;
xmlPath = Path.Combine(extFolder, extFolder + ".xml");
bool reval = false;
if (File.Exists(xmlPath))
{
XmlDataDocument xDoc = new XmlDataDocument();
xDoc.Load(xmlPath);
int fCount = 0;
int n = 0;
Dictionary<int, string> mdDictionary = new Dictionary<int, string>();
XmlNodeList xnList = null;

xnList = xDoc.SelectNodes("medias/md");
fCount = xnList.Count - GetNoCount(xnList);
foreach (XmlNode node in xnList)
{
string urlPath = string.Empty;
string srcPath = string.Empty;
string srcRoot = string.Empty;
string subFolder = string.Empty;
string desPath = string.Empty;
string currFolder = string.Empty;
string fullName = string.Empty;
string mName = string.Empty;
string eName = string.Empty;
string newFullName = string.Empty;
MediaFolderInfo mFolder = null;
MediaInfo md = null;
string dTime = string.Empty;

string pName = string.Empty;
int type = 0;
XmlDocument xdoc = null;
string nFilePath = string.Empty;
FileInfo fn = null;

//------------------------------------------构造媒体文件名-------------------------------------//
dTime = DateTime.Now.ToString("yyyyMMddHHmmss");
//媒体类型
type = node.SelectSingleNode("type").InnerText.Length == 0 ? 0 : int.Parse(node.SelectSingleNode("type").InnerText);
fullName = node.SelectSingleNode("name").InnerText;//fx.jpg
mName = Path.GetFileNameWithoutExtension(fullName);//fx
eName = Path.GetExtension(fullName);//.jpg
newFullName = mName + "_in" + dTime + eName;
//newFullName = mName + "_in" + eName;
//------------------------------------------构造媒体文件名-------------------------------------//

currFolder = Path.Combine("0", Properties.Settings.Default.LastLoginUser);//0\xxq
srcPath = node.SelectSingleNode("physical_path").InnerText;//0\root\aa\bb
srcRoot = GetRootFolder(srcPath);//root
subFolder = srcPath.Substring(Path.Combine("0", srcRoot).Length);//aa\bb
subFolder = subFolder.StartsWith("\\") ? subFolder.TrimStart('\\') : subFolder;

//------------------------------------------构造媒体目录-------------------------------------//
//子目录不存在
if (string.IsNullOrEmpty(subFolder))
{
desPath = currFolder;//0\AAA
}
else
{
string tmp = string.Empty;
int t = 0;

foreach (string folder in subFolder.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries))
{
t++;
tmp += folder + '\\';
desPath = Path.Combine(currFolder, tmp.TrimEnd('\\'));//0\AAA\aa
if (!folderService.IsFolderExtsit(desPath))//不存在
{
int parentId = 0;
if (t == 1)
{
parentId = folderService.GetParentId(currFolder).Value;
}
else
{
parentId = folderService.GetParentId(desPath).Value;
}
mFolder = folderService.CreateUserFolder(parentId, folder, "");
if (mFolder == null)
{
Program.ThreadSafe(this, delegate
{
if (ofd.Tag != null)
{
ImportMd imMd = new ImportMd();
imMd.FilePath = file;
imMd.State = 2;
imMd.Message = desPath + ",目录创建失败!";
importList.Add(imMd);
}
});
}
}
}
}

desPath = Path.Combine(currFolder, subFolder);//0\AAA\aa\bb
mFolder = folderService.GetFolderByPhysicalPath(desPath);
if (mFolder == null)
{
Program.ThreadSafe(this, delegate
{
if (ofd.Tag != null)
{
ImportMd imMd = new ImportMd();
imMd.FilePath = file;
imMd.State = 2;
imMd.Message = desPath + ",目录不存在!";
importList.Add(imMd);
}
});
Directory.Delete(extFolder, true);
continue;
}

//------------------------------------------构造媒体目录-------------------------------------//
switch (type)
{
case (int)MediaType.Video:
case (int)MediaType.Audio:
case (int)MediaType.Image:
case (int)MediaType.Text:
//------------------------------------------媒体物理文件上传-------------------------------------//
n++;
pName = Path.Combine(Path.Combine(extFolder, srcPath), fullName);//文件本地存放路径
fn = new FileInfo(pName);
Program.ThreadSafe(lblimTolProcess, delegate
{
//当前处理媒体条目
this.lblimTolProcess.Text = "(" + n + "/" + fCount + ")";
});
Program.ThreadSafe(lblimCurrenFile, delegate
{
//当前媒体
this.lblimCurrenFile.Text = fn.Name + "[" + new FileSizeData(fn.Length) + "]";
});

nFilePath = Path.Combine(desPath, newFullName);
urlPath = nFilePath.Replace(@"\", "/");
reval = UploadFile(urlPath, pName, imPBar, lblimPercent, lblimTolProcess, lblimCurrenFile);
if (!reval)
{
Program.ThreadSafe(this, delegate
{
if (ofd.Tag != null)
{
ImportMd imMd = new ImportMd();
imMd.FilePath = file;
imMd.State = 2;
imMd.Message = fullName + ",上传失败!";
importList.Add(imMd);
}
});
}
//------------------------------------------媒体物理文件上传-------------------------------------//

//------------------------------------------媒体逻辑文件入库-------------------------------------//
md = mediaService.CreateAndSaveAsMediaInfo(mFolder.Id, nFilePath,false);
if (md == null)
{
Program.ThreadSafe(this, delegate
{
if (ofd.Tag != null)
{
ImportMd imMd = new ImportMd();
imMd.FilePath = file;
imMd.State = 2;
imMd.Message = fullName + ",入库失败!";
importList.Add(imMd);
}
});
}
else
{
mdDictionary.Add(md.Id, fullName);
}
//------------------------------------------媒体逻辑文件入库-------------------------------------//
break;
case (int)MediaType.Rss:
md = new RssMediaInfo();
md.Xml = node.SelectSingleNode("xml/Media").OuterXml;

xdoc = new XmlDocument();
xdoc.LoadXml(md.Xml);
XmlNode xsn = xdoc.SelectSingleNode("Media");
if (xsn.Attributes["id"] != null)
{
XmlElement xe = (XmlElement)xsn;
xe.RemoveAttribute("id");
}
md = mediaService.CreateAndSaveAsMediaInfoFromXml(mFolder.Id, MediaType.Rss, xdoc.OuterXml) as RssMediaInfo;
if (md != null)
{
reval = true;
}
else
{
Program.ThreadSafe(this, delegate
{
ImportMd imMd = new ImportMd();
imMd.FilePath = file;
imMd.State = 2;
imMd.Message = fullName + ",入库失败!";
importList.Add(imMd);
});
reval = false;
}
break;
case (int)MediaType.NetworkImage:
md = new NetworkImageMediaInfo();
md.Xml = node.SelectSingleNode("xml/Media").OuterXml;

xdoc = new XmlDocument();
xdoc.LoadXml(md.Xml);
XmlNode xnn = xdoc.SelectSingleNode("Media");
if (xnn.Attributes["id"] != null)
{
XmlElement xe = (XmlElement)xnn;
xe.RemoveAttribute("id");
}
md = mediaService.CreateAndSaveAsMediaInfoFromXml(mFolder.Id, MediaType.NetworkImage, xdoc.OuterXml) as NetworkImageMediaInfo;
if (md != null)
{
reval = true;
}
else
{
Program.ThreadSafe(this, delegate
{
ImportMd imMd = new ImportMd();
imMd.FilePath = file;
imMd.State = 2;
imMd.Message = fullName + ",入库失败!";
importList.Add(imMd);
});
reval = false;
}
break;
case (int)MediaType.BroadcastVideo:
md = new BroadcastVideoMediaInfo();
md.Xml = node.SelectSingleNode("xml/Media").OuterXml;

xdoc = new XmlDocument();
xdoc.LoadXml(md.Xml);
XmlNode xbn = xdoc.SelectSingleNode("Media");
if (xbn.Attributes["id"] != null)
{
XmlElement xe = (XmlElement)xbn;
xe.RemoveAttribute("id");
}
md = mediaService.CreateAndSaveAsMediaInfoFromXml(mFolder.Id, MediaType.BroadcastVideo, xdoc.OuterXml) as BroadcastVideoMediaInfo;
if (md != null)
{
reval = true;
}
else
{
Program.ThreadSafe(this, delegate
{
ImportMd imMd = new ImportMd();
imMd.FilePath = file;
imMd.State = 2;
imMd.Message = fullName + ",入库失败!";
importList.Add(imMd);
});
reval = false;
}
break;
case (int)MediaType.NetworkFinanceImage:
md = new NetworkFinanceImageMediaInfo();
md.Xml = node.SelectSingleNode("xml/Media").OuterXml;

xdoc = new XmlDocument();
xdoc.LoadXml(md.Xml);
XmlNode xfn = xdoc.SelectSingleNode("Media");
if (xfn.Attributes["id"] != null)
{
XmlElement xe = (XmlElement)xfn;
xe.RemoveAttribute("id");
}
md = mediaService.CreateAndSaveAsMediaInfoFromXml(mFolder.Id, MediaType.NetworkFinanceImage, xdoc.OuterXml) as NetworkFinanceImageMediaInfo;
if (md != null)
{
reval = true;
}
else
{
Program.ThreadSafe(this, delegate
{
ImportMd imMd = new ImportMd();
imMd.FilePath = file;
imMd.State = 2;
imMd.Message = fullName + ",入库失败!";
importList.Add(imMd);
});
reval = false;
}
break;
case (int)MediaType.NetworkFinanceText:
md = new NetworkFinanceTextMediaInfo();
md.Xml = node.SelectSingleNode("xml/Media").OuterXml;

xdoc = new XmlDocument();
xdoc.LoadXml(md.Xml);
XmlNode xwn = xdoc.SelectSingleNode("Media");
if (xwn.Attributes["id"] != null)
{
XmlElement xe = (XmlElement)xwn;
xe.RemoveAttribute("id");
}
md = mediaService.CreateAndSaveAsMediaInfoFromXml(mFolder.Id, MediaType.NetworkFinanceText, xdoc.OuterXml) as NetworkFinanceTextMediaInfo;
if (md != null)
{
reval = true;
}
else
{
Program.ThreadSafe(this, delegate
{
ImportMd imMd = new ImportMd();
imMd.FilePath = file;
imMd.State = 2;
imMd.Message = fullName + ",入库失败!";
importList.Add(imMd);
});
reval = false;
}
break;
case (int)MediaType.DVBChannel:
md = new DVBChannelMediaInfo();
md.Xml = node.SelectSingleNode("xml/Media").OuterXml;

xdoc = new XmlDocument();
xdoc.LoadXml(md.Xml);
XmlNode xdn = xdoc.SelectSingleNode("Media");
if (xdn.Attributes["id"] != null)
{
XmlElement xe = (XmlElement)xdn;
xe.RemoveAttribute("id");
}
md = mediaService.CreateAndSaveAsMediaInfoFromXml(mFolder.Id, MediaType.DVBChannel, xdoc.OuterXml) as DVBChannelMediaInfo;
if (md != null)
{
reval = true;
}
else
{
Program.ThreadSafe(this, delegate
{
ImportMd imMd = new ImportMd();
imMd.FilePath = file;
imMd.State = 2;
imMd.Message = fullName + ",入库失败!";
importList.Add(imMd);
});
reval = false;
}
break;
case (int)MediaType.WebSnapImage:
md = new WebSnapImageMediaInfo();
md.Xml = node.SelectSingleNode("xml/Media").OuterXml;

xdoc = new XmlDocument();
xdoc.LoadXml(md.Xml);
XmlNode xpn = xdoc.SelectSingleNode("Media");
if (xpn.Attributes["id"] != null)
{
XmlElement xe = (XmlElement)xpn;
xe.RemoveAttribute("id");
}
md = mediaService.CreateAndSaveAsMediaInfoFromXml(mFolder.Id, MediaType.WebSnapImage, xdoc.OuterXml) as WebSnapImageMediaInfo;
if (md != null)
{
reval = true;
}
else
{
Program.ThreadSafe(this, delegate
{
ImportMd imMd = new ImportMd();
imMd.FilePath = file;
imMd.State = 2;
imMd.Message = fullName + ",入库失败!";
importList.Add(imMd);
});
reval = false;
}
break;
case (int)MediaType.Template:
//------------------------------------------缩略图物理文件上传-------------------------------------//
n++;
pName = Path.Combine(Path.Combine(extFolder, srcPath), fullName + ".thumbnail");//文件本地存放路径
fn = new FileInfo(pName);
Program.ThreadSafe(lblimTolProcess, delegate
{
//当前处理媒体条目
this.lblimTolProcess.Text = "(" + n + "/" + fCount + ")";
});
Program.ThreadSafe(lblimCurrenFile, delegate
{
//当前媒体
this.lblimCurrenFile.Text = fn.Name + "[" + new FileSizeData(fn.Length) + "]";
});

nFilePath = Path.Combine(desPath, newFullName + ".thumbnail");//缩略图远程存放路径
urlPath = nFilePath.Replace(@"\", "/");
reval = UploadFile(urlPath, pName, imPBar, lblimPercent, lblimTolProcess, lblimCurrenFile);
if (!reval)
{
Program.ThreadSafe(this, delegate
{
ImportMd imMd = new ImportMd();
imMd.FilePath = file;
imMd.State = 2;
imMd.Message = fullName + ",上传失败!";
importList.Add(imMd);
});
}

//------------------------------------------缩略图物理文件上传-------------------------------------//
md = new TemplateMediaInfo();
md.Xml = node.SelectSingleNode("xml/Template").OuterXml;
xdoc = new XmlDocument();
xdoc.LoadXml(md.Xml);

XmlNode xn = xdoc.SelectSingleNode("Template");
if (xn.Attributes["id"] != null)
{
XmlElement xe = (XmlElement)xn;
xe.RemoveAttribute("id");
}

if (xn.Attributes["name"] != null)
{
XmlElement xe = (XmlElement)xn;
xn.Attributes["name"].Value = newFullName;
}

foreach (XmlNode na in xdoc.SelectNodes("Template/Areas/Area/Playlists/Playlist"))
{
foreach (XmlNode nb in na.SelectNodes("Media"))
{
if (nb.Attributes["id"] != null)
{
foreach (KeyValuePair<int, string> mDic in mdDictionary)
{
if (nb.Attributes["name"] != null)
{
if (nb.Attributes["name"].Value == mDic.Value)
{
nb.Attributes["id"].Value = mDic.Key.ToString();
}
}
}
}
}
}

md = mediaService.SaveMediaInfoFromTerminalXml(null, mFolder.Id, MediaType.Template, xdoc.OuterXml, 0) as TemplateMediaInfo;
if (md != null)
{
mdDictionary.Add(md.Id, fullName);
reval = true;
}
else
{
Program.ThreadSafe(this, delegate
{
ImportMd imMd = new ImportMd();
imMd.FilePath = file;
imMd.State = 2;
imMd.Message = fullName + ",入库失败!";
importList.Add(imMd);
});
reval = false;
}
break;
case (int)MediaType.Program:
//------------------------------------------缩略图物理文件上传-------------------------------------//
n++;
pName = Path.Combine(Path.Combine(extFolder, srcPath), fullName + ".thumbnail");//文件本地存放路径
fn = new FileInfo(pName);
Program.ThreadSafe(lblimTolProcess, delegate
{
//当前处理媒体条目
this.lblimTolProcess.Text = "(" + n + "/" + fCount + ")";
});
Program.ThreadSafe(lblimCurrenFile, delegate
{
//当前媒体
this.lblimCurrenFile.Text = fn.Name + "[" + new FileSizeData(fn.Length) + "]";
});

nFilePath = Path.Combine(desPath, newFullName + ".thumbnail");//缩略图远程存放路径
urlPath = nFilePath.Replace(@"\", "/");
reval = UploadFile(urlPath, pName, imPBar, lblimPercent, lblimTolProcess, lblimCurrenFile);
if (!reval)
{
Program.ThreadSafe(this, delegate
{
ImportMd imMd = new ImportMd();
imMd.FilePath = file;
imMd.State = 2;
imMd.Message = fullName + ",上传失败!";
importList.Add(imMd);
});
}
//------------------------------------------缩略图物理文件上传-------------------------------------//
md = new ProgramMediaInfo();
//md.Xml = node.SelectSingleNode("xml/Program").InnerXml;//不包括节点仅子节点
md.Xml = node.SelectSingleNode("xml/Program").OuterXml;//不包括节点仅子节点
xdoc = new XmlDocument();
xdoc.LoadXml(md.Xml);

//更改Program 主键值
XmlNode xmn = xdoc.SelectSingleNode("Program");
if (xmn.Attributes["id"] != null)
{
XmlElement xe = (XmlElement)xmn;
xe.RemoveAttribute("id");
}
if (xmn.Attributes["name"] != null)
{
XmlElement xe = (XmlElement)xmn;
xmn.Attributes["name"].Value = newFullName;
}
//更改Template 主键值
XmlNode xtn = xdoc.SelectSingleNode("Program/Template");
if (xtn.Attributes["id"] != null)
{
foreach (KeyValuePair<int, string> mDic in mdDictionary)
{
if (xtn.Attributes["name"].Value == mDic.Value)
{
xtn.Attributes["id"].Value = mDic.Key.ToString();
}
}
}
//更改资源媒体文件 主键值
foreach (XmlNode na in xdoc.SelectNodes("Program/Areas/Area/Playlists/Playlist"))
{
foreach (XmlNode nb in na.SelectNodes("Media"))
{
if (nb.Attributes["id"] != null)
{
foreach (KeyValuePair<int, string> mDic in mdDictionary)
{
if (nb.Attributes["name"] != null)
{
if (nb.Attributes["name"].Value == mDic.Value)
{
nb.Attributes["id"].Value = mDic.Key.ToString();
}
}
}
}
}
}
md = mediaService.SaveMediaInfoFromTerminalXml(null, mFolder.Id, MediaType.Program, xdoc.OuterXml, 0) as ProgramMediaInfo;
if (md != null)
{
reval = true;
}
else
{
Program.ThreadSafe(this, delegate
{
ImportMd imMd = new ImportMd();
imMd.FilePath = file;
imMd.State = 2;
imMd.Message = fullName + ",入库失败!";
importList.Add(imMd);
});
reval = false;
}
break;
default:
break;
}
}
}
else
{
Program.ThreadSafe(this, delegate
{
ImportMd imMd = new ImportMd();
imMd.FilePath = file;
imMd.State = 2;
imMd.Message = extFolder + ".xml,不存在!";
importList.Add(imMd);
});
reval = false;
}

if (reval)
{
//--------------------处理条目成功结束-------------------//
Directory.Delete(extFolder, true);
Program.ThreadSafe(this, delegate
{
ImportMd imMd = new ImportMd();
imMd.FilePath = file;
imMd.State = 0;
imMd.Message = "导入成功!";
importList.Add(imMd);
});
//--------------------处理条目成功结束-------------------//
}
}
catch (Exception ex)
{
Program.ThreadSafe(this, delegate
{
Directory.Delete(extFolder, true);
MessageBox.Show(this, "节目导入失败!原因:" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
});
continue;
}
}
Program.ThreadSafe(this, delegate
{
LstViewBind(importList);
this.btnImport.Enabled = true;
this.btnimDelete.Enabled = true;
MessageBox.Show(this, "节目导入完毕!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
});
});
imThread.IsBackground = true;
imThread.Start();
}

private void btnImClose_Click(object sender, EventArgs e)
{
if (MessageBox.Show("确定退出系统吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK)
{
System.Environment.Exit(0);
}
}
private void uzip7_FileExtractionStarted(object sender, FileInfoEventArgs e)
{
Program.ThreadSafe(lblpmTolProcess, delegate
{
this.lblexTolProcess.Text = exTolProcess;
});
Program.ThreadSafe(exPBar, delegate
{
this.exPBar.Value = e.PercentDone;
});
Program.ThreadSafe(lblexPercent, delegate
{
this.lblexPercent.Text = "[" + e.PercentDone + "%]";
});
}
private void btnimDelete_Click(object sender, EventArgs e)
{
if (this.lvImport.CheckedItems.Count == 0)
{
MessageBox.Show(this, "请选择要移除的节目包!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
else
{
foreach (ListViewItem lvi in this.lvImport.CheckedItems)
{
lvi.Remove();
}
}
}
private int GetNoCount(XmlNodeList xnlist)
{
int iCount=0;
iCount = xnlist.Count;
int i = 0;
int type = 0;
foreach (XmlNode xn in xnlist)
{
type = xn.SelectSingleNode("type").InnerText.Length == 0 ? 0 : int.Parse(xn.SelectSingleNode("type").InnerText);
switch (type)
{
case (int)MediaType.Rss://.rss
case (int)MediaType.NetworkImage://.url
case (int)MediaType.BroadcastVideo://.bdv
case (int)MediaType.DVBChannel://.dvb
case (int)MediaType.NetworkFinanceImage://.fimg.url
case (int)MediaType.NetworkFinanceText://.ftxt.url
case (int)MediaType.WebSnapImage://.web.url
i++;
break;
default:
break;
}
}
return i;
}
private string CreateFolder(string folder, string user)
{
int i = 0;
string path = string.Empty;
string tmp = string.Empty;
bool isPreview = false;
foreach (string fd in folder.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries))
{
i++;
if (fd == "_preview") isPreview = true;

if (isPreview)
{
if (i == 3)
{
tmp = fd;
tmp = user;
}
else
{
tmp = fd;
}
}
else
{
if (i == 2)
{
tmp = fd;
tmp = user;
}
else
{
tmp = fd;
}
}
path += tmp + @"\";
}
return path.TrimEnd('\\');
}
private string GetRootFolder(string folder)
{
int i = 0;
string tmp = string.Empty;
foreach (string fd in folder.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries))
{
i++;
if (i == 2)
{
tmp = fd;
break;
}
}
return tmp;
}
public class ImportMd
{
private string filePath;

public string FilePath
{
get { return filePath; }
set { filePath = value; }
}
private int state;

public int State
{
get { return state; }
set { state = value; }
}
private string message;

public string Message
{
get { return message; }
set { message = value; }
}
}
#endregion

public MainFrm()
{
InitializeComponent();
this.Text = "网络多媒体导入导出工具 v2.0.4";
this.lblversion.Text = "版本:v2.0.4";
IntPublic();
}

private void MainFrm_Load(object sender, EventArgs e)
{
PlayTrViewInt();
this.btnplCancel.Enabled = false;
this.btnpmCancel.Enabled = false;
this.btnimDelete.Enabled = false;
this.btnImport.Enabled = false;
//this.btnImCancel.Enabled = false;
}

private void tabControl1_Click(object sender, EventArgs e)
{
tabName = this.tabControl1.SelectedTab.Name;
switch (tabName)
{
case "tabPlExtport":
break;
case "tabMdExtport":
MediaTrViewInt();
break;
case "tabMdImport":
break;
default:
break;
}
}

private void MainFrm_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("确定退出系统吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK)
{
Process.GetCurrentProcess().Kill();
}
else
{
e.Cancel = true;
}
}

private void btnpmClose_Click(object sender, EventArgs e)
{
if (MessageBox.Show("确定退出系统吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK)
{
System.Environment.Exit(0);
}
}

private void btnplClose_Click(object sender, EventArgs e)
{
if (MessageBox.Show("确定退出系统吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK)
{
System.Environment.Exit(0);
}
}

}
}

---------------------------------------------------------------------------------------------------------------------------------

/// <summary>
/// FTP下载方法
/// </summary>
/// <param name="remote"></param>
/// <param name="local"></param>
/// <param name="length"></param>
/// <param name="ub"></param>
/// <returns></returns>
private bool DownloadFile(string remote, string local, long length, ProgressBar pbar, Label lblpercent, Label lbltolprocess, Label lblcurrentfile)
{
bool result = false;
int downlength = 0;//当前下载大小

//-------------------建立连接----------------//
string url = string.Empty;
url = (uribuilder.Host.ToLower().StartsWith("ftp://") ? uribuilder.Host : "ftp://" + uribuilder.Host) + ((uribuilder.Host.ToLower().StartsWith("ftp://") ? uribuilder.Host : "ftp://" + uribuilder.Host).EndsWith("/") ? "" : "/") + remote;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.Credentials = new NetworkCredential(uribuilder.UserName, uribuilder.Password);
request.Proxy = null;
//命令执行完毕之后关闭连接
request.KeepAlive = false;
request.UseBinary = true;
request.UsePassive = true;
request.EnableSsl = false;
request.Method = WebRequestMethods.Ftp.DownloadFile;
//-------------------建立连接----------------//

//创建或打开本地文件
using (FileStream fileStream = new FileStream(local, FileMode.OpenOrCreate))
{
//request.ContentOffset = fileStream.Length;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Stream stream = response.GetResponseStream();
//fileStream.Position = fileStream.Length;
int bufferLength = 256 * 1024;//256K
byte[] buffer = new byte[bufferLength];
int readCount = 0;
while ((readCount = stream.Read(buffer, 0, bufferLength) )> 0)
{
//是否终止任务
if (isAbort)
{
fileStream.Dispose();
Program.ThreadSafe(pbar, delegate
{
pbar.Value = 0;
});
Program.ThreadSafe(lblpercent, delegate
{
lblpercent.Text = "[0%]";
});
Program.ThreadSafe(lbltolprocess, delegate
{
lbltolprocess.Text = "(0/0)";
});
Program.ThreadSafe(lblcurrentfile, delegate
{
lblcurrentfile.Text = "------";
});
break;
}
downlength += readCount;//已经下载大小
fileStream.Write(buffer, 0, readCount);
int tolpercent = (int)((float)(downlength / (float)length * 100));
Program.ThreadSafe(pbar, delegate
{
pbar.Value = tolpercent;
});
Program.ThreadSafe(lblpercent, delegate
{
lblpercent.Text = "[" + tolpercent.ToString() + "%]";
});
//readCount = stream.Read(buffer, 0, bufferLength);
}
response.GetResponseStream().Close();
}
result = true;
}
return result;
}
private bool DownloadFile(string remote, string local)
{
//-------------------建立连接----------------//
bool result = false;
string url = string.Empty;
url = (uribuilder.Host.ToLower().StartsWith("ftp://") ? uribuilder.Host : "ftp://" + uribuilder.Host) + ((uribuilder.Host.ToLower().StartsWith("ftp://") ? uribuilder.Host : "ftp://" + uribuilder.Host).EndsWith("/") ? "" : "/") + remote;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.Credentials = new NetworkCredential(uribuilder.UserName, uribuilder.Password);
request.Proxy = null;
//命令执行完毕之后关闭连接
request.KeepAlive = false;
request.UseBinary = true;
request.UsePassive = true;
request.EnableSsl = false;
request.Method = WebRequestMethods.Ftp.DownloadFile;
//-------------------建立连接----------------//

//创建或打开本地文件
using (FileStream fileStream = new FileStream(local, FileMode.OpenOrCreate))
{
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Stream stream = response.GetResponseStream();
int bufferLength = 256 * 1024;//256K
byte[] buffer = new byte[bufferLength];
int readCount = 0;
while ((readCount = stream.Read(buffer, 0, buffer.Length)) > 0)
{
//是否终止任务
if (isAbort)
{
fileStream.Dispose();
Program.ThreadSafe(pdPBar, delegate
{
pdPBar.Value = 0;
});
Program.ThreadSafe(lblpdPercent, delegate
{
lblpdPercent.Text = "[0%]";
});
Program.ThreadSafe(lblpdTolProcess, delegate
{
lblpdTolProcess.Text = "(0/0)";
});
Program.ThreadSafe(lblpdCurrenFile, delegate
{
lblpdCurrenFile.Text = "------";
});
break;
}
fileStream.Write(buffer, 0, readCount);
}
response.GetResponseStream().Close();
}
result = true;
}
return result;
}
//private bool DownloadFile(string remote, string local)
//{
// FtpClient ftpClient = new FtpClient(uribuilder);
// return ftpClient.DownloadFile(remote, local);
//}
//private byte[] DownloadData(string remote)
//{
// FtpClient ftpClient = new FtpClient(uribuilder);
// return ftpClient.DownloadData(remote);
//}
private bool? IsDirExists(string dir)
{
FtpClient ftpClient = new FtpClient(uribuilder);
return ftpClient.DirExists(dir);
}
private bool? IsFileExists(string fName)
{
FtpClient ftpClient = new FtpClient(uribuilder);
return ftpClient.FileExists(fName);
}
private bool CreateDir(string dir)
{
FtpClient ftpClient = new FtpClient(uribuilder);
return ftpClient.MakeDir(dir);
}

private bool UploadFile(string remote, string local)
{
bool result = false;
int uploadlength = 0;//当前上载大小

if (File.Exists(local))
{
FileInfo fileInfo = new FileInfo(local);
long length = fileInfo.Length;
//-------------------建立连接----------------//
string url = string.Empty;
url = (uribuilder.Host.ToLower().StartsWith("ftp://") ? uribuilder.Host : "ftp://" + uribuilder.Host) + ((uribuilder.Host.ToLower().StartsWith("ftp://") ? uribuilder.Host : "ftp://" + uribuilder.Host).EndsWith("/") ? "" : "/") + remote;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.Credentials = new NetworkCredential(uribuilder.UserName, uribuilder.Password);
request.Proxy = null;
//命令执行完毕之后关闭连接
request.KeepAlive = false;
request.UseBinary = true;
request.UsePassive = true;
request.EnableSsl = false;
request.ContentLength = length;
request.Method = WebRequestMethods.Ftp.UploadFile;
//-------------------建立连接----------------//

//创建或打开本地文件
using (FileStream fileStream = fileInfo.OpenRead())
{
using (Stream stream = request.GetRequestStream())
{
int bufferLength = 256 * 1024;//256K
byte[] buffer = new byte[bufferLength];
int readCount = 0;
while ((readCount=stream.Read(buffer, 0, bufferLength))> 0)
{
uploadlength += readCount;//已经上载大小
stream.Write(buffer, 0, readCount);
int tolpercent = (int)((float)(uploadlength / (float)length * 100));
}
}
result = true;
}
}
else
{
result = false;
}
return result;
}
private bool UploadFile(string remote, string local, ProgressBar pbar, Label lblpercent, Label lbltolprocess, Label lblcurrentfile)
{
bool result = false;
int upLength = 0;//当前上载大小

if (File.Exists(local))
{
FileInfo fileInfo = new FileInfo(local);
if (!fileInfo.Exists) throw new FileNotFoundException("待上传的本地文件不存在!", local);
long length = fileInfo.Length;
//-------------------建立连接----------------//
string url = string.Empty;
url = (uribuilder.Host.ToLower().StartsWith("ftp://") ? uribuilder.Host : "ftp://" + uribuilder.Host) + ((uribuilder.Host.ToLower().StartsWith("ftp://") ? uribuilder.Host : "ftp://" + uribuilder.Host).EndsWith("/") ? "" : "/") + remote;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.Credentials = new NetworkCredential(uribuilder.UserName, uribuilder.Password);
request.Proxy = null;
//命令执行完毕之后关闭连接
request.KeepAlive = false;
request.UseBinary = true;
request.UsePassive = true;
request.EnableSsl = false;
request.ContentLength = length;
request.Method = WebRequestMethods.Ftp.UploadFile;
//-------------------建立连接----------------//

//创建或打开本地文件
using (Stream stream = request.GetRequestStream())
{
int bufferLength = 256 * 1024;//256K
byte[] buffer = new byte[bufferLength];
int readCount = 0;
using (FileStream fileStream = fileInfo.OpenRead())
{
while ((readCount = fileStream.Read(buffer, 0, bufferLength)) > 0)
{
upLength += readCount;//已经上载大小
stream.Write(buffer, 0, readCount);
int tolpercent = (int)((float)(upLength / (float)length * 100));
Program.ThreadSafe(pbar, delegate
{
pbar.Value = tolpercent;
});
Program.ThreadSafe(lblpercent, delegate
{
lblpercent.Text = "[" + tolpercent.ToString() + "%]";
});
}
}
result = true;
}
}
else
{
result = false;
}
return result;
}

05-11 22:55