ComboCronPushController.py 10.0 KB

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