InitController.py 7.0 KB

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