TransparentTransmissionPushController.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. # @Author : peng
  2. # @File : TransparentTransmissionPushController.py
  3. # @Time : 2024年7月9日17:22:19
  4. import json
  5. import threading
  6. import time
  7. import requests
  8. from django.http import HttpResponse
  9. from django.views import View
  10. from Model.models import UidPushModel, GatewayPush
  11. from Object.ResponseObject import ResponseObject
  12. from Service.HuaweiPushService.HuaweiPushService import HuaweiPushObject
  13. from Service.PushService import PushObject
  14. from AnsjerPush.config import XM_PUSH_CHANNEL_ID, HONORPUSH_CONFIG, LOGGER, APP_MAPPING
  15. import logging
  16. ERROR_INFO_LOGGER = logging.getLogger('error_info')
  17. class TransparentTransmissionPushView(View):
  18. def get(self, request, *args, **kwargs):
  19. request.encoding = 'utf-8'
  20. operation = kwargs.get('operation')
  21. return self.validation(request.GET, operation)
  22. def post(self, request, *args, **kwargs):
  23. request.encoding = 'utf-8'
  24. operation = kwargs.get('operation')
  25. return self.validation(request.POST, operation)
  26. def validation(self, request_dict, operation):
  27. response = ResponseObject()
  28. if operation == 'logout-push': # 强制退出推送
  29. return self.logout_push(request_dict, response)
  30. elif operation == 'del-device-push': # 删除设备推送
  31. return self.del_device_push(request_dict, response)
  32. @staticmethod
  33. def logout_push(request_dict, response):
  34. LOGGER.info('进入登出推送接口,参数:{}'.format(request_dict))
  35. push_token = request_dict.get('push_token', None)
  36. user_id = request_dict.get('user_id', None)
  37. app_bundle_id = request_dict.get('app_bundle_id', None)
  38. if not all([push_token, user_id, app_bundle_id]):
  39. return response.json(444)
  40. try:
  41. app_bundle_list = APP_MAPPING.get(app_bundle_id, None)
  42. uid_push_qs = GatewayPush.objects.filter(user_id=user_id, app_bundle_id__in=app_bundle_list,
  43. logout=False).exclude(token_val=push_token).values('token_val',
  44. 'push_type',
  45. 'app_bundle_id',
  46. 'jg_token_val').distinct().order_by(
  47. 'token_val')
  48. if not uid_push_qs.exists():
  49. return response.json(173)
  50. uid_push_list = list(uid_push_qs)
  51. LOGGER.info('{}推送列表:{}'.format(user_id, uid_push_list))
  52. push_thread = threading.Thread(target=TransparentTransmissionPushView.thread_push,
  53. args=(uid_push_list, user_id, '强制登出', '强制登出', 705))
  54. push_thread.start()
  55. # 删除推送信息
  56. UidPushModel.objects.filter(userID=user_id, appBundleId__in=app_bundle_list).exclude(
  57. token_val=push_token).delete()
  58. GatewayPush.objects.filter(user_id=user_id, app_bundle_id__in=app_bundle_list).exclude(
  59. token_val=push_token).update(logout=True)
  60. return response.json(0)
  61. except Exception as e:
  62. return HttpResponse(repr(e), status=500)
  63. @staticmethod
  64. def del_device_push(request_dict, response):
  65. uid = request_dict.get('uid', None)
  66. if not all([uid]):
  67. return response.json(444)
  68. try:
  69. uid_push_qs = UidPushModel.objects.filter(uid_set_uid=uid).values(
  70. 'token_val', 'appBundleId', 'push_type', 'jg_token_val')
  71. if not uid_push_qs.exists():
  72. return response.json(173)
  73. push_thread = threading.Thread(target=TransparentTransmissionPushView.thread_push,
  74. args=(uid_push_qs, uid, '删除设备', '删除设备'))
  75. push_thread.start()
  76. return response.json(0)
  77. except Exception as e:
  78. return HttpResponse(repr(e), status=500)
  79. @staticmethod
  80. def thread_push(push_list, user_id, title, content, event_type):
  81. try:
  82. now_time = int(time.time())
  83. for push_item in push_list:
  84. kwargs = {
  85. 'nickname': user_id,
  86. 'app_bundle_id': push_item['app_bundle_id'],
  87. 'token_val': push_item['token_val'],
  88. 'n_time': now_time,
  89. 'event_type': event_type,
  90. 'msg_title': title,
  91. 'msg_text': content,
  92. }
  93. LOGGER.info('进入登出推送线程,参数:{}'.format(kwargs))
  94. if push_item['push_type'] == 0: # 苹果
  95. PushObject.ios_apns_push(**kwargs)
  96. elif push_item['push_type'] == 1: # 谷歌
  97. PushObject.android_fcm_push_v1(**kwargs)
  98. elif push_item['push_type'] == 2: # 极光
  99. PushObject.jpush_transparent_transmission(title, content, push_item['app_bundle_id'],
  100. push_item['token_val'], kwargs)
  101. elif push_item['push_type'] == 3: # 华为
  102. huawei_push_object = HuaweiPushObject()
  103. huawei_push_object.huawei_transparent_transmission(user_id=user_id, **kwargs)
  104. elif push_item['push_type'] == 4: # 小米
  105. channel_id = XM_PUSH_CHANNEL_ID['single_login']
  106. PushObject.android_xmpush(channel_id=channel_id, **kwargs)
  107. elif push_item['push_type'] in [5, 6]: # vivo, oppo
  108. kwargs['token_val'] = push_item['jg_token_val']
  109. PushObject.jpush_transparent_transmission(title, content, push_item['app_bundle_id'],
  110. push_item['jg_token_val'], kwargs)
  111. elif push_item['push_type'] == 7: # 魅族
  112. PushObject.android_meizupush(**kwargs)
  113. elif push_item['push_type'] == 8: # 荣耀
  114. TransparentTransmissionPushView.honor_transparent_transmission(**kwargs)
  115. except Exception as e:
  116. ERROR_INFO_LOGGER.info(
  117. 'TransparentTransmissionPushView推送线程异常:errLine:{}, errMsg:{}, 参数:{}'.format(
  118. e.__traceback__.tb_lineno, repr(e), push_list))
  119. @staticmethod
  120. def honor_transparent_transmission(token_val, n_time, event_type, msg_title, msg_text, app_bundle_id, nickname=''):
  121. """
  122. android honor 推送
  123. @param nickname: 设备昵称
  124. @param app_bundle_id: app包id
  125. @param token_val: 推送token
  126. @param n_time: 当前时间
  127. @param event_type: 事件类型
  128. @param msg_title: 推送标题
  129. @param msg_text: 推送内容
  130. @return: bool
  131. """
  132. try:
  133. client_id = HONORPUSH_CONFIG[app_bundle_id]['client_id']
  134. client_secret = HONORPUSH_CONFIG[app_bundle_id]['client_secret']
  135. app_id = HONORPUSH_CONFIG[app_bundle_id]['app_id']
  136. get_access_token_url = 'https://iam.developer.hihonor.com/auth/token'
  137. post_data = {
  138. 'grant_type': 'client_credentials',
  139. 'client_id': client_id,
  140. 'client_secret': client_secret
  141. }
  142. headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  143. access_token_response = requests.post(get_access_token_url, data=post_data, headers=headers)
  144. access_result = access_token_response.json()
  145. authorization_token = 'Bearer ' + access_result['access_token']
  146. # 发送推送
  147. push_url = 'https://push-api.cloud.hihonor.com/api/v1/{}/sendMessage'.format(app_id)
  148. headers = {'Content-Type': 'application/json', 'Authorization': authorization_token,
  149. 'timestamp': str(int(time.time()) * 1000)}
  150. extra_data = {'alert': msg_text, 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  151. 'received_at': n_time, 'event_time': n_time, 'event_type': str(event_type),
  152. 'nickname': nickname, 'title': msg_title, 'body': msg_text}
  153. # 透传推送
  154. push_data = {
  155. "data": json.dumps(extra_data),
  156. "token": [token_val]
  157. }
  158. response = requests.post(push_url, json=push_data, headers=headers)
  159. LOGGER.info("用户:{},时间:{},荣耀透传推送返回值:{}".format(nickname, n_time, response.json()))
  160. return True
  161. except Exception as e:
  162. LOGGER.info("荣耀推送异常:error_line:{},error_msg:{}".format(e.__traceback__.tb_lineno, repr(e)))
  163. return False