using AppletMvcService.Common;
using AppletMvcService.Hanlder;
using AppletMvcService.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WX.CRM.Common;
using WX.CRM.Model.weapp;
namespace AppletMvcService.Controllers
{
//[EnableCors("http://localhost:10229", "*", "*")]
public class WxMessageSvrController : Controller
{
#region 消息接口
//
// GET: /WxMessageSvr/
public string AppletMsg(AppletMsgModel appletMsg, string signature, string timestamp, string nonce)
{
try
{
if (ConfigurationManager.AppSettings["weappIsTest"] != null && ConfigurationManager.AppSettings["weappIsTest"] == "false")
{ //不是测试的有些数据需要转发到测试站点去
if (MessageHandler.GetWxAccount().ContainsKey(appletMsg.ToUserName) && MessageHandler.GetWxAccount()[appletMsg.ToUserName].isonline == 0)
{
return AppletMsgRedirect(appletMsg, signature, timestamp, nonce);
}
}
//LogHelper.Info("数据:" + Utility.ConvertToJSON(appletMsg));
if (!IsFromWxServ(signature, timestamp, nonce))
{
//LogHelper.Info("验证失败");
return "fail";
}
//LogHelper.Info("验证成功");
//LogHelper.Info(string.Format("FromUserName:{0},MsgId:{1},MsgType:{2},ToUserName:{3},Content:{4}", appletMsg.FromUserName, appletMsg.MsgId, appletMsg.MsgType, appletMsg.ToUserName, appletMsg.Content));
string eid = "1";
int isNew = 0;
int isNeedSendMsg = 1;//是否需要发送提示消息到前段
int ntype = 1;//1.普通消息 2.关注 3.取消关注 0界面操作
int isNeedFenPei = 1;
string msgType = "txt";//消息类型
if (MessageHandler.GetWxAccount().ContainsKey(appletMsg.ToUserName))
{
if (appletMsg.MsgType == "event" && appletMsg.Event == "subscribe")//关注和取消关注
{
msgType = "subscribe";
appletMsg.Content = "关注了公众号!";
ntype = 2;
MessageHandler.weapp_update_subscribe(appletMsg.FromUserName, appletMsg.Event, DateTimeTool.GetTimeFromLinuxShortTime(appletMsg.CreateTime), appletMsg.ToUserName);
}
else if (appletMsg.MsgType == "event" && appletMsg.Event == "unsubscribe")
{
msgType = "unsubscribe";
appletMsg.Content = "取消了公众号关注!";
ntype = 3;
MessageHandler.weapp_update_subscribe(appletMsg.FromUserName, appletMsg.Event, DateTimeTool.GetTimeFromLinuxShortTime(appletMsg.CreateTime), appletMsg.ToUserName);
//isNeedSendMsg = 0;
isNeedFenPei = 1;
}
else if (appletMsg.MsgType == "event")
{
ntype = 0;
isNeedSendMsg = 0;
}
if (isNeedFenPei == 1)//需要分配
eid = MessageHandler.GetFenPeiEID(ntype, appletMsg.FromUserName, "", appletMsg.ToUserName, MessageHandler.GetWxAccount()[appletMsg.ToUserName].fenPeiPoc, ref isNew);
}
//LogHelper.Error("isNew:" + isNew);
bool issucced = MessageHandler.appletmsg.WeapAddMessage(appletMsg, Convert.ToInt32(eid), 0, 0);//插入消息表
if (appletMsg.MsgType == "image")
{
//图片类型,进行图片下载
msgType = "image";
string imagepath = DownLoadPath(appletMsg.PicUrl);
MessageHandler.appletmsg.WeapAddFilePath(appletMsg.MsgId, appletMsg.MediaId, imagepath);
if (eid != "1" && isNeedSendMsg == 1)
ChatHub.SendAllMessage(eid, appletMsg.FromUserName, "[imagepath]:" + imagepath, msgType, appletMsg.ToUserName, isNew);
//else
// MessageHandler.SendNoLineMsg(appletMsg.FromUserName);
}
else if (appletMsg.MsgType == "voice")
{
//MessageHandler.GetSuCaiUrl(appletMsg.MediaId, appletMsg.ToUserName);
GetVoice(appletMsg.MediaId, appletMsg.ToUserName);
ChatHub.SendAllMessage(eid, appletMsg.FromUserName, "[voice]:" + appletMsg.MediaId, msgType, appletMsg.ToUserName, isNew);
}
else
{
if (eid != "1" && isNeedSendMsg == 1)
ChatHub.SendAllMessage(eid, appletMsg.FromUserName, appletMsg.Content, msgType, appletMsg.ToUserName, isNew);
//else
// MessageHandler.SendNoLineMsg(appletMsg.FromUserName);
}
if (issucced)
return "success";
else
return "fail";
}
catch (Exception ex)
{
LogHelper.Error(ex.ToString());
return "fail";
}
}
#endregion
#region 从定向数据
///
/// 转发重定向消息
///
///
///
///
///
///
public string AppletMsgRedirect(AppletMsgModel appletMsg, string signature, string timestamp, string nonce)
{
string nul = "";
try
{
string url = ConfigurationManager.AppSettings["weappTestService"] + "/WxMessageSvr/AppletMsg?signature=" + signature + "×tamp=" + timestamp + "&nonce=" + nonce;
nul = url;
string result = RequestHelper.WebClientRequest(url, Utility.ConvertToJSON(appletMsg), Encoding.UTF8);
}
catch (Exception ex)
{
LogHelper.Error("转接出现错误:" + ex.ToString());
LogHelper.Error("转接出现数据:" + Utility.ConvertToJSON(appletMsg));
LogHelper.Error("转接出现地址:" + nul);
}
return "success";
}
#endregion
#region 用户信息接口
public string UserInfoReceive(web_push_wxUserServiceModel t)
{
bool issucced = true;
try
{
ValidationErrors errors = new ValidationErrors();
DateTime time = DateTimeTool.GetTimeFromLinuxShortTime(t.SubscribeTime);
issucced = MessageHandler.userinfo.weapp_userinfo_Storage(t.OpenId, t.NickName, t.Gender, t.Language, t.City, t.Province, t.Country, t.AvatarUrl, t.Type, t.UnionId, t.Subscribe, time, t.AccountNum);
}
catch (Exception ex)
{
issucced = false;
LogHelper.Error("数据:" + JsonConvert.SerializeObject(t));
LogHelper.Error(ex.ToString());
}
if (issucced)
return "success";
else
return "fail";
}
#endregion
#region 文件上传
//保存文件
public JsonResult UploadImage(string toUser, string accountnum, int eid)
{
string filepath = string.Empty;
string erromsg = string.Empty;
int issucced = 1;
try
{
HttpPostedFileBase file = Request.Files["uploadFile"];
var yearMonth = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString();
string uploadFolder = (ConfigurationManager.AppSettings["weappfile"] ?? "weappfile") + "/" + yearMonth;
string filename = file.FileName;
string suffix = filename.Substring(filename.LastIndexOf(".") + 1, (filename.Length - filename.LastIndexOf(".") - 1)); //扩展名
suffix = suffix.ToLower();
string fileType = "image";
if (suffix == "amr" || suffix == "mp3")
{
fileType = "voice";
}
else if (suffix == "mp4")
{
fileType = "video";
}
else if (suffix == "png" || suffix == "jpeg" || suffix == "jpg" || suffix == "gif")
{
fileType = "image";
}
else
{
var json2 = new
{
fileName = "",
result = 0,
erro = "文件格式不对!"
};
JsonResult rs2 = Json(json2);
rs2.ContentType = "text/html";
return rs2;
}
//string suffix = "png";
if (!Directory.Exists(uploadFolder))
{
Directory.CreateDirectory(uploadFolder);
}
string imgname = "S" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + "." + suffix;//文件名称
string path = Path.Combine(uploadFolder, imgname);
filepath = "/" + yearMonth + "/" + imgname;
file.SaveAs(path);
ImageMsg imgmodel = MessageHandler.SendImg(fileType, accountnum, path, "/" + yearMonth + "/" + imgname);
if (imgmodel == null)
{
filepath = "";
erromsg = "发送临时素材失败!";
issucced = 0;
}
else
{
string[] opeIds = toUser.Split(',');
string content = string.Empty;
foreach (string opeId in opeIds)
{
if (string.IsNullOrEmpty(opeId))
continue;
MessageHandler.SendImgMsg(imgmodel, fileType, opeId, accountnum, eid, "", ref content);
}
}
}
catch (Exception ex)
{
filepath += "";
erromsg = ex.ToString();
issucced = 0;
}
var json = new
{
fileName = filepath,
result = issucced,
erro = erromsg
};
JsonResult rs = Json(json);
rs.ContentType = "text/html";
return rs;
}
#endregion
#region 发送素材
public JsonResult SendSuCai(string toUserId, string name, string media_id, string sucaitype, string url, string accountnum, int eid)
{
string filepath = string.Empty;
string erromsg = string.Empty;
int issucced = 1;
string content = string.Empty;
try
{
//if (sucaitype != "news")
//{
ImageMsg msg = new ImageMsg();
msg.media_id = media_id;
string[] openIds = toUserId.Split(',');
foreach (string openId in openIds)
{
if (string.IsNullOrEmpty(openId))
continue;
MessageHandler.SendImgMsg(msg, sucaitype, openId, accountnum, eid, name, ref content);
}
if (sucaitype == "image")
{
DataTable tab = MessageHandler.IsNeedDownLoadSuCai(media_id);
if (tab != null && tab.Rows.Count == 0)
{
if (!string.IsNullOrEmpty(url) && url != "null")
{
string imagepath = MessageHandler.DownLoadSuCaiPath(media_id, url);
MessageHandler.appletmsg.WeapAddFilePath(0, media_id, imagepath);
filepath = imagepath;
}
}
else if (tab != null && tab.Rows.Count > 0)
{
filepath = tab.Rows[0]["Path"].ToString();
}
}
//}
}
catch (Exception ex)
{
LogHelper.Error(ex.ToString());
filepath += "";
erromsg = ex.ToString();
issucced = 0;
}
var json = new
{
fileName = filepath,
result = issucced,
erro = erromsg,
content = content
};
JsonResult rs = Json(json);
rs.ContentType = "text/html";
return rs;
}
#endregion
#region 预览图片素材
///
/// 预览图片素材
///
/// 素材ID
/// 素材URL
///
public JsonResult ImgPreview(string media_id, string url)
{
string filepath = string.Empty;
string erromsg = string.Empty;
int issucced = 1;
try
{
DataTable tab = MessageHandler.IsNeedDownLoadSuCai(media_id);
if (tab != null && tab.Rows.Count == 0)
{
string imagepath = MessageHandler.DownLoadSuCaiPath(media_id, url);
MessageHandler.appletmsg.WeapAddFilePath(0, media_id, imagepath);
filepath = imagepath;
}
else if (tab != null && tab.Rows.Count > 0)
{
filepath = tab.Rows[0]["Path"].ToString();
}
}
catch (Exception ex)
{
LogHelper.Error(ex.ToString());
filepath += "";
erromsg = ex.ToString();
issucced = 0;
}
var json = new
{
fileName = filepath,
result = issucced,
erro = erromsg
};
JsonResult rs = Json(json);
rs.ContentType = "text/html";
return rs;
}
#endregion
#region 下载文件
///
/// 下载文件
///
///
///
private string DownLoadPath(string URLAddress)
{
string filepath = string.Empty;
try
{
WebClient client = new WebClient();
Stream str = client.OpenRead(URLAddress);
StreamReader reader = new StreamReader(str);
byte[] mbyte = new byte[1000000];
int allmybyte = (int)mbyte.Length;
int startmbyte = 0;
while (allmybyte > 0)
{
int m = str.Read(mbyte, startmbyte, allmybyte);
if (m == 0)
break;
startmbyte += m;
allmybyte -= m;
}
reader.Dispose();
str.Dispose();
var yearMonth = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString();
string uploadFolder = (ConfigurationManager.AppSettings["weappfile"] ?? "weappfile") + "/" + yearMonth;
if (!Directory.Exists(uploadFolder))
{
Directory.CreateDirectory(uploadFolder);
}
string imgname = "G" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".jpg";
string path = Path.Combine(uploadFolder, imgname);
filepath = "/" + yearMonth + "/" + imgname;
FileStream fstr = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
fstr.Write(mbyte, 0, startmbyte);
fstr.Flush();
fstr.Close();
}
catch (Exception ex)
{
LogHelper.Error("download erro:" + ex.ToString());
filepath = "";
}
return filepath;
}
#endregion
#region 获取素材列表
///
/// 获取素材列表
///
/// 素材类型 图片(image)、视频(video)、语音 (voice)、图文(news)
/// 显示数量
///
public JsonResult GetSuCai(string type, int count, int offset, string accountnum)
{
try
{
string[] ntypes = { "image", "video", "voice", "news" };
if (!type.Contains(type))
return Json(new { result = false, msg = "参数错误" });
object obj = MessageHandler.GetSucaiModel(type, count, offset, accountnum);
return Json(obj);
}
catch (Exception ex)
{
LogHelper.Error(ex.ToString());
return Json(new { result = false, msg = "系统错误:" + ex.ToString() });
}
}
#endregion
#region 接口验证
private const string Token = "wxapi_hc";
private bool IsFromWxServ(string signature, string timestamp, string nonce)
{
var strArray = new string[] { nonce, timestamp, Token };
Array.Sort(strArray);
string strContent = string.Join("", strArray);
strContent = EncryptSHA1(strContent);//进行sha1加密
strContent = strContent.ToLower();
if (signature == strContent)
{
return true;
}
else
return false;
}
public static string EncryptSHA1(string value)
{
if (value == null || value.Trim() == "")
{
return string.Empty;
}
else
{
return FormsAuthentication.HashPasswordForStoringInConfigFile(value, "SHA1");
}
}
#endregion
#region 获取未读消息
///
/// 获取未读消息
///
/// 工号
///
public JsonResult GetUnReadMsg(int eid, string accountnum)
{
DataTable tab = MessageHandler.appletmsg.GetUnReadMsg(eid, accountnum);
List list = new List();
if (tab != null && tab.Rows.Count > 0)
{
UnReadMsgModel model = null;
foreach (DataRow row in tab.Rows)
{
model = new UnReadMsgModel();
model.id = Convert.ToInt32(row["id"]);
model.issend = Convert.ToInt32(row["issend"]);
model.msgtype = row["msgtype"].ToString();
model.openId = row["fromusername"].ToString();
model.content = row["content"].ToString();
model.createtime = Convert.ToInt64(row["createtime"]);
model.eid = Convert.ToInt32(row["eid"]);
if (row["Path"] != DBNull.Value)
model.filepath = row["Path"].ToString();
else
model.filepath = "";
list.Add(model);
}
}
return Json(list);
}
#endregion
#region 获取已读的新消息(虽然已读,但是未生成在JSON文件中)
///
/// 获取已读的新消息(虽然已读,但是未生成在JSON文件中)
///
/// 工号
/// 公众号
/// 界面加载的最大PKID
///
public JsonResult GetNewAndIsReadMsg(int eid, string accountnum, string openid, long pkid)
{
DataTable tab = MessageHandler.appletmsg.GetNewAndIsReadMsg(eid, accountnum, openid, pkid);
List list = new List();
if (tab != null && tab.Rows.Count > 0)
{
UnReadMsgModel model = null;
foreach (DataRow row in tab.Rows)
{
model = new UnReadMsgModel();
model.id = Convert.ToInt32(row["id"]);
model.issend = Convert.ToInt32(row["issend"]);
model.msgtype = row["msgtype"].ToString();
model.openId = row["fromusername"].ToString();
model.content = row["content"].ToString();
model.createtime = Convert.ToInt64(row["createtime"]);
model.eid = Convert.ToInt32(row["eid"]);
if (row["Path"] != DBNull.Value)
model.filepath = row["Path"].ToString();
else
model.filepath = "";
if (row["mediaid"] != DBNull.Value)
model.mediaid = row["mediaid"].ToString();
else
model.mediaid = "";
list.Add(model);
}
}
return Json(list);
}
#endregion
#region 修改状态
///
/// 修改状态
///
///
public JsonResult UpdateIsAlreadyRead(int eid, string openId, string accountnum)
{
string erromsg = string.Empty;
int issucced = 1;
try
{
if (!MessageHandler.appletmsg.UpdateIsAlreadyRead(eid, openId, accountnum))
issucced = 0;
}
catch (Exception ex)
{
LogHelper.Error(ex.ToString());
erromsg = ex.ToString();
issucced = 0;
}
var json = new
{
result = issucced,
erro = erromsg
};
JsonResult rs = Json(json);
rs.ContentType = "text/html";
return rs;
}
#endregion
#region 获取历史消息文件列表
public JsonResult GetHisMsgFile(string openid, string accountnum)
{
string erroMsg = string.Empty;
List list = new List();//定义list变量,存放获取到的路径
int issucced = 0;
try
{
string path = ConfigurationManager.AppSettings["WxMsgFile"] == null ? "D:\\web\\WXCRM\\MessageGh\\" : System.Configuration.ConfigurationManager.AppSettings["WxMsgFile"] + accountnum + "/" + openid + "/";
DirectoryInfo dir = new DirectoryInfo(path);
if (dir.Exists)
{
FileInfo[] fil = dir.GetFiles();
DirectoryInfo[] dii = dir.GetDirectories();
foreach (FileInfo f in fil)
{
list.Add(f.Name);//添加文件的路径到列表
}
list = list.OrderByDescending(m => m).ToList();
}
issucced = 1;
}
catch (Exception ex)
{
LogHelper.Error(ex.ToString());
erroMsg = ex.ToString();
}
JsonResult rs = Json(new { result = issucced, data = list, erro = erroMsg });
rs.ContentType = "text/html";
return rs;
}
#endregion
#region 获取语音地址
public JsonResult GetVoice(string MediaId, string accountNum)
{
if (string.IsNullOrEmpty(MediaId))
return Json(new { result = false, msg = "参数错误" });
bool result = false;
string erro = string.Empty;
string filepath = string.Empty;
try
{
DataTable tab = MessageHandler.IsNeedDownLoadSuCai(MediaId);
if (tab != null && tab.Rows.Count == 0)//需要进行文件下载
{
string voicePath = MessageHandler.GetSuCaiUrl(MediaId, accountNum, ref erro);//先进行文件下载
if (!string.IsNullOrEmpty(voicePath))
{
MessageHandler.appletmsg.WeapAddFilePath(0, MediaId, voicePath);//然后进行
filepath = voicePath;
result = true;
}
}
else if (tab != null && tab.Rows.Count > 0)
{
filepath = tab.Rows[0]["Path"].ToString();
result = true;
}
}
catch (Exception ex)
{
erro = ex.ToString();
LogHelper.Error(ex.ToString());
}
return Json(new { result = result, voicePath = filepath, msg = erro });
}
#endregion
#region 将客户转接给目标客服
///
/// 将客户转接给目标客服
///
/// 原工号
/// 目标工号
/// openId
/// 公众号
///
public JsonResult TransferEid(int fromEid, int toEid, string openId, string accountNum)
{
string erro = string.Empty;
int result = 0;
try
{
DataTable tab = MessageHandler.userinfo.TransferEid(fromEid, toEid, openId, accountNum);
if (tab != null)
{
result = Convert.ToInt32(tab.Rows[0]["xresult"]);
erro = tab.Rows[0]["message"].ToString();
}
if (result == 1)//转接数据修改成功,进行推送一条通知
{
AppletMsgModel appletMsg = new AppletMsgModel()
{
Content = "系统提示:[" + fromEid + "]将此客户转接给你!",
CreateTime = DateTimeTool.ConvertDateTimeInt(DateTime.Now),
FromUserName = openId,
MsgId = 1,
ToUserName = accountNum,
MsgType = "txt"
};
bool issucced = MessageHandler.appletmsg.WeapAddMessage(appletMsg, toEid, 0, 0);//插入消息表
ChatHub.SendAllMessage(toEid.ToString(), openId, appletMsg.Content, "txt", accountNum, 1);
}
//result = 1;
}
catch (Exception ex)
{
erro = ex.ToString();
LogHelper.Error(ex.ToString());
}
return Json(new { result = result, msg = erro });
}
#endregion
}
}