InitController.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. # @Author : Rocky
  2. # @File : InitController.py
  3. # @Time : 2023/4/11 17:26
  4. import json
  5. import logging
  6. import os
  7. import time
  8. import apns2
  9. from _ssl import SSLError
  10. from django.http import HttpResponse
  11. from django.views import View
  12. from AnsjerPush.config import CONFIG_INFO
  13. from Model.models import Device_Info, SceneLog, EquipmentInfo1
  14. from Object.RedisObject import RedisObject
  15. from Object.ResponseObject import ResponseObject
  16. from AnsjerPush.config import APP_BUNDLE_DICT, APNS_MODE, BASE_DIR, APNS_CONFIG, DATA_PUSH_EVENT_TYPE_LIST
  17. from Object.S3Email import S3Email
  18. from Service.CommonService import CommonService
  19. ERROR_INFO_LOGGER = logging.getLogger('error_info')
  20. class InitView(View):
  21. def get(self, request, *args, **kwargs):
  22. request.encoding = 'utf-8'
  23. operation = kwargs.get('operation')
  24. return self.validation(request.GET, operation)
  25. def post(self, request, *args, **kwargs):
  26. request.encoding = 'utf-8'
  27. operation = kwargs.get('operation')
  28. return self.validation(request.POST, operation)
  29. def validation(self, request_dict, operation):
  30. if operation == 'health-check': # 负载均衡器健康检测接口
  31. return self.health_check(request_dict)
  32. if operation == 'checkApnsPem': # 检查🍎推送证书
  33. return self.check_apns_pem()
  34. elif operation == 'oci_redis_test':
  35. return self.oci_redis_test(request_dict)
  36. elif operation == 'oci_redis_test_2':
  37. return self.oci_redis_test_2(request_dict)
  38. @staticmethod
  39. def health_check(request_dict):
  40. try:
  41. redis_obj = RedisObject()
  42. redis_obj.set_data('health_check', 1)
  43. response = ResponseObject()
  44. Device_Info.objects.filter().values('id').first()
  45. SceneLog.objects.filter().values('id').first()
  46. return response.json(0)
  47. except Exception as e:
  48. ERROR_INFO_LOGGER.info(
  49. '健康检查接口异常,error_line:{},error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  50. return HttpResponse(repr(e), status=500)
  51. @staticmethod
  52. def check_apns_pem():
  53. response = ResponseObject()
  54. try:
  55. n_time = int(time.time())
  56. uid, msg_title, msg_text, launch_image, event_type, channel, nickname, token_val = \
  57. '', '', '', '', 1, '', '', ''
  58. app_bundle_id_list = [
  59. 'com.ansjer.zccloud', 'com.ansjer.loocamccloud', 'com.cloudlife.commissionf', 'com.ansjer.customizeda',
  60. 'com.ansjer.customizedb', 'com.ansjer.customizedc', 'com.ansjer.customizedd', 'com.ansjer.customizede'
  61. ]
  62. for app_bundle_id in app_bundle_id_list:
  63. pem_path = os.path.join(BASE_DIR, APNS_CONFIG[app_bundle_id]['pem_path'])
  64. cli = apns2.APNSClient(mode=APNS_MODE, client_cert=pem_path)
  65. alert = apns2.PayloadAlert(title=msg_title, body=msg_text, launch_image=launch_image)
  66. # 跳转类型,1:推送消息,2:系统消息,3:音视频通话消息
  67. jump_type = CommonService.get_jump_type(event_type)
  68. push_data = {
  69. 'alert': msg_text, 'msg': '', 'sound': '', 'zpush': '1', 'uid': uid, 'channel': channel,
  70. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  71. 'image_url': launch_image, 'jump_type': jump_type
  72. }
  73. sound = 'call_phone.mp3' if event_type in DATA_PUSH_EVENT_TYPE_LIST else 'default'
  74. payload = apns2.Payload(alert=alert, custom=push_data, sound=sound, category='myCategory',
  75. mutable_content=True)
  76. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  77. try:
  78. res = cli.push(n=n, device_token=token_val, topic=app_bundle_id)
  79. except SSLError as e:
  80. email_content = '{}服苹果推送证书过期: {}'.format(CONFIG_INFO, pem_path)
  81. S3Email().faEmail(email_content, 'servers@ansjer.com')
  82. return response.json(0)
  83. except Exception as e:
  84. return response.json(0, 'error_line:{},error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  85. @staticmethod
  86. def oci_redis_test(request_dict):
  87. try:
  88. key = request_dict.get('key', None)
  89. value = request_dict.get('value', None)
  90. response = ResponseObject()
  91. redis_obj = RedisObject()
  92. redis_obj.set_data(key, value, 60)
  93. redis_value = redis_obj.get_data(key)
  94. res = {
  95. 'redis_value': redis_value
  96. }
  97. return response.json(0, res)
  98. except Exception as e:
  99. return HttpResponse(repr(e), status=500)
  100. @staticmethod
  101. def oci_redis_test_2(request_dict):
  102. try:
  103. redis_obj = RedisObject()
  104. pipe = redis_obj.CONN.pipeline()
  105. response = ResponseObject()
  106. equipment_info_kwargs = {
  107. 'device_user_id': '163417566733313800138000',
  108. 'event_time': int(time.time()),
  109. 'event_type': 0,
  110. 'device_uid': 'H47UZJ7PHY2NXKNW111A',
  111. 'device_nick_name': 'redis_test',
  112. 'channel': 1,
  113. 'alarm': 'Motion',
  114. 'is_st': 0,
  115. 'add_time': int(time.time()),
  116. 'storage_location': 1,
  117. 'event_tag': '',
  118. 'answer_status': 0
  119. }
  120. # 保存到redis列表
  121. equipment_info_value = json.dumps(equipment_info_kwargs)
  122. equipment_info_key = 'equipment_info'
  123. pipe.rpush(equipment_info_key, equipment_info_value)
  124. pipe.rpush(equipment_info_key, equipment_info_value)
  125. pipe.execute()
  126. equipment_info_redis_list = redis_obj.lrange(equipment_info_key, 0, 99)
  127. redis_obj.ltrim(equipment_info_key, 100, -1)
  128. equipment_info_list = []
  129. for equipment_info in equipment_info_redis_list:
  130. equipment_info_data = eval(equipment_info)
  131. # 设备昵称存在表情,解码utf-8
  132. if equipment_info_data.get('device_nick_name') is not None:
  133. equipment_info_data['device_nick_name'] = equipment_info_data['device_nick_name']. \
  134. encode('UTF-8', 'ignore').decode('UTF-8')
  135. equipment_info_list.append(EquipmentInfo1(**equipment_info_data))
  136. EquipmentInfo1.objects.bulk_create(equipment_info_list)
  137. return response.json(0)
  138. except Exception as e:
  139. return HttpResponse(repr(e), status=500)