DeviceVersionInfoController.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : DeviceVersionInfoController.py
  4. @Time : 2024/11/20 14:20
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import json
  10. import time
  11. from django.http import QueryDict
  12. from django.views import View
  13. from Ansjer.config import LOGGER
  14. from Model.models import DeviceVersionInfo, Device_Info
  15. from Object.Enums.RedisKeyConstant import RedisKeyConstant
  16. from Object.RedisObject import RedisObject
  17. from Object.ResponseObject import ResponseObject
  18. from Object.TokenObject import TokenObject
  19. from Service.CommonService import CommonService
  20. class DeviceVersionInfoView(View):
  21. def get(self, request, *args, **kwargs):
  22. request.encoding = 'utf-8'
  23. operation = kwargs.get('operation')
  24. return self.validation(request.GET, request, operation)
  25. def post(self, request, *args, **kwargs):
  26. request.encoding = 'utf-8'
  27. operation = kwargs.get('operation')
  28. return self.validation(request.POST, request, operation)
  29. def delete(self, request, *args, **kwargs):
  30. request.encoding = 'utf-8'
  31. operation = kwargs.get('operation')
  32. delete = QueryDict(request.body)
  33. if not delete:
  34. delete = request.GET
  35. return self.validation(delete, request, operation)
  36. def put(self, request, *args, **kwargs):
  37. request.encoding = 'utf-8'
  38. operation = kwargs.get('operation')
  39. put = QueryDict(request.body)
  40. return self.validation(put, request, operation)
  41. def validation(self, request_dict, request, operation):
  42. response = ResponseObject('cn')
  43. if operation == 'syncVerConfig':
  44. return self.sync_ver_config(request, request_dict, response)
  45. tko = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
  46. if tko.code != 0:
  47. return response.json(tko.code)
  48. response.lang = tko.lang
  49. userID = tko.userID
  50. if operation == 'getInfo':
  51. return self.get_device_version_info(userID, request, request_dict, response)
  52. elif operation == 'validateUserDevice':
  53. return self.validateUserDevice(userID, request, request_dict, response)
  54. elif operation == 'clearDeviceVersionCache':
  55. return self.clear_device_version_cache(userID, request, request_dict, response)
  56. elif operation == 'getDeviceVersion':
  57. d_code = request_dict.get('d_code')
  58. ver = request_dict.get('ver')
  59. res = self.cache_device_version_info(d_code, ver)
  60. return response.json(0, res)
  61. else:
  62. return response.json(414)
  63. @classmethod
  64. def clear_device_version_cache(cls, user_id, request, request_dict, response):
  65. """
  66. 清除设备版本缓存
  67. @param user_id: 用户ID
  68. @param request: 请求对象
  69. @param request_dict: 请求参数
  70. @param response: 响应对象
  71. @return: 响应结果
  72. """
  73. d_code = request_dict.get('d_code', None)
  74. timestamp = request_dict.get('timestamp', None)
  75. if not d_code and not timestamp:
  76. return response.json(444) # 错误代码:缺少必要参数
  77. try:
  78. LOGGER.info(f'清除缓存 user: {user_id}, d_code: {d_code}, timestamp: {timestamp}')
  79. redis = RedisObject()
  80. if d_code:
  81. # 清除指定d_code的所有版本缓存
  82. pattern = RedisKeyConstant.ZOSI_DEVICE_VERSION_INFO.value + '*' + d_code
  83. matched_keys = redis.get_keys(pattern) # 将结果赋值给 matched_keys
  84. if matched_keys:
  85. for key in matched_keys: # 使用正确的变量名
  86. redis.del_data(key)
  87. if timestamp:
  88. # 清除创建时间早于指定时间戳的缓存
  89. devices = DeviceVersionInfo.objects.filter(created_time__lt=timestamp).values('d_code', 'software_ver')
  90. for device in devices:
  91. key = RedisKeyConstant.ZOSI_DEVICE_VERSION_INFO.value + device['software_ver'] + device['d_code']
  92. redis.del_data(key)
  93. return response.json(0, "缓存清除成功")
  94. except Exception as e:
  95. error_line = e.__traceback__.tb_lineno
  96. LOGGER.error(f'清除缓存失败 user:{user_id}, error_line:{error_line}, error_msg:{repr(e)}')
  97. return response.json(500, f'error_line:{error_line}, error_msg:{repr(e)}')
  98. @classmethod
  99. def get_device_version_info(cls, user_id, request, request_dict, response):
  100. # 从请求字典中获取uid和version
  101. uid = request_dict.get('uid')
  102. version = request_dict.get('version')
  103. # 检查version是否存在
  104. if not version:
  105. return response.json(444) # 错误代码:没有提供version
  106. try:
  107. # 示例输入字符串
  108. ip = CommonService.get_ip_address(request)
  109. LOGGER.info(f'获取设备版本配置信息 user: {user_id}, uid: {uid}, version: {version}, ip: {ip} ')
  110. # 从右侧分割字符串,获取版本和设备代码
  111. ver, d_code = version.rsplit('.', 1) # 使用从右到左分割
  112. ver = ver.replace('V', '') # 移除版本前的'V'
  113. other_features_fields = [
  114. 'supports_lighting',
  115. 'is_support_multi_speed',
  116. 'supports_algorithm_switch',
  117. 'supports_playback_filtering'
  118. ]
  119. # 创建Redis对象
  120. redis = RedisObject()
  121. # 构建Redis键
  122. version_key = RedisKeyConstant.ZOSI_DEVICE_VERSION_INFO.value + ver + d_code
  123. # 尝试从Redis中获取数据
  124. version_info = redis.get_data(version_key)
  125. if version_info:
  126. device_info = json.loads(version_info)
  127. if not device_info.get("other_features"):
  128. device_info["other_features"] = {field: -1 for field in other_features_fields}
  129. else:
  130. try:
  131. if isinstance(device_info["other_features"], str):
  132. device_info["other_features"] = json.loads(device_info["other_features"])
  133. for field in other_features_fields:
  134. if field not in device_info["other_features"] or device_info["other_features"][field] in (
  135. None, ''):
  136. device_info["other_features"][field] = -1
  137. except json.JSONDecodeError:
  138. device_info["other_features"] = {field: -1 for field in other_features_fields}
  139. # 更新Redis中的数据
  140. redis.set_data(version_key, json.dumps(device_info), 60 * 60 * 24) # 设置TTL为24小时
  141. return response.json(0, device_info)
  142. # 从数据库查询设备版本信息
  143. device_version_qs = DeviceVersionInfo.objects.filter(d_code=d_code, software_ver=ver).values()
  144. if not device_version_qs.exists():
  145. LOGGER.info(f'获取设备版本配置信息失败 user: {user_id}, uid: {uid}, version: {version}, ip: {ip} ')
  146. return response.json(173) # 错误代码:未找到设备版本信息
  147. # 从QuerySet中获取设备信息
  148. device_info = device_version_qs.first()
  149. if not device_info.get("other_features"):
  150. device_info["other_features"] = {field: -1 for field in other_features_fields}
  151. else:
  152. try:
  153. if isinstance(device_info["other_features"], str):
  154. device_info["other_features"] = json.loads(device_info["other_features"])
  155. for field in other_features_fields:
  156. if field not in device_info["other_features"] or device_info["other_features"][field] in (None,
  157. ''):
  158. device_info["other_features"][field] = -1
  159. except json.JSONDecodeError:
  160. device_info["other_features"] = {field: -1 for field in other_features_fields}
  161. # 将设备信息序列化为JSON
  162. device_json = json.dumps(device_info)
  163. # 将数据写入Redis,以便后续使用
  164. redis.set_data(version_key, device_json, 60 * 60 * 24) # 设置TTL为24小时
  165. # 返回设备信息
  166. return response.json(0, device_info)
  167. except Exception as e:
  168. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  169. @classmethod
  170. def cache_device_version_info(cls, d_code, ver):
  171. """
  172. 缓存设备版本信息
  173. :param d_code: 设备规格码(软件方案)
  174. :param ver: 设备版本号
  175. :return: 设备版本信息字典或 None
  176. """
  177. redis = RedisObject()
  178. version_key = f"{RedisKeyConstant.ZOSI_DEVICE_VERSION_INFO.value}{ver}{d_code}"
  179. try:
  180. version_info = redis.get_data(version_key)
  181. if version_info:
  182. return json.loads(version_info)
  183. except Exception as e:
  184. LOGGER.error(f"Redis get failed for key {version_key}: {e}")
  185. return None
  186. device_info = DeviceVersionInfo.objects.filter(
  187. d_code=d_code, software_ver=ver
  188. ).values().first()
  189. if not device_info:
  190. return None
  191. try:
  192. redis.set_data(version_key, json.dumps(device_info), 60 * 60 * 24)
  193. except Exception as e:
  194. LOGGER.error(f"Redis set failed for key {version_key}: {e}")
  195. return None
  196. return device_info
  197. @classmethod
  198. def validateUserDevice(cls, user_id, request, request_dict, response):
  199. """
  200. 验证用户设备
  201. @param user_id: 用户id
  202. @param request: 请求
  203. @param request_dict: 请求参数
  204. @param response: 响应参数
  205. @return: 成功 0 失败 173
  206. """
  207. uid = request_dict.get('uid')
  208. serial_number = request_dict.get('serialNumber')
  209. app_bundle_id = request_dict.get('appBundleId')
  210. m_code = request_dict.get('mCode')
  211. if not uid:
  212. return response.json(444) # 错误代码:没有提供uid
  213. try:
  214. LOGGER.info(f'直播验证用户uid:{uid},user:{user_id},m_code:{m_code}')
  215. redis = RedisObject(3)
  216. # 构建Redis键
  217. device_key = f"{RedisKeyConstant.BASIC_USER.value}{user_id}:UID:{uid}"
  218. # 尝试从Redis中获取数据
  219. device_info = redis.get_data(device_key)
  220. # 检查缓存命中和UID匹配
  221. if device_info == uid:
  222. return response.json(0, uid) # 缓存命中返回 0
  223. ip = CommonService.get_ip_address(request)
  224. LOGGER.info(f'直播验证用户uid:{uid},ip:{ip},serial:{serial_number},app{app_bundle_id}')
  225. # 从数据库查询设备版本信息
  226. try:
  227. device_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid).values('UID')
  228. if not device_qs.exists() or uid != device_qs.first().get('UID'):
  229. LOGGER.error(f'验证用户uid错误,未找到设备信息 uid:{uid}')
  230. return response.json(173) # 错误代码:未找到设备信息
  231. # 将数据写入Redis,以便后续使用,设置TTL为48小时
  232. redis.set_data(device_key, uid, 60 * 60 * 24 * 2)
  233. return response.json(0, uid) # 返回设备信息
  234. except Exception as db_exception:
  235. LOGGER.error(f'数据库查询失败 user:{user_id}, uid:{uid}, error: {repr(db_exception)}')
  236. return response.json(500, '数据库查询错误')
  237. except Exception as e:
  238. error_line = e.__traceback__.tb_lineno
  239. LOGGER.error(f'验证用户uid异常 user:{user_id}, uid:{uid}, error_line:{error_line}, error_msg:{repr(e)}')
  240. return response.json(500, f'error_line:{error_line}, error_msg:{repr(e)}')
  241. @classmethod
  242. def sync_ver_config(cls, request, request_dict, response):
  243. # 定义必要字段列表
  244. required_fields = ['dCode', 'softwareVer', 'videoCode', 'deviceType', 'supportsAlarm', 'screenChannels',
  245. 'networkType']
  246. # 验证必要参数是否存在
  247. if not all(request_dict.get(field) for field in required_fields):
  248. LOGGER.error(f'缺少必要参数: {request_dict}')
  249. return response.json(444)
  250. LOGGER.info(f'同步设备版本信息 params: {request_dict}')
  251. try:
  252. d_code = request_dict.get('dCode', '')
  253. ver = request_dict.get('softwareVer', '')
  254. # 提取参数并设置默认值(添加必要字段的类型转换)
  255. params = {
  256. 'd_code': d_code, # 字符串类型,添加默认空字符串
  257. 'software_ver': ver, # 字符串类型,添加默认空字符串
  258. 'firmware_ver': request_dict.get('firmwareVer', ''), # 已有默认空字符串,保持不变
  259. 'video_code': int(request_dict.get('videoCode', 0)), # 使用get()添加默认值0,避免KeyError
  260. 'region_alexa': request_dict.get('regionAlexa', 'ALL'), # 匹配模型默认值'ALL'
  261. 'supports_human_tracking': bool(int(request_dict.get('supportsHumanTracking', 0))), # 转为布尔值
  262. 'supports_custom_voice': bool(int(request_dict.get('supportsCustomVoice', 0))), # 转为布尔值
  263. 'supports_dual_band_wifi': bool(int(request_dict.get('supportsDualBandWifi', 0))), # 转为布尔值
  264. 'supports_four_point': bool(int(request_dict.get('supportsFourPoint', 0))), # 转为布尔值
  265. 'supports_4g': bool(int(request_dict.get('supports4g', 0))), # 转为布尔值
  266. 'supports_ptz': bool(int(request_dict.get('supportsPTZ', 0))), # 转为布尔值
  267. 'supports_ai': bool(int(request_dict.get('supportsAi', 0))), # 转为布尔值
  268. 'supports_cloud_storage': bool(int(request_dict.get('supportsCloudStorage', 0))), # 转为布尔值
  269. 'supports_alexa': bool(int(request_dict.get('supportsAlexa', 0))), # 转为布尔值
  270. 'device_type': int(request_dict.get('deviceType', 0)), # 使用get()添加默认值0
  271. 'resolution': request_dict.get('resolution', ''), # 字符串类型,添加默认空字符串
  272. 'ai_type': int(request_dict.get('aiType', 0)), # 使用get()添加默认值0
  273. 'supports_alarm': int(request_dict.get('supportsAlarm', -1)), # 使用get()添加默认值-1
  274. 'supports_night_vision': int(request_dict.get('supportsNightVision', -1)), # 使用get()添加默认值-1
  275. 'screen_channels': int(request_dict.get('screenChannels', 1)), # 匹配模型默认值1
  276. 'network_type': int(request_dict.get('networkType', 1)), # 匹配模型默认值1
  277. 'other_features': json.loads(request_dict['otherFeatures']) if request_dict.get(
  278. 'otherFeatures') else None, # 保持不变
  279. 'electricity_statistics': int(request_dict.get('electricityStatistics', 0)), # 使用get()添加默认值0
  280. 'supports_pet_tracking': int(request_dict.get('supportsPetTracking', 0)), # 使用get()添加默认值0
  281. }
  282. now_time = int(time.time())
  283. # 使用 update_or_create 合并更新和创建操作
  284. version_config_qs = DeviceVersionInfo.objects.filter(
  285. d_code=params['d_code'],
  286. software_ver=params['software_ver']
  287. )
  288. if version_config_qs.exists():
  289. version_config_qs.update(**params, updated_time=now_time)
  290. # 创建Redis对象
  291. redis = RedisObject()
  292. # 构建Redis键
  293. version_key = RedisKeyConstant.ZOSI_DEVICE_VERSION_INFO.value + ver + d_code
  294. redis.del_data(version_key)
  295. else:
  296. DeviceVersionInfo.objects.create(**params, created_time=now_time, updated_time=now_time)
  297. except json.JSONDecodeError as e:
  298. # 专门捕获 JSON 解析错误
  299. LOGGER.error(f"JSON 解析失败: {str(e)}")
  300. return response.json(500, f'Invalid JSON format: {str(e)}')
  301. except KeyError as e:
  302. # 处理字段缺失(理论上 required_fields 已校验,此处作为备用)
  303. LOGGER.error(f"参数缺失: {str(e)}")
  304. return response.json(444, f'Missing parameter: {str(e)}')
  305. except ValueError as e:
  306. # 处理整型转换失败
  307. LOGGER.error(f"参数类型错误: {str(e)}")
  308. return response.json(400, f'Invalid parameter type: {str(e)}')
  309. except Exception as e:
  310. # 通用异常处理(建议替换为具体异常类型)
  311. LOGGER.exception("同步设备配置失败")
  312. return response.json(500, f'Server error: {str(e)}')
  313. return response.json(0)