EquipmentFamilyManager.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : EquipmentFamilyManager.py
  4. @Time : 2022/5/13 15:50
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import base64
  10. import time
  11. import oss2
  12. from django.db import transaction
  13. from django.db.models import Q
  14. from django.views.generic.base import View
  15. from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY
  16. from Controller.CheckUserData import RandomStr
  17. from Controller.DeviceConfirmRegion import Device_Region
  18. from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidChannelSetModel, \
  19. iotdeviceInfoModel, UIDModel
  20. from Object.ResponseObject import ResponseObject
  21. from Object.TokenObject import TokenObject
  22. from Service.CommonService import CommonService
  23. # 家庭设备管理
  24. class EquipmentFamilyManager(View):
  25. def get(self, request, *args, **kwargs):
  26. request.encoding = 'utf-8'
  27. operation = kwargs.get('operation')
  28. return self.validation(request.GET, request, operation)
  29. def post(self, request, *args, **kwargs):
  30. request.encoding = 'utf-8'
  31. operation = kwargs.get('operation')
  32. return self.validation(request.POST, request, operation)
  33. def validation(self, request_dict, request, operation):
  34. token = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
  35. lang = request_dict.get('lang', None)
  36. if lang:
  37. response = ResponseObject(lang)
  38. else:
  39. response = ResponseObject(token.lang) if token.lang else ResponseObject()
  40. if token.code != 0:
  41. return response.json(token.code)
  42. user_id = token.userID
  43. # 手机端添加设备,查询,修改
  44. if operation == 'add':
  45. return self.do_save(user_id, request_dict, response, request)
  46. if operation == 'page':
  47. return self.do_device_page(user_id, request_dict, response)
  48. if operation == 'query':
  49. return self.do_device_query(user_id, request_dict, response)
  50. else:
  51. return response.json(414)
  52. @classmethod
  53. def do_save(cls, user_id, request_dict, response, request):
  54. """
  55. 添加设备
  56. @param request:
  57. @param user_id:
  58. @param request_dict:
  59. @param response:
  60. @return:
  61. """
  62. nick_name = request_dict.get('nickName', None)
  63. serial_number = request_dict.get('serialNumber', None)
  64. device_type = request_dict.get('deviceType', None)
  65. # type 可能为0
  66. if not all([nick_name, serial_number, device_type]):
  67. return response.json(444, {'param': 'nick_name, serial_number, device_type'})
  68. device_info_qs = Device_Info.objects.filter(serial_number=serial_number, userID_id=user_id)
  69. if device_info_qs:
  70. # 判断设备是否已存在
  71. if device_info_qs[0].isExist == 1:
  72. return response.json(174)
  73. else:
  74. device_info_qs.delete()
  75. try:
  76. with transaction.atomic():
  77. # 格式化后的日期时间
  78. now_time = CommonService.timestamp_to_str(int(time.time()))
  79. device_id = CommonService.getUserID(getUser=False)
  80. Device_Info.objects.create(id=device_id, userID_id=user_id, NickName=nick_name,
  81. Type=device_type,
  82. serial_number=serial_number, data_joined=now_time,
  83. update_time=now_time)
  84. # 判断是否有用户绑定
  85. us_qs = UidSetModel.objects.filter(uid=serial_number)
  86. if not us_qs:
  87. n_time = int(time.time())
  88. ip = CommonService.get_ip_address(request)
  89. region_id = Device_Region().get_device_region(ip)
  90. region_alexa = 'CN' if region_id == 1 else 'ALL'
  91. uid_set_create_dict = {
  92. 'uid': serial_number,
  93. 'addTime': n_time,
  94. 'updTime': n_time,
  95. 'ip': CommonService.get_ip_address(request_dict),
  96. 'nickname': nick_name,
  97. 'region_alexa': region_alexa,
  98. }
  99. UidSetModel.objects.create(**uid_set_create_dict)
  100. return response.json(0)
  101. except Exception as e:
  102. print(e)
  103. return response.json(177, repr(e))
  104. @classmethod
  105. def do_device_page(cls, user_id, request_dict, response):
  106. """
  107. 查询设备列表
  108. @param user_id:
  109. @param request_dict:
  110. @param response:
  111. @return:
  112. """
  113. page_no = request_dict.get('pageNo', None)
  114. page_size = request_dict.get('pageSize', None)
  115. if not all([page_no, page_size]):
  116. return response.json(444)
  117. page = int(page_no)
  118. line = int(page_size)
  119. device_info_qs = Device_Info.objects.filter(userID=user_id)
  120. device_info_qs = device_info_qs.filter(~Q(isExist=0))
  121. total = device_info_qs.count()
  122. device_info_qs = device_info_qs.values("id", "userID_id", "NickName", "Type", "serial_number",
  123. "data_joined",
  124. "update_time")[(page - 1) * line: page * line]
  125. data = []
  126. for item in device_info_qs:
  127. data.append({
  128. 'id': item['id'],
  129. 'userId': item['userID_id'],
  130. 'nickName': item['NickName'],
  131. 'type': item['Type'],
  132. 'serialNumber': item['serial_number'],
  133. 'dataJoined': item['data_joined'].strftime("%Y-%m-%d %H:%M:%S"),
  134. 'updateTime': item['update_time'].strftime("%Y-%m-%d %H:%M:%S")
  135. })
  136. return response.json(0, {'list': data, 'total': total})
  137. @classmethod
  138. def do_device_query(cls, user_id, request_dict, response):
  139. """
  140. 查询用户设备信息
  141. @param user_id: 用户id
  142. @param request_dict: 请求参数
  143. @param response: 响应对象
  144. @return: response
  145. """
  146. page = request_dict.get('page', None)
  147. line = request_dict.get('line', None)
  148. nick_name = request_dict.get('NickName', None)
  149. page = int(page)
  150. line = int(line)
  151. uid = request_dict.get('uid', None)
  152. device_start = time.time()
  153. device_info_list = cls.get_device_info_list(user_id, nick_name, uid,
  154. page, line)
  155. device_end = time.time()
  156. print("设备信息代码执行时间")
  157. print(device_end - device_start)
  158. uid_list = []
  159. # 判断是否是主用户 isPrimaryUser=0:否,1:是
  160. for dvl in device_info_list:
  161. if dvl['primaryUserID'] and dvl['id'] == dvl['primaryUserID']:
  162. dvl['isPrimaryUser'] = 1
  163. else:
  164. dvl['isPrimaryUser'] = 0
  165. uid_list.append(dvl['UID'])
  166. print(uid_list)
  167. # 设备关联套餐,设备预览图
  168. bucket_start = time.time()
  169. uid_bucket_qs, uid_preview_qs = cls.get_bucket_and_preview_by_uid(uid_list)
  170. bucket_end = time.time()
  171. print("设备套餐代码执行时间")
  172. print(bucket_end - bucket_start)
  173. # 设备配置信息
  174. uid_set_start = time.time()
  175. uid_set_dict = cls.get_uid_set_dict(uid_list)
  176. uid_set_end = time.time()
  177. print("设备配置详情代码执行时间")
  178. print(uid_set_end - uid_set_start)
  179. # 设备详情信息
  180. details_start = time.time()
  181. result = cls.get_device_details(device_info_list, uid_bucket_qs, uid_preview_qs, uid_set_dict)
  182. details_end = time.time()
  183. print("设备uid详情代码执行时间")
  184. print(details_end - details_start)
  185. # print('NickName搜索缓存')
  186. # print('缓存分页')
  187. items = []
  188. pwd_start = time.time()
  189. for index, item in enumerate(result):
  190. # 加密
  191. if item['View_Password']:
  192. item['View_Password'] = cls.encrypt_pwd(item['View_Password'])
  193. items.append(item)
  194. pwd_end = time.time()
  195. print("加密代码执行时间")
  196. print(pwd_end - pwd_start)
  197. return response.json(0, items)
  198. @classmethod
  199. def get_device_info_list(cls, user_id, nick_name, uid, page, line):
  200. """
  201. 根据用户id获取设备信息
  202. @param uid: uid
  203. @param nick_name: 设备名称
  204. @param line: 条数
  205. @param page: 页数
  206. @param user_id: 用户id
  207. @return: device_info_list 设备信息列表
  208. """
  209. # 获取用户设备信息
  210. device_info_qs = Device_Info.objects.filter(userID_id=user_id)
  211. # 过滤已重置的设备
  212. device_info_qs = device_info_qs.filter(~Q(isExist=2))
  213. if nick_name:
  214. device_info_qs = device_info_qs.filter(NickName__icontains=nick_name)
  215. if uid:
  216. device_info_qs.filter(UID=uid)
  217. device_info_values = device_info_qs.values('id', 'userID', 'NickName', 'UID', 'View_Account', 'View_Password',
  218. 'ChannelIndex',
  219. 'Type', 'isShare', 'primaryUserID', 'primaryMaster', 'data_joined',
  220. 'vodPrimaryUserID',
  221. 'vodPrimaryMaster', 'userID__userEmail', 'version', 'isVod',
  222. 'isExist', 'NotificationMode',
  223. 'isCameraOpenCloud', 'serial_number')
  224. device_info_values = device_info_values[(page - 1) * line:page * line]
  225. device_info_list = CommonService.qs_to_list(device_info_values)
  226. return device_info_list
  227. @classmethod
  228. def get_bucket_and_preview_by_uid(cls, uid_list):
  229. """
  230. 根据uid列表查询套餐
  231. @param uid_list: uid列表
  232. @return: uid_bucket_qs
  233. """
  234. uid_bucket_qs = UID_Bucket.objects.filter(uid__in=uid_list).values('bucket__content', 'status', 'channel',
  235. 'endTime', 'uid')
  236. uid_preview_qs = UID_Preview.objects.filter(uid__in=uid_list).order_by('channel').values('id', 'uid', 'channel')
  237. return uid_bucket_qs, uid_preview_qs
  238. @classmethod
  239. def get_uid_set_dict(cls, uid_list):
  240. """
  241. @param uid_list: uid列表
  242. @return: uid_set_dict uid配置信息
  243. """
  244. uid_set_qs = UidSetModel.objects.filter(uid__in=uid_list) \
  245. .values('id', 'uid', 'version', 'nickname', 'ucode',
  246. 'detect_status', 'detect_group',
  247. 'detect_interval',
  248. 'region_alexa', 'is_alexa', 'deviceModel',
  249. 'TimeZone', 'TimeStatus', 'SpaceUsable',
  250. 'SpaceSum', 'MirrorType', 'RecordType',
  251. 'OutdoorModel', 'WIFIName', 'isDetector',
  252. 'DetectorRank', 'is_human', 'is_custom_voice',
  253. 'is_ptz', 'double_wifi', 'is_ai')
  254. uid_set_dict = {}
  255. for us in uid_set_qs:
  256. uid_set_dict[us['uid']] = {
  257. 'version': us['version'],
  258. 'nickname': us['nickname'],
  259. 'ucode': us['ucode'],
  260. 'detect_interval': us['detect_interval'],
  261. 'detect_group': us['detect_group'],
  262. 'detect_status': us['detect_status'],
  263. 'region_alexa': us['region_alexa'],
  264. 'is_alexa': us['is_alexa'],
  265. 'deviceModel': us['deviceModel'],
  266. 'TimeZone': us['TimeZone'],
  267. 'TimeStatus': us['TimeStatus'],
  268. 'SpaceUsable': us['SpaceUsable'],
  269. 'SpaceSum': us['SpaceSum'],
  270. 'MirrorType': us['MirrorType'],
  271. 'RecordType': us['RecordType'],
  272. 'OutdoorModel': us['OutdoorModel'],
  273. 'WIFIName': us['WIFIName'],
  274. 'isDetector': us['isDetector'],
  275. 'DetectorRank': us['DetectorRank'],
  276. 'is_human': us['is_human'],
  277. 'is_custom_voice': us['is_custom_voice'],
  278. 'is_ptz': us['is_ptz'],
  279. 'double_wifi': us['double_wifi'],
  280. 'is_ai': us['is_ai']
  281. }
  282. # 从uid_channel里面取出通道配置信息
  283. uid_channel_set_qs = UidChannelSetModel.objects.filter(uid__id=us['id']) \
  284. .values('channel', 'channel_name',
  285. 'pir_audio', 'mic_audio',
  286. 'battery_status',
  287. 'battery_level',
  288. 'sleep_status',
  289. 'sleep_time',
  290. 'light_night_model',
  291. 'light_alarm_type',
  292. 'light_alarm_level',
  293. 'light_alarm_man_en',
  294. 'light_alarm_vol',
  295. 'light_long_light'
  296. )
  297. channels_list = []
  298. for ucs in uid_channel_set_qs:
  299. channels_dict = {
  300. 'channel': ucs['channel'],
  301. 'channel_name': ucs['channel_name'],
  302. 'pir_audio': ucs['pir_audio'],
  303. 'mic_audio': ucs['mic_audio'],
  304. 'battery_status': ucs['battery_status'],
  305. 'battery_level': ucs['battery_level'],
  306. 'sleep_status': ucs['sleep_status'],
  307. 'sleep_time': ucs['sleep_time'],
  308. 'light_night_model': ucs['light_night_model'],
  309. 'light_alarm_type': ucs['light_alarm_type'],
  310. 'light_alarm_level': ucs['light_alarm_level'],
  311. 'light_alarm_man_en': ucs['light_alarm_man_en'],
  312. 'light_alarm_vol': ucs['light_alarm_vol'],
  313. 'light_long_light': ucs['light_long_light']
  314. }
  315. channels_list.append(channels_dict)
  316. uid_set_dict[us['uid']]['channels'] = channels_list
  317. return uid_set_dict
  318. @classmethod
  319. def get_device_details(cls, device_info_list, uid_bucket_qs, uid_preview_qs, uid_set_dict):
  320. """
  321. 设备详情
  322. @param device_info_list: 设备信息列表
  323. @param uid_bucket_qs: 套餐对象
  324. @param uid_preview_qs:
  325. @param uid_set_dict:
  326. @return:
  327. """
  328. now_time = int(time.time())
  329. data = []
  330. for p in device_info_list:
  331. # 获取iotDeviceInfo表的endpoint和tokenIotNumber
  332. p['iot'] = []
  333. if p['serial_number']: # 存在序列号根据序列号查询
  334. iot_device_info_qs = iotdeviceInfoModel.objects.filter(serial_number=p['serial_number'][0:6])
  335. else: # 根据uid查询
  336. iot_device_info_qs = iotdeviceInfoModel.objects.filter(uid=p['UID'])
  337. if iot_device_info_qs.exists():
  338. iot_device_Info = iot_device_info_qs.values('endpoint', 'token_iot_number')
  339. p['iot'].append({
  340. 'endpoint': iot_device_Info[0]['endpoint'],
  341. 'token_iot_number': iot_device_Info[0]['token_iot_number']
  342. })
  343. p['vod'] = []
  344. for dm in uid_bucket_qs:
  345. if p['UID'] == dm['uid']:
  346. if dm['endTime'] > now_time:
  347. p['vod'].append(dm)
  348. p['preview'] = []
  349. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  350. bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
  351. for up in uid_preview_qs:
  352. if p['UID'] == up['uid']:
  353. obj = 'uid_preview/{uid}/channel_{channel}.png'.format(uid=up['uid'], channel=up['channel'])
  354. img_sign = bucket.sign_url('GET', obj, 300)
  355. p['preview'].append(img_sign)
  356. p_uid = p['UID']
  357. # 返回设备初始化字符
  358. uid_qs = UIDModel.objects.filter(uid=p_uid).values('platform', 'init_string', 'init_string_app')
  359. if uid_qs.exists():
  360. p['platform'] = uid_qs[0]['platform']
  361. p['initString'] = uid_qs[0]['init_string']
  362. p['initStringApp'] = uid_qs[0]['init_string_app']
  363. if p_uid in uid_set_dict:
  364. # 设备版本号
  365. uidversion = uid_set_dict[p_uid]['version']
  366. if len(uidversion) > 6:
  367. uidversion = uidversion[0: uidversion.rfind('.')]
  368. p['uid_version'] = uidversion
  369. p['ucode'] = uid_set_dict[p_uid]['ucode']
  370. p['detect_interval'] = uid_set_dict[p_uid]['detect_interval']
  371. p['detect_status'] = uid_set_dict[p_uid]['detect_status']
  372. p['detect_group'] = uid_set_dict[p_uid]['detect_group']
  373. p['region_alexa'] = uid_set_dict[p_uid]['region_alexa']
  374. p['is_alexa'] = uid_set_dict[p_uid]['is_alexa']
  375. p['deviceModel'] = uid_set_dict[p_uid]['deviceModel']
  376. p['TimeZone'] = uid_set_dict[p_uid]['TimeZone']
  377. p['TimeStatus'] = uid_set_dict[p_uid]['TimeStatus']
  378. p['SpaceUsable'] = uid_set_dict[p_uid]['SpaceUsable']
  379. p['SpaceSum'] = uid_set_dict[p_uid]['SpaceSum']
  380. p['MirrorType'] = uid_set_dict[p_uid]['MirrorType']
  381. p['RecordType'] = uid_set_dict[p_uid]['RecordType']
  382. p['OutdoorModel'] = uid_set_dict[p_uid]['OutdoorModel']
  383. p['WIFIName'] = uid_set_dict[p_uid]['WIFIName']
  384. p['isDetector'] = uid_set_dict[p_uid]['isDetector']
  385. p['DetectorRank'] = uid_set_dict[p_uid]['DetectorRank']
  386. p['is_human'] = uid_set_dict[p_uid]['is_human']
  387. p['is_custom_voice'] = uid_set_dict[p_uid]['is_custom_voice']
  388. p['is_ptz'] = uid_set_dict[p_uid]['is_ptz']
  389. p['channels'] = uid_set_dict[p_uid]['channels']
  390. p['double_wifi'] = uid_set_dict[p_uid]['double_wifi']
  391. p['is_ai'] = uid_set_dict[p_uid]['is_ai']
  392. # 设备昵称 调用影子信息昵称,先阶段不可
  393. if uid_set_dict[p_uid]['nickname']:
  394. p['NickName'] = uid_set_dict[p_uid]['nickname']
  395. else:
  396. # 设备版本号
  397. p['uid_version'] = ''
  398. p['ucode'] = ''
  399. data.append(p)
  400. return data
  401. @classmethod
  402. def encrypt_pwd(cls, user_pwd):
  403. """
  404. 用户密码加密
  405. @param user_pwd:用户密码
  406. @return: user_pwd 加密后的pwd
  407. """
  408. for i in range(1, 4):
  409. if i == 1:
  410. user_pwd = RandomStr(3, False) + user_pwd + RandomStr(3, False)
  411. user_pwd = base64.b64encode(str(user_pwd).encode("utf-8")).decode('utf8')
  412. if i == 2:
  413. user_pwd = RandomStr(2, False) + str(user_pwd) + RandomStr(2, False)
  414. user_pwd = base64.b64encode(str(user_pwd).encode("utf-8")).decode('utf8')
  415. if i == 3:
  416. user_pwd = RandomStr(1, False) + str(user_pwd) + RandomStr(1, False)
  417. user_pwd = base64.b64encode(str(user_pwd).encode("utf-8")).decode('utf8')
  418. return user_pwd
  419. # @classmethod
  420. # def family_save(cls, user_id, save_type, lang):
  421. # # 0:默认创建家庭,1:新增,2:修改
  422. # n_time = int(time.time())
  423. # if save_type == 0:
  424. # device_qs = Device_User.objects.filter(userID=user_id)
  425. # if device_qs.exists():
  426. # device_user = device_qs.first()
  427. # family_name = device_user.username if device_user.username else device_user.userEmail
  428. # family_name = family_name + "的家" if lang == 'cn' else family_name + " home"
  429. # user_family = LoocamUserFamily.objects.create(name=family_name, updated_time=n_time,
  430. # created_time=n_time)
  431. # if user_family.id:
  432. # pass
  433. #
  434. # return ''
  435. # @classmethod
  436. # def family_query(cls, user_id):
  437. # family_qs = LoocamFamilyMember.objects.filter(user_id=user_id)
  438. # if family_qs.exists():
  439. # return True
  440. # else:
  441. # return False