TransparentTransmissionPushController.py 10 KB

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