TransparentTransmissionPushController.py 8.7 KB

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