EquipmentManagerV3.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. import re
  2. import threading
  3. import time
  4. import traceback
  5. import requests
  6. from Controller.CheckUserData import RandomStr
  7. import oss2, base64
  8. from django.db.models import Q
  9. from django.views.generic.base import View
  10. from Controller.DeviceConfirmRegion import Device_Region
  11. from Object.RedisObject import RedisObject
  12. from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY, BASE_DIR
  13. from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidPushModel, UidChannelSetModel, \
  14. Device_User, iotdeviceInfoModel, UIDCompanySerialModel, UIDMainUser, UIDModel
  15. from Object.ResponseObject import ResponseObject
  16. from Object.TokenObject import TokenObject
  17. from Service.CommonService import CommonService
  18. from Service.ModelService import ModelService
  19. import time, json
  20. class EquipmentManagerV3(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 validation(self, request_dict, request, operation):
  30. response = ResponseObject()
  31. token = request_dict.get('token', None)
  32. # 设备主键uid
  33. if operation == 'notLoginMainUserDevice':
  34. return self.not_login_do_mainUserDevice(request_dict, response)
  35. tko = TokenObject(token)
  36. if tko.code != 0:
  37. return response.json(tko.code)
  38. response.lang = tko.lang
  39. userID = tko.userID
  40. # 手机端添加设备,查询,修改
  41. if operation == 'add':
  42. return self.do_add(userID, request_dict, response, request)
  43. elif operation == 'query':
  44. return self.do_query(userID, request_dict, response)
  45. elif operation == 'modify':
  46. return self.do_modify(userID, request_dict, response, request)
  47. elif operation == 'modifyChannelName':
  48. return self.do_modify_channel_name(userID, request_dict, response, request)
  49. elif operation == 'fuzzyQuery':
  50. return self.do_fuzzy_query(userID, request_dict, response)
  51. elif operation == 'mainUserDevice':
  52. return self.do_mainUserDevice( request_dict, response)
  53. elif operation == 'getDeviceFeatures':
  54. return self.do_get_device_features(request_dict, response)
  55. else:
  56. return response.json(414)
  57. def do_add(self, userID, request_dict, response, request):
  58. UID = request_dict.get('UID', None)
  59. NickName = request_dict.get('NickName', None)
  60. View_Account = request_dict.get('View_Account', None)
  61. View_Password = request_dict.get('View_Password', '')
  62. encrypt_pass = View_Password
  63. print("准备解密")
  64. View_Password = self.decode_pwd(View_Password)
  65. Type = request_dict.get('Type', None)
  66. ChannelIndex = request_dict.get('ChannelIndex', None)
  67. version = request_dict.get('version', '')
  68. isCheckMainUser = request_dict.get('isCheckMainUser', None)
  69. isMainUserExists = False
  70. if not all([UID, NickName, View_Account, Type, ChannelIndex]): # Type和ChannelIndex可能为0
  71. return response.json(444, {'param': 'UID, NickName, View_Account, Type, ChannelIndex'})
  72. Type = int(Type)
  73. ChannelIndex = int(ChannelIndex)
  74. re_uid = re.compile(r'^[A-Za-z0-9]{14,20}$')
  75. if not re_uid.match(UID):
  76. return response.json(444, {'param': 'UID'})
  77. device_info_qs = Device_Info.objects.filter(UID=UID, userID_id=userID)
  78. if device_info_qs:
  79. # 判断设备是否已存在
  80. if device_info_qs[0].isExist == 1:
  81. return response.json(174)
  82. else:
  83. device_info_qs.delete()
  84. id = CommonService.getUserID(getUser=False)
  85. userName = Device_User.objects.get(userID=userID).username
  86. main_exist = Device_Info.objects.filter(UID=UID)
  87. main_exist = main_exist.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID', 'vodPrimaryMaster')
  88. vodPrimaryUserID = userID
  89. vodPrimaryMaster = userName
  90. if main_exist.exists():
  91. vodPrimaryUserID = main_exist[0]['vodPrimaryUserID']
  92. vodPrimaryMaster = main_exist[0]['vodPrimaryMaster']
  93. is_bind = Device_Info.objects.filter(UID=UID, isShare=False).values('userID__userID', 'vodPrimaryUserID')
  94. isvodPrimaryUserID = ''
  95. for forbind in is_bind:
  96. if forbind['vodPrimaryUserID'] != '':
  97. isvodPrimaryUserID = forbind['vodPrimaryUserID']
  98. if isCheckMainUser != '1' :
  99. if main_exist.exists():
  100. vodPrimaryUserID = main_exist[0]['vodPrimaryUserID']
  101. vodPrimaryMaster = main_exist[0]['vodPrimaryMaster']
  102. else:
  103. vodPrimaryUserID = ''
  104. vodPrimaryMaster = ''
  105. isusermain = False
  106. if is_bind and isvodPrimaryUserID != userID and isvodPrimaryUserID != '':
  107. isusermain = True
  108. # 判断是否有已绑定用户
  109. if isCheckMainUser == '1' and isusermain:
  110. res = {
  111. 'id': id,
  112. 'userID': userID,
  113. 'NickName': NickName,
  114. 'UID': UID,
  115. 'View_Account': View_Account,
  116. 'View_Password': View_Password,
  117. 'ChannelIndex': ChannelIndex,
  118. 'Type': Type,
  119. 'isShare': False,
  120. 'primaryUserID': '',
  121. 'primaryMaster': '',
  122. 'vodPrimaryUserID': vodPrimaryUserID,
  123. 'vodPrimaryMaster': vodPrimaryMaster,
  124. 'data_joined': '',
  125. 'version': version,
  126. 'isVod': 0,
  127. 'isExist': 1,
  128. 'userID__userEmail': ''
  129. }
  130. res['vod'] = [
  131. {
  132. "status": 1,
  133. "channel": ChannelIndex,
  134. "endTime": '',
  135. "bucket__content": '',
  136. "uid": UID
  137. }
  138. ]
  139. res['isMainUserExists'] = 1
  140. return response.json(0, res)
  141. try:
  142. # 判断是否有用户绑定
  143. nowTime = int(time.time())
  144. us_qs = UidSetModel.objects.filter(uid=UID)
  145. if us_qs.exists():
  146. us_qs.update(nickname=NickName)
  147. UidSet_id = us_qs.first().id
  148. else:
  149. ip = CommonService.get_ip_address(request)
  150. region_id = Device_Region().get_device_region(ip)
  151. region_alexa = 'CN' if region_id == 1 else 'ALL'
  152. uid_set_create_dict = {
  153. 'uid': UID,
  154. 'addTime': nowTime,
  155. 'updTime': nowTime,
  156. 'ip': CommonService.get_ip_address(request_dict),
  157. 'channel': ChannelIndex,
  158. 'nickname': NickName,
  159. 'version': version,
  160. 'region_alexa': region_alexa,
  161. }
  162. UidSet = UidSetModel.objects.create(**uid_set_create_dict)
  163. UidSet_id = UidSet.id
  164. # 查询uid_channel表有无该uid的数据
  165. uid_channel_set = UidChannelSetModel.objects.filter(uid_id=UidSet_id)
  166. if not uid_channel_set.exists():
  167. # 多通道设备设置通道名
  168. multi_channel_list = [1, 2, 3, 4, 10001]
  169. if Type in multi_channel_list:
  170. UidChannelSet_bulk = []
  171. for i in range(1, ChannelIndex+1):
  172. channel_name = 'channel'+str(i) # channel1,channel2...
  173. UidChannelSet = UidChannelSetModel(uid_id=UidSet_id, channel=i, channel_name=channel_name)
  174. UidChannelSet_bulk.append(UidChannelSet)
  175. UidChannelSetModel.objects.bulk_create(UidChannelSet_bulk)
  176. userDevice = Device_Info(id=id, userID_id=userID, UID=UID, NickName=NickName, View_Account=View_Account,
  177. View_Password=View_Password, Type=Type, ChannelIndex=ChannelIndex, version=version,
  178. vodPrimaryUserID=vodPrimaryUserID, vodPrimaryMaster=vodPrimaryMaster)
  179. userDevice.save()
  180. uid_serial_qs = UIDCompanySerialModel.objects.filter(uid__uid=UID)
  181. if uid_serial_qs.exists():
  182. uid_serial = uid_serial_qs[0]
  183. Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
  184. vodPrimaryMaster=vodPrimaryMaster,
  185. serial_number=uid_serial.company_serial.serial_number + uid_serial.company_serial.company.mark)
  186. else:
  187. Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
  188. vodPrimaryMaster=vodPrimaryMaster)
  189. if not us_qs.exists():
  190. us_qs = UidSetModel.objects.filter(uid=UID)
  191. if us_qs.exists() and us_qs[0].is_alexa == 1:
  192. asy = threading.Thread(target=ModelService.notify_alexa_add,
  193. args=(UID, userID, NickName, encrypt_pass))
  194. asy.start()
  195. except Exception as e:
  196. return response.json(10, repr(e))
  197. else:
  198. dvqs = Device_Info.objects.filter(id=id).values('id', 'userID', 'NickName', 'UID',
  199. 'View_Account',
  200. 'View_Password', 'ChannelIndex', 'Type',
  201. 'isShare',
  202. 'primaryUserID', 'primaryMaster',
  203. 'vodPrimaryUserID', 'vodPrimaryMaster',
  204. 'userID__userEmail',
  205. 'data_joined', 'version',
  206. 'isVod', 'isExist', 'isCameraOpenCloud', 'serial_number')
  207. dvql = CommonService.qs_to_list(dvqs)
  208. ubqs = UID_Bucket.objects.filter(uid=UID). \
  209. values('bucket__content', 'status', 'channel', 'endTime', 'uid')
  210. res = dvql[0]
  211. res['vod'] = list(ubqs)
  212. iotqs = iotdeviceInfoModel.objects.filter(serial_number=dvql[0]['serial_number'])
  213. if iotqs.exists():
  214. res['iot'] = {
  215. 'endpoint': iotqs[0].endpoint,
  216. 'token_iot_number': iotqs[0].endpoint
  217. }
  218. return response.json(0, res)
  219. def do_modify(self, userID, request_dict, response, request):
  220. token = request_dict.get('token', None)
  221. deviceContent = request_dict.get('content', None)
  222. id = request_dict.get('id', None)
  223. if not deviceContent or not id:
  224. return response.json(444, 'content,id')
  225. tko = TokenObject(token)
  226. response.lang = tko.lang
  227. if tko.code != 0:
  228. return response.json(tko.code)
  229. userID = tko.userID
  230. if userID is None:
  231. return response.json(309)
  232. deviceData = None
  233. dev_info_qs = None
  234. try:
  235. # deviceData = json.loads(deviceContent)
  236. deviceData = eval(deviceContent)
  237. if deviceData.__contains__('userID_id'):
  238. asy = threading.Thread(target=ModelService.update_log,
  239. args=(CommonService.get_ip_address(request), userID, 'modifyV3', deviceData, id))
  240. asy.start()
  241. return response.json(10, '110')
  242. if deviceData.__contains__('UID'):
  243. del deviceData['UID']
  244. # print(deviceData['View_Password'])
  245. if deviceData.__contains__('View_Password'):
  246. encrypt_pwd = deviceData['View_Password']
  247. deviceData['View_Password'] = self.decode_pwd(deviceData['View_Password'])
  248. dev_info_qs = Device_Info.objects.filter(userID_id=userID, id=id)
  249. dev_info_qs.update(**deviceData)
  250. except Exception as e:
  251. print(e)
  252. return response.json(177, repr(e))
  253. else:
  254. qs = Device_Info.objects.filter(userID_id=userID, id=id)
  255. res = CommonService.qs_to_dict(qs)
  256. if qs.exists():
  257. uid = qs[0].UID
  258. nickname = qs[0].NickName
  259. # 增加设备影子信息修改昵称 start
  260. us_qs = UidSetModel.objects.filter(uid=uid)
  261. if us_qs.exists():
  262. if deviceData.__contains__('NickName'):
  263. us_qs.update(nickname=nickname)
  264. else:
  265. ChannelIndex = qs[0].ChannelIndex
  266. nowTime = int(time.time())
  267. uid_set_create_dict = {
  268. 'uid': uid,
  269. 'addTime': nowTime,
  270. 'updTime': nowTime,
  271. # 'ip': CommonService.get_ip_address(request),
  272. 'channel': ChannelIndex,
  273. 'nickname': nickname,
  274. }
  275. UidSetModel.objects.create(**uid_set_create_dict)
  276. di_qs = Device_Info.objects.filter(UID=uid)
  277. di_qs.update(NickName=nickname)
  278. if deviceData is not None and deviceData.__contains__('NickName') and us_qs[0].is_alexa == 1:
  279. password = encrypt_pwd if deviceData.__contains__('View_Password') else ''
  280. asy = threading.Thread(target=ModelService.notify_alexa_add, args=(uid, userID, nickname, password))
  281. asy.start()
  282. # redisObj = RedisObject(db=8)
  283. # redisObj.del_data(key='uid_qs_' + userID)
  284. return response.json(0, res)
  285. # 编辑通道名
  286. def do_modify_channel_name(self, userID, request_dict, response):
  287. uid = request_dict.get('uid', None)
  288. channel = request_dict.get('channel', None)
  289. channel_name = request_dict.get('channel_name', None)
  290. if not all([uid, channel, channel_name]):
  291. return response.json(444)
  292. # 更新通道名
  293. UidChannelSetModel.objects.filter(uid__uid=uid).update(channel_name=channel_name)
  294. return response.json(0)
  295. # 新查询设备字段
  296. def do_query(self, userID, request_dict, response):
  297. token = request_dict.get('token', None)
  298. page = request_dict.get('page', None)
  299. line = request_dict.get('line', None)
  300. NickName = request_dict.get('NickName', None)
  301. if not token or not page or not line:
  302. return response.json(444)
  303. page = int(page)
  304. line = int(line)
  305. uid = request_dict.get('uid', None)
  306. tko = TokenObject(token)
  307. response.lang = tko.lang
  308. if page <= 0:
  309. return response.json(0)
  310. if tko.code != 0:
  311. return response.json(tko.code)
  312. userID = tko.userID
  313. dvqs = Device_Info.objects.filter(userID_id=userID)
  314. # # 过滤已重置的设备
  315. dvqs = dvqs.filter(~Q(isExist=2))
  316. dvql = dvqs.values('id', 'userID', 'NickName', 'UID', 'View_Account','View_Password', 'ChannelIndex',
  317. 'Type', 'isShare', 'primaryUserID', 'primaryMaster', 'data_joined', 'vodPrimaryUserID',
  318. 'vodPrimaryMaster', 'userID__userEmail', 'version', 'isVod', 'isExist', 'NotificationMode',
  319. 'isCameraOpenCloud', 'serial_number')
  320. dvls = CommonService.qs_to_list(dvql)
  321. uid_list = []
  322. serial_number_list = []
  323. for dvl in dvls:
  324. if dvl['primaryUserID'] and dvl['id'] == dvl['primaryUserID']:
  325. dvl['isPrimaryUser'] = 1
  326. else:
  327. dvl['isPrimaryUser'] = 0
  328. uid_list.append(dvl['UID'])
  329. serial_number_list.append(dvl['serial_number'][0:6])
  330. # 新增获取IOT证书内容
  331. iotqs = iotdeviceInfoModel.objects.filter(serial_number__in=serial_number_list)
  332. ubqs = UID_Bucket.objects.filter(uid__in=uid_list). \
  333. values('bucket__content', 'status', 'channel', 'endTime', 'uid')
  334. upqs = UID_Preview.objects.filter(uid__in=uid_list).order_by('channel').values('id', 'uid', 'channel')
  335. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  336. bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
  337. nowTime = int(time.time())
  338. data = []
  339. # 设备拓展信息表
  340. us_qs = UidSetModel.objects.filter(uid__in=uid_list).values('id', 'uid', 'version', 'nickname', 'ucode',
  341. 'detect_status', 'detect_group',
  342. 'detect_interval',
  343. 'region_alexa', 'is_alexa', 'deviceModel',
  344. 'TimeZone', 'TimeStatus', 'SpaceUsable',
  345. 'SpaceSum', 'MirrorType', 'RecordType',
  346. 'OutdoorModel', 'WIFIName', 'isDetector',
  347. 'DetectorRank', 'is_human', 'is_custom_voice')
  348. uv_dict = {}
  349. for us in us_qs:
  350. uv_dict[us['uid']] = {
  351. 'version': us['version'],
  352. 'nickname': us['nickname'],
  353. 'ucode': us['ucode'],
  354. 'detect_interval': us['detect_interval'],
  355. 'detect_group': us['detect_group'],
  356. 'detect_status': us['detect_status'],
  357. 'region_alexa': us['region_alexa'],
  358. 'is_alexa': us['is_alexa'],
  359. 'deviceModel': us['deviceModel'],
  360. 'TimeZone': us['TimeZone'],
  361. 'TimeStatus': us['TimeStatus'],
  362. 'SpaceUsable': us['SpaceUsable'],
  363. 'SpaceSum': us['SpaceSum'],
  364. 'MirrorType': us['MirrorType'],
  365. 'RecordType': us['RecordType'],
  366. 'OutdoorModel': us['OutdoorModel'],
  367. 'WIFIName': us['WIFIName'],
  368. 'isDetector': us['isDetector'],
  369. 'DetectorRank': us['DetectorRank'],
  370. 'is_human': us['is_human'],
  371. 'is_custom_voice': us['is_custom_voice']
  372. }
  373. # 从uid_channel里面取出通道配置信息
  374. ucs_qs = UidChannelSetModel.objects.filter(uid__id=us['id']).values('channel', 'channel_name',
  375. 'pir_audio', 'mic_audio',
  376. 'battery_status', 'battery_level',
  377. 'sleep_status', 'sleep_time',
  378. 'light_night_model',
  379. 'light_alarm_type',
  380. 'light_alarm_level',
  381. 'light_alarm_man_en',
  382. 'light_alarm_vol',
  383. 'light_long_light'
  384. )
  385. channels = []
  386. for ucs in ucs_qs:
  387. channels_dict = {
  388. 'channel': ucs['channel'],
  389. 'channel_name': ucs['channel_name'],
  390. 'pir_audio': ucs['pir_audio'],
  391. 'mic_audio': ucs['mic_audio'],
  392. 'battery_status': ucs['battery_status'],
  393. 'battery_level': ucs['battery_level'],
  394. 'sleep_status': ucs['sleep_status'],
  395. 'sleep_time': ucs['sleep_time'],
  396. 'light_night_model': ucs['light_night_model'],
  397. 'light_alarm_type': ucs['light_alarm_type'],
  398. 'light_alarm_level': ucs['light_alarm_level'],
  399. 'light_alarm_man_en': ucs['light_alarm_man_en'],
  400. 'light_alarm_vol': ucs['light_alarm_vol'],
  401. 'light_long_light': ucs['light_long_light']
  402. }
  403. channels.append(channels_dict)
  404. uv_dict[us['uid']]['channels'] = channels
  405. for p in dvls:
  406. # 新增IOT
  407. p['iot'] = []
  408. for iot in iotqs:
  409. if p['serial_number'][0:6] == iot.serial_number:
  410. p['iot'].append(
  411. {
  412. 'endpoint': iot.endpoint,
  413. 'token_iot_number': iot.token_iot_number
  414. }
  415. )
  416. p['vod'] = []
  417. for dm in ubqs:
  418. if p['UID'] == dm['uid']:
  419. if dm['endTime'] > nowTime:
  420. p['vod'].append(dm)
  421. p['preview'] = []
  422. for up in upqs:
  423. if p['UID'] == up['uid']:
  424. obj = 'uid_preview/{uid}/channel_{channel}.png'.format(uid=up['uid'], channel=up['channel'])
  425. img_sign = bucket.sign_url('GET', obj, 300)
  426. p['preview'].append(img_sign)
  427. p_uid = p['UID']
  428. # 返回设备初始化字符
  429. uid_qs = UIDModel.objects.filter(uid=p_uid).values('platform', 'init_string', 'init_string_app')
  430. if uid_qs.exists():
  431. p['platform'] = uid_qs[0]['platform']
  432. p['initString'] = uid_qs[0]['init_string']
  433. p['initStringApp'] = uid_qs[0]['init_string_app']
  434. if p_uid in uv_dict:
  435. # 设备版本号
  436. p['uid_version'] = uv_dict[p_uid]['version']
  437. p['ucode'] = uv_dict[p_uid]['ucode']
  438. p['detect_interval'] = uv_dict[p_uid]['detect_interval']
  439. p['detect_status'] = uv_dict[p_uid]['detect_status']
  440. p['detect_group'] = uv_dict[p_uid]['detect_group']
  441. p['region_alexa'] = uv_dict[p_uid]['region_alexa']
  442. p['is_alexa'] = uv_dict[p_uid]['is_alexa']
  443. p['deviceModel'] = uv_dict[p_uid]['deviceModel']
  444. p['TimeZone'] = uv_dict[p_uid]['TimeZone']
  445. p['TimeStatus'] = uv_dict[p_uid]['TimeStatus']
  446. p['SpaceUsable'] = uv_dict[p_uid]['SpaceUsable']
  447. p['SpaceSum'] = uv_dict[p_uid]['SpaceSum']
  448. p['MirrorType'] = uv_dict[p_uid]['MirrorType']
  449. p['RecordType'] = uv_dict[p_uid]['RecordType']
  450. p['OutdoorModel'] = uv_dict[p_uid]['OutdoorModel']
  451. p['WIFIName'] = uv_dict[p_uid]['WIFIName']
  452. p['isDetector'] = uv_dict[p_uid]['isDetector']
  453. p['DetectorRank'] = uv_dict[p_uid]['DetectorRank']
  454. p['is_human'] = uv_dict[p_uid]['is_human']
  455. p['is_custom_voice'] = uv_dict[p_uid]['is_custom_voice']
  456. p['channels'] = uv_dict[p_uid]['channels']
  457. # 设备昵称 调用影子信息昵称,先阶段不可
  458. if uv_dict[p_uid]['nickname']:
  459. p['NickName'] = uv_dict[p_uid]['nickname']
  460. else:
  461. # 设备版本号
  462. p['uid_version'] = ''
  463. p['ucode'] = ''
  464. data.append(p)
  465. result = data
  466. if NickName:
  467. # print('NickName搜索缓存')
  468. data = []
  469. for index, item in enumerate(result):
  470. if NickName == item['NickName']:
  471. # 加密
  472. item['View_Password'] = self.encrypt_pwd(item['View_Password'])
  473. data.append(item)
  474. return response.json(0, data)
  475. if uid:
  476. # print('uid搜索缓存')
  477. data = []
  478. for index, item in enumerate(result):
  479. if uid == item['UID']:
  480. # 加密
  481. item['View_Password'] = self.encrypt_pwd(item['View_Password'])
  482. data.append(item)
  483. return response.json(0, data)
  484. items = []
  485. # print('缓存分页')
  486. for index, item in enumerate(result):
  487. if (page - 1) * line <= index:
  488. if index < page * line:
  489. # 加密
  490. item['View_Password'] = self.encrypt_pwd(item['View_Password'])
  491. print(item)
  492. items.append(item)
  493. print(items)
  494. return response.json(0, items)
  495. def do_fuzzy_query(self, userID, request_dict, response):
  496. fuzzy = request_dict.get('fuzzy', None)
  497. page = request_dict.get('page', None)
  498. line = request_dict.get('line', None)
  499. if page and line:
  500. page = int(page)
  501. line = int(line)
  502. device_qs = Device_Info.objects.filter(userID=userID)
  503. device_qs = device_qs.filter(~Q(isExist=2))
  504. if device_qs.exists():
  505. if fuzzy:
  506. device_qs = device_qs.filter(Q(UID__contains=fuzzy) | Q(NickName__contains=fuzzy))
  507. device_qs = device_qs.values('id', 'userID', 'NickName', 'UID', 'View_Account',
  508. 'View_Password', 'ChannelIndex', 'Type', 'isShare',
  509. 'primaryUserID', 'primaryMaster', 'data_joined', 'vodPrimaryUserID',
  510. 'vodPrimaryMaster', 'userID__userEmail',
  511. 'version', 'isVod', 'isExist', 'NotificationMode', 'isCameraOpenCloud', 'serial_number')
  512. dvls = CommonService.qs_to_list(device_qs)
  513. uid_list = []
  514. serial_number_list = []
  515. for dvl in dvls:
  516. uid_list.append(dvl['UID'])
  517. serial_number_list.append(dvl['serial_number'][0:6])
  518. # 新增获取IOT证书内容
  519. iotqs = iotdeviceInfoModel.objects.filter(serial_number__in=serial_number_list)
  520. ubqs = UID_Bucket.objects.filter(uid__in=uid_list). \
  521. values('bucket__content', 'status', 'channel', 'endTime', 'uid')
  522. upqs = UID_Preview.objects.filter(uid__in=uid_list).order_by('channel').values('id', 'uid', 'channel')
  523. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  524. bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
  525. nowTime = int(time.time())
  526. data = []
  527. # 设备拓展信息表
  528. us_qs = UidSetModel.objects.filter(uid__in=uid_list).values('id', 'uid', 'version', 'nickname', 'ucode',
  529. 'detect_status', 'detect_group',
  530. 'detect_interval',
  531. 'region_alexa', 'is_alexa', 'deviceModel',
  532. 'TimeZone', 'TimeStatus', 'SpaceUsable',
  533. 'SpaceSum', 'MirrorType', 'RecordType',
  534. 'OutdoorModel', 'WIFIName', 'isDetector',
  535. 'DetectorRank')
  536. uv_dict = {}
  537. for us in us_qs:
  538. uv_dict[us['uid']] = {
  539. 'version': us['version'],
  540. 'nickname': us['nickname'],
  541. 'ucode': us['ucode'],
  542. 'detect_interval': us['detect_interval'],
  543. 'detect_group': us['detect_group'],
  544. 'detect_status': us['detect_status'],
  545. 'region_alexa': us['region_alexa'],
  546. 'is_alexa': us['is_alexa'],
  547. 'deviceModel': us['deviceModel'],
  548. 'TimeZone': us['TimeZone'],
  549. 'TimeStatus': us['TimeStatus'],
  550. 'SpaceUsable': us['SpaceUsable'],
  551. 'SpaceSum': us['SpaceSum'],
  552. 'MirrorType': us['MirrorType'],
  553. 'RecordType': us['RecordType'],
  554. 'OutdoorModel': us['OutdoorModel'],
  555. 'WIFIName': us['WIFIName'],
  556. 'isDetector': us['isDetector'],
  557. 'DetectorRank': us['DetectorRank']
  558. }
  559. # 从uid_channel里面取出通道配置信息
  560. ucs_qs = UidChannelSetModel.objects.filter(uid__id=us['id']).values()
  561. channels = []
  562. for ucs in ucs_qs:
  563. channel = {
  564. 'channel': ucs['channel'],
  565. 'channel_name': ucs['channel_name'],
  566. 'pir_audio': ucs['pir_audio'],
  567. 'mic_audio': ucs['mic_audio'],
  568. 'battery_status': ucs['battery_status'],
  569. 'battery_level': ucs['battery_level'],
  570. 'sleep_status': ucs['sleep_status'],
  571. 'sleep_time': ucs['sleep_time'],
  572. 'light_night_model': ucs['light_night_model'],
  573. 'light_alarm_type': ucs['light_alarm_type'],
  574. 'light_alarm_level': ucs['light_alarm_level'],
  575. 'light_alarm_man_en': ucs['light_alarm_man_en'],
  576. 'light_alarm_vol': ucs['light_alarm_vol'],
  577. 'light_long_light': ucs['light_long_light']
  578. }
  579. channels.append(channel)
  580. uv_dict[us['uid']]['channels'] = channels
  581. for p in dvls:
  582. # 新增IOT
  583. p['iot'] = []
  584. for iot in iotqs:
  585. if p['serial_number'][0:6] == iot.serial_number:
  586. p['iot'].append(
  587. {
  588. 'endpoint': iot.endpoint,
  589. 'token_iot_number': iot.token_iot_number
  590. }
  591. )
  592. p['vod'] = []
  593. for dm in ubqs:
  594. if p['UID'] == dm['uid']:
  595. if dm['endTime'] > nowTime:
  596. p['vod'].append(dm)
  597. p['preview'] = []
  598. for up in upqs:
  599. if p['UID'] == up['uid']:
  600. obj = 'uid_preview/{uid}/channel_{channel}.png'.format(uid=up['uid'], channel=up['channel'])
  601. img_sign = bucket.sign_url('GET', obj, 300)
  602. p['preview'].append(img_sign)
  603. p_uid = p['UID']
  604. if p_uid in uv_dict:
  605. # 设备版本号
  606. p['uid_version'] = uv_dict[p_uid]['version']
  607. p['ucode'] = uv_dict[p_uid]['ucode']
  608. p['detect_interval'] = uv_dict[p_uid]['detect_interval']
  609. p['detect_status'] = uv_dict[p_uid]['detect_status']
  610. p['detect_group'] = uv_dict[p_uid]['detect_group']
  611. p['region_alexa'] = uv_dict[p_uid]['region_alexa']
  612. p['is_alexa'] = uv_dict[p_uid]['is_alexa']
  613. p['deviceModel'] = uv_dict[p_uid]['deviceModel']
  614. p['TimeZone'] = uv_dict[p_uid]['TimeZone']
  615. p['TimeStatus'] = uv_dict[p_uid]['TimeStatus']
  616. p['SpaceUsable'] = uv_dict[p_uid]['SpaceUsable']
  617. p['SpaceSum'] = uv_dict[p_uid]['SpaceSum']
  618. p['MirrorType'] = uv_dict[p_uid]['MirrorType']
  619. p['RecordType'] = uv_dict[p_uid]['RecordType']
  620. p['OutdoorModel'] = uv_dict[p_uid]['OutdoorModel']
  621. p['WIFIName'] = uv_dict[p_uid]['WIFIName']
  622. p['isDetector'] = uv_dict[p_uid]['isDetector']
  623. p['DetectorRank'] = uv_dict[p_uid]['DetectorRank']
  624. p['channels'] = uv_dict[p_uid]['channels']
  625. # 设备昵称 调用影子信息昵称,先阶段不可
  626. if uv_dict[p_uid]['nickname']:
  627. p['NickName'] = uv_dict[p_uid]['nickname']
  628. else:
  629. # 设备版本号
  630. p['uid_version'] = ''
  631. p['ucode'] = ''
  632. data.append(p)
  633. result = data
  634. items = []
  635. # print('缓存分页')
  636. for index, item in enumerate(result):
  637. if (page - 1) * line <= index:
  638. if index < page * line:
  639. # 加密
  640. item['View_Password'] = self.encrypt_pwd(item['View_Password'])
  641. print(item)
  642. items.append(item)
  643. print(items)
  644. return response.json(0, items)
  645. else:
  646. return response.json(0, [])
  647. else:
  648. return response.json(444)
  649. # 加密
  650. def encrypt_pwd(self, userPwd):
  651. for i in range(1, 4):
  652. if i == 1:
  653. userPwd = RandomStr(3, False) + userPwd + RandomStr(3, False)
  654. userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
  655. if i == 2:
  656. userPwd = RandomStr(2, False) + str(userPwd) + RandomStr(2, False)
  657. userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
  658. if i == 3:
  659. userPwd = RandomStr(1, False) + str(userPwd) + RandomStr(1, False)
  660. userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
  661. return userPwd
  662. # 解密
  663. def decode_pwd(self, password):
  664. for i in range(1, 4):
  665. if i == 1:
  666. # 第一次先解密
  667. password = base64.b64decode(password)
  668. password = password.decode('utf-8')
  669. # 截去第一位,最后一位
  670. password = password[1:-1]
  671. if i == 2:
  672. # 第2次先解密
  673. password = base64.b64decode(password)
  674. password = password.decode('utf-8')
  675. # 去前2位,后2位
  676. password = password[2:-2]
  677. if i == 3:
  678. # 第3次先解密
  679. password = base64.b64decode(password)
  680. password = password.decode('utf-8')
  681. # 去前3位,后3位
  682. password = password[3:-3]
  683. return password
  684. def do_mainUserDevice(self, request_dict, response):
  685. UID = request_dict.get('UID')
  686. dvq = Device_Info.objects.filter(UID=UID)
  687. dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  688. qs = {}
  689. if dvq.exists():
  690. qs = Device_User.objects.filter(userID=dvq[0]['vodPrimaryUserID']).values('userID', 'NickName', 'username',
  691. 'userEmail', 'phone')
  692. NickName = qs[0]['username']
  693. userEmail = qs[0]['userEmail']
  694. phone = qs[0]['phone']
  695. username = qs[0]['username']
  696. qs = CommonService.qs_to_list(qs)
  697. if NickName =='':
  698. qs[0]['NickName'] = username
  699. # if userEmail =='':
  700. # qs[0]['userEmail'] = NickName
  701. if phone =='':
  702. qs[0]['phone'] = NickName
  703. # if not qs:
  704. # uidq = UIDMainUser.objects.filter(UID=UID).values('user_id')
  705. # if uidq.exists():
  706. # qs = Device_User.objects.filter(userID=uidq[0]['user_id']).values('userID', 'NickName', 'username', 'userEmail', 'phone')
  707. # qs = CommonService.qs_to_list(qs)
  708. return response.json(0, qs)
  709. def not_login_do_mainUserDevice(self, request_dict, response):
  710. UID = request_dict.get('UID')
  711. token = request_dict.get('token', None)
  712. time_stamp = request_dict.get('time_stamp', None)
  713. if not all([token, time_stamp]):
  714. return response.json(444)
  715. now_time = int(time.time())
  716. distance = now_time - time_stamp
  717. if token != time_stamp or distance > 60000 or distance < -60000: # 为了全球化时间控制在一天内
  718. return response.json(404)
  719. dvq = Device_Info.objects.filter(UID=UID)
  720. dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  721. qs = {}
  722. if dvq.exists():
  723. qs = Device_User.objects.filter(userID=dvq[0]['vodPrimaryUserID']).values('userID', 'NickName', 'username',
  724. 'userEmail', 'phone')
  725. NickName = qs[0]['username']
  726. phone = qs[0]['phone']
  727. username = qs[0]['username']
  728. qs = CommonService.qs_to_list(qs)
  729. if NickName =='':
  730. qs[0]['NickName'] = username
  731. if phone =='':
  732. qs[0]['phone'] = NickName
  733. return response.json(0, qs)
  734. def do_get_device_features(self, request_dict, response):
  735. uid = request_dict.get('uid', None)
  736. if uid:
  737. uid = CommonService.decode_data(uid)
  738. if uid:
  739. uid_qs = UidSetModel.objects.filter(uid=uid)
  740. if uid_qs.exists():
  741. uid_qs = uid_qs.values('is_alexa', 'is_human', 'is_custom_voice', 'double_wifi')
  742. return response.json(0, uid_qs[0])
  743. else:
  744. return response.json(173)
  745. else:
  746. return response.json(444)
  747. else:
  748. return response.json(444)