ComboCronPushController.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. user_list = []
  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. if user_id not in user_list:
  107. cls.sys_msg_save(user_id, nickname, now_time, sys_msg_text)
  108. user_list.append(user_id)
  109. if not cls.msg_push(push_type, **kwargs):
  110. continue
  111. return True
  112. @classmethod
  113. def sys_msg_save(cls, user_id, serial_no, n_time, text_msg):
  114. """
  115. 系统消息存库
  116. """
  117. logger = logging.getLogger('info')
  118. try:
  119. data = {'addTime': n_time, 'updTime': n_time, 'userID_id': user_id, 'eventType': 0, 'msg': text_msg,
  120. 'uid': serial_no}
  121. SysMsgModel.objects.create(**data)
  122. except Exception as e:
  123. logger.info('---4G流量存库异常--- {}'.format(repr(e)))
  124. @classmethod
  125. def flow_warning_push(cls, response):
  126. """
  127. 流量到期或者流量预警消息推送
  128. """
  129. logger = logging.getLogger('info')
  130. flow_push_qs = UnicomFlowPush.objects.filter(status=0)
  131. if not flow_push_qs.exists():
  132. return response.json(0)
  133. for item in flow_push_qs:
  134. try:
  135. user_id = item.user_id
  136. if not user_id:
  137. continue
  138. user_push_qs = GatewayPush.objects.filter(user_id=user_id)
  139. if not user_push_qs:
  140. continue
  141. now_time = int(time.time())
  142. # 查询推送配置数据
  143. push_qs = GatewayPush.objects.filter(user_id=user_id, logout=False). \
  144. values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'tz')
  145. if not push_qs.exists():
  146. continue
  147. usage = cls.flow_split(item.flow_total_usage)
  148. total = cls.flow_split(item.flow_total)
  149. usable = cls.flow_split(item.flow_total - item.flow_total_usage)
  150. msg = False
  151. if item.type != 0 and item.type != 1:
  152. unicom_order_qs = UnicomComboOrderInfo.objects.filter(id=item.combo_order_id) \
  153. .values('combo__combo_name')
  154. combo_name = unicom_order_qs.first()['combo__combo_name'] if unicom_order_qs.exists() else ''
  155. sys_msg = cls.get_sys_msg_text(item.serial_no, combo_name, item.type)
  156. msg = True
  157. else:
  158. user_qs = Device_User.objects.filter(userID=user_id).values('phone')
  159. if user_qs.exists() and user_qs.first()['phone']:
  160. params = u'{"devname":"' + item.serial_no + '","usage":"流量' + usage + '","usable":"流量' + \
  161. usable + '","total":"流量共' + total + '"}'
  162. cls.send_aliyun_sms(user_qs.first()['phone'], params, 'SMS_246100414')
  163. sys_msg = cls.get_msg_text(item.serial_no, push_qs[0]['lang'], total, usage, usable)
  164. for push_vo in push_qs:
  165. kwargs = {
  166. 'n_time': now_time,
  167. 'event_type': 1,
  168. 'nickname': item.serial_no,
  169. }
  170. push_type = push_vo['push_type']
  171. token_val = push_vo['token_val']
  172. lang = push_vo['lang']
  173. app_bundle_id = push_vo['app_bundle_id']
  174. # 获取推送所需数据
  175. msg_title = PushObject.get_msg_title(item.serial_no)
  176. sys_msg_text = sys_msg if msg else cls.get_msg_text(item.serial_no, lang, total, usage, usable)
  177. kwargs['app_bundle_id'] = app_bundle_id
  178. kwargs['token_val'] = token_val
  179. kwargs['msg_title'] = msg_title
  180. kwargs['msg_text'] = sys_msg_text
  181. if not cls.msg_push(push_type, **kwargs):
  182. continue
  183. cls.sys_msg_save(user_id, item.serial_no, now_time, sys_msg)
  184. # 修改推送状态
  185. UnicomFlowPush.objects.filter(id=item.id).update(status=1)
  186. except Exception as e:
  187. logger.info('出错了~4G流量推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  188. continue
  189. return response.json(0)
  190. @staticmethod
  191. def get_msg_text(serial_no, lang, total, usage, usable):
  192. """
  193. app消息推送内容
  194. """
  195. if lang == 'cn':
  196. sys_msg_text = "温馨提示:尊敬的客户,您" + serial_no + "设备当前套餐总流量共" + total + ",已使用" + \
  197. usage + "" + ",剩余" + usable + ""
  198. else:
  199. sys_msg_text = 'Warm tip: Dear customer, the total traffic of your ' + serial_no + \
  200. ' device is ' + total + 'g in the current package. ' + usage + \
  201. ' has been used and ' + usable + ' is left'
  202. return sys_msg_text
  203. @staticmethod
  204. def msg_push(push_type, **kwargs):
  205. """
  206. app推送
  207. """
  208. logger = logging.getLogger('info')
  209. try:
  210. # ios apns
  211. if push_type == 0:
  212. PushObject.ios_apns_push(**kwargs)
  213. # android gcm
  214. elif push_type == 1:
  215. PushObject.android_fcm_push_v1(**kwargs)
  216. # android 极光推送
  217. elif push_type == 2:
  218. PushObject.android_jpush(**kwargs)
  219. elif push_type == 3:
  220. huawei_push_object = HuaweiPushObject()
  221. huawei_push_object.send_push_notify_message(**kwargs)
  222. # android 小米推送
  223. elif push_type == 4:
  224. channel_id = 104552
  225. PushObject.android_xmpush(channel_id=channel_id, **kwargs)
  226. # android vivo推送
  227. elif push_type == 5:
  228. PushObject.android_vivopush(**kwargs)
  229. # android oppo推送
  230. elif push_type == 6:
  231. channel_id = 'VALUE_ADDED'
  232. PushObject.android_oppopush(channel_id=channel_id, **kwargs)
  233. # android 魅族推送
  234. elif push_type == 7:
  235. PushObject.android_meizupush(**kwargs)
  236. return True
  237. except Exception as e:
  238. logger.info('流量预警推送异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  239. return False
  240. @staticmethod
  241. def send_aliyun_sms(phone, params, temp_code):
  242. """
  243. 推送阿里云国内短信通知
  244. """
  245. sign = '周视'
  246. ali_sms = AliyunSmsObject()
  247. ali_sms.send_code_sms_cloud(phone, params, sign, temp_code)
  248. @staticmethod
  249. def flow_split(flow):
  250. """
  251. 流量保留两位小数并带单位
  252. """
  253. if flow >= 1024:
  254. flow = flow / 1024
  255. return str(round(flow, 2)) + "G"
  256. else:
  257. return str(round(flow, 2)) + "M"
  258. @staticmethod
  259. def get_sys_msg_text(serial_no, combo_name, sys_type):
  260. """
  261. 获取系统消息文本
  262. @return:
  263. """
  264. if sys_type == 4:
  265. sys_msg_text = "温馨提示:尊敬的客户,您" + serial_no + "设备当前4G" + combo_name + "已到期"
  266. elif sys_type == 3:
  267. sys_msg_text = "温馨提示:尊敬的客户,您" + serial_no + "设备当前4G" + combo_name + "已激活"
  268. else:
  269. sys_msg_text = "温馨提示:尊敬的客户,您" + serial_no + "设备当前4G" + combo_name + "已用完"
  270. return sys_msg_text