using DAL.Redis; using Ninject; using System; using System.Configuration; using System.IO; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Web; using System.Threading.Tasks; using System.Web; using WX.CRM.Common; using WX.CRM.DAL.Redis; using WX.CRM.IBLL.Wx; using WX.CRM.Model.DTO; using WX.CRM.Model.Entity; using WX.CRM.Model.Enum; using WX.CRM.WebHelper.Infrastructure; namespace WxService { // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“WxFilePath”。 // 注意: 为了启动 WCF 测试客户端以测试此服务,请在解决方案资源管理器中选择 WxFilePath.svc 或 WxFilePath.svc.cs,然后开始调试。 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")] public class FilePath : IFilePath { private IWX_DBUPLOADLOG dbpubliclog = NinjectControllerFactory.ninjectKernel.Get(); private IWX_RCONTACT rcontact = NinjectControllerFactory.ninjectKernel.Get(); private IWx_MsgKey msgkey = NinjectControllerFactory.ninjectKernel.Get(); private readonly PubSub _sub = new PubSub(); private static string _isSaveUploadFile; public FilePath() { _isSaveUploadFile = Utility.GetSettingOrNullByKey("IsSaveUploadFile"); } public async Task> GetPath(string msgSvrId) { try { var host = ConfigurationManager.AppSettings["fileHost"] ?? "http://192.168.1.45:809"; string keyname = "wx:" + msgSvrId; RedisString redis = new RedisString(keyname); var filePath = await redis.GetAsync(); if (string.IsNullOrEmpty(filePath)) { filePath = msgkey.GetFile(keyname);//如果redis查找不到,就从数据库中查找一次 } if (string.IsNullOrEmpty(filePath)) return new JsonResult() { result = true, retcode = 100, retmsg = filePath }; return new JsonResult() { result = true, retcode = 200, retmsg = "" + msgSvrId + "_" + host + filePath }; } catch (Exception ex) { LogHelper.Error(ex.ToString()); return new JsonResult() { result = false, retcode = 50, retmsg = "系统错误" }; } } public async Task> Get(string msgSvrId, string fileName) { try { string md5 = string.Empty; if (fileName.IndexOf(".") == -1) { md5 = fileName; } else { md5 = fileName.Substring(0, fileName.LastIndexOf(".")); } //string keyname = "wx:" + msgSvrId; //RedisString redis = new RedisString(keyname); //var ret = await redis.GetAsync(); //if (string.IsNullOrEmpty(ret)) //{ string ret = msgkey.HasOrAddFileMd5Relation(md5, msgSvrId);//如果redis查找不到,就从数据库中查找一次 //} if (string.IsNullOrEmpty(ret)) { return new JsonResult() { result = true, retcode = 100, retmsg = msgSvrId }; } //PushRedis(msgSvrId, fileName);//先去除 return new JsonResult() { result = true, retcode = 200, retmsg = msgSvrId }; } catch (Exception ex) { LogHelper.Error(ex.ToString()); return new JsonResult() { result = false, retcode = 50, retmsg = "系统错误" }; } } public void Upload(Stream input, string msgSvrId, string fileName) { try { #region 上传文件 if (!input.CanRead) { throw new Exception("数据流不可读!"); } if ((!string.IsNullOrEmpty(_isSaveUploadFile) && _isSaveUploadFile == "0")) { var yearMonth = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString(); string uploadFolder = (ConfigurationManager.AppSettings["uploadfile"] ?? "uploadfile") + "/" + yearMonth; //string savaPath = "uploadfile/" + yearMonth; //string uploadFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, savaPath); //Stream sourceStream = request.FileData; FileStream targetStream = null; if (!Directory.Exists(uploadFolder)) { Directory.CreateDirectory(uploadFolder); } string filePath = Path.Combine(uploadFolder, fileName); using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None)) { const int bufferLen = 4096; byte[] buffer = new byte[bufferLen]; int count = 0; while ((count = input.Read(buffer, 0, bufferLen)) > 0) { targetStream.Write(buffer, 0, count); } targetStream.Close(); input.Close(); } } #endregion #region 写入数据库 PushRedis(msgSvrId, fileName); #endregion HttpContext.Current.Response.Write(Utility.ObjectToJson(new { result = true, message = "接收成功", url = fileName })); } catch (Exception ex) { LogHelper.Error(ex.ToString()); HttpContext.Current.Response.Write(Utility.ObjectToJson(new { result = false, message = "接收失败:" + ex.Message })); } } private async void PushRedis(string msgSvrId, string fileName) { await PushRedisAsync(msgSvrId, fileName); } private async Task PushRedisAsync(string msgSvrId, string fileName) { var redisKey = "wx:" + msgSvrId; var fileWebUrl = "/uploadfile/" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + "/" + fileName; var model = new wxfilepath { MsgSvrId = long.Parse(msgSvrId), FileName = redisKey, FileUrl = fileWebUrl, CTime = DateTime.Now }; RedisString rdb = new RedisString(redisKey); await rdb.SetAsync(fileWebUrl); await PushRedisAndPublish(model, "filepath"); } private async Task PushRedisAndPublish(T model, string key) { //写入队列 var result = await new RedisList().LeftPushAsync(key, model); if (result > 0) { //发送订阅通知 await _sub.PublishAsync("sub:" + key, ""); } } public void DbUpload(Stream input, string username, string password, string copytime) { try { //LogHelper.Info(string.Format("username:{0},password:{1},copytime:{2}", username, password, copytime)); #region 上传文件 if (!input.CanRead) { throw new Exception("数据流不可读!"); } if (string.IsNullOrEmpty(username)) { throw new Exception("username不能为空!"); } var yearMonth = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString(); string uploadFolder = (ConfigurationManager.AppSettings["dbuploadfile"] ?? "dbuploadfile") + "/" + yearMonth; //string savaPath = "uploadfile/" + yearMonth; //string uploadFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, savaPath); //Stream sourceStream = request.FileData; FileStream targetStream = null; if (!Directory.Exists(uploadFolder)) { Directory.CreateDirectory(uploadFolder); } string timejiewei = DateTime.Now.ToString("yyMMddhhmmss"); string fileName = string.Format("{0}-{1}-{2}.db", username, password, timejiewei); string filePath = Path.Combine(uploadFolder, fileName); LogHelper.Info(string.Format("filePath:{0}", filePath)); using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None)) { const int bufferLen = 4096; byte[] buffer = new byte[bufferLen]; int count = 0; while ((count = input.Read(buffer, 0, bufferLen)) > 0) { targetStream.Write(buffer, 0, count); } targetStream.Close(); input.Close(); } WX_DBUPLOADLOG model = new WX_DBUPLOADLOG(); LogHelper.Info("成功否!"); if (!string.IsNullOrEmpty(copytime)) { try { model.COPYTIME = DateTimeTool.GetTimeFromLinuxTime(Convert.ToInt64(copytime)); } catch (Exception ex) { LogHelper.Error(ex.ToString()); } } model.USERNAME = username; model.PASSWORD = password; model.DBFILE = filePath; bool resu = dbpubliclog.Add(model); #endregion if (resu) HttpContext.Current.Response.Write(Utility.ObjectToJson(new { result = true, retcode = (int)EnumInterfaceErrcode.调用成功, retmsg = "接收成功" })); else HttpContext.Current.Response.Write(Utility.ObjectToJson(new { result = false, retcode = (int)EnumInterfaceErrcode.调用成功但有错误, retmsg = "新增数据失败" })); } catch (Exception ex) { LogHelper.Error(ex.ToString()); HttpContext.Current.Response.Write(Utility.ObjectToJson(new { result = false, retcode = (int)EnumInterfaceErrcode.调用成功但有错误, retmsg = "接收失败:" + ex.Message })); } } public void DbUpload2(Stream input, string username, string password, string copytime, string createtime, string qunfaclientid) { try { //LogHelper.Info(string.Format("username:{0},password:{1},copytime:{2},createtime:{3},qunfaclientid{4}", username, password, copytime, createtime, qunfaclientid)); #region 上传文件 if (!input.CanRead) { throw new Exception("数据流不可读!"); } if (string.IsNullOrEmpty(username)) { throw new Exception("username不能为空!"); } var yearMonth = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString(); string uploadFolder = (ConfigurationManager.AppSettings["dbuploadfile"] ?? "dbuploadfile") + "/" + yearMonth; //string savaPath = "uploadfile/" + yearMonth; //string uploadFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, savaPath); //Stream sourceStream = request.FileData; FileStream targetStream = null; if (!Directory.Exists(uploadFolder)) { Directory.CreateDirectory(uploadFolder); } string timejiewei = DateTime.Now.ToString("yyMMddhhmmss"); string fileName = string.Format("{0}-{1}-{2}.db", username, password, timejiewei); string filePath = Path.Combine(uploadFolder, fileName); //LogHelper.Info(string.Format("filePath:{0}", filePath)); using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None)) { const int bufferLen = 4096; byte[] buffer = new byte[bufferLen]; int count = 0; while ((count = input.Read(buffer, 0, bufferLen)) > 0) { targetStream.Write(buffer, 0, count); } targetStream.Close(); input.Close(); } WX_DBUPLOADLOG model = new WX_DBUPLOADLOG(); //LogHelper.Info("成功否!"); if (!string.IsNullOrEmpty(copytime)) { try { model.COPYTIME = DateTimeTool.GetTimeFromLinuxTime(Convert.ToInt64(copytime)); } catch (Exception ex) { LogHelper.Error(ex.ToString()); } } model.USERNAME = username; model.PASSWORD = password; model.DBFILE = filePath; long createTimeL = 0; if (!string.IsNullOrEmpty(copytime)) { createTimeL = Convert.ToInt64(createtime); } DateTime createTimeT = DateTimeTool.GetTimeFromLinuxTime(createTimeL); bool resu = rcontact.WxDbUploadLog(model, createTimeL, createTimeT, qunfaclientid); #endregion if (resu) HttpContext.Current.Response.Write(Utility.ObjectToJson(new { result = true, retcode = (int)EnumInterfaceErrcode.调用成功, retmsg = "接收成功" })); else HttpContext.Current.Response.Write(Utility.ObjectToJson(new { result = false, retcode = (int)EnumInterfaceErrcode.调用成功但有错误, retmsg = "新增数据失败" })); } catch (Exception ex) { LogHelper.Error(ex.ToString()); HttpContext.Current.Response.Write(Utility.ObjectToJson(new { result = false, retcode = (int)EnumInterfaceErrcode.调用成功但有错误, retmsg = "接收失败:" + ex.Message })); } } } [ServiceContract] public interface IFilePath { [OperationContract] [WebInvoke(Method = "*", //RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetPath/{msgSvrId}")] Task> GetPath(string msgSvrId); [OperationContract] [WebInvoke(Method = "*", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "Get/{msgSvrId}/{fileName}")] Task> Get(string msgSvrId, string fileName); [OperationContract] [WebInvoke(Method = "*", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "Upload/{msgSvrId}/{fileName}")] void Upload(Stream input, string msgSvrId, string fileName); [OperationContract] [WebInvoke(Method = "*", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "DbUpload/{username}/{password}/{copytime}")] void DbUpload(Stream input, string username, string password, string copytime); [OperationContract] [WebInvoke(Method = "*", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "DbUpload2/{username}/{password}/{copytime}/{createtime}/{qunfaclientid}")] void DbUpload2(Stream input, string username, string password, string copytime, string createtime, string qunfaclientid); } }