InitController.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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. server_id = os.environ.get('ServerID', 0)
  56. n_time = int(time.time())
  57. uid, msg_title, msg_text, launch_image, event_type, channel, nickname, token_val = \
  58. '', '', '', '', 1, '', '', ''
  59. app_bundle_id_list = [
  60. 'com.ansjer.zccloud', 'com.ansjer.loocamccloud', 'com.cloudlife.commissionf', 'com.ansjer.customizeda',
  61. 'com.ansjer.customizedb', 'com.ansjer.customizedc', 'com.ansjer.customizedd', 'com.ansjer.customizede'
  62. ]
  63. for app_bundle_id in app_bundle_id_list:
  64. pem_path = os.path.join(BASE_DIR, APNS_CONFIG[app_bundle_id]['pem_path'])
  65. cli = apns2.APNSClient(mode=APNS_MODE, client_cert=pem_path)
  66. alert = apns2.PayloadAlert(title=msg_title, body=msg_text, launch_image=launch_image)
  67. # 跳转类型,1:推送消息,2:系统消息,3:音视频通话消息
  68. jump_type = CommonService.get_jump_type(event_type)
  69. push_data = {
  70. 'alert': msg_text, 'msg': '', 'sound': '', 'zpush': '1', 'uid': uid, 'channel': channel,
  71. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  72. 'image_url': launch_image, 'jump_type': jump_type
  73. }
  74. sound = 'call_phone.mp3' if event_type in DATA_PUSH_EVENT_TYPE_LIST else 'default'
  75. payload = apns2.Payload(alert=alert, custom=push_data, sound=sound, category='myCategory',
  76. mutable_content=True)
  77. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  78. try:
  79. res = cli.push(n=n, device_token=token_val, topic=app_bundle_id)
  80. except SSLError as e:
  81. email_content = '{}服第{}台服务器苹果推送证书过期: {}'.format(CONFIG_INFO, server_id, pem_path)
  82. S3Email().faEmail(email_content, 'servers@ansjer.com')
  83. return response.json(0)
  84. except Exception as e:
  85. return response.json(0, 'error_line:{},error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  86. @staticmethod
  87. def oci_redis_test(request_dict):
  88. try:
  89. key = request_dict.get('key', None)
  90. value = request_dict.get('value', None)
  91. response = ResponseObject()
  92. redis_obj = RedisObject()
  93. redis_obj.set_data(key, value, 60)
  94. redis_value = redis_obj.get_data(key)
  95. res = {
  96. 'redis_value': redis_value
  97. }
  98. return response.json(0, res)
  99. except Exception as e:
  100. return HttpResponse(repr(e), status=500)
  101. @staticmethod
  102. def oci_redis_test_2(request_dict):
  103. try:
  104. redis_obj = RedisObject()
  105. pipe = redis_obj.CONN.pipeline()
  106. response = ResponseObject()
  107. equipment_info_kwargs = {
  108. 'device_user_id': '163417566733313800138000',
  109. 'event_time': int(time.time()),
  110. 'event_type': 0,
  111. 'device_uid': 'H47UZJ7PHY2NXKNW111A',
  112. 'device_nick_name': 'redis_test',
  113. 'channel': 1,
  114. 'alarm': 'Motion',
  115. 'is_st': 0,
  116. 'add_time': int(time.time()),
  117. 'storage_location': 1,
  118. 'event_tag': '',
  119. 'answer_status': 0
  120. }
  121. # 保存到redis列表
  122. equipment_info_value = json.dumps(equipment_info_kwargs)
  123. equipment_info_key = 'equipment_info'
  124. pipe.rpush(equipment_info_key, equipment_info_value)
  125. pipe.rpush(equipment_info_key, equipment_info_value)
  126. pipe.execute()
  127. equipment_info_redis_list = redis_obj.lrange(equipment_info_key, 0, 99)
  128. redis_obj.ltrim(equipment_info_key, 100, -1)
  129. equipment_info_list = []
  130. for equipment_info in equipment_info_redis_list:
  131. equipment_info_data = eval(equipment_info)
  132. # 设备昵称存在表情,解码utf-8
  133. if equipment_info_data.get('device_nick_name') is not None:
  134. equipment_info_data['device_nick_name'] = equipment_info_data['device_nick_name']. \
  135. encode('UTF-8', 'ignore').decode('UTF-8')
  136. equipment_info_list.append(EquipmentInfo1(**equipment_info_data))
  137. EquipmentInfo1.objects.bulk_create(equipment_info_list)
  138. return response.json(0)
  139. except Exception as e:
  140. return HttpResponse(repr(e), status=500)