ComboCronPushController.py 12 KB

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