You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

292 lines
12 KiB

  1. 
  2. namespace CounsellorBL.GROUP
  3. {
  4. using CounsellorBL.BLStructure;
  5. using CounsellorBL.Common;
  6. using CounsellorBL.Helper;
  7. using MonumentDefine;
  8. using Newtonsoft.Json;
  9. using OT.COM.ArsenalDB;
  10. using OT.COM.SignalerMessage;
  11. using SoldierData.EnterprizeV4;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Linq;
  15. using System.Net.Http;
  16. using System.Text;
  17. using static CounsellorBL.GROUP.Helper.FbHelper;
  18. public class GroupUserConnectService : SingleDataTableTemplate<tb_grp_group>
  19. {
  20. #region 私有類
  21. private class Group2UserViewModel
  22. {
  23. public string app_id { get; set; }
  24. public string client_secret { get; set; }
  25. public string user_token { get; set; }
  26. public string fb_account { get; set; }
  27. }
  28. private class FbTokenVerification
  29. {
  30. public VerificationContent data { get; set; }
  31. }
  32. private class VerificationContent
  33. {
  34. public string app_id { get; set; }
  35. public string type { get; set; }
  36. public int data_access_expires_at { get; set; }
  37. public error error { get; set; }
  38. public int expires_at { get; set; }
  39. public bool is_valid { get; set; }
  40. public string user_id { get; set; }
  41. }
  42. private class error
  43. {
  44. public int code { get; set; }
  45. public string message { get; set; }
  46. public int subcode { get; set; }
  47. }
  48. private class ErrorMsg
  49. {
  50. public string message { get; set; }
  51. public string fb_account { get; set; }
  52. }
  53. #endregion
  54. #region 私有方法
  55. /// <summary>
  56. /// 驗證token
  57. /// </summary>
  58. /// <param name="authorizationToken">user_token</param>
  59. /// <param name="client_id">app_id</param>
  60. /// <param name="client_secret">client_secret</param>
  61. /// <param name="status"> 預設0: 正常 1: 即將到期 2: 驗證失敗</param>
  62. /// <returns></returns>
  63. private string CallFbCheckTokenGetAPI(string authorizationToken, string client_id, string client_secret, out int status)
  64. {
  65. // 送出資料
  66. status = 0; // 預設0: 正常 1: 即將到期 2: 驗證失敗
  67. string uri = "https://graph.facebook.com/debug_token?";
  68. var dicData = new Dictionary<string, string>()
  69. {
  70. { "input_token", authorizationToken },
  71. { "access_token", string.Format("{0}|{1}",client_id,client_secret) },
  72. };
  73. APIHelper.BaseGet(uri, null, dicData, out HttpResponseMessage responseMessage);
  74. if (responseMessage.IsSuccessStatusCode)
  75. {
  76. var responseData = JsonConvert.DeserializeObject<FbTokenVerification>(responseMessage.Content.ReadAsStringAsync().Result);
  77. if (responseData.data.is_valid)
  78. {
  79. return null;
  80. }
  81. else
  82. {
  83. status = 2;
  84. return responseData.data.error.message;
  85. }
  86. }
  87. else
  88. {
  89. status = 2;
  90. var error = $"{nameof(CallFbCheckTokenGetAPI)} Error, ReasonPhrase:{responseMessage.ReasonPhrase} hrmResult.Headers.WwwAuthenticate:{responseMessage.Headers.WwwAuthenticate} ";
  91. return $"Token Check 失敗, {error}";
  92. }
  93. }
  94. /// <summary>
  95. /// 取得Group2User列表
  96. /// </summary>
  97. /// <param name="appId"></param>
  98. /// <param name="qdGroup"></param>
  99. /// <returns></returns>
  100. private string GetListGroup2User(string appId, out List<Group2UserViewModel> qdGroup)
  101. {
  102. // 送出資料
  103. qdGroup = new List<Group2UserViewModel>();
  104. string sMsg;
  105. QueryJsonElementCollection lBlocks = new QueryJsonElementCollection();
  106. QueryJsonElement qjeGroup = lBlocks.GetInst();
  107. qjeGroup.table = tb_grp_group.TABLENAME;
  108. qjeGroup.displaycols = new List<string>()
  109. {
  110. tb_grp_group.CN_APP_ID,
  111. tb_grp_group.CN_CLIENT_SECRET
  112. };
  113. qjeGroup.wherecols = new WhereNode(tb_grp_group.CN_APP_ID, WhereNode.EColumnOperation.EOT_EQ, typeof(tb_grp_group), appId);
  114. lBlocks.Add(qjeGroup);
  115. QueryJsonElement qjeGroupUser = lBlocks.GetInst();
  116. qjeGroupUser.table = tb_grp_group2user.TABLENAME;
  117. qjeGroupUser.jointable = qjeGroup;
  118. qjeGroupUser.jointype = QueryJsonElement.LEFT_JOIN;
  119. qjeGroupUser.joincols = new Dictionary<string, string> { { tb_grp_group2user.CN_GROUP_UID, tb_grp_group.CN_UID } };
  120. qjeGroupUser.displaycols = new List<string>()
  121. {
  122. tb_grp_group2user.CN_USER_TOKEN,
  123. tb_grp_group2user.CN_FB_ACCOUNT
  124. };
  125. qjeGroupUser.wherecols = new WhereNode(tb_grp_group2user.CN_STATUS_FLAG, WhereNode.EColumnOperation.EOT_EQ, typeof(tb_grp_group2user), BLWording.STATUS_FLAG_ON);
  126. lBlocks.Add(qjeGroupUser);
  127. sMsg = MakeSelectJoinByBlocks(lBlocks, out Command cRes);
  128. if (sMsg != null)
  129. {
  130. qdGroup = null;
  131. return sMsg;
  132. }
  133. ArsenalInterface ai = ArsenalDBMgr.GetInst(cRes);
  134. qdGroup = ai.RunQueryList<Group2UserViewModel>(cRes);
  135. sMsg = GetLastErrorCode(cRes);
  136. if (sMsg != null)
  137. {
  138. return sMsg;
  139. }
  140. return sMsg;
  141. }
  142. /// <summary>
  143. /// 取得設定中的值
  144. /// </summary>
  145. /// <param name="i_crmInput"></param>
  146. /// <returns></returns>
  147. private string GetAppId(CRequestMessage i_crmInput)
  148. {
  149. object oAppId = i_crmInput != null && i_crmInput.customparam != null && i_crmInput.customparam.ContainsKey(BLWording.APP_ID) ? i_crmInput.customparam[BLWording.APP_ID] : null;
  150. return oAppId?.ToString();
  151. }
  152. #endregion
  153. [Auth(false)]
  154. public CResponseMessage FbCheckToken(CRequestMessage i_crmInput)
  155. {
  156. Logger.Info("FbCheckToken debug start");
  157. string sMsg = null;
  158. CResponseMessage crmRes = null;
  159. try
  160. {
  161. do
  162. {
  163. string strAppId = GetAppId(i_crmInput);
  164. if (string.IsNullOrEmpty(strAppId))
  165. {
  166. Logger.Info(string.Format("請在appsettings.join中添加{0}的配置", BLWording.APP_ID));
  167. sMsg = string.Format("請在appsettings.join中添加{0}的配置", BLWording.APP_ID) ;
  168. break;
  169. }
  170. List<MailAccountInfo> lsMailList = new List<MailAccountInfo>();
  171. // 取得當發文錯誤要發送的名單
  172. string sMsgMailList = SystemSettingHelper.GetSetting(BLWording.ERROR_MAILLIST, out var mailList);
  173. if (sMsg != null)
  174. {
  175. Logger.Error(sMsgMailList);
  176. }
  177. if (mailList != null && !string.IsNullOrEmpty(mailList.key_value))
  178. {
  179. var lsMail = mailList.key_value.Split(new String[] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
  180. foreach (var mail in lsMail)
  181. {
  182. lsMailList.Add(new MailAccountInfo() { EMail = mail });
  183. Logger.Info(string.Format("errorMail:{0}", mail));
  184. }
  185. }
  186. else
  187. {
  188. Logger.Info(string.Format("請先設置{0}的值", BLWording.ERROR_MAILLIST));
  189. sMsg = string.Format("請先設置{0}的值", BLWording.ERROR_MAILLIST);
  190. break;
  191. }
  192. sMsg = GetListGroup2User(strAppId, out var qdGroup);
  193. if (sMsg != null)
  194. {
  195. break;
  196. }
  197. if (qdGroup.Count() <0)
  198. {
  199. Logger.Info("未查詢到user資料");
  200. sMsg = "未查詢到user資料";
  201. break;
  202. }
  203. List<ErrorMsg> lsErrorMsg = new List<ErrorMsg>();
  204. foreach (Group2UserViewModel Group2UserData in qdGroup)
  205. {
  206. string isValid = CallFbCheckTokenGetAPI(Group2UserData.user_token, Group2UserData.app_id, Group2UserData.client_secret, out int status);
  207. if (isValid != null)
  208. {
  209. sMsg = isValid;
  210. if (status == 2)
  211. {
  212. Logger.Info(string.Format("Token驗證失敗:fb_account:{0}&&&app_id:{1}&&&client_secret:{2}&&&user_token:{3}", Group2UserData.fb_account, Group2UserData.app_id, Group2UserData.client_secret, Group2UserData.user_token));
  213. lsErrorMsg.Add(new ErrorMsg() { fb_account = Group2UserData.fb_account,message= sMsg });
  214. }
  215. }
  216. else
  217. {
  218. Logger.Info(string.Format("Token驗證成功:fb_account:{0}&&&app_id:{1}&&&client_secret:{2}&&&user_token:{3}", Group2UserData.fb_account, Group2UserData.app_id, Group2UserData.client_secret, Group2UserData.user_token));
  219. }
  220. }
  221. //存在錯誤訊息時
  222. if (lsErrorMsg.Count() > 0)
  223. {
  224. var mailHelper = new MailHelper();
  225. var strBody = "";
  226. foreach (ErrorMsg ErrorMsgData in lsErrorMsg)
  227. {
  228. strBody += string.Format("fb賬號:{0}錯誤信息:{1}<br/>", ErrorMsgData.fb_account, ErrorMsgData.message);
  229. }
  230. var mailMsg = mailHelper.Send(string.Format("appid:{0}驗證token錯誤", strAppId), strBody, lsMailList);
  231. if (string.IsNullOrEmpty(mailMsg))
  232. {
  233. Logger.Info("信件發送成功");
  234. }
  235. else
  236. {
  237. Logger.Error(string.Format("信件發送失敗:{0} => {1}", mailMsg, lsMailList));
  238. }
  239. }
  240. else
  241. {
  242. Logger.Info(string.Format("app_id:{0}下未有驗證token錯誤的user", strAppId));
  243. }
  244. crmRes = new CSuccessResponseMessage(null, i_crmInput);
  245. // 填寫回傳
  246. }
  247. while (false);
  248. }
  249. catch (Exception ex)
  250. {
  251. sMsg = $"{nameof(PushPost)} exception. i_crmInput={JsonConvert.SerializeObject(i_crmInput)}. ex={ex.Message}";
  252. Logger.Error(sMsg);
  253. #if DEBUG
  254. System.Diagnostics.Debug.WriteLine(sMsg);
  255. #endif
  256. }
  257. if (!string.IsNullOrEmpty(sMsg))
  258. {
  259. crmRes = new CErrorResponseMessage(sMsg, i_crmInput);
  260. Logger.Error(JsonConvert.SerializeObject(i_crmInput));
  261. Logger.Error(JsonConvert.SerializeObject(crmRes));
  262. }
  263. return crmRes;
  264. }
  265. }
  266. }