BotClient.Chat.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. using CommonLang;
  2. using CommonLang.Concurrent;
  3. using CommonLang.IO;
  4. using CommonLang.Property;
  5. using CommonNetwork.Http;
  6. using pomelo.chat;
  7. using SimpleJson;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Text;
  13. namespace XmdsBattleClientBot.Bot
  14. {
  15. partial class BotClient
  16. {
  17. public ChatManager CurrentChatManager { get; private set; }
  18. public GetChatServerIdResponse LastGetChatServerIdResponse { get; private set; }
  19. /// <summary>
  20. /// 0综合,1世界,2区域,3交易,4公会,5队伍,6系统,7喇叭,8私聊
  21. /// </summary>
  22. public enum ChatChannel
  23. {
  24. [Desc("世界")]
  25. WORLD = 1, // 世界
  26. [Desc("公会")]
  27. SOCIETY = 2, // 公会
  28. [Desc("队伍")]
  29. GROUPS = 3, // 队伍
  30. [Desc("私聊")]
  31. PRIVATE = 4, // 私聊
  32. [Desc("连服")]
  33. ZONE = 5, // 连服(跨服)
  34. [Desc("附近")]
  35. NEARBY = 6, // 附近
  36. [Desc("喇叭")]
  37. HORM = 8 // 喇叭
  38. }
  39. public enum ChatAt
  40. {
  41. Normal = 0,
  42. All = 1,
  43. Single = 2,
  44. }
  45. public enum ChatFunType
  46. {
  47. NA = 0,
  48. Roll = 1,
  49. }
  50. public void chat_SendChat(Action<Exception, JsonObject> callback,
  51. string content,
  52. string titleMsg = "",
  53. ChatChannel ch = ChatChannel.WORLD,
  54. string acceptRoleId = "",
  55. ChatAt at = ChatAt.Normal,
  56. ChatFunType funtype = ChatFunType.NA)
  57. {
  58. dynamic input = new
  59. {
  60. s2c_name = this.PlayerData.name,//DataMgr.Instance.UserData.Name
  61. s2c_level = this.PlayerData.level, // DataMgr.Instance.UserData:TryToGetIntAttribute(UserData.NotiFyStatus.LEVEL, 0);
  62. s2c_pro = this.PlayerData.pro,// DataMgr.Instance.UserData.Pro;
  63. s2c_zoneId = this.PlayerData.zoneId,//DataMgr.Instance.UserData:GetAttribute(UserData.NotiFyStatus.ZONEID);
  64. s2c_vip = this.PlayerData.vip,// DataMgr.Instance.UserData:GetAttribute(UserData.NotiFyStatus.VIP);
  65. s2c_isAtAll = (int)at,
  66. s2c_titleMsg = titleMsg,
  67. s2c_funtype = (int)funtype,
  68. s2c_color = (uint)0xFFFFFFFF,
  69. acceptRoleId = acceptRoleId,
  70. };
  71. string msg = SimpleJson.SimpleJson.SerializeObject(input);
  72. new ChatManager.ChatRequest(this)
  73. {
  74. channel = ch,
  75. chatContent = content,
  76. acceptRoleId = acceptRoleId,
  77. serverData = msg,
  78. }.Send(callback);
  79. }
  80. public virtual string FormatChat(OnChatPush push)
  81. {
  82. StringBuilder sb = new StringBuilder();
  83. var ch = (BotClient.ChatChannel)push.s2c_scope;
  84. var desc = PropertyUtil.GetEnumAttribute<DescAttribute>(ch);
  85. dynamic input = SimpleJson.SimpleJson.DeserializeObject(push.s2c_serverData);
  86. sb.Append(push.s2c_time);
  87. sb.Append(" ");
  88. sb.Append(string.Format("[{0}]", desc.Desc));
  89. try
  90. {
  91. sb.Append(string.Format("{0}(Lv{1})", input["s2c_name"], input["s2c_level"]));
  92. string s2c_titleMsg = input["s2c_titleMsg"];
  93. if (!string.IsNullOrEmpty(s2c_titleMsg))
  94. {
  95. sb.Append(string.Format(":\"{0}\"", s2c_titleMsg));
  96. }
  97. }
  98. catch (Exception err)
  99. {
  100. sb.Append(err.Message);
  101. }
  102. sb.Append(": " + push.s2c_content);
  103. return sb.ToString();
  104. }
  105. public class ChatManager
  106. {
  107. public ChatManager(BotClient bot)
  108. {
  109. bot.client.GameSocket.chatHandler.getChatServerIdRequest((err, rsp) =>
  110. {
  111. bot.LastGetChatServerIdResponse = rsp;
  112. });
  113. }
  114. public class ChatRequest
  115. {
  116. private readonly BotClient bot;
  117. public static string BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符
  118. public ChatChannel channel = ChatChannel.WORLD;
  119. public string chatContent = "0";
  120. public string acceptRoleId = "1";
  121. public string serverData = "0";
  122. public string chatType = "1";//0 is sound
  123. public bool Result { get; private set; }
  124. public ChatRequest(BotClient bot)
  125. {
  126. this.bot = bot;
  127. }
  128. public void Send(Action<Exception, JsonObject> callback)
  129. {
  130. if (bot.LastGetChatServerIdResponse == null)
  131. {
  132. callback(new Exception("No Server ID"), null);
  133. return;
  134. }
  135. try
  136. {
  137. #if OLD_CHAT
  138. HttpWebRequest webRequest = System.Net.WebRequest.Create(bot.LastGetChatServerIdResponse.s2c_clientHttp) as HttpWebRequest;
  139. webRequest.Method = "POST";
  140. webRequest.BeginGetRequestStream(new System.AsyncCallback((System.IAsyncResult asynchronousResult) =>
  141. {
  142. try
  143. {
  144. HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
  145. request.Timeout = 1000 * 300;
  146. request.ContentType = "multipart/form-data; boundary=" + BOUNDARY;
  147. request.KeepAlive = true;
  148. request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)";
  149. Stream stream = request.EndGetRequestStream(asynchronousResult);
  150. StreamWriter postStream = new StreamWriter(stream);
  151. Dictionary<string, string> textMap = new Dictionary<string, string>();
  152. {
  153. textMap.Add("account", bot.Account);
  154. textMap.Add("appid", bot.config.Appid.ToString());
  155. ///************************/
  156. //textMap.Add("serverId", DataMgr.Instance.AccountData.CurSrvInfo.ServerId.ToString());
  157. textMap.Add("serverId", bot.LastGetChatServerIdResponse.s2c_serverId);
  158. string zoneid = bot.PlayerData.zoneId;//(string)DataMgr.Instance.UserData.GetAttribute(UserData.NotiFyStatus.ZONEID);
  159. string[] array = zoneid.Split('-');
  160. int zoneidnum = int.Parse(array[0]) * 1000000 + int.Parse(array[1]);
  161. textMap.Add("realServerId", zoneidnum + "");
  162. textMap.Add("myRoleId", bot.PlayerData.id/*DataMgr.Instance.UserData.RoleID.ToString()*/);
  163. textMap.Add("acceptRoleId", acceptRoleId);
  164. textMap.Add("channel", ((int)channel).ToString());
  165. textMap.Add("chatContent", chatContent);
  166. textMap.Add("chatType", chatType);
  167. textMap.Add("serverData", serverData);
  168. }
  169. {
  170. var strBuf = new StringBuilder();
  171. foreach (string key in textMap.Keys)
  172. {
  173. string inputName = key;
  174. string inputValue = "";
  175. if (textMap[key] == null)
  176. {
  177. continue;
  178. }
  179. inputValue = (string)textMap[key];
  180. strBuf.Append("\r\n" + "--" + BOUNDARY + "\r\n");
  181. strBuf.Append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
  182. strBuf.Append(inputValue);
  183. }
  184. postStream.Write(strBuf);
  185. }
  186. postStream.Write("\r\n--" + BOUNDARY + "--\r\n");
  187. postStream.Flush();
  188. postStream.Close();
  189. postStream = null;
  190. WebResponse wrp = request.GetResponse();
  191. StreamReader respRs = new StreamReader(wrp.GetResponseStream());
  192. string responseData = "";
  193. string readCallBackFileResponse = "";
  194. while ((responseData = respRs.ReadLine()) != null)
  195. {
  196. readCallBackFileResponse += responseData + "\n";
  197. }
  198. JsonObject obj = (JsonObject)SimpleJson.SimpleJson.DeserializeObject(readCallBackFileResponse);
  199. object status;
  200. if (obj.TryGetValue("status", out status) && (status as string) == "1")
  201. {
  202. Result = (true);
  203. }
  204. else
  205. {
  206. Result = (false);
  207. }
  208. bot.QueueTask(() =>
  209. {
  210. callback(null, obj);
  211. });
  212. }
  213. catch (Exception err)
  214. {
  215. bot.log.Error(err.Message, err);
  216. bot.QueueTask(() =>
  217. {
  218. callback(err, null);
  219. });
  220. }
  221. }), webRequest);
  222. #else
  223. var url = new Uri(bot.LastGetChatServerIdResponse.s2c_clientHttp);
  224. using (WebClient client = new WebClient(url))
  225. {
  226. client.Request.Method = HttpRequest.METHOD_POST;
  227. client.Request.Referer = url.AbsoluteUri;
  228. {
  229. StringBuilder postStream = new StringBuilder();
  230. Dictionary<string, string> textMap = new Dictionary<string, string>();
  231. {
  232. textMap.Add("account", bot.Account);
  233. textMap.Add("appid", bot.config.Appid.ToString());
  234. ///************************/
  235. //textMap.Add("serverId", DataMgr.Instance.AccountData.CurSrvInfo.ServerId.ToString());
  236. textMap.Add("serverId", bot.LastGetChatServerIdResponse.s2c_serverId);
  237. string zoneid = bot.PlayerData.zoneId;//(string)DataMgr.Instance.UserData.GetAttribute(UserData.NotiFyStatus.ZONEID);
  238. string[] array = zoneid.Split('-');
  239. int zoneidnum = int.Parse(array[0]) * 1000000 + int.Parse(array[1]);
  240. textMap.Add("realServerId", zoneidnum + "");
  241. textMap.Add("myRoleId", bot.PlayerData.id/*DataMgr.Instance.UserData.RoleID.ToString()*/);
  242. textMap.Add("acceptRoleId", acceptRoleId);
  243. textMap.Add("channel", ((int)channel).ToString());
  244. textMap.Add("chatContent", chatContent);
  245. textMap.Add("chatType", chatType);
  246. textMap.Add("serverData", serverData);
  247. }
  248. {
  249. foreach (string key in textMap.Keys)
  250. {
  251. string inputName = key;
  252. string inputValue = "";
  253. if (textMap[key] == null)
  254. {
  255. continue;
  256. }
  257. inputValue = (string)textMap[key];
  258. postStream.Append("\r\n" + "--" + BOUNDARY + "\r\n");
  259. postStream.Append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
  260. postStream.Append(inputValue);
  261. }
  262. }
  263. postStream.Append("\r\n--" + BOUNDARY + "--\r\n");
  264. var content = postStream.ToString();
  265. client.Request.Content = CUtils.UTF8.GetBytes(content);
  266. client.Request.ContentType = "multipart/form-data; boundary=" + BOUNDARY;
  267. }
  268. client.ConnectAsync((www)=>
  269. {
  270. try
  271. {
  272. byte[] data = client.Response.ReadContentToEnd();
  273. string ret = CUtils.UTF8.GetString(data);
  274. JsonObject obj = (JsonObject)SimpleJson.SimpleJson.DeserializeObject(ret);
  275. object status;
  276. if (obj.TryGetValue("status", out status) && (status as string) == "1")
  277. {
  278. Result = (true);
  279. }
  280. else
  281. {
  282. Result = (false);
  283. }
  284. bot.QueueTask(() =>
  285. {
  286. callback(null, obj);
  287. });
  288. }
  289. catch (Exception err)
  290. {
  291. bot.log.Error(err.Message, err);
  292. bot.QueueTask(() =>
  293. {
  294. callback(err, null);
  295. });
  296. }
  297. });
  298. }
  299. #endif
  300. }
  301. catch (Exception err)
  302. {
  303. bot.log.Error(err.Message, err);
  304. callback(err, null);
  305. }
  306. }
  307. }
  308. }
  309. }
  310. }