ComboCronPushController.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : ComboCronPushController.py
  4. @Time : 2022/7/8 19:52
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import logging
  10. import time
  11. import traceback
  12. from django.db.models import Q
  13. from django.views import View
  14. from Model.models import UnicomComboOrderInfo, UnicomDeviceInfo, GatewayPush, SysMsgModel, UnicomFlowPush, Device_User
  15. from Object.AliyunSmsObject import AliyunSmsObject
  16. from Object.ResponseObject import ResponseObject
  17. from Service.HuaweiPushService.HuaweiPushService import HuaweiPushObject
  18. from Service.PushService import PushObject
  19. from AnsjerPush.config import XM_PUSH_CHANNEL_ID
  20. class ComboCronPushView(View):
  21. def get(self, request, *args, **kwargs):
  22. request.encoding = 'utf-8'
  23. operation = kwargs.get('operation')
  24. return self.validation(request.GET, request, operation)
  25. def post(self, request, *args, **kwargs):
  26. request.encoding = 'utf-8'
  27. operation = kwargs.get('operation')
  28. return self.validation(request.POST, request, operation)
  29. def validation(self, request_dict, request, operation):
  30. print(request_dict)
  31. print(request)
  32. response = ResponseObject()
  33. if operation == 'expire-push':
  34. return self.combo_expire_push(response)
  35. elif operation == 'warning-push':
  36. return self.flow_warning_push(response)
  37. else:
  38. return response.json(404)
  39. @classmethod
  40. def combo_expire_push(cls, response):
  41. """
  42. 套餐到期预警通知,分别7前3天前消息推送
  43. """
  44. logger = logging.getLogger('info')
  45. logger.info('进入流量包过期消息推送')
  46. try:
  47. now_time = int(time.time())
  48. combo_order_qs = UnicomComboOrderInfo.objects.filter(
  49. ~Q(status=2) & Q(expire_time__gt=now_time + 3600 * 144) & Q(
  50. expire_time__lte=(now_time + 3600 * 168)), is_del=False).values()
  51. if combo_order_qs.exists():
  52. cls.phone_msg_push(combo_order_qs)
  53. combo_order_qs = UnicomComboOrderInfo.objects.filter(
  54. ~Q(status=2) & Q(expire_time__gt=now_time + 3600 * 48) & Q(
  55. expire_time__lte=(now_time + 3600 * 72)), is_del=False).values()
  56. if combo_order_qs.exists():
  57. cls.phone_msg_push(combo_order_qs)
  58. return response.json(0)
  59. except Exception as e:
  60. print(e.args)
  61. ex = traceback.format_exc()
  62. print(ex)
  63. return response.json(177, ex)
  64. @classmethod
  65. def phone_msg_push(cls, combo_order_qs):
  66. """
  67. 消息推送
  68. """
  69. now_time = int(time.time())
  70. for item in combo_order_qs:
  71. iccid = item['iccid']
  72. device_info = UnicomDeviceInfo.objects.filter(iccid=iccid).values()
  73. if not device_info.exists():
  74. continue
  75. nickname = device_info.first()['serial_no']
  76. user_id = device_info.first()['user_id']
  77. if not user_id:
  78. continue
  79. # 查询推送配置数据
  80. push_qs = GatewayPush.objects.filter(user_id=user_id, logout=False). \
  81. values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'tz')
  82. if not push_qs.exists():
  83. continue
  84. for push_vo in push_qs:
  85. kwargs = {
  86. 'n_time': now_time,
  87. 'event_type': 1,
  88. 'nickname': nickname,
  89. }
  90. push_type = push_vo['push_type']
  91. token_val = push_vo['token_val']
  92. lang = push_vo['lang']
  93. app_bundle_id = push_vo['app_bundle_id']
  94. # 获取推送所需数据
  95. msg_title = PushObject.get_msg_title(nickname)
  96. if lang == 'cn':
  97. sys_msg_text = "温馨提示:尊敬的客户,您" + nickname + "设备4G流量套餐将在" + time.strftime("%Y-%m-%d", time.localtime(
  98. item['expire_time'])) + "到期"
  99. else:
  100. sys_msg_text = 'Dear customer,the flow package for your device ' + nickname + ' will expire on ' + \
  101. time.strftime('%m-%d-%y', time.localtime(item['expire_time']))
  102. kwargs['app_bundle_id'] = app_bundle_id
  103. kwargs['token_val'] = token_val
  104. kwargs['msg_title'] = msg_title
  105. kwargs['msg_text'] = sys_msg_text
  106. cls.sys_msg_save(user_id, nickname, now_time, sys_msg_text)
  107. if not cls.msg_push(push_type, **kwargs):
  108. continue
  109. return True
  110. @classmethod
  111. def sys_msg_save(cls, user_id, serial_no, n_time, text_msg):
  112. """
  113. 系统消息存库
  114. """
  115. logger = logging.getLogger('info')
  116. try:
  117. data = {'addTime': n_time, 'updTime': n_time, 'userID_id': user_id, 'eventType': 0, 'msg': text_msg,
  118. 'uid': serial_no}
  119. SysMsgModel.objects.create(**data)
  120. except Exception as e:
  121. logger.info('---4G流量存库异常--- {}'.format(repr(e)))
  122. @classmethod
  123. def flow_warning_push(cls, response):
  124. """
  125. 流量到期或者流量预警消息推送
  126. """
  127. logger = logging.getLogger('info')
  128. flow_push_qs = UnicomFlowPush.objects.filter(status=0)
  129. if not flow_push_qs.exists():
  130. return response.json(0)
  131. for item in flow_push_qs:
  132. try:
  133. user_id = item.user_id
  134. if not user_id:
  135. continue
  136. user_push_qs = GatewayPush.objects.filter(user_id=user_id)
  137. if not user_push_qs:
  138. continue
  139. now_time = int(time.time())
  140. # 查询推送配置数据
  141. push_qs = GatewayPush.objects.filter(user_id=user_id, logout=False). \
  142. values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'tz')
  143. if not push_qs.exists():
  144. continue
  145. usage = cls.flow_split(item.flow_total_usage)
  146. total = cls.flow_split(item.flow_total)
  147. usable = cls.flow_split(item.flow_total - item.flow_total_usage)
  148. msg = False
  149. if item.type != 0 and item.type != 1:
  150. unicom_order_qs = UnicomComboOrderInfo.objects.filter(id=item.combo_order_id) \
  151. .values('combo__combo_name')
  152. combo_name = unicom_order_qs.first()['combo__combo_name'] if unicom_order_qs.exists() else ''
  153. sys_msg = cls.get_sys_msg_text(item.serial_no, combo_name, item.type)
  154. msg = True
  155. else:
  156. user_qs = Device_User.objects.filter(userID=user_id).values('phone')
  157. if user_qs.exists() and user_qs.first()['phone']:
  158. params = u'{"devname":"' + item.serial_no + '","usage":"流量' + usage + '","usable":"流量' + \
  159. usable + '","total":"流量共' + total + '"}'
  160. cls.send_aliyun_sms(user_qs.first()['phone'], params, 'SMS_246100414')
  161. sys_msg = cls.get_msg_text(item.serial_no, push_qs[0]['lang'], total, usage, usable)
  162. for push_vo in push_qs:
  163. kwargs = {
  164. 'n_time': now_time,
  165. 'event_type': 1,
  166. 'nickname': item.serial_no,
  167. }
  168. push_type = push_vo['push_type']
  169. token_val = push_vo['token_val']
  170. lang = push_vo['lang']
  171. app_bundle_id = push_vo['app_bundle_id']
  172. # 获取推送所需数据
  173. msg_title = PushObject.get_msg_title(item.serial_no)
  174. sys_msg_text = sys_msg if msg else cls.get_msg_text(item.serial_no, lang, total, usage, usable)
  175. kwargs['app_bundle_id'] = app_bundle_id
  176. kwargs['token_val'] = token_val
  177. kwargs['msg_title'] = msg_title
  178. kwargs['msg_text'] = sys_msg_text
  179. if not cls.msg_push(push_type, **kwargs):
  180. continue
  181. cls.sys_msg_save(user_id, item.serial_no, now_time, sys_msg)
  182. # 修改推送状态
  183. UnicomFlowPush.objects.filter(id=item.id).update(status=1)
  184. except Exception as e:
  185. logger.info('出错了~4G流量推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  186. continue
  187. return response.json(0)
  188. @staticmethod
  189. def get_msg_text(serial_no, lang, total, usage, usable):
  190. """
  191. app消息推送内容
  192. """
  193. if lang == 'cn':
  194. sys_msg_text = "温馨提示:尊敬的客户,您" + serial_no + "设备当前套餐总流量共" + total + ",已使用" + \
  195. usage + "" + ",剩余" + usable + ""
  196. else:
  197. sys_msg_text = 'Warm tip: Dear customer, the total traffic of your ' + serial_no + \
  198. ' device is ' + total + 'g in the current package. ' + usage + \
  199. ' has been used and ' + usable + ' is left'
  200. return sys_msg_text
  201. @staticmethod
  202. def msg_push(push_type, **kwargs):
  203. """
  204. app推送
  205. """
  206. logger = logging.getLogger('info')
  207. try:
  208. # ios apns
  209. if push_type == 0:
  210. PushObject.ios_apns_push(**kwargs)
  211. # android gcm
  212. elif push_type == 1:
  213. PushObject.android_fcm_push_v1(**kwargs)
  214. # android 极光推送
  215. elif push_type == 2:
  216. PushObject.android_jpush(**kwargs)
  217. elif push_type == 3:
  218. huawei_push_object = HuaweiPushObject()
  219. huawei_push_object.send_push_notify_message(**kwargs)
  220. # android 小米推送
  221. elif push_type == 4:
  222. channel_id = XM_PUSH_CHANNEL_ID['service_reminder']
  223. PushObject.android_xmpush(channel_id=channel_id, **kwargs)
  224. # android vivo推送
  225. elif push_type == 5:
  226. PushObject.android_vivopush(**kwargs)
  227. # android oppo推送
  228. elif push_type == 6:
  229. channel_id = 'VALUE_ADDED'
  230. PushObject.android_oppopush(channel_id=channel_id, **kwargs)
  231. # android 魅族推送
  232. elif push_type == 7:
  233. PushObject.android_meizupush(**kwargs)
  234. return True
  235. except Exception as e:
  236. logger.info('流量预警推送异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  237. return False
  238. @staticmethod
  239. def send_aliyun_sms(phone, params, temp_code):
  240. """
  241. 推送阿里云国内短信通知
  242. """
  243. sign = '周视'
  244. ali_sms = AliyunSmsObject()
  245. ali_sms.send_code_sms_cloud(phone, params, sign, temp_code)
  246. @staticmethod
  247. def flow_split(flow):
  248. """
  249. 流量保留两位小数并带单位
  250. """
  251. if flow >= 1024:
  252. flow = flow / 1024
  253. return str(round(flow, 2)) + "G"
  254. else:
  255. return str(round(flow, 2)) + "M"
  256. @staticmethod
  257. def get_sys_msg_text(serial_no, combo_name, sys_type):
  258. """
  259. 获取系统消息文本
  260. @return:
  261. """
  262. if sys_type == 4:
  263. sys_msg_text = "温馨提示:尊敬的客户,您" + serial_no + "设备当前4G" + combo_name + "已到期"
  264. elif sys_type == 3:
  265. sys_msg_text = "温馨提示:尊敬的客户,您" + serial_no + "设备当前4G" + combo_name + "已激活"
  266. else:
  267. sys_msg_text = "温馨提示:尊敬的客户,您" + serial_no + "设备当前4G" + combo_name + "已用完"
  268. return sys_msg_text