TransparentTransmissionPushController.py 9.2 KB

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