using LYFZ.BLL.OssCloudDiskSDK; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace LYFZ.Software.MainBusiness.OssTask { public class frmOssTask : LYFZ.Software.OssTask.frmOssTask { public frmOssTask() { MyfrmOssTask = this; this.Load += FrmOssTask_Load; this.Shown += FrmOssTask_Shown; // 按钮事件; this.btn_refresh.Click += Btn_refresh_Click; // 窗口关闭事件; this.FormClosed += FrmOssTask_FormClosed; // 双击DataGridView; this.dgv.CellDoubleClick += Dgv_CellDoubleClick; } private void Dgv_CellDoubleClick( object sender, DataGridViewCellEventArgs e ) { if ( e.ColumnIndex == 12 ) { DataGridViewRow row = this.dgv.Rows[e.RowIndex]; JsonOssTask ossTask = (JsonOssTask)row.Tag; if ( ossTask != null ) { // 检查手机合法性; string okPhones = ""; LYFZ.WinAPI.CustomPublicMethod.ValidationPhones( row.Cells[5].Value.ToString().Replace( '/', ',' ), ref okPhones ); if ( ossTask.OsType == 2 ) {// 手动百度云分享; if ( string.IsNullOrEmpty( ossTask.BaiduShareUrl ) ) { OssTask.frmBaiduShareUrl dlg = new frmBaiduShareUrl(); dlg.ShowDialog(); if ( dlg.DialogResult == DialogResult.OK ) { ossTask.BaiduExtrCode = dlg.tx_code.Text; ossTask.BaiduShareUrl = dlg.tx_url.Text; // 发送到web服务器; ossTask.FinishedTime = DateTime.Now.ToString( "yyyy-MM-dd 00:00:00" ); ossTask.DownloadExpireTime = DateTime.Now.ToString( "yyyy-MM-dd 00:00:00" ); string strResult = LYFZ.WinAPI.CustomPublicMethod.HttpContentPOST( "http://p.lyfz.net/api/ChargeDataControl.ashx/SetChargeDetail", JsonConvert.SerializeObject( ossTask ), Encoding.UTF8 ); ResultCode result = JsonConvert.DeserializeObject( strResult ); if ( result.code == 200 && result.data.Status ) { MessageBoxCustom.Show( "推送成功" ); row.Cells[12].Value = ossTask.BaiduShareUrl; // 更新到服务器; string strJson = JsonConvert.SerializeObject( ossTask ); LYFZ.Network.PlatinumClientProcess.SendOssTaskJson2Svr( strJson, ossTask.TaskID, true ); } else { MessageBoxCustom.Show( result.info + ". " + result.data.StatusMsg ); } } } else { LYFZ.Software.MainBusiness.SMSManagement.SmsSend.FrmSendSms sendSMSDlg = new SMSManagement.SmsSend.FrmSendSms(); sendSMSDlg.Phone = okPhones.Trim().Trim( ',' ); sendSMSDlg.SetDefaultSmsText( string.Format( "{0} 您好, 您的相片已上传到百度云,请前行小程序查看下载地址,提取码:{1}!", row.Cells[3].Value.ToString(), ossTask.BaiduExtrCode ) ); sendSMSDlg.ShowDialog(); } } else if ( row.Cells[12].Value != null && !string.IsNullOrEmpty( row.Cells[12].Value.ToString() ) ) {// 阿里或腾讯; LYFZ.Software.MainBusiness.SMSManagement.SmsSend.FrmSendSms sendSMSDlg = new SMSManagement.SmsSend.FrmSendSms(); sendSMSDlg.Phone = okPhones.Trim().Trim( ',' ); sendSMSDlg.SetDefaultSmsText( string.Format( "{0} 您好, 您的相片已上传完成,请前行小程序查看下载地址!", row.Cells[3].Value.ToString() ) ); sendSMSDlg.ShowDialog(); } } } } private void FrmOssTask_Shown( object sender, EventArgs e ) { LYFZ.ComponentLibrary.FrmLoadHandling.LoadDoWorkMethod( delegate ( object obj, BackgroundWorker backgroundWorker ) { backgroundWorker.ReportProgress( 0, "正在加载中,请稍等..." ); // 从服务器加载文件数据; List listJson; if ( LYFZ.Network.PlatinumClientProcess.GetOssTaskInfoFromSvr( out listJson ) ) { LoadOssTask2( listJson ); PaddingData(); } } ); } /// /// 窗口关闭事件; /// /// /// private void FrmOssTask_FormClosed( object sender, FormClosedEventArgs e ) { MyfrmOssTask = null; } /// /// 窗口加载事件; /// /// /// private void FrmOssTask_Load( object sender, EventArgs e ) { } /// /// 刷新按钮; /// /// /// private void Btn_refresh_Click( object sender, EventArgs e ) { if ( !CanUploadImage( _uploadOss.AppInterface.AppEnId ) ) { MessageBoxCustom.Show( "无上传权限,请充值流量!" ); return; } LYFZ.ComponentLibrary.FrmLoadHandling.LoadDoWorkMethod( delegate ( object obj, BackgroundWorker backgroundWorker ) { backgroundWorker.ReportProgress( 0, "正在加载中,请稍等..." ); // 清空datagridview; dgv.Rows.Clear(); // 从服务器加载文件数据; List listJson; if ( LYFZ.Network.PlatinumClientProcess.GetOssTaskInfoFromSvr( out listJson ) ) { LoadOssTask2( listJson ); PaddingData(); } } ); } /// /// 填充数据; /// private void PaddingData() { this.dgv.Rows.Clear(); if ( _listOssTask == null ) return; DataGridViewRow data = null; foreach ( JsonOssTask item in _listOssTask ) { data = new DataGridViewRow(); data.Tag = item; data.CreateCells( this.dgv ); data.Cells[0].Value = item.TaskID; data.Cells[1].Value = item.OrderNumber; data.Cells[2].Value = item.OrderType; data.Cells[3].Value = item.CusNames; data.Cells[4].Value = item.CusGenders; data.Cells[5].Value = item.CusPhones; data.Cells[6].Value = item.PhotosType; data.Cells[7].Value = item.ShootName; data.Cells[8].Value = item.DownloadBranchIDs; // 上传完成的数量; int nCompletedCount = 0; if ( item.ArrayPhotos != null ) { foreach ( PhotoArray array in item.ArrayPhotos ) { if ( array.ListPhotos == null ) continue; foreach ( PhotoItem phitem in array.ListPhotos ) { if ( !string.IsNullOrEmpty( phitem.PhotoUrl ) ) nCompletedCount++; } } // 上传进度; data.Cells[9].Value = string.Format( "{0}/{1}", nCompletedCount, item.PhotoCount ); } data.Cells[10].Value = item.FinishedTime; data.Cells[11].Value = item.DownloadExpireTime; // 如果已经完成,生成连接; PaddingUrl( item, data ); this.dgv.Rows.Add( data ); } } /// /// 填充url到DataGridView中; /// /// /// private void PaddingUrl( JsonOssTask ossTask, DataGridViewRow row ) { // check arg; if ( ossTask == null || row == null ) return; // 如果已经完成,生成连接; if ( !string.IsNullOrEmpty( ossTask.FinishedTime ) ) { if ( ossTask.OsType == 2 ) row.Cells[12].Value = ossTask.BaiduShareUrl; else row.Cells[12].Value = GenerateUrl( ossTask.TaskID ); } } /// /// 生成客户云相片下载地址; /// /// /// private static string GenerateUrl( string strTaskId ) { return string.Format( "http://p.lyfz.net/ImgDownload.aspx?id={0}", strTaskId ); } #region 成员变量或静态变量; public static frmOssTask MyfrmOssTask { get; set; } = null; // 是否加载过任务文件; public static bool IsTaskloaded { get; set; } = false; // 安全锁; private static object _lockJson = new object(); // 安全锁; private static object _lockTask = new object(); // 上传下载oss的执行对象; private static BLL.OssCloudDiskSDK.UploadOssCloudDisk _uploadOss = new UploadOssCloudDisk(); // 任务Json数据队列; private static List _listOssTask = null; // 任务线程对象; private static System.Threading.Thread _thread = null; // 任务Task对象队列; private static List _listTask = null; private static string _host_url = ""; #endregion #region 静态方法 public static void SendBaiduShare2WebSrv( JsonOssTask ossTask ) { // 发送到web服务器; ossTask.FinishedTime = DateTime.Now.ToString( "yyyy-MM-dd 00:00:00" ); ossTask.DownloadExpireTime = DateTime.Now.ToString( "yyyy-MM-dd 00:00:00" ); string strResult = LYFZ.WinAPI.CustomPublicMethod.HttpContentPOST( "http://p.lyfz.net/api/ChargeDataControl.ashx/SetChargeDetail", JsonConvert.SerializeObject( ossTask ), Encoding.UTF8 ); ResultCode result = JsonConvert.DeserializeObject( strResult ); if ( result.code == 200 && result.data.Status ) { MessageBoxCustom.Show( "推送成功" ); // 更新到服务器; string strJson = JsonConvert.SerializeObject( ossTask ); LYFZ.Network.PlatinumClientProcess.SendOssTaskJson2Svr( strJson, ossTask.TaskID, true ); } else { MessageBoxCustom.Show( result.info + ". " + result.data.StatusMsg ); } } /// /// task list is null or empty; /// /// public static bool IsTaskListNullOrEmpty() { if ( _listOssTask == null || _listOssTask.Count == 0 ) return true; return false; } /// /// 是否具有企业ID; /// /// public static bool IsExistsEnterpriseID() { if ( _uploadOss.AppInterface == null || string.IsNullOrEmpty( _uploadOss.AppInterface.AppEnId ) ) return false; return true; } public static bool CanUploadImage() { string url = string.Format( "http://p.lyfz.net/api/ChargeDataControl.ashx/CheckChargeDetailData?EntID={0}", _uploadOss.AppInterface.AppEnId ); string strResult = LYFZ.WinAPI.CustomPublicMethod.HttpWebRequestGET( url, Encoding.UTF8 ); ResultCode result = JsonConvert.DeserializeObject( strResult ); if ( result.code == 200 && result.data.Status ) { return true; } return false; } public static bool CanUploadImageEx() { if ( _uploadOss.AppInterface == null || string.IsNullOrEmpty( _uploadOss.AppInterface.AppEnId ) ) return false; string url = string.Format( "http://p.lyfz.net/api/ChargeDataControl.ashx/CheckChargeDetailData?EntID={0}", _uploadOss.AppInterface.AppEnId ); string strResult = LYFZ.WinAPI.CustomPublicMethod.HttpWebRequestGET( url, Encoding.UTF8 ); ResultCode result = JsonConvert.DeserializeObject( strResult ); if ( result.code == 200 && result.data.Status ) { return true; } return false; } public static bool CanUploadImage( string entId ) { string url = string.Format( "http://p.lyfz.net/api/ChargeDataControl.ashx/CheckChargeDetailData?EntID={0}", entId ); string strResult = LYFZ.WinAPI.CustomPublicMethod.HttpWebRequestGET( url, Encoding.UTF8 ); ResultCode result = JsonConvert.DeserializeObject( strResult ); if ( result.code == 200 && result.data.Status ) { return true; } return false; } /// /// 生成客户云链接的上传任务; /// /// 订单号 /// 客户姓名 /// 客户性别 /// 客户电话 /// 相片类型:原片, 初修, 精修, 设计, 选好的片 /// 拍摄名称 /// 要上传的相片路径, 如果为null则要手动获取相片路径 public static JsonOssTask GenerateOssTask( int osType, string downloadExpire, int downloadTiems, string order, string viceOrder, string order_type, string cus_name, string cus_gender, string cus_tel, string photoType, string shootName, List listImagesPath = null, string download_branchs = "" ) { if ( string.IsNullOrEmpty( order ) ) return null; if ( string.IsNullOrEmpty( _uploadOss.AppInterface.AppEnId ) ) { MessageBoxCustom.Show( "未注册云账号,请联系服务商注册" ); return null; } // 创建任务; JsonOssTask jsonOssTask = new JsonOssTask(); // 企业编号; jsonOssTask.EnterpriseID = _uploadOss.AppInterface.AppEnId; // 本店分店ID(上传分店ID) jsonOssTask.UploadBranchID = LYFZ.BLL.BLL_ErpCompanyInfo.CurrentCompanyInfoID; // 下载的分店ID串, ID值前后使用'#'分隔; jsonOssTask.DownloadBranchIDs = download_branchs; jsonOssTask.OrderNumber = order; jsonOssTask.OrderViceNumber = viceOrder; jsonOssTask.OrderType = order_type; jsonOssTask.CusNames = cus_name; jsonOssTask.CusGenders = cus_gender; jsonOssTask.CusPhones = cus_tel; jsonOssTask.ShootName = shootName; jsonOssTask.PhotosType = photoType; // 创建时,默认完成时间空; jsonOssTask.FinishedTime = ""; jsonOssTask.listPhotos = new List(); jsonOssTask.OsType = osType; if ( osType == -1 ) {// 阿里或腾讯云; jsonOssTask.DownloadExpireTime = downloadExpire; jsonOssTask.CustomizeDownloadTimes = downloadTiems; } // 任务id; jsonOssTask.TaskID = LYFZ.WinAPI.SDKSecurity.MD5Encrypt( string.Format( "{0}{1}{2}{3}{4}{5}", jsonOssTask.OsType, jsonOssTask.EnterpriseID, jsonOssTask.UploadBranchID, order, viceOrder, shootName ) ); if ( listImagesPath == null ) return jsonOssTask; ulong nPhotoSize = 0; foreach ( string file in listImagesPath ) { // 文件是否存在; if ( !System.IO.File.Exists( file ) || _uploadOss == null ) continue; // 文件大小; System.IO.FileInfo fileInfo = new System.IO.FileInfo( file ); nPhotoSize += (ulong)fileInfo.Length; PhotoItem photoItem = new PhotoItem( System.IO.Path.GetFileName( file ).Remove( 0, 9 /*'Original_'*/), file, fileInfo.Length, ""/*创建时,默认url空*/ ); // 添加到list中; jsonOssTask.listPhotos.Add( photoItem ); } jsonOssTask.PhotoCount = jsonOssTask.listPhotos.Count; jsonOssTask.PhotoSize = nPhotoSize; return jsonOssTask; } /// /// 生成任务Json, 并发送给服务器; /// /// 订单号 /// 订单类型,可能用于统计使用 /// 用户姓名,用于短信发送 /// 用户性别,用于短信发送 /// 用户电话,用于短信发送 /// 上传的相片类型, 用于统计查看,类型有:原片,初修, 选好的片,精修,设计 /// 拍摄名称,可能用于统计查看 /// 要上传的相片绝对路径集合 /// 用于分店传片,指定能下载相片的分店, 如果该值为空,则没有分店要下载 /// public static bool GenerateOssTaskEx( int osType, string downloadExpire, int downloadTiems, string order, string order_type, string cus_name, string cus_gender, string cus_tel, string photoType, string shootName, List listImagesPath = null, string download_branchs = "" ) { if ( string.IsNullOrEmpty( order ) ) return false; if ( string.IsNullOrEmpty( _uploadOss.AppInterface.AppEnId ) ) { MessageBoxCustom.Show( "未注册云账号,请联系服务商注册" ); return false; } if ( listImagesPath == null ) {// 需要重新获取相片; listImagesPath = new List(); // 暂时不处理这块,默认返回false; return false; } else { // 创建任务; JsonOssTask jsonOssTask = new JsonOssTask(); // 企业编号; jsonOssTask.EnterpriseID = _uploadOss.AppInterface.AppEnId; // 本店分店ID(上传分店ID) jsonOssTask.UploadBranchID = LYFZ.BLL.BLL_ErpCompanyInfo.CurrentCompanyInfoID; // 下载的分店ID串, ID值前后使用'#'分隔; jsonOssTask.DownloadBranchIDs = download_branchs; jsonOssTask.OrderNumber = order; jsonOssTask.OrderType = order_type; jsonOssTask.CusNames = cus_name; jsonOssTask.CusGenders = cus_gender; jsonOssTask.CusPhones = cus_tel; jsonOssTask.ShootName = shootName; jsonOssTask.PhotosType = photoType; // 创建时,默认完成时间空; jsonOssTask.FinishedTime = ""; jsonOssTask.listPhotos = new List(); jsonOssTask.OsType = osType; if ( osType == -1 ) {// 阿里或腾讯云; jsonOssTask.DownloadExpireTime = downloadExpire; jsonOssTask.CustomizeDownloadTimes = downloadTiems; } // 任务id; jsonOssTask.TaskID = LYFZ.WinAPI.SDKSecurity.MD5Encrypt( string.Format( "{0}{1}{2}{3}{4}{5}{6}", jsonOssTask.OsType, jsonOssTask.EnterpriseID, jsonOssTask.UploadBranchID, order, order_type, photoType, shootName ) ); ulong nPhotoSize = 0; foreach ( string file in listImagesPath ) { // 文件是否存在; if ( !System.IO.File.Exists( file ) || _uploadOss == null ) continue; // 文件大小; System.IO.FileInfo fileInfo = new System.IO.FileInfo( file ); nPhotoSize += (ulong)fileInfo.Length; PhotoItem photoItem = new PhotoItem( System.IO.Path.GetFileName( file ).Remove( 0, 9 /*'Original_'*/), file, fileInfo.Length, ""/*创建时,默认url空*/ ); // 添加到list中; jsonOssTask.listPhotos.Add( photoItem ); } jsonOssTask.PhotoCount = jsonOssTask.listPhotos.Count; jsonOssTask.PhotoSize = nPhotoSize; // 将对象转储为Json格式的文件; if ( jsonOssTask != null ) { try { string strJson = JsonConvert.SerializeObject( jsonOssTask ); return LYFZ.Network.PlatinumClientProcess.SendOssTaskJson2Svr( strJson, jsonOssTask.TaskID ); } catch ( Exception e ) { return false; } } } return false; } public static void AddPhoto2TaskObj( JsonOssTask jsonOssTask, string strPhotoType, List listPhotos ) { if ( listPhotos == null || jsonOssTask == null ) return; OssTask.PhotoArray photoArray = null; foreach ( PhotoArray item in jsonOssTask.ArrayPhotos ) { if ( item.PhotosType.ToUpper() == strPhotoType.ToUpper() ) { photoArray = item; if ( photoArray.ListPhotos == null ) photoArray.ListPhotos = new List(); break; } } if ( photoArray == null ) { photoArray = new PhotoArray(); photoArray.PhotosType = strPhotoType; if ( photoArray.ListPhotos == null ) photoArray.ListPhotos = new List(); jsonOssTask.ArrayPhotos.Add( photoArray ); } ulong nPhotoSize = 0; foreach ( string file in listPhotos ) { // 文件是否存在; if ( !System.IO.File.Exists( file ) || _uploadOss == null ) continue; // 文件大小; System.IO.FileInfo fileInfo = new System.IO.FileInfo( file ); nPhotoSize += (ulong)fileInfo.Length; OssTask.PhotoItem photoItem = new OssTask.PhotoItem( System.IO.Path.GetFileName( file ).Remove( 0, 9 /*'Original_'*/), file, fileInfo.Length, ""/*创建时,默认url空*/ ); // 添加到list中; photoArray.ListPhotos.Add( photoItem ); } jsonOssTask.PhotoCount += listPhotos.Count; jsonOssTask.PhotoSize += nPhotoSize; } public static bool SendOssTask2Svr( JsonOssTask jsonOssTask ) { if ( jsonOssTask != null ) { try { string strJson = JsonConvert.SerializeObject( jsonOssTask ); return LYFZ.Network.PlatinumClientProcess.SendOssTaskJson2Svr( strJson, jsonOssTask.TaskID ); } catch ( Exception e ) { return false; } } return false; } /// /// 获取已选好的相片; /// /// /// /// public static List GetSelectedPhotos( string order, string viceOrder, string strScenery ) { LYFZ.BLL.BLL_ErpOrderDigital bLL_ErpOrderDigital = new BLL.BLL_ErpOrderDigital(); LYFZ.Model.Model_ErpOrderDigital model = bLL_ErpOrderDigital.GetModel( "Ordv_ViceNumber", viceOrder ); try { // 将字符串转成枚举; Model.Model_ErpOrder.DirectoryType directoryType = (Model.Model_ErpOrder.DirectoryType)Enum.Parse( typeof( Model.Model_ErpOrder.DirectoryType ), model.Ordv_SelectedPhotoType ); // 相片类型; string strPhotosType = (directoryType == Model.Model_ErpOrder.DirectoryType.EarlyRetouch) ? "初修" : "原片"; // 相片串,解析出相片名; string strImages = model.Ordv_SelectionFilm; if ( string.IsNullOrEmpty( strImages ) ) { //MessageBoxCustom.Show( "该订单未有选片记录,不可生成任务" ); return null; } int nStart = 0/*冒号位置*/, nEndof = 0/*星号位置*/; string strResult; // 选片结果; List listGoodsImage = strImages.Split( '|' ).ToList(); List listImages = new List(); foreach ( string item in listGoodsImage ) { nStart = item.IndexOf( ':' ) + 1; nEndof = item.IndexOf( '*' ); if ( nEndof != -1 && nStart >= nEndof ) continue; strResult = (nEndof == -1 ? item.Substring( nStart ) : item.Substring( nStart, nEndof - nStart )); listImages = strResult.Split( '?' ).ToList().Union( listImages ).ToList(); //listImages = item.Substring( item.IndexOf( ':' ) + 1 ).Split( '?' ).ToList().Union( listImages ).ToList(); } // 实际相片的目录; BLL.SelectPhotoHandling photoHandling = new BLL.SelectPhotoHandling( new BLL.BLL_ErpOrder().GetModel( "Ord_Number", order ), bLL_ErpOrderDigital.GetModel( "Ordv_ViceNumber", viceOrder ) ); List listPaths = BLL.SelectPhotoHandling.GetFromServerSpecifyDirectoryList( directoryType ); List listFiles = photoHandling.GetSpecifyTypePhotoList( directoryType, BLL.SelectPhotoHandling.PhotoType.Original, strScenery ); List listPhotos = new List(); foreach ( string item in listImages ) { for ( int i = 0; i < listFiles.Count; i++ ) { // 文件名; string name = System.IO.Path.GetFileName( listFiles[i] ).Remove( 0, 9 /*'Original_'*/); if ( item.ToUpper() == name.ToUpper() ) { listPhotos.Add( listFiles[i] ); listFiles.RemoveAt( i ); break; } } } return listPhotos; } catch { // 可能字符串转枚举时出错了; } return null; } public static List GetSelectedPhotos( string order, string viceOrder, string strScenery, Model.Model_ErpOrder.DirectoryType directoryType ) { LYFZ.BLL.BLL_ErpOrderDigital bLL_ErpOrderDigital = new BLL.BLL_ErpOrderDigital(); LYFZ.Model.Model_ErpOrderDigital model = bLL_ErpOrderDigital.GetModel( "Ordv_ViceNumber", viceOrder ); try { // 将字符串转成枚举; //Model.Model_ErpOrder.DirectoryType directoryType = (Model.Model_ErpOrder.DirectoryType)Enum.Parse( typeof( Model.Model_ErpOrder.DirectoryType ), model.Ordv_SelectedPhotoType ); // 相片类型; //string strPhotosType = (directoryType == Model.Model_ErpOrder.DirectoryType.EarlyRetouch) ? "初修" : "原片"; // 相片串,解析出相片名; string strImages = model.Ordv_SelectionFilm; if ( string.IsNullOrEmpty( strImages ) ) { //MessageBoxCustom.Show( "该订单未有选片记录,不可生成任务" ); return null; } int nStart = 0/*冒号位置*/, nEndof = 0/*星号位置*/; string strResult; // 选片结果; List listGoodsImage = strImages.Split( '|' ).ToList(); List listImages = new List(); foreach ( string item in listGoodsImage ) { nStart = item.IndexOf( ':' ) + 1; nEndof = item.IndexOf( '*' ); if ( nEndof != -1 && nStart >= nEndof ) continue; strResult = (nEndof == -1 ? item.Substring( nStart ) : item.Substring( nStart, nEndof - nStart )); listImages = strResult.Split( '?' ).ToList().Union( listImages ).ToList(); //listImages = item.Substring( item.IndexOf( ':' ) + 1 ).Split( '?' ).ToList().Union( listImages ).ToList(); } // 实际相片的目录; BLL.SelectPhotoHandling photoHandling = new BLL.SelectPhotoHandling( new BLL.BLL_ErpOrder().GetModel( "Ord_Number", order ), bLL_ErpOrderDigital.GetModel( "Ordv_ViceNumber", viceOrder ) ); List listPaths = BLL.SelectPhotoHandling.GetFromServerSpecifyDirectoryList( directoryType ); List listFiles = photoHandling.GetSpecifyTypePhotoList( directoryType, BLL.SelectPhotoHandling.PhotoType.Original, strScenery ); List listPhotos = new List(); foreach ( string item in listImages ) { for ( int i = 0; i < listFiles.Count; i++ ) { // 文件名; string name = System.IO.Path.GetFileName( listFiles[i] ).Remove( 0, 9 /*'Original_'*/); if ( item.ToUpper() == name.ToUpper() ) { listPhotos.Add( listFiles[i] ); listFiles.RemoveAt( i ); break; } } } return listPhotos; } catch { // 可能字符串转枚举时出错了; } return null; } /// /// 从目录中加载任务文件; /// public static void LoadOssTask() { if ( !System.IO.Directory.Exists( JsonOssTask.TaskJsonPath ) ) { System.IO.Directory.CreateDirectory( JsonOssTask.TaskJsonPath ); return; } // 加载任务文件; string strJson = null; var files = System.IO.Directory.GetFiles( JsonOssTask.TaskJsonPath, "*.Json" ); foreach ( var file in files ) { strJson = System.IO.File.ReadAllText( file ); try { if ( !IsTaskExists( System.IO.Path.GetFileNameWithoutExtension( file ) ) ) { JsonOssTask jsonOssTask = JsonConvert.DeserializeObject( strJson ); PushTask( jsonOssTask ); } } catch { } } // 标识加载过; IsTaskloaded = true; } public static void LoadOssTask2( List listJson ) { // 加载前,先移除之前的; if ( _listOssTask != null ) _listOssTask.Clear(); foreach ( var strJson in listJson ) { try { JsonOssTask jsonOssTask = JsonConvert.DeserializeObject( strJson ); if ( !IsTaskExists( jsonOssTask.TaskID ) ) { PushTask( jsonOssTask ); } } catch ( Exception e ) { System.Diagnostics.Debug.Write( e.Message ); } } // 标识加载过; IsTaskloaded = true; } /// /// 任务是否存在; /// /// /// public static bool IsTaskExists( JsonOssTask jsonOssTask ) { if ( _listOssTask == null || _listOssTask.Count == 0 ) return false; bool exists = false; foreach ( JsonOssTask task in _listOssTask ) { if ( task.TaskID.ToUpper() == jsonOssTask.TaskID.ToUpper() ) { exists = true; break; } } return exists; } public static bool IsTaskExists( string strTaskID ) { if ( _listOssTask == null || _listOssTask.Count == 0 ) return false; bool exists = false; foreach ( JsonOssTask task in _listOssTask ) { if ( task.TaskID.ToUpper() == strTaskID.ToUpper() ) { exists = true; break; } } return exists; } /// /// 将新任务压入任务队列; /// /// /// public static void PushTask( JsonOssTask jsonOssTask ) { if ( jsonOssTask == null ) return; lock ( _lockJson ) { if ( _listOssTask == null ) _listOssTask = new List(); if ( !IsTaskExists( jsonOssTask ) ) { jsonOssTask.IsWorking = false; _listOssTask.Add( jsonOssTask ); } } } /// /// 取出任务,先进先出方式; /// /// public static JsonOssTask PopTask() { if ( _listOssTask == null || _listOssTask.Count == 0 ) return null; lock ( _lockJson ) { /* // 先进先出; JsonOssTask jsonOssTask = _listOssTask.Last(); // 从任务队列中移除; _listOssTask.RemoveAt( _listOssTask.Count - 1 ); */ // 先进先出,找到可以开始的任务; JsonOssTask jsonOssTask = null; for ( int i = _listOssTask.Count - 1; i > -1; i-- ) { if ( !_listOssTask[i].IsWorking // 正在运行的任务; && _listOssTask[i].MyTask != null // 被开始的任务; && string.IsNullOrEmpty( _listOssTask[i].FinishedTime ) // 未完成的任务; ) { jsonOssTask = _listOssTask[i]; break; } } return jsonOssTask; } } /// /// 删除一个任务(删除前,如果任务在进行,必须停止任务); /// /// 订单号+相片类型+拍摄景点的MD5值, 也是文件名 public static void RemoveTask( string taskID ) { if ( _listOssTask == null || _listOssTask.Count == 0 ) return; lock ( _lockJson ) { JsonOssTask jsonOssTask = null; for ( int i = _listOssTask.Count - 1; i > -1; i-- ) { jsonOssTask = _listOssTask[i]; if ( taskID.ToUpper() == jsonOssTask.TaskID.ToUpper() ) { _listOssTask.RemoveAt( i ); break; } } } } public static void RemoveTask( JsonOssTask ossTask ) { if ( _listOssTask == null || _listOssTask.Count == 0 ) return; lock ( _lockJson ) { JsonOssTask jsonOssTask = null; for ( int i = _listOssTask.Count - 1; i > -1; i-- ) { jsonOssTask = _listOssTask[i]; if ( ossTask == jsonOssTask ) { _listOssTask.RemoveAt( i ); // 并且移除任务文件; DeleteTaskFile( jsonOssTask.TaskID ); break; } } } } /// /// 删除任务文件; /// /// public static void DeleteTaskFile( string strTaskID ) { try { string taskfile = string.Format( "{0}{1}.Json", JsonOssTask.TaskJsonPath, strTaskID ); if ( System.IO.File.Exists( taskfile ) ) System.IO.File.Delete( taskfile ); } catch { // 可能没有权限删除,或都文件被占用; } } /// /// 启动线程; /// public static void StartThread() { if ( _thread == null ) { _thread = new System.Threading.Thread( TaskThread ); _thread.Start(); } } /// /// 任务线程; /// private static void TaskThread() { JsonOssTask ossTask = null; while ( true ) { if ( _listOssTask == null || _listOssTask.Count == 0 ) { Thread.Sleep( 150 ); continue; } // 弹出一个未执行的任务; ossTask = PopTask(); if ( ossTask != null && string.IsNullOrEmpty( ossTask.FinishedTime ) && !ossTask.IsWorking ) { ossTask.StartTask(); try { while ( !ossTask.MyTask.IsCompleted ) {// 等待任务完成; Thread.Sleep( 150 ); } } catch { // 异常时,表示任务被取消; } // 如果任务未完成,再次入队列中; if ( string.IsNullOrEmpty( ossTask.FinishedTime ) ) { PushTask( ossTask ); } } } } public delegate void SetRowTextDelegate( string md5, string pro, string time ); /// /// 设置datagridview行文本; /// /// 进度文本 /// 完成时间 public void SetRowText( string md5, string pro, string time ) { if ( this.dgv.InvokeRequired ) { SetRowTextDelegate setRowText = new SetRowTextDelegate( SetRowText ); this.dgv.Invoke( setRowText, md5, pro, time ); } else { JsonOssTask jsonOssTask = null; foreach ( DataGridViewRow item in this.dgv.Rows ) { jsonOssTask = (JsonOssTask)item.Tag; if ( jsonOssTask != null && jsonOssTask.TaskID.ToUpper() == md5.ToUpper() ) { item.Cells[7].Value = pro; item.Cells[8].Value = time; // 如果已经完成,生成连接; PaddingUrl( jsonOssTask, item ); } } } } #endregion } [Serializable] /// /// Json格式的OSS任务; /// public class JsonOssTask { /// /// 任务是否运行; /// [JsonIgnore] public bool IsWorking { get; set; } = false; [JsonIgnore] public Task MyTask { get; set; } = null; [JsonIgnore] public CancellationTokenSource MyCancellationTokenSource { get; set; } = null; [JsonIgnore] // 上传下载oss的执行对象; private UploadOssCloudDisk _uploadOss = new UploadOssCloudDisk(); [JsonIgnore] public static string TaskJsonPath { get; } = LYFZ.WinAPI.CustomPublicMethod.GetFullDirectoryPath( LYFZ.WinAPI.CustomPublicMethod.BasePath ) + "Temp\\.OssTask\\"; /// /// 任务ID值(由企业ID+分店ID+订单号+相片类型+拍摄名称计算); /// public string TaskID { get; set; } = ""; /// /// 对象存储类型: 0 = 阿里云(默认), 1 = 腾讯云, 2 = 手动百度云分享;; /// public int OsType { get; set; } = 0; /// /// 百度云分享链接; /// public string BaiduShareUrl { get; set; } = ""; /// /// 百度提取码; /// public string BaiduExtrCode { get; set; } = ""; /// /// 可下载到期日期; /// public string DownloadExpireTime { get; set; } = ""; /// /// 自定义下载次数; /// public int CustomizeDownloadTimes { get; set; } = 1; /// /// 企业ID; /// public string EnterpriseID { get; set; } = ""; /// /// 上传分店ID,即本店ID; /// public string UploadBranchID { get; set; } = ""; /// /// 下载分店串,前后都必须使用#分隔,如:"#SSN001#SSN002#SSN003#" /// public string DownloadBranchIDs { get; set; } = ""; /// /// 订单号; /// public string OrderNumber { get; set; } = ""; /// /// 子订单号; /// public string OrderViceNumber { get; set; } = ""; /// /// 订单类型; /// public string OrderType { get; set; } = ""; /// /// 顾客姓名; /// public string CusNames { get; set; } = ""; /// /// 顾客性别; /// public string CusGenders { get; set; } = ""; /// /// 顾客性别; /// public string CusPhones { get; set; } = ""; /// /// 拍摄名称; /// public string ShootName { get; set; } = ""; /// /// 像片类型 <固定以下字符串:"原片,初修,精修,设计,已选">; /// public string PhotosType { get; set; } = ""; /// /// 已上传的相片数量; /// public int PhotoCount { get; set; } = 0; /// /// 已上传的相片总大小; /// public ulong PhotoSize { get; set; } = 0; /// /// 上传的大小(不包含已存在的,即Status=1); /// public ulong UploadedSize { get; set; } = 0; /// /// 上传完成时间(可以作为完成状态使用, 只有全部相片上传完了,才能设置时间); /// public string FinishedTime { get; set; } = ""; [JsonIgnore] /// /// 客户要上传至云的相片集合; /// public List listPhotos { get; set; } = null; public List ArrayPhotos { get; set; } = null; /// /// 开始任务; /// public void StartTask() { if ( !MarkTask() ) { MessageBoxCustom.Show( "仍有相片在上传,重新开始失败!" ); return; } MyTask.Start(); IsWorking = true; } /// /// 标记任务为可执行状态,等待执行; /// public bool MarkTask() { if ( MyTask == null || MyTask.Status == TaskStatus.RanToCompletion ) { MyCancellationTokenSource = new CancellationTokenSource(); MyTask = new Task( () => TaskWorking( this, MyCancellationTokenSource.Token ), MyCancellationTokenSource.Token ); return true; } return false; } /// /// 停止任务; /// public void StopTask() { if ( MyTask != null && MyCancellationTokenSource != null ) { IsWorking = false; MyCancellationTokenSource.Cancel(); } } /// /// 任务函数; /// /// /// public static void TaskWorking( JsonOssTask ossTask, CancellationToken ct ) { // 参数校验; if ( ossTask.listPhotos == null || ossTask.listPhotos.Count == 0 ) { ossTask.IsWorking = false; return; } // 开始上传; Int64 nCompleteSize = 0; int nCompleteCount = 0; PhotoItem photoItem = null; for ( int i = ossTask.listPhotos.Count - 1; i > -1 && !ct.IsCancellationRequested; i-- ) { photoItem = ossTask.listPhotos[i]; if ( string.IsNullOrEmpty( photoItem.PhotoUrl ) ) { OSSUpdateReturnData returnData = ossTask._uploadOss.UpLoadFile( photoItem.PhotoName, OssCloudDiskFileType.PhotoCloudBackup, null ); if ( returnData.State ) { photoItem.PhotoUrl = returnData.OssFileWebUrl; // 将文件路径替换成key值; //photoItem.PhotoName = returnData.OssFileKey; // 将文件路径替换成文件名; photoItem.PhotoName = System.IO.Path.GetFileNameWithoutExtension( photoItem.PhotoName ).Replace( BLL.SelectPhotoHandling.PhotoType.Original.ToString() + "_", "" ); ++nCompleteCount; nCompleteSize += photoItem.PhotoSize; } } else { ++nCompleteCount; nCompleteSize += photoItem.PhotoSize; } // 更新界面的进度; RefreshUI( ossTask, nCompleteCount ); } // 如果全部上传完成,生成完成时间,并且保存到文件中; if ( nCompleteCount == ossTask.listPhotos.Count && string.IsNullOrEmpty( ossTask.FinishedTime ) ) { try { ossTask.FinishedTime = DateTime.Now.ToString( "yyyy-MM-dd HH:mm:ss" ); string strJson = JsonConvert.SerializeObject( ossTask.listPhotos ); // 向服务器发送Json数据,Post发送; string url = "http://xiangpianxiazai.lyfz.net:8090/Upload.aspx"; //string url = "http://localhost:60336/Upload.aspx"; string post_date = string.Format( "EntID={0}&OrderNumber={1}&ShootName={2}&PhotoType={3}&PhotoCount={4}&PhotoSize={5}&TaskMD5={6}&TaskJson={7}", ossTask.EnterpriseID, ossTask.OrderNumber, ossTask.ShootName, ossTask.PhotosType, nCompleteCount, nCompleteSize, ossTask.TaskID, strJson ); string strResult = LYFZ.WinAPI.CustomPublicMethod.HttpWebRequestPOST( url, post_date, Encoding.UTF8 ); try { ResultCode resultCode = JsonConvert.DeserializeObject( strResult ); //if ( resultCode.Status == 200 ) if ( true ) { // 写入文件; if ( !System.IO.Directory.Exists( JsonOssTask.TaskJsonPath ) ) System.IO.Directory.CreateDirectory( JsonOssTask.TaskJsonPath ); strJson = JsonConvert.SerializeObject( ossTask ); System.IO.File.WriteAllText( JsonOssTask.TaskJsonPath + ossTask.TaskID + ".Json", strJson ); } else { // 上传失败; ossTask.FinishedTime = ""; } } catch { // 上传失败; ossTask.FinishedTime = ""; } } catch { } // 更新界面的进度; RefreshUI( ossTask, nCompleteCount ); // 任务置为false; ossTask.IsWorking = false; } } /// /// 刷新UI; /// /// /// public static void RefreshUI( JsonOssTask ossTask, int nCompleteCount ) { try { if ( frmOssTask.MyfrmOssTask != null ) { frmOssTask.MyfrmOssTask.SetRowText( ossTask.TaskID, string.Format( "{0}/{1}", nCompleteCount, ossTask.listPhotos.Count ), ossTask.FinishedTime ); } } catch { // 可能界面被关闭后, SetRowText函数未执行完, 导致异常发生; } } } [Serializable] public class PhotoArray { /// /// 相片类型:选好的原片, 选好的初修, 原片, 初修, 精修, 设计; /// public string PhotosType { get; set; } = ""; /// /// 相片集合; /// public List ListPhotos { get; set; } = null; } [Serializable] /// /// 嵌套类,作为子项; /// public class PhotoItem { public PhotoItem() { } public PhotoItem( string path, long size, string url ) { PhotoName = path; PhotoSize = size; PhotoUrl = url; DownloadTimes = 0; } public PhotoItem( string name, string path, long size, string url ) { PhotoName = name; PhotoSize = size; PhotoUrl = url; DownloadTimes = 0; PhotoPath = path; } /// /// 上传状态: -1,无状态, 0, 不存在, 1,已存在, 2,已上传; /// //public int Status { get; set; } = -1; /// /// 相片路径; /// public string PhotoName { get; set; } = ""; /// /// 相片的文件路径, 用于分店下载时,保存到指定的路径; /// public string PhotoPath { get; set; } = ""; /// /// 相片大小; /// public long PhotoSize { get; set; } = 0; /// /// 相片上传完成后的Oss Key值; /// public string PhotoKey { get; set; } = ""; // url有限制有限期; /// /// 上传成功后,记录下来的oss链接地址(可以作为上传状态使用, 只有上传成的相片,才有url地址); /// public string PhotoUrl { get; set; } = ""; /// /// 该相片被下载的次数; /// public int DownloadTimes { get; set; } = 0; } [Serializable] public class BaiduInfo { public string BaiduShareUrl { get; set; } = ""; public string BaiduExtrCode { get; set; } = ""; } public class ResultCode { /// /// 状态,200为成功; /// public int code { get; set; } = 201; /// /// 描述; /// public string info { get; set; } = ""; public class ServeData { public int StatusCode { get; set; } = 0; public bool Status { get; set; } = false; public string StatusMsg { get; set; } = ""; } public ServeData data { get; set; } = new ServeData(); } }