ComboCronPushController.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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.PushService import PushObject
  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 = PushObject.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. msg = False
  147. if item.type != 0 and item.type != 1:
  148. unicom_order_qs = UnicomComboOrderInfo.objects.filter(id=item.combo_order_id) \
  149. .values('combo__combo_name')
  150. combo_name = unicom_order_qs.first()['combo__combo_name'] if unicom_order_qs.exists() else ''
  151. sys_msg = cls.get_sys_msg_text(item.serial_no, combo_name, item.type)
  152. msg = True
  153. else:
  154. user_qs = Device_User.objects.filter(userID=user_id).values('phone')
  155. if user_qs.exists() and user_qs.first()['phone']:
  156. params = u'{"devname":"' + item.serial_no + '","usage":"流量' + usage + '","usable":"流量' + \
  157. usable + '","total":"流量共' + total + '"}'
  158. cls.send_aliyun_sms(user_qs.first()['phone'], params, 'SMS_246100414')
  159. sys_msg = cls.get_msg_text(item.serial_no, push_qs[0]['lang'], total, usage, usable)
  160. for push_vo in push_qs:
  161. kwargs = {
  162. 'n_time': now_time,
  163. 'event_type': 1,
  164. 'nickname': item.serial_no,
  165. }
  166. push_type = push_vo['push_type']
  167. token_val = push_vo['token_val']
  168. lang = push_vo['lang']
  169. app_bundle_id = push_vo['app_bundle_id']
  170. # 获取推送所需数据
  171. msg_title = PushObject.get_msg_title(app_bundle_id, item.serial_no)
  172. sys_msg_text = sys_msg if msg else cls.get_msg_text(item.serial_no, lang, total, usage, usable)
  173. kwargs['app_bundle_id'] = app_bundle_id
  174. kwargs['token_val'] = token_val
  175. kwargs['msg_title'] = msg_title
  176. kwargs['msg_text'] = sys_msg_text
  177. if not cls.msg_push(push_type, **kwargs):
  178. continue
  179. cls.sys_msg_save(user_id, item.serial_no, now_time, sys_msg)
  180. # 修改推送状态
  181. UnicomFlowPush.objects.filter(id=item.id).update(status=1)
  182. except Exception as e:
  183. logger.info('出错了~4G流量推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  184. continue
  185. return response.json(0)
  186. @staticmethod
  187. def get_msg_text(serial_no, lang, total, usage, usable):
  188. """
  189. app消息推送内容
  190. """
  191. if lang == 'cn':
  192. sys_msg_text = "温馨提示:尊敬的客户,您" + serial_no + "设备当前套餐总流量共" + total + ",已使用" + \
  193. usage + "" + ",剩余" + usable + ""
  194. else:
  195. sys_msg_text = 'Warm tip: Dear customer, the total traffic of your ' + serial_no + \
  196. ' device is ' + total + 'g in the current package. ' + usage + \
  197. ' has been used and ' + usable + ' is left'
  198. return sys_msg_text
  199. @staticmethod
  200. def msg_push(push_type, **kwargs):
  201. """
  202. app推送
  203. """
  204. logger = logging.getLogger('info')
  205. try:
  206. # ios apns
  207. if push_type == 0:
  208. PushObject.ios_apns_push(**kwargs)
  209. # android gcm
  210. elif push_type == 1:
  211. PushObject.android_fcm_push(**kwargs)
  212. # android 极光推送
  213. elif push_type == 2:
  214. PushObject.android_jpush(**kwargs)
  215. # android 小米推送
  216. elif push_type == 4:
  217. PushObject.android_xmpush(**kwargs)
  218. # android vivo推送
  219. elif push_type == 5:
  220. PushObject.android_vivopush(**kwargs)
  221. # android 魅族推送
  222. elif push_type == 7:
  223. PushObject.android_meizupush(**kwargs)
  224. return True
  225. except Exception as e:
  226. logger.info('流量预警推送异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  227. return False
  228. @staticmethod
  229. def send_aliyun_sms(phone, params, temp_code):
  230. """
  231. 推送阿里云国内短信通知
  232. """
  233. sign = '周视'
  234. ali_sms = AliyunSmsObject()
  235. ali_sms.send_code_sms_cloud(phone, params, sign, temp_code)
  236. @staticmethod
  237. def flow_split(flow):
  238. """
  239. 流量保留两位小数并带单位
  240. """
  241. if flow >= 1024:
  242. flow = flow / 1024
  243. return str(round(flow, 2)) + "G"
  244. else:
  245. return str(round(flow, 2)) + "M"
  246. @staticmethod
  247. def get_sys_msg_text(serial_no, combo_name, sys_type):
  248. """
  249. 获取系统消息文本
  250. @return:
  251. """
  252. if sys_type == 4:
  253. sys_msg_text = "温馨提示:尊敬的客户,您" + serial_no + "设备当前4G" + combo_name + "已到期"
  254. elif sys_type == 3:
  255. sys_msg_text = "温馨提示:尊敬的客户,您" + serial_no + "设备当前4G" + combo_name + "已激活"
  256. else:
  257. sys_msg_text = "温馨提示:尊敬的客户,您" + serial_no + "设备当前4G" + combo_name + "已用完"
  258. return sys_msg_text