Browse Source

基本更新完成

lqq 7 years ago
parent
commit
e871326700

+ 9 - 1
Winsoft.GOV.WXAuth/Controllers/MessageController.cs

@@ -10,6 +10,7 @@ using Microsoft.Extensions.Options;
 using Winsoft.GOV.WXAuth.Models;
 using System.Text;
 using Winsoft.GOV.WXAuth.Filters;
+using Microsoft.Extensions.Logging;
 
 // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
 
@@ -20,10 +21,12 @@ namespace Winsoft.GOV.WXAuth.Controllers
     {
         private SenparcWeixinSetting _senparcWeixinSetting;
         private List<WhiteIP> _whiteList;
-        public MessageController(IOptions<SenparcWeixinSetting> senparcWeixinSetting, IOptions<List<WhiteIP>> whiteList)
+        private ILogger _logger;
+        public MessageController(IOptions<SenparcWeixinSetting> senparcWeixinSetting, IOptions<List<WhiteIP>> whiteList, ILogger<MessageController> logger)
         {
             _senparcWeixinSetting = senparcWeixinSetting.Value;
             _whiteList = whiteList.Value;
+            _logger = logger;
         }
 
         // POST api/values
@@ -37,10 +40,15 @@ namespace Winsoft.GOV.WXAuth.Controllers
                 if (r.errcode == ReturnCode.请求成功)
                     return Ok();
                 else
+                {
+                    _logger.LogError(r.errcode.ToString());
                     return BadRequest(r.errcode.ToString());
+                }
+                    
             }
             catch(Exception e)
             {
+                _logger.LogError(e.Message);
                 return BadRequest(HttpContext.Connection.RemoteIpAddress.ToString());
             }
         }

+ 1 - 1
Winsoft.GOV.WXAuth/Filters/IPFilterAttribute.cs

@@ -22,7 +22,7 @@ namespace Winsoft.GOV.WXAuth.Filters
 
         public override void OnActionExecuted(ActionExecutedContext context)
         {
-            _logger.LogInformation(context.HttpContext.Connection.RemoteIpAddress.ToString());
+            _logger.LogInformation("请求IP:"+context.HttpContext.Connection.RemoteIpAddress.ToString());
             if (!_whiteList.Value.Exists(e => e.IP.Equals(context.HttpContext.Connection.RemoteIpAddress.ToString(), StringComparison.CurrentCultureIgnoreCase)))
                 context.Result = new BadRequestObjectResult(_whiteList.Value.Count);
         }

+ 39 - 20
Winsoft.GOV.XF.WebApi.WXCore/Controllers/BundleController.cs

@@ -30,16 +30,19 @@ namespace Winsoft.GOV.XF.WebApi.WXCore.Controllers
         AssetsService _assetsService;
         ImagesService _imagesService;
         XFApiService _xfApiService;
+        WXApiService _wxApiService;
         public BundleController(IOptions<SenparcWeixinSetting> senparcWeixinSetting, 
             ILoggerFactory loggerFactory, UsersService usersService, 
             BundlesService bundlesService, AssetsService assetsService,
-            ImagesService imagesService, XFApiService xfApiService) : base(senparcWeixinSetting, loggerFactory)
+            ImagesService imagesService, XFApiService xfApiService, 
+            WXApiService wxApiService) : base(senparcWeixinSetting, loggerFactory)
         {
             _usersService = usersService;
             _bundlesService = bundlesService;
             _assetsService = assetsService;
             _imagesService = imagesService;
             _xfApiService = xfApiService;
+            _wxApiService = wxApiService;
         }
         // GET: api/values
         [HttpGet("{id}")]
@@ -86,6 +89,22 @@ namespace Winsoft.GOV.XF.WebApi.WXCore.Controllers
             return Ok(b);
         }
 
+        [HttpGet("QueryEvaluate/{id}")]
+        [Produces(typeof(EvaluateModel))]
+        [WeixinInternalRequest("访问被拒绝,请通过微信客户端访问!", "nofilter")]
+        [WXOAuthCheck(appId: null, oauthCallbackUrl: "api/Auth")]
+        public async Task<IActionResult> QueryEvaluate(string id)
+        {
+            Bundle b = await _bundlesService.Get(id);
+            if (b == null)
+                return BadRequest();
+            string msg;
+            EvaluateModel e = await _xfApiService.QueryEvaluate(b.SearchCode, m => msg = m);
+            if (e == null)
+                return BadRequest();
+            return Ok(e);
+        }
+
         //[HttpGet("reply/{id}")]
         //[Produces(typeof(Bundle))]
         //[WeixinInternalRequest("访问被拒绝,请通过微信客户端访问!", "nofilter")]
@@ -110,7 +129,6 @@ namespace Winsoft.GOV.XF.WebApi.WXCore.Controllers
         //    return Ok(b);
         //}
 
-
         [HttpGet("bySearchCode/{searchCode}")]
         [Produces(typeof(Bundle))]
         [WeixinInternalRequest("访问被拒绝,请通过微信客户端访问!", "nofilter")]
@@ -177,23 +195,23 @@ namespace Winsoft.GOV.XF.WebApi.WXCore.Controllers
         //    return Ok(r);
         //}
 
-        [HttpGet("queryEvaluate/{id}")]
-        [Produces(typeof(EvaluateModel))]
-        [WeixinInternalRequest("访问被拒绝,请通过微信客户端访问!", "nofilter")]
-        [WXOAuthCheck(appId: null, oauthCallbackUrl: "api/Auth")]
-        public async Task<IActionResult> IsEvaluate(string id)
-        {
-            string failsMessage = String.Empty;
-            if (String.IsNullOrEmpty(id))
-                return BadRequest("此信访信件不正确");
-            Bundle b = await _bundlesService.Get(id);
-            if (b == null && String.IsNullOrEmpty(b.SearchCode))
-                return BadRequest("此信访信件异常");
-            //if (!await _xfApiService.IsEvaluate(b.LetterId, m => failsMessage = m))
-            //    return BadRequest("还不能对此信件的办理结果评价");
-            EvaluateModel r = await _xfApiService.QueryEvaluate(b.SearchCode, m => failsMessage = m);
-            return Ok(r);
-        }
+        //[HttpGet("IsEvaluate/{id}")]
+        //[Produces(typeof(EvaluateModel))]
+        //[WeixinInternalRequest("访问被拒绝,请通过微信客户端访问!", "nofilter")]
+        //[WXOAuthCheck(appId: null, oauthCallbackUrl: "api/Auth")]
+        //public async Task<IActionResult> IsEvaluate(string id)
+        //{
+        //    string failsMessage = String.Empty;
+        //    if (String.IsNullOrEmpty(id))
+        //        return BadRequest("此信访信件不正确");
+        //    Bundle b = await _bundlesService.Get(id);
+        //    if (b == null && String.IsNullOrEmpty(b.SearchCode))
+        //        return BadRequest("此信访信件异常");
+        //    if (!await _xfApiService.IsEvaluate(b.LetterId, m => failsMessage = m))
+        //        return BadRequest("还不能对此信件的办理结果评价");
+        //    //EvaluateModel r = await _xfApiService.QueryEvaluate(b.SearchCode, m => failsMessage = m);
+        //    return Ok(r);
+        //}
 
         [HttpGet("all")]
         [Produces(typeof(IEnumerable<Bundle>))]
@@ -300,7 +318,8 @@ namespace Winsoft.GOV.XF.WebApi.WXCore.Controllers
             await _bundlesService.Add(value);
             if (await _xfApiService.PostLetter(value, HttpContext.Request.Cookies["BaseUrl"], e => failsMessage = e))
             {
-                
+                await _xfApiService.PostAssets(value);
+                await _wxApiService.Notify(value.OpenID, String.Format("感谢您的来信,请记住您的信件查询码。通过查询码,您可以在浙江政务服务网上查询该信件的受理情况。同样,您可以在我们丽水微信端的12345政务咨询投诉举报平台上的“结果查询”中,查看信件的受理情况。\n查询码:{0}", value.SearchCode));
                 return Ok();
             }
             await _bundlesService.Delete(value);

+ 6 - 1
Winsoft.GOV.XF.WebApi.WXCore/Controllers/HomeController.cs

@@ -21,9 +21,11 @@ namespace Winsoft.GOV.XF.WebApi.WXCore.Controllers
     public class HomeController : BaseController
     {
         UsersService _usersService;
-        public HomeController(IOptions<SenparcWeixinSetting> senparcWeixinSetting, ILoggerFactory loggerFactory, UsersService usersService) : base(senparcWeixinSetting, loggerFactory)
+        WXApiService _wxApiService;
+        public HomeController(IOptions<SenparcWeixinSetting> senparcWeixinSetting, ILoggerFactory loggerFactory, UsersService usersService, WXApiService wxApiService) : base(senparcWeixinSetting, loggerFactory)
         {
             _usersService = usersService;
+            _wxApiService = wxApiService;
         }
         // GET: /<controller>/
         [WeixinInternalRequest("访问被拒绝,请通过微信客户端访问!", "nofilter")]
@@ -35,6 +37,9 @@ namespace Winsoft.GOV.XF.WebApi.WXCore.Controllers
             if (u != null)
                 HttpContext.Response.Cookies.Append("User", JsonConvert.SerializeObject(u));
             HttpContext.Response.Cookies.Append("BaseUrl", HttpContext.Request.GetBaseURL());
+            //await _wxApiService.Notify(HttpContext.Session.GetString("OpenId"),
+            //    String.Format("{0},欢迎您访问丽水市12345建议投诉举报平台!", u.Nickname));
+
             return Redirect(HttpContext.Request.GetBaseURL()+ "web12345/index.html");
         }
 

+ 6 - 0
Winsoft.GOV.XF.WebApi.WXCore/Models/Asset.cs

@@ -26,5 +26,11 @@ namespace Winsoft.GOV.XF.WebApi.WXCore.Models
         public string Data { get; set; }
         [JsonConverter(typeof(ChinaDateTimeConverter))]
         public DateTime CreateDate { get; set; }
+        [NotMapped]
+        [JsonIgnore]
+        public byte[] FileBytes { set; get; }
+        [NotMapped]
+        [JsonIgnore]
+        public string FileName { get; set; }
     }
 }

+ 26 - 8
Winsoft.GOV.XF.WebApi.WXCore/Services/BundlesService.cs

@@ -44,7 +44,7 @@ namespace Winsoft.GOV.XF.WebApi.WXCore.Services
             Guid g;
             if (!String.IsNullOrWhiteSpace(id) && Guid.TryParse(id, out g))
             {
-                Bundle b = await _context.Bundles.SingleOrDefaultAsync<Bundle>(m => m.Id == g);
+                Bundle b = await _context.Bundles.AsNoTracking().SingleOrDefaultAsync<Bundle>(m => m.Id == g);
                 if (b != null && b.Assets == null)
                     b.Assets = await _context.Assets.Where(m => m.BundleId == g).AsNoTracking().ToArrayAsync<Asset>();
                 Logger.LogInformation("多媒体资源数是{0}", b.Assets.Count());
@@ -88,7 +88,12 @@ namespace Winsoft.GOV.XF.WebApi.WXCore.Services
         {
             if (b != null)
             {
-                _context.Entry(b).Property(x => x.SearchCode).IsModified = true;
+                Bundle b2 = new Bundle()
+                {
+                    Id = b.Id,
+                    SearchCode = b.SearchCode
+                };
+                _context.Entry(b2).Property(x => x.SearchCode).IsModified = true;
                 await _context.SaveChangesAsync();
             }
         }
@@ -96,11 +101,19 @@ namespace Winsoft.GOV.XF.WebApi.WXCore.Services
         public async Task UpdateReply(Bundle b)
         {
             if (b != null)
-            {                               
-                _context.Entry(b).Property(x => x.LetterId).IsModified = true;
-                _context.Entry(b).Property(x => x.Reply).IsModified = true;
-                _context.Entry(b).Property(x => x.ResultFromXF).IsModified = true;
-                _context.Entry(b).Property(x => x.Status).IsModified = true;
+            {
+                Bundle b2 = new Bundle()
+                {
+                    Id = b.Id,
+                    LetterId = b.LetterId,
+                    Reply = b.Reply,
+                    ResultFromXF = b.ResultFromXF,
+                    Status = b.Status
+                };
+                _context.Entry(b2).Property(x => x.LetterId).IsModified = true;
+                _context.Entry(b2).Property(x => x.Reply).IsModified = true;
+                _context.Entry(b2).Property(x => x.ResultFromXF).IsModified = true;
+                _context.Entry(b2).Property(x => x.Status).IsModified = true;
                 //_context.Bundles.Update(b);
                 await _context.SaveChangesAsync();
              }
@@ -110,7 +123,12 @@ namespace Winsoft.GOV.XF.WebApi.WXCore.Services
         {
             if (b != null)
             {
-                _context.Entry(b).Property(x => x.Status).IsModified = true;
+                Bundle b2 = new Bundle()
+                {
+                    Id = b.Id,
+                    IsAssessed = b.IsAssessed
+                };
+                _context.Entry(b2).Property(x => x.IsAssessed).IsModified = true;
                 await _context.SaveChangesAsync();
             }              
 

+ 2 - 0
Winsoft.GOV.XF.WebApi.WXCore/Services/ImagesService.cs

@@ -33,6 +33,8 @@ namespace Winsoft.GOV.XF.WebApi.WXCore.Services
             string base64Str = Regex.Replace(a.Data, @"data:image/(\S+);base64,", "");
             byte[] bt = Convert.FromBase64String(base64Str);
             string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff.") + exName;
+            a.FileBytes = bt;
+            a.FileName = filename;
             string diskPath = "";
             string absPath = "";
             GetUploadPath(out diskPath, out absPath);

+ 74 - 0
Winsoft.GOV.XF.WebApi.WXCore/Services/WXApiService.cs

@@ -0,0 +1,74 @@
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.Logging;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Text;
+using System.Threading.Tasks;
+using Winsoft.GOV.XF.WebApi.WXCore.Data;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+
+namespace Winsoft.GOV.XF.WebApi.WXCore.Services
+{
+    public class WXApiService : BaseService
+    {
+        public WXApiService(XFDbContext context, ILoggerFactory loggerFactory, IConfigurationRoot config): base(context, loggerFactory, config)
+        {
+
+        }
+
+        public async Task Notify(string openId, string msg)
+        {
+            Logger.LogInformation(await HttpPostAsync(_config["WXApi"] + "/api/Message", "{\"OpenId\":\"" + openId + "\",\"Content\":\"" + msg + "\"}"));
+        }
+
+        private async Task<string> HttpPostAsync(string url, string data)
+        {
+            try
+            {
+                Logger.LogInformation(url);
+
+                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
+                Encoding encoding = Encoding.UTF8;
+                string param = data;
+                byte[] bs = Encoding.UTF8.GetBytes(param.ToString());
+                //byte[] bs = new byte[]{};  
+                string responseData = String.Empty;
+                req.Method = "POST";
+               
+                req.ContentType = "application/json;charset=utf-8";
+                req.ContentLength = bs.Length;
+                //return;  
+                using (Stream reqStream = req.GetRequestStream())
+                {
+                    reqStream.Write(bs, 0, bs.Length);
+                    reqStream.Close();
+                }
+
+                using (HttpWebResponse response = (HttpWebResponse)await req.GetResponseAsync())
+                {
+                    return GetResponseAsString(response);
+                }
+            }
+            catch (Exception ex)
+            {
+                Logger.LogError("微信接口POST错误:{0}", ex.Message);
+                return String.Empty;
+            }
+        }
+
+        private string GetResponseAsString(HttpWebResponse rsp)
+        {
+            Stream stream = null;
+            StreamReader reader = null;
+
+            // 以字符流的方式读取HTTP响应
+            stream = rsp.GetResponseStream();
+            reader = new StreamReader(stream, Encoding.UTF8);
+            return reader.ReadToEnd();
+        }
+    }
+}

+ 65 - 1
Winsoft.GOV.XF.WebApi.WXCore/Services/XFApiService.cs

@@ -26,6 +26,69 @@ namespace Winsoft.GOV.XF.WebApi.WXCore.Services
         {
             _bundlesService = bundlesService;
         }
+
+        public async Task<bool> PostAssets(Bundle b)
+        {
+            string end = "\r\n";
+            string twoHyphens = "--";
+            string boundary = "*****";
+            byte[] endbyte = Encoding.UTF8.GetBytes(end);
+            byte[] twoHyphensbyte = Encoding.UTF8.GetBytes(twoHyphens);
+            byte[] boundarybyte = Encoding.UTF8.GetBytes(boundary);
+
+            
+            HttpClientHandler handler = new HttpClientHandler();
+            HttpClient client = new HttpClient(handler);
+            MemoryStream ms = new MemoryStream();                     
+            int j = 0;
+            for (int i = 0; i < b.Assets.Count(); i++)
+            {
+                Asset a = b.Assets.ElementAt(i);
+                if (a.AssetType != AssetType.Image)
+                    continue;
+
+                ms.Write(twoHyphensbyte, 0, twoHyphensbyte.Length);               
+                ms.Write(boundarybyte, 0, boundarybyte.Length);
+                ms.Write(endbyte, 0, endbyte.Length);
+                byte[] s = Encoding.UTF8.GetBytes(String.Format("Content-Disposition: form-data; name=\"file{0}\";filename=\"{1}\"\r\n", j, a.FileName));
+                ms.Write(s, 0, s.Length);
+                ms.Write(endbyte, 0, endbyte.Length);
+                await ms.WriteAsync(a.FileBytes, 0, a.FileBytes.Length);
+
+                ms.Write(endbyte, 0, endbyte.Length);
+                j++;
+            }
+            ms.Write(twoHyphensbyte, 0, twoHyphensbyte.Length);
+            ms.Write(boundarybyte, 0, boundarybyte.Length);
+            ms.Write(twoHyphensbyte, 0, twoHyphensbyte.Length);
+            ms.Write(endbyte, 0, endbyte.Length);
+            HttpContent hc = new StreamContent(ms);
+            hc.Headers.Add("APIKey", "MUA5NmU3OTIxOEPSOFTDQ1YTMzMDExMg");
+
+            client.DefaultRequestHeaders.Add("Accept", "*/*");
+            client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
+            client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
+            client.DefaultRequestHeaders.Add("Charset", "UTF-8");
+            hc.Headers.Add("Content-Type", "Multipart/Form-Data; Boundary=" + boundary);
+            var r = await client.PostAsync(_config["XFApi"] + "/letter/uploadFile;app_id=" + b.LetterId, hc);
+            if (r.StatusCode != HttpStatusCode.OK)
+            {
+                Logger.LogError("省统一平台异常反馈:状态“{0}”", r.StatusCode);
+                return false;
+            }
+            byte[] tmp = await r.Content.ReadAsByteArrayAsync();
+            string rStr = Encoding.UTF8.GetString(tmp);
+            Logger.LogInformation(rStr);
+            JObject rObj = JsonConvert.DeserializeObject<JObject>(rStr);
+            if (rObj == null)
+            {
+                Logger.LogError("数据提交省统一平台失败,原因:{0}", "数据为空");
+                return false;
+            }
+            return true;
+        }
+
+
         /// <summary>
         /// 提交信件
         /// </summary>
@@ -168,7 +231,7 @@ namespace Winsoft.GOV.XF.WebApi.WXCore.Services
         //http://<服务器IP>/query/submitEvaluate
         public async Task<EvaluateModel> QueryEvaluate(string searchCode, OnFails onFails)
         {
-            JObject rObj = await HttpPostAsync<JObject>(_config["XFApi"] + "/query/queryEvaluate;", String.Format("cxm={0}", searchCode), onFails);
+            JObject rObj = await HttpGetAsync<JObject>(_config["XFApi"] + "/query/queryEvaluate;", String.Format("cxm={0}", searchCode), onFails);
 
             
             if (rObj == null)
@@ -179,6 +242,7 @@ namespace Winsoft.GOV.XF.WebApi.WXCore.Services
                 onFails(string.Format("数据提交省统一平台失败,原因:{0}", rObj["message"].ToString()));
                 return null;
             }
+            Logger.LogInformation(rObj.ToString());
             EvaluateModel em = new EvaluateModel();
             em.type = rObj["data"]["type"].ToString();
             em.xfbmmyd = rObj["data"]["xfbmmyd"].ToString();

+ 2 - 1
Winsoft.GOV.XF.WebApi.WXCore/Startup.cs

@@ -49,7 +49,8 @@ namespace Winsoft.GOV.XF.WebApi.WXCore
             services.AddSingleton<AssetsService>();
             services.AddSingleton<ImagesService>();
             services.AddSingleton<XFApiService>();
-            
+            services.AddSingleton<WXApiService>();
+
             services.AddDbContext<XFDbContext>(option => option.UseMySql(Configuration["Data:DefaultConnection:ConnectionString"]));
 
             services.AddSession(options =>

+ 1 - 0
Winsoft.GOV.XF.WebApi.WXCore/appsettings.json

@@ -9,6 +9,7 @@
   },
   "BaseURL": "http://ef7eb3cc.ngrok.io",
   "XFApi": "http://118.178.118.50/test1",
+  "WXApi": "http://www.lszszw.gov.cn/OAuth",
   // LogLevel Severity: "Trace", "Debug", "Information", "Warning", "Error", "Critical", "None"
   "Logging": {
     "PathFormat": "Logs/log-{Date}.log",