ComboCronPushController.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. logger = logging.getLogger('info')
  123. flow_push_qs = UnicomFlowPush.objects.filter(type=0, status=0)
  124. if not flow_push_qs.exists():
  125. return response.json(0)
  126. for item in flow_push_qs:
  127. try:
  128. user_id = item.user_id
  129. if not user_id:
  130. continue
  131. user_push_qs = GatewayPush.objects.filter(user_id=user_id)
  132. if not user_push_qs:
  133. continue
  134. now_time = int(time.time())
  135. # 查询推送配置数据
  136. push_qs = GatewayPush.objects.filter(user_id=user_id, logout=False). \
  137. values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'tz')
  138. if not push_qs.exists():
  139. continue
  140. usage = cls.flow_split(item.flow_total_usage)
  141. total = cls.flow_split(item.flow_total)
  142. usable = cls.flow_split(item.flow_total - item.flow_total_usage)
  143. user_qs = Device_User.objects.filter(userID=user_id).values('phone')
  144. if user_qs.exists() and user_qs.first()['phone']:
  145. params = u'{"devname":"' + item.serial_no + '","usage":"流量' + usage + '","usable":"流量' + \
  146. usable + '"}'
  147. cls.send_aliyun_sms(user_qs.first()['phone'], params, 'SMS_246090429')
  148. for push_vo in push_qs:
  149. kwargs = {
  150. 'n_time': now_time,
  151. 'event_type': 1,
  152. 'nickname': item.serial_no,
  153. }
  154. push_type = push_vo['push_type']
  155. token_val = push_vo['token_val']
  156. lang = push_vo['lang']
  157. app_bundle_id = push_vo['app_bundle_id']
  158. # 获取推送所需数据
  159. msg_title = GatewayPushService.get_msg_title(app_bundle_id, item.serial_no)
  160. sys_msg_text = cls.get_msg_text(item.serial_no, lang, total, usage, usable)
  161. kwargs['app_bundle_id'] = app_bundle_id
  162. kwargs['token_val'] = token_val
  163. kwargs['msg_title'] = msg_title
  164. kwargs['msg_text'] = sys_msg_text
  165. cls.sys_msg_save(user_id, item.serial_no, now_time, sys_msg_text)
  166. if not cls.msg_push(push_type, **kwargs):
  167. continue
  168. # 修改推送状态
  169. UnicomFlowPush.objects.filter(id=item.id).update(status=1)
  170. except Exception as e:
  171. logger.info('出错了~4G流量10%预警推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  172. continue
  173. return response.json(0)
  174. @staticmethod
  175. def get_msg_text(serial_no, lang, total, usage, usable):
  176. """
  177. app消息推送内容
  178. """
  179. if lang == 'cn':
  180. sys_msg_text = "温馨提示:尊敬的客户,您" + serial_no + "设备当前套餐总流量共" + total + ",已使用" + \
  181. usage + "" + ",剩余" + usable + ""
  182. else:
  183. sys_msg_text = 'Warm tip: Dear customer, the total traffic of your ' + serial_no + \
  184. ' device is ' + total + 'g in the current package. ' + usage + \
  185. ' has been used and ' + usable + ' is left'
  186. return sys_msg_text
  187. @staticmethod
  188. def msg_push(push_type, **kwargs):
  189. """
  190. app推送
  191. """
  192. logger = logging.getLogger('info')
  193. try:
  194. # ios apns
  195. if push_type == 0:
  196. GatewayPushService.ios_apns_push(**kwargs)
  197. # android gcm
  198. elif push_type == 1:
  199. GatewayPushService.android_fcm_push(**kwargs)
  200. # android 极光推送
  201. elif push_type == 2:
  202. GatewayPushService.android_jpush(**kwargs)
  203. return True
  204. except Exception as e:
  205. logger.info('流量预警推送异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  206. return False
  207. @staticmethod
  208. def send_aliyun_sms(phone, params, temp_code):
  209. """
  210. 推送阿里云国内短信通知
  211. """
  212. sign = '周视'
  213. ali_sms = AliyunSmsObject()
  214. ali_sms.send_code_sms_cloud(phone, params, sign, temp_code)
  215. @staticmethod
  216. def flow_split(flow):
  217. """
  218. 流量保留两位小数并带单位
  219. """
  220. if flow >= 1024:
  221. flow = flow / 1024
  222. return str(round(flow, 2)) + "G"
  223. else:
  224. return str(round(flow, 2)) + "M"