TransparentTransmissionPushController.py 8.6 KB

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