callServer.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. # coding:utf-8
  2. from apps.models import app
  3. from flask import request
  4. from apps.models import db
  5. from apps.models import Customer
  6. from apps.models import CustomerUpdateLogs
  7. from apps.models import CallRecords, CustomerFollowUp
  8. from typing import Dict
  9. from loguru import logger
  10. from apps.send_email import sendMail
  11. from apps.normal_field import FieldCleanMap
  12. import datetime
  13. from hashlib import md5
  14. from docs.config import voice_secret_key
  15. import json
  16. import urllib.parse
  17. import re
  18. logger.add('./logs/runtime_{time}.log', rotation='00:00')
  19. SpecialField = {"regtime": "time", "lastlogintime": "time", "lastUpdateTime": "time", "isclickkf": "int",
  20. "isDelete": "int", "createTime": "time"}
  21. def insert_body(json_body: Dict) -> bool:
  22. try:
  23. customer = Customer(**json_body)
  24. db.session.add(customer)
  25. db.session.commit()
  26. except Exception as e:
  27. logger.warning(f"{json_body.get('unique_id')}更新失败--->{e}")
  28. db.session.rollback()
  29. sendMail(f"{json_body.get('unique_id')}插入失败--->{e}")
  30. return False
  31. return True
  32. def insert2db(db_object: Dict, errcode: str) -> bool:
  33. try:
  34. db.session.add(db_object)
  35. db.session.commit()
  36. except Exception as e:
  37. print(e)
  38. db.session.rollback()
  39. sendMail(f"{errcode}插入失败--->{e}")
  40. return False
  41. return True
  42. def update_body(exists_body, json_body: Dict) -> bool:
  43. try:
  44. for state, value in json_body.items():
  45. setattr(exists_body, state, value)
  46. db.session.commit()
  47. except Exception as e:
  48. db.session.rollback()
  49. logger.warning(f"{json_body.get('unique_id')}更新失败--->{e}")
  50. sendMail(f"{json_body.get('unique_id')}更新失败--->{e}")
  51. return False
  52. return True
  53. def insert_logs(json_body: Dict) -> bool:
  54. try:
  55. logs = CustomerUpdateLogs(**json_body)
  56. db.session.add(logs)
  57. db.session.commit()
  58. except Exception as e:
  59. logger.warning(f"{json_body.get('unique_id')}日志更新失败--->{e}")
  60. db.session.rollback()
  61. sendMail(f"{json_body.get('unique_id')}日志插入失败--->{e}")
  62. return False
  63. return True
  64. def verify_code(verify_body: dict) -> bool:
  65. """
  66. 请求头密钥验证
  67. :param verify_body:
  68. :return:
  69. """
  70. timestamp = verify_body.get("TimestampKey").strip()
  71. code = verify_body.get("EncryptionToken").strip()
  72. verify_data = str(timestamp) + voice_secret_key
  73. real_key = md5(verify_data.encode("utf-8")).hexdigest()
  74. if real_key == code:
  75. return True
  76. return False
  77. def replace_pic(body, fields):
  78. '''
  79. 检查替换头像特殊编码
  80. :param body:
  81. :param fields:
  82. :return:
  83. '''
  84. for field in fields:
  85. if body.get(field):
  86. body[field] = re.sub(u'[\U00010000-\U0010ffff]', " ", body.get(field, ""))
  87. return body
  88. @app.route('/', methods=['POST'])
  89. def tell():
  90. if request.method == 'POST':
  91. body = dict(request.form)
  92. print(body)
  93. if "phoneMemo" in body:
  94. del body["phoneMemo"]
  95. unique_id = body.get("unique_id", "")
  96. body = replace_pic(body, ["usernickname", "company", "username"])
  97. if not unique_id:
  98. return "false"
  99. # 字段类型转换
  100. change_fields = []
  101. for field, f_type in SpecialField.items():
  102. body = FieldCleanMap[f_type](body, field)
  103. # 更新时间
  104. body["lastUpdateTime"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  105. # 查询
  106. exists_body = Customer.query.filter(Customer.unique_id == unique_id).first()
  107. if not exists_body:
  108. state = insert_body(body)
  109. body["logCreateTime"] = body["lastUpdateTime"]
  110. body["updateStatus"] = 1 if state else 0
  111. body["updateType"] = "插入"
  112. change_fields = [key for key, value in body.items()]
  113. body["changeField"] = ";".join(change_fields)
  114. insert_logs(body)
  115. else:
  116. try:
  117. for key, val in body.items():
  118. if str(exists_body.__dict__.get(key)) != str(val):
  119. if key not in ['createTime', 'lastUpdateTime']:
  120. change_fields.append(key)
  121. except Exception as e:
  122. logger.warning(e)
  123. state = update_body(exists_body, body)
  124. if change_fields:
  125. body["logCreateTime"] = body["lastUpdateTime"]
  126. body["updateStatus"] = 1 if state else 0
  127. body["updateType"] = "更新"
  128. body["changeField"] = ";".join(change_fields)
  129. insert_logs(body)
  130. else:
  131. print("未更新")
  132. if not state:
  133. return "false"
  134. return "200"
  135. @app.route('/voice', methods=['GET'])
  136. def voice_sync():
  137. time_dict = {"Ring": "time", "RingingTime": "time", "Begin": "time", 'End': "time", 'QueueTime': "time","CallTimeLength":"int"}
  138. if request.method == 'GET':
  139. body = dict(request.args)
  140. is_real = verify_code(body)
  141. if not is_real:
  142. return
  143. for field, f_type in time_dict.items():
  144. body = FieldCleanMap[f_type](body, field)
  145. call_sheet_id = body.get("CallSheetID")
  146. body = replace_pic(body, ["CustomerName"])
  147. callId = body["callId"]
  148. if callId:
  149. body["callHistoryId"] = callId
  150. exists_body = CallRecords.query.filter(CallRecords.CallSheetID == call_sheet_id).first()
  151. if exists_body:
  152. update_body(exists_body, body)
  153. return "succeed"
  154. call = CallRecords()
  155. this_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  156. setattr(call, "createTime", this_time)
  157. for attr_key, value in body.items():
  158. if attr_key in CallRecords.__dict__:
  159. if attr_key !="CallTimeLength":
  160. value = value.strip()
  161. setattr(call, attr_key, value)
  162. state = insert2db(call, f"语音同步失败-->{call_sheet_id}")
  163. if not state:
  164. return "error"
  165. return "succeed"
  166. @app.route('/followup', methods=['POST'])
  167. def followup():
  168. TimeStr = {"followRemindTime": "time"}
  169. if request.method == 'POST':
  170. body = request.get_data()
  171. if body is None or body == "":
  172. return "200"
  173. body = json.loads(body)
  174. body = replace_pic(body, ["customerName"])
  175. convert_body = {}
  176. for key, val in body.items():
  177. convert_body[key] = urllib.parse.unquote(val)
  178. body = convert_body
  179. print(body)
  180. for field, f_type in SpecialField.items():
  181. body = FieldCleanMap[f_type](body, field)
  182. customerId = body.get("customerId", "")
  183. if not customerId:
  184. return "200"
  185. try:
  186. body["createTime"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  187. customerFollowUp = CustomerFollowUp()
  188. for attr in ["customerId", "customerName", "createTime", "remark", "followRemindTime", "isNotFollow",
  189. "dataType", "dbTypeName"]:
  190. if attr in body:
  191. if attr in TimeStr:
  192. if not body[attr]:
  193. continue
  194. setattr(customerFollowUp, attr, body[attr])
  195. state = insert2db(customerFollowUp, f"跟进客户{customerId}状态同步错误")
  196. if not state:
  197. return "error"
  198. except Exception as e:
  199. logger.warning(e)
  200. return "error"
  201. return "200"
  202. if __name__ == '__main__':
  203. app.run(host="0.0.0.0", port=15001, processes=True)