ComboCronPushController.py 12 KB

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