EquipmentManagerV3.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  1. import base64
  2. import json
  3. import re
  4. import threading
  5. import time
  6. import oss2
  7. import requests
  8. from django.db.models import Q
  9. from django.views.generic.base import View
  10. from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY
  11. from Controller.CheckUserData import RandomStr
  12. from Controller.DeviceConfirmRegion import Device_Region
  13. from Controller.SensorGateway.EquipmentFamilyController import EquipmentFamilyView
  14. from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidChannelSetModel, \
  15. Device_User, iotdeviceInfoModel, UIDCompanySerialModel, UIDModel, UnicomDeviceInfo, CountryModel, \
  16. DeviceCloudPhotoInfo
  17. from Object.ResponseObject import ResponseObject
  18. from Object.TokenObject import TokenObject
  19. from Service.CommonService import CommonService
  20. from Service.ModelService import ModelService
  21. from Service.UserDeviceService import UserDeviceService
  22. class EquipmentManagerV3(View):
  23. def get(self, request, *args, **kwargs):
  24. request.encoding = 'utf-8'
  25. operation = kwargs.get('operation')
  26. return self.validation(request.GET, request, operation)
  27. def post(self, request, *args, **kwargs):
  28. request.encoding = 'utf-8'
  29. operation = kwargs.get('operation')
  30. return self.validation(request.POST, request, operation)
  31. def validation(self, request_dict, request, operation):
  32. response = ResponseObject()
  33. if operation == 'notLoginMainUserDevice':
  34. return self.not_login_do_mainUserDevice(request_dict, response)
  35. elif operation == 'notLoginMainDelDevice':
  36. return self.test_tool_del_device(request_dict, response)
  37. token = request_dict.get('token', None)
  38. tko = TokenObject(token)
  39. if tko.code != 0:
  40. return response.json(tko.code)
  41. response.lang = tko.lang
  42. userID = tko.userID
  43. # 手机端添加设备,查询,修改
  44. if operation == 'add':
  45. return self.do_add(userID, request_dict, response, request)
  46. if operation == 'batchAdd':
  47. return self.do_batch_add(userID, request_dict, response, request)
  48. elif operation == 'query':
  49. return self.do_query(userID, request_dict, response)
  50. elif operation == 'modify':
  51. return self.do_modify(userID, request_dict, response, request)
  52. elif operation == 'modifyChannelName':
  53. return self.do_modify_channel_name(userID, request_dict, response, request)
  54. elif operation == 'fuzzyQuery':
  55. return self.do_fuzzy_query(userID, request_dict, response)
  56. elif operation == 'mainUserDevice':
  57. return self.do_mainUserDevice(request_dict, response)
  58. elif operation == 'getDeviceFeatures':
  59. return self.do_get_device_features(request_dict, response)
  60. else:
  61. return response.json(414)
  62. def do_add(self, userID, request_dict, response, request):
  63. UID = request_dict.get('UID', None)
  64. NickName = request_dict.get('NickName', None)
  65. View_Account = request_dict.get('View_Account', None)
  66. View_Password = request_dict.get('View_Password', '')
  67. encrypt_pass = View_Password
  68. print("准备解密")
  69. Type = request_dict.get('Type', None)
  70. ChannelIndex = request_dict.get('ChannelIndex', None)
  71. version = request_dict.get('version', '')
  72. isCheckMainUser = request_dict.get('isCheckMainUser', None)
  73. family_id = request_dict.get('familyId', None)
  74. room_id = request_dict.get('roomId', None)
  75. if not all([UID, NickName, View_Account, Type, ChannelIndex]): # Type和ChannelIndex可能为0
  76. return response.json(444, {'param': 'UID, NickName, View_Account, Type, ChannelIndex'})
  77. Type = int(Type)
  78. ChannelIndex = int(ChannelIndex)
  79. re_uid = re.compile(r'^[A-Za-z0-9]{14,20}$')
  80. if not re_uid.match(UID):
  81. return response.json(444, {'param': 'UID'})
  82. device_info_qs = Device_Info.objects.filter(UID=UID, userID_id=userID)
  83. if device_info_qs:
  84. # 判断设备是否已存在
  85. if device_info_qs[0].isExist == 1:
  86. return response.json(174)
  87. else:
  88. device_info_qs.delete()
  89. dvr_type_list = [1, 2, 3, 4, 10001]
  90. View_Password = '' if Type in dvr_type_list else 'admin'
  91. id = CommonService.getUserID(getUser=False)
  92. userName = Device_User.objects.get(userID=userID).username
  93. main_exist = Device_Info.objects.filter(UID=UID)
  94. main_exist = main_exist.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID', 'vodPrimaryMaster')
  95. vodPrimaryUserID = userID
  96. vodPrimaryMaster = userName
  97. primaryUserID = ''
  98. primaryMaster = ''
  99. isShare = False
  100. is_bind = Device_Info.objects.filter(UID=UID, isShare=False).values('userID__userID', 'primaryUserID',
  101. 'primaryMaster')
  102. if main_exist.exists():
  103. vodPrimaryUserID = main_exist[0]['vodPrimaryUserID']
  104. vodPrimaryMaster = main_exist[0]['vodPrimaryMaster']
  105. if is_bind.exists():
  106. primaryUserID = is_bind[0]['primaryUserID']
  107. primaryMaster = is_bind[0]['primaryMaster']
  108. isShare = True
  109. isusermain = False
  110. if (vodPrimaryUserID != userID and vodPrimaryUserID != '') or (primaryUserID != userID and primaryUserID != ''):
  111. isusermain = True
  112. # 判断是否有已绑定用户
  113. if isCheckMainUser == '1' and isusermain:
  114. res = {
  115. 'id': id,
  116. 'userID': userID,
  117. 'NickName': NickName,
  118. 'UID': UID,
  119. 'View_Account': View_Account,
  120. 'View_Password': View_Password,
  121. 'ChannelIndex': ChannelIndex,
  122. 'Type': Type,
  123. 'isShare': isShare,
  124. 'primaryUserID': primaryUserID,
  125. 'primaryMaster': primaryMaster,
  126. 'vodPrimaryUserID': vodPrimaryUserID,
  127. 'vodPrimaryMaster': vodPrimaryMaster,
  128. 'data_joined': '',
  129. 'version': version,
  130. 'isVod': 0,
  131. 'isExist': 1,
  132. 'userID__userEmail': ''
  133. }
  134. res['vod'] = [
  135. {
  136. "status": 1,
  137. "channel": ChannelIndex,
  138. "endTime": '',
  139. "bucket__content": '',
  140. "uid": UID
  141. }
  142. ]
  143. res['isMainUserExists'] = 1
  144. return response.json(0, res)
  145. try:
  146. # 判断是否有用户绑定
  147. nowTime = int(time.time())
  148. us_qs = UidSetModel.objects.filter(uid=UID)
  149. if us_qs.exists():
  150. us_qs.update(nickname=NickName, device_type=Type)
  151. UidSet_id = us_qs.first().id
  152. else:
  153. ip = CommonService.get_ip_address(request)
  154. ipInfo = CommonService.getIpIpInfo(ip, 'CN')
  155. country_qs = CountryModel.objects.filter(country_code=ipInfo['country_code']).values('id')
  156. country = country_qs.exists() if country_qs[0]['id'] else 0
  157. region_id = Device_Region().get_device_region(ip)
  158. region_alexa = 'CN' if region_id == 1 else 'ALL'
  159. uid_set_create_dict = {
  160. 'uid': UID,
  161. 'addTime': nowTime,
  162. 'updTime': nowTime,
  163. 'ip': CommonService.get_ip_address(request_dict),
  164. 'channel': ChannelIndex,
  165. 'nickname': NickName,
  166. 'version': version,
  167. 'region_alexa': region_alexa,
  168. 'device_type': Type,
  169. 'tb_country': country
  170. }
  171. UidSet = UidSetModel.objects.create(**uid_set_create_dict)
  172. UidSet_id = UidSet.id
  173. # 查询uid_channel表有无该uid的数据
  174. uid_channel_set = UidChannelSetModel.objects.filter(uid_id=UidSet_id)
  175. if not uid_channel_set.exists():
  176. # 多通道设备设置通道名
  177. if Type in dvr_type_list:
  178. UidChannelSet_bulk = []
  179. for i in range(1, ChannelIndex + 1):
  180. channel_name = 'channel' + str(i) # channel1,channel2...
  181. UidChannelSet = UidChannelSetModel(uid_id=UidSet_id, channel=i, channel_name=channel_name)
  182. UidChannelSet_bulk.append(UidChannelSet)
  183. UidChannelSetModel.objects.bulk_create(UidChannelSet_bulk)
  184. userDevice = Device_Info(id=id, userID_id=userID, UID=UID, NickName=NickName, View_Account=View_Account,
  185. View_Password=View_Password, Type=Type, ChannelIndex=ChannelIndex, version=version,
  186. vodPrimaryUserID=vodPrimaryUserID, vodPrimaryMaster=vodPrimaryMaster)
  187. userDevice.save()
  188. # 添加到家庭房间
  189. if family_id:
  190. EquipmentFamilyView.family_room_device_save(family_id, room_id, userDevice.id, Type)
  191. uid_serial_qs = UIDCompanySerialModel.objects.filter(uid__uid=UID)
  192. if uid_serial_qs.exists():
  193. uid_serial = uid_serial_qs[0]
  194. serial_number = uid_serial.company_serial.serial_number + uid_serial.company_serial.company.mark
  195. Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
  196. vodPrimaryMaster=vodPrimaryMaster,
  197. serial_number=serial_number)
  198. self.unicom_user_info_save(userID, serial_number)
  199. else:
  200. Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
  201. vodPrimaryMaster=vodPrimaryMaster)
  202. if not us_qs.exists():
  203. us_qs = UidSetModel.objects.filter(uid=UID)
  204. if us_qs.exists() and us_qs[0].is_alexa == 1:
  205. if us_qs[0].channel > 1:
  206. data_list = []
  207. uid_channel_set_qs = UidChannelSetModel.objects.filter(uid_id=us_qs[0].id). \
  208. values('channel', 'channel_name')
  209. if uid_channel_set_qs.exists():
  210. # 多通道设备名为 UidChannelSetModel 的 channel_name
  211. for uid_channel_set in uid_channel_set_qs:
  212. data_list.append({'userID': userID, 'UID': UID, 'uid_nick': uid_channel_set['channel_name'],
  213. 'channel': uid_channel_set['channel'], 'password': encrypt_pass})
  214. else:
  215. data_list = [{'userID': userID, 'UID': UID, 'uid_nick': NickName, 'password': encrypt_pass}]
  216. # 请求Alexa服务器更新事件网关
  217. data_list = json.dumps(data_list)
  218. data = {'data_list': data_list}
  219. url = 'https://www.zositech.xyz/deviceStatus/addOrUpdateV2'
  220. requests.post(url, data=data, timeout=2)
  221. except Exception as e:
  222. return response.json(10, repr(e))
  223. else:
  224. dvqs = Device_Info.objects.filter(id=id).values('id', 'userID', 'NickName', 'UID',
  225. 'View_Account',
  226. 'View_Password', 'ChannelIndex', 'Type',
  227. 'isShare',
  228. 'primaryUserID', 'primaryMaster',
  229. 'vodPrimaryUserID', 'vodPrimaryMaster',
  230. 'userID__userEmail',
  231. 'data_joined', 'version',
  232. 'isVod', 'isExist', 'isCameraOpenCloud', 'serial_number')
  233. dvql = CommonService.qs_to_list(dvqs)
  234. ubqs = UID_Bucket.objects.filter(uid=UID). \
  235. values('bucket__content', 'status', 'channel', 'endTime', 'uid')
  236. res = dvql[0]
  237. res['vod'] = list(ubqs)
  238. iotqs = iotdeviceInfoModel.objects.filter(serial_number=dvql[0]['serial_number'])
  239. if iotqs.exists():
  240. res['iot'] = {
  241. 'endpoint': iotqs[0].endpoint,
  242. 'token_iot_number': iotqs[0].endpoint
  243. }
  244. # 存在序列号返回完整序列号
  245. if res['serial_number']:
  246. res['serial_number'] = CommonService.get_full_serial_number(UID, res['serial_number'], Type)
  247. return response.json(0, res)
  248. @classmethod
  249. def unicom_user_info_save(cls, user_id, serial_number):
  250. """
  251. 保存联通与用户信息绑定
  252. @param user_id: 用户id
  253. @param serial_number: 序列号
  254. @return: True | False
  255. """
  256. unicom_device_info_qs = UnicomDeviceInfo.objects.filter(serial_no=serial_number)
  257. if not unicom_device_info_qs.exists():
  258. return False
  259. if not unicom_device_info_qs[0].user_id:
  260. unicom_device_info_qs.update(user_id=user_id)
  261. return True
  262. def do_batch_add(self, userID, request_dict, response, request):
  263. # 批量添加设备
  264. uidContent = request_dict.get('uidContent', None)
  265. if not uidContent:
  266. return response.json(444, {'param': 'uidContent'})
  267. try:
  268. deviceNumber = 0 # 添加成功数量
  269. add_success_flag = False # 添加成功标识
  270. exception_flag = False # 异常标识
  271. exists_flag = False # 已存在标识
  272. uid_content_list = eval(uidContent)
  273. print('uidContent: ', uid_content_list)
  274. re_uid = re.compile(r'^[A-Za-z0-9]{14,20}$')
  275. for uid_content in uid_content_list:
  276. exception_flag = False # 重置异常标识
  277. exists_flag = False # 已存在标识
  278. UID = uid_content['uid']
  279. NickName = uid_content['nickName']
  280. Type = uid_content['type']
  281. ChannelIndex = uid_content['channelIndex']
  282. version = uid_content['version']
  283. isCheckMainUser = uid_content['isCheckMainUser']
  284. View_Account = uid_content['viewAccount']
  285. encryptPassword = uid_content['encryptPassword']
  286. View_Password = self.decode_pwd(encryptPassword)
  287. if not all([UID, NickName, View_Account]): # Type和ChannelIndex可能为0
  288. return response.json(444, {'param': 'UID, NickName, View_Account'})
  289. if not re_uid.match(UID): # 检查uid长度
  290. return response.json(444, {'error uid length': UID})
  291. device_info_qs = Device_Info.objects.filter(UID=UID, userID_id=userID)
  292. if device_info_qs:
  293. # 判断设备是否已存在
  294. if device_info_qs[0].isExist == 1:
  295. exists_res = {UID: 'device already exists!'}
  296. exists_flag = True
  297. continue
  298. else:
  299. device_info_qs.delete()
  300. id = CommonService.getUserID(getUser=False)
  301. userName = Device_User.objects.get(userID=userID).username
  302. main_exist = Device_Info.objects.filter(UID=UID)
  303. main_exist = main_exist.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID', 'vodPrimaryMaster')
  304. vodPrimaryUserID = userID
  305. vodPrimaryMaster = userName
  306. primaryUserID = ''
  307. primaryMaster = ''
  308. isShare = False
  309. is_bind = Device_Info.objects.filter(UID=UID, isShare=False).values('userID__userID', 'primaryUserID',
  310. 'primaryMaster', 'Type')
  311. if main_exist.exists():
  312. vodPrimaryUserID = main_exist[0]['vodPrimaryUserID']
  313. vodPrimaryMaster = main_exist[0]['vodPrimaryMaster']
  314. if is_bind.exists():
  315. primaryUserID = is_bind[0]['primaryUserID']
  316. primaryMaster = is_bind[0]['primaryMaster']
  317. isShare = True
  318. isusermain = False
  319. if (vodPrimaryUserID != userID and vodPrimaryUserID != '') or (
  320. primaryUserID != userID and primaryUserID != ''):
  321. isusermain = True
  322. # 判断是否有已绑定用户
  323. if isCheckMainUser == 1 and isusermain:
  324. res = {
  325. 'id': id,
  326. 'userID': userID,
  327. 'NickName': NickName,
  328. 'UID': UID,
  329. 'View_Account': View_Account,
  330. 'View_Password': View_Password,
  331. 'ChannelIndex': ChannelIndex,
  332. 'Type': Type,
  333. 'isShare': isShare,
  334. 'primaryUserID': primaryUserID,
  335. 'primaryMaster': primaryMaster,
  336. 'vodPrimaryUserID': vodPrimaryUserID,
  337. 'vodPrimaryMaster': vodPrimaryMaster,
  338. 'data_joined': '',
  339. 'version': version,
  340. 'isVod': 0,
  341. 'isExist': 1,
  342. 'userID__userEmail': ''
  343. }
  344. res['vod'] = [
  345. {
  346. "status": 1,
  347. "channel": ChannelIndex,
  348. "endTime": '',
  349. "bucket__content": '',
  350. "uid": UID
  351. }
  352. ]
  353. res['isMainUserExists'] = 1
  354. continue
  355. # 判断是否有用户绑定
  356. nowTime = int(time.time())
  357. us_qs = UidSetModel.objects.filter(uid=UID)
  358. if us_qs.exists():
  359. us_qs.update(nickname=NickName)
  360. UidSet_id = us_qs.first().id
  361. else:
  362. ip = CommonService.get_ip_address(request)
  363. ipInfo = CommonService.getIpIpInfo(ip, 'CN')
  364. country_qs = CountryModel.objects.filter(country_code=ipInfo['country_code']).values('id')
  365. country = country_qs.exists() if country_qs[0]['id'] else 0
  366. region_id = Device_Region().get_device_region(ip)
  367. region_alexa = 'CN' if region_id == 1 else 'ALL'
  368. uid_set_create_dict = {
  369. 'uid': UID,
  370. 'addTime': nowTime,
  371. 'updTime': nowTime,
  372. 'ip': CommonService.get_ip_address(request_dict),
  373. 'channel': ChannelIndex,
  374. 'nickname': NickName,
  375. 'version': version,
  376. 'region_alexa': region_alexa,
  377. 'device_type': is_bind[0]['Type'],
  378. 'tb_country': country
  379. }
  380. UidSet = UidSetModel.objects.create(**uid_set_create_dict)
  381. UidSet_id = UidSet.id
  382. # 查询uid_channel表有无该uid的数据
  383. uid_channel_set = UidChannelSetModel.objects.filter(uid_id=UidSet_id)
  384. if not uid_channel_set.exists():
  385. # 多通道设备设置通道名
  386. multi_channel_list = [1, 2, 3, 4, 10001]
  387. if Type in multi_channel_list:
  388. UidChannelSet_bulk = []
  389. for i in range(1, ChannelIndex + 1):
  390. channel_name = 'channel' + str(i) # channel1,channel2...
  391. UidChannelSet = UidChannelSetModel(uid_id=UidSet_id, channel=i, channel_name=channel_name)
  392. UidChannelSet_bulk.append(UidChannelSet)
  393. UidChannelSetModel.objects.bulk_create(UidChannelSet_bulk)
  394. userDevice = Device_Info(id=id, userID_id=userID, UID=UID, NickName=NickName, View_Account=View_Account,
  395. View_Password=View_Password, Type=Type, ChannelIndex=ChannelIndex,
  396. version=version,
  397. vodPrimaryUserID=vodPrimaryUserID, vodPrimaryMaster=vodPrimaryMaster)
  398. userDevice.save()
  399. uid_serial_qs = UIDCompanySerialModel.objects.filter(uid__uid=UID)
  400. if uid_serial_qs.exists():
  401. uid_serial = uid_serial_qs[0]
  402. Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
  403. vodPrimaryMaster=vodPrimaryMaster,
  404. serial_number=uid_serial.company_serial.serial_number + uid_serial.company_serial.company.mark)
  405. else:
  406. Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
  407. vodPrimaryMaster=vodPrimaryMaster)
  408. if not us_qs.exists():
  409. us_qs = UidSetModel.objects.filter(uid=UID)
  410. if us_qs.exists() and us_qs[0].is_alexa == 1:
  411. if us_qs[0].channel > 1:
  412. data_list = []
  413. uid_channel_set_qs = UidChannelSetModel.objects.filter(uid_id=us_qs[0].id). \
  414. values('channel', 'channel_name')
  415. if uid_channel_set_qs.exists():
  416. # 多通道设备名为 UidChannelSetModel 的 channel_name
  417. for uid_channel_set in uid_channel_set_qs:
  418. data_list.append(
  419. {'userID': userID, 'UID': UID, 'uid_nick': uid_channel_set['channel_name'],
  420. 'channel': uid_channel_set['channel'], 'password': encryptPassword})
  421. else:
  422. data_list = [{'userID': userID, 'UID': UID, 'uid_nick': NickName, 'password': encryptPassword}]
  423. # 请求Alexa服务器更新事件网关
  424. data_list = json.dumps(data_list)
  425. data = {'data_list': data_list}
  426. url = 'https://www.zositech.xyz/deviceStatus/addOrUpdateV2'
  427. requests.post(url, data=data, timeout=2)
  428. dvqs = Device_Info.objects.filter(id=id).values('id', 'userID', 'NickName', 'UID',
  429. 'View_Account',
  430. 'View_Password', 'ChannelIndex', 'Type',
  431. 'isShare',
  432. 'primaryUserID', 'primaryMaster',
  433. 'vodPrimaryUserID', 'vodPrimaryMaster',
  434. 'userID__userEmail',
  435. 'data_joined', 'version',
  436. 'isVod', 'isExist', 'isCameraOpenCloud',
  437. 'serial_number')
  438. dvql = CommonService.qs_to_list(dvqs)
  439. ubqs = UID_Bucket.objects.filter(uid=UID). \
  440. values('bucket__content', 'status', 'channel', 'endTime', 'uid')
  441. success_res = dvql[0]
  442. success_res['vod'] = list(ubqs)
  443. iotqs = iotdeviceInfoModel.objects.filter(serial_number=dvql[0]['serial_number'])
  444. if iotqs.exists():
  445. success_res['iot'] = {'endpoint': iotqs[0].endpoint, 'token_iot_number': iotqs[0].endpoint}
  446. deviceNumber += 1
  447. success_res['deviceNumber'] = deviceNumber
  448. add_success_flag = True
  449. except Exception as e:
  450. print(e)
  451. error_res = repr(e)
  452. exception_flag = True
  453. pass
  454. finally:
  455. if add_success_flag: # 有一台添加成功则返回成功
  456. return response.json(0, success_res)
  457. if exists_flag: # 全部设备已存在
  458. return response.json(174, exists_res)
  459. if exception_flag:
  460. return response.json(500, error_res)
  461. return response.json(0, res)
  462. def do_modify(self, userID, request_dict, response, request):
  463. token = request_dict.get('token', None)
  464. deviceContent = request_dict.get('content', None)
  465. id = request_dict.get('id', None)
  466. if not deviceContent or not id:
  467. return response.json(444, 'content,id')
  468. tko = TokenObject(token)
  469. response.lang = tko.lang
  470. if tko.code != 0:
  471. return response.json(tko.code)
  472. userID = tko.userID
  473. if userID is None:
  474. return response.json(309)
  475. try:
  476. deviceData = eval(deviceContent)
  477. if deviceData.__contains__('userID_id'):
  478. asy = threading.Thread(target=ModelService.update_log,
  479. args=(CommonService.get_ip_address(request), userID, 'modifyV3', deviceData, id))
  480. asy.start()
  481. return response.json(10, '110')
  482. if deviceData.__contains__('UID'):
  483. del deviceData['UID']
  484. # print(deviceData['View_Password'])
  485. if deviceData.__contains__('View_Password'):
  486. encrypt_pwd = deviceData['View_Password']
  487. deviceData['View_Password'] = self.decode_pwd(deviceData['View_Password'])
  488. dev_info_qs = Device_Info.objects.filter(userID_id=userID, id=id)
  489. dev_info_qs.update(**deviceData)
  490. except Exception as e:
  491. print(e)
  492. return response.json(177, repr(e))
  493. else:
  494. qs = Device_Info.objects.filter(userID_id=userID, id=id)
  495. res = CommonService.qs_to_dict(qs)
  496. if qs.exists():
  497. uid = qs[0].UID
  498. nickname = qs[0].NickName
  499. # 增加设备影子信息修改昵称 start
  500. us_qs = UidSetModel.objects.filter(uid=uid)
  501. if us_qs.exists():
  502. if deviceData.__contains__('NickName'):
  503. us_qs.update(nickname=nickname)
  504. else:
  505. ip = CommonService.get_ip_address(request)
  506. ipInfo = CommonService.getIpIpInfo(ip, 'CN')
  507. country_qs = CountryModel.objects.filter(country_code=ipInfo['country_code']).values('id')
  508. country = country_qs.exists() if country_qs[0]['id'] else 0
  509. ChannelIndex = qs[0].ChannelIndex
  510. nowTime = int(time.time())
  511. uid_set_create_dict = {
  512. 'uid': uid,
  513. 'addTime': nowTime,
  514. 'updTime': nowTime,
  515. 'ip': CommonService.get_ip_address(request),
  516. 'channel': ChannelIndex,
  517. 'nickname': nickname,
  518. 'device_type': qs[0].Type,
  519. 'tb_country': country
  520. }
  521. UidSetModel.objects.create(**uid_set_create_dict)
  522. di_qs = Device_Info.objects.filter(UID=uid)
  523. di_qs.update(NickName=nickname)
  524. if deviceData is not None and deviceData.__contains__('NickName') and us_qs[0].is_alexa == 1:
  525. # 请求Alexa服务器更新事件网关
  526. url = 'https://www.zositech.xyz/deviceStatus/addOrUpdateV2'
  527. password = encrypt_pwd if deviceData.__contains__('View_Password') else ''
  528. data_list = [{'userID': userID, 'UID': uid, 'uid_nick': nickname, 'password': password}]
  529. data_list = json.dumps(data_list)
  530. data = {'data_list': data_list}
  531. requests.post(url, data=data, timeout=2)
  532. return response.json(0, res)
  533. # 编辑通道名
  534. def do_modify_channel_name(self, userID, request_dict, response):
  535. uid = request_dict.get('uid', None)
  536. channel = request_dict.get('channel', None)
  537. channel_name = request_dict.get('channel_name', None)
  538. if not all([uid, channel, channel_name]):
  539. return response.json(444)
  540. # 更新通道名
  541. UidChannelSetModel.objects.filter(uid__uid=uid).update(channel_name=channel_name)
  542. return response.json(0)
  543. def do_query(self, userID, request_dict, response):
  544. """
  545. 首页查询设备列表
  546. @param userID: 用户id
  547. @param request_dict: 请求参数
  548. @param response: 响应结果
  549. """
  550. token = request_dict.get('token', None)
  551. page = request_dict.get('page', None)
  552. line = request_dict.get('line', None)
  553. NickName = request_dict.get('NickName', None)
  554. if not token or not page or not line:
  555. return response.json(444)
  556. page = int(page)
  557. line = int(line)
  558. uid = request_dict.get('uid', None)
  559. tko = TokenObject(token)
  560. response.lang = tko.lang
  561. if page <= 0:
  562. return response.json(0)
  563. if tko.code != 0:
  564. return response.json(tko.code)
  565. userID = tko.userID
  566. # 查询设备列表以及设备uid集合
  567. dv_list, uid_list = UserDeviceService.query_device_list(userID, uid, NickName, page, line)
  568. ub_qs = UserDeviceService.query_device_uid_bucket(uid_list) # 根据uid集合查询云存套餐
  569. up_qs = UserDeviceService.query_device_preview(uid_list) # 根据uid集合查询设备预览图
  570. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  571. bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
  572. nowTime = int(time.time())
  573. data = []
  574. uv_dict = UserDeviceService.query_device_channel(uid_list) # 查询设备uid通道配置属性
  575. # 遍历设备列表,查询设备关联数据详情
  576. for p in dv_list:
  577. p['UID'] = p['UID'].replace('\n', '').replace('\r', '')
  578. p_uid = p['UID'].upper()
  579. UserDeviceService.get_sim_by_serial_number(p) # 获取SIM卡属性
  580. p['cloudPhoto'] = self.get_cloud_photo_status(p['UID'])
  581. # 获取iot_deviceInfo表的endpoint和token_iot_number
  582. p['iot'] = []
  583. if p['serial_number']: # 存在序列号根据序列号查询
  584. iotdeviceInfo_qs = iotdeviceInfoModel.objects.filter(serial_number=p['serial_number'][0:6])
  585. else: # 根据uid查询
  586. iotdeviceInfo_qs = iotdeviceInfoModel.objects.filter(uid=p_uid)
  587. if iotdeviceInfo_qs.exists():
  588. iotdeviceInfo = iotdeviceInfo_qs.values('endpoint', 'token_iot_number')
  589. p['iot'].append({
  590. 'endpoint': iotdeviceInfo[0]['endpoint'],
  591. 'token_iot_number': iotdeviceInfo[0]['token_iot_number']
  592. })
  593. p['vod'] = []
  594. for dm in ub_qs:
  595. if p_uid == dm['uid']:
  596. if dm['endTime'] > nowTime:
  597. p['vod'].append(dm)
  598. p['preview'] = []
  599. for up in up_qs:
  600. if p_uid == up['uid']:
  601. obj = 'uid_preview/{uid}/channel_{channel}.png'.format(uid=up['uid'], channel=up['channel'])
  602. img_sign = bucket.sign_url('GET', obj, 300)
  603. p['preview'].append(img_sign)
  604. UserDeviceService.get_uid_info(p, p_uid) # 获取uid初始化信息
  605. if p_uid in uv_dict:
  606. # 获取设备信息DTO
  607. UserDeviceService.get_device_info_dto(p, p_uid, uv_dict)
  608. else:
  609. # 设备版本号
  610. p['uid_version'] = ''
  611. p['ucode'] = ''
  612. p['View_Password'] = self.encrypt_pwd(p['View_Password'])
  613. data.append(p)
  614. result = data
  615. return response.json(0, result)
  616. @staticmethod
  617. def get_cloud_photo_status(uid):
  618. """
  619. 根据UID获取云相册开关状态
  620. @param uid: 设备uid
  621. @return: 0 or 1
  622. """
  623. cloud_photo_qs = DeviceCloudPhotoInfo.objects.filter(uid=uid).values('status')
  624. if not cloud_photo_qs.exists():
  625. return 0
  626. return cloud_photo_qs[0]['status']
  627. def do_fuzzy_query(self, userID, request_dict, response):
  628. fuzzy = request_dict.get('fuzzy', None)
  629. page = request_dict.get('page', None)
  630. line = request_dict.get('line', None)
  631. if page and line:
  632. page = int(page)
  633. line = int(line)
  634. device_qs = Device_Info.objects.filter(userID=userID)
  635. device_qs = device_qs.filter(~Q(isExist=2))
  636. if device_qs.exists():
  637. if fuzzy:
  638. device_qs = device_qs.filter(Q(UID__icontains=fuzzy) | Q(NickName__icontains=fuzzy))
  639. device_qs = device_qs.values('id', 'userID', 'NickName', 'UID', 'View_Account',
  640. 'View_Password', 'ChannelIndex', 'Type', 'isShare',
  641. 'primaryUserID', 'primaryMaster', 'data_joined', 'vodPrimaryUserID',
  642. 'vodPrimaryMaster', 'userID__userEmail',
  643. 'version', 'isVod', 'isExist', 'NotificationMode', 'isCameraOpenCloud',
  644. 'serial_number')
  645. dvls = CommonService.qs_to_list(device_qs)
  646. uid_list = []
  647. for dvl in dvls:
  648. uid_list.append(dvl['UID'])
  649. ubqs = UID_Bucket.objects.filter(uid__in=uid_list). \
  650. values('bucket__content', 'status', 'channel', 'endTime', 'uid')
  651. upqs = UID_Preview.objects.filter(uid__in=uid_list).order_by('channel').values('id', 'uid', 'channel')
  652. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  653. bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
  654. nowTime = int(time.time())
  655. data = []
  656. # 设备拓展信息表
  657. us_qs = UidSetModel.objects.filter(uid__in=uid_list).values('id', 'uid', 'version', 'nickname', 'ucode',
  658. 'detect_status', 'detect_group',
  659. 'detect_interval',
  660. 'region_alexa', 'is_alexa', 'deviceModel',
  661. 'TimeZone', 'TimeStatus', 'SpaceUsable',
  662. 'SpaceSum', 'MirrorType', 'RecordType',
  663. 'OutdoorModel', 'WIFIName', 'isDetector',
  664. 'DetectorRank')
  665. uv_dict = {}
  666. for us in us_qs:
  667. uv_dict[us['uid']] = {
  668. 'version': us['version'],
  669. 'nickname': us['nickname'],
  670. 'ucode': us['ucode'],
  671. 'detect_interval': us['detect_interval'],
  672. 'detect_group': us['detect_group'],
  673. 'detect_status': us['detect_status'],
  674. 'region_alexa': us['region_alexa'],
  675. 'is_alexa': us['is_alexa'],
  676. 'deviceModel': us['deviceModel'],
  677. 'TimeZone': us['TimeZone'],
  678. 'TimeStatus': us['TimeStatus'],
  679. 'SpaceUsable': us['SpaceUsable'],
  680. 'SpaceSum': us['SpaceSum'],
  681. 'MirrorType': us['MirrorType'],
  682. 'RecordType': us['RecordType'],
  683. 'OutdoorModel': us['OutdoorModel'],
  684. 'WIFIName': us['WIFIName'],
  685. 'isDetector': us['isDetector'],
  686. 'DetectorRank': us['DetectorRank']
  687. }
  688. # 从uid_channel里面取出通道配置信息
  689. ucs_qs = UidChannelSetModel.objects.filter(uid__id=us['id']).values()
  690. channels = []
  691. for ucs in ucs_qs:
  692. channel = {
  693. 'channel': ucs['channel'],
  694. 'channel_name': ucs['channel_name'],
  695. 'pir_audio': ucs['pir_audio'],
  696. 'mic_audio': ucs['mic_audio'],
  697. 'battery_status': ucs['battery_status'],
  698. 'battery_level': ucs['battery_level'],
  699. 'sleep_status': ucs['sleep_status'],
  700. 'sleep_time': ucs['sleep_time'],
  701. 'light_night_model': ucs['light_night_model'],
  702. 'light_alarm_type': ucs['light_alarm_type'],
  703. 'light_alarm_level': ucs['light_alarm_level'],
  704. 'light_alarm_man_en': ucs['light_alarm_man_en'],
  705. 'light_alarm_vol': ucs['light_alarm_vol'],
  706. 'light_long_light': ucs['light_long_light']
  707. }
  708. channels.append(channel)
  709. uv_dict[us['uid']]['channels'] = channels
  710. for p in dvls:
  711. # 获取iot_deviceInfo表的endpoint和token_iot_number
  712. p['iot'] = []
  713. if p['serial_number']: # 存在序列号根据序列号查询
  714. iotdeviceInfo_qs = iotdeviceInfoModel.objects.filter(serial_number=p['serial_number'][0:6])
  715. else: # 根据uid查询
  716. iotdeviceInfo_qs = iotdeviceInfoModel.objects.filter(uid=p['UID'])
  717. if iotdeviceInfo_qs.exists():
  718. iotdeviceInfo = iotdeviceInfo_qs.values('endpoint', 'token_iot_number')
  719. p['iot'].append({
  720. 'endpoint': iotdeviceInfo[0]['endpoint'],
  721. 'token_iot_number': iotdeviceInfo[0]['token_iot_number']
  722. })
  723. p['vod'] = []
  724. for dm in ubqs:
  725. if p['UID'] == dm['uid']:
  726. if dm['endTime'] > nowTime:
  727. p['vod'].append(dm)
  728. p['preview'] = []
  729. for up in upqs:
  730. if p['UID'] == up['uid']:
  731. obj = 'uid_preview/{uid}/channel_{channel}.png'.format(uid=up['uid'], channel=up['channel'])
  732. img_sign = bucket.sign_url('GET', obj, 300)
  733. p['preview'].append(img_sign)
  734. p_uid = p['UID']
  735. if p_uid in uv_dict:
  736. # 设备版本号
  737. p['uid_version'] = uv_dict[p_uid]['version']
  738. p['ucode'] = uv_dict[p_uid]['ucode']
  739. p['detect_interval'] = uv_dict[p_uid]['detect_interval']
  740. p['detect_status'] = uv_dict[p_uid]['detect_status']
  741. p['detect_group'] = uv_dict[p_uid]['detect_group']
  742. p['region_alexa'] = uv_dict[p_uid]['region_alexa']
  743. p['is_alexa'] = uv_dict[p_uid]['is_alexa']
  744. p['deviceModel'] = uv_dict[p_uid]['deviceModel']
  745. p['TimeZone'] = uv_dict[p_uid]['TimeZone']
  746. p['TimeStatus'] = uv_dict[p_uid]['TimeStatus']
  747. p['SpaceUsable'] = uv_dict[p_uid]['SpaceUsable']
  748. p['SpaceSum'] = uv_dict[p_uid]['SpaceSum']
  749. p['MirrorType'] = uv_dict[p_uid]['MirrorType']
  750. p['RecordType'] = uv_dict[p_uid]['RecordType']
  751. p['OutdoorModel'] = uv_dict[p_uid]['OutdoorModel']
  752. p['WIFIName'] = uv_dict[p_uid]['WIFIName']
  753. p['isDetector'] = uv_dict[p_uid]['isDetector']
  754. p['DetectorRank'] = uv_dict[p_uid]['DetectorRank']
  755. p['channels'] = uv_dict[p_uid]['channels']
  756. # 设备昵称 调用影子信息昵称,先阶段不可
  757. if uv_dict[p_uid]['nickname']:
  758. p['NickName'] = uv_dict[p_uid]['nickname']
  759. else:
  760. # 设备版本号
  761. p['uid_version'] = ''
  762. p['ucode'] = ''
  763. data.append(p)
  764. result = data
  765. items = []
  766. # print('缓存分页')
  767. for index, item in enumerate(result):
  768. if (page - 1) * line <= index:
  769. if index < page * line:
  770. # 加密
  771. item['View_Password'] = self.encrypt_pwd(item['View_Password'])
  772. print(item)
  773. items.append(item)
  774. print(items)
  775. return response.json(0, items)
  776. else:
  777. return response.json(0, [])
  778. else:
  779. return response.json(444)
  780. # 加密
  781. def encrypt_pwd(self, userPwd):
  782. for i in range(1, 4):
  783. if i == 1:
  784. userPwd = RandomStr(3, False) + userPwd + RandomStr(3, False)
  785. userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
  786. if i == 2:
  787. userPwd = RandomStr(2, False) + str(userPwd) + RandomStr(2, False)
  788. userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
  789. if i == 3:
  790. userPwd = RandomStr(1, False) + str(userPwd) + RandomStr(1, False)
  791. userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
  792. return userPwd
  793. # 解密
  794. def decode_pwd(self, password):
  795. for i in range(1, 4):
  796. if i == 1:
  797. # 第一次先解密
  798. password = base64.b64decode(password)
  799. password = password.decode('utf-8')
  800. # 截去第一位,最后一位
  801. password = password[1:-1]
  802. if i == 2:
  803. # 第2次先解密
  804. password = base64.b64decode(password)
  805. password = password.decode('utf-8')
  806. # 去前2位,后2位
  807. password = password[2:-2]
  808. if i == 3:
  809. # 第3次先解密
  810. password = base64.b64decode(password)
  811. password = password.decode('utf-8')
  812. # 去前3位,后3位
  813. password = password[3:-3]
  814. return password
  815. def do_mainUserDevice(self, request_dict, response):
  816. UID = request_dict.get('UID')
  817. dvq = Device_Info.objects.filter(UID=UID)
  818. dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  819. qs = {}
  820. if dvq.exists():
  821. qs = Device_User.objects.filter(userID=dvq[0]['vodPrimaryUserID']).values('userID', 'NickName', 'username',
  822. 'userEmail', 'phone')
  823. NickName = qs[0]['username']
  824. userEmail = qs[0]['userEmail']
  825. phone = qs[0]['phone']
  826. username = qs[0]['username']
  827. qs = CommonService.qs_to_list(qs)
  828. if NickName == '':
  829. qs[0]['NickName'] = username
  830. # if userEmail =='':
  831. # qs[0]['userEmail'] = NickName
  832. if phone == '':
  833. qs[0]['phone'] = NickName
  834. # if not qs:
  835. # uidq = UIDMainUser.objects.filter(UID=UID).values('user_id')
  836. # if uidq.exists():
  837. # qs = Device_User.objects.filter(userID=uidq[0]['user_id']).values('userID', 'NickName', 'username', 'userEmail', 'phone')
  838. # qs = CommonService.qs_to_list(qs)
  839. return response.json(0, qs)
  840. def not_login_do_mainUserDevice(self, request_dict, response):
  841. UID = request_dict.get('UID')
  842. token = request_dict.get('token', None)
  843. time_stamp = request_dict.get('time_stamp', None)
  844. if not all([token, time_stamp]):
  845. return response.json(444)
  846. # 时间戳token校验
  847. if not CommonService.check_time_stamp_token(token, time_stamp):
  848. return response.json(13)
  849. dvq = Device_Info.objects.filter(UID=UID)
  850. dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  851. qs = {}
  852. if dvq.exists():
  853. qs = Device_User.objects.filter(userID=dvq[0]['vodPrimaryUserID']).values('userID', 'NickName', 'username',
  854. 'userEmail', 'phone')
  855. NickName = qs[0]['username']
  856. phone = qs[0]['phone']
  857. username = qs[0]['username']
  858. qs = CommonService.qs_to_list(qs)
  859. if NickName == '':
  860. qs[0]['NickName'] = username
  861. if phone == '':
  862. qs[0]['phone'] = NickName
  863. return response.json(0, qs)
  864. @staticmethod
  865. def test_tool_del_device(request_dict, response):
  866. """
  867. 测试工具删除设备
  868. @param request_dict: 请求数据
  869. @request_dict user_id: 用户id
  870. @request_dict uid: uid
  871. @request_dict time_stamp: 时间戳
  872. @request_dict time_stamp_token: 时间戳token
  873. @param response: 响应
  874. @return: response
  875. """
  876. user_id = request_dict.get('user_id')
  877. uid = request_dict.get('uid')
  878. time_stamp = request_dict.get('time_stamp', None)
  879. time_stamp_token = request_dict.get('time_stamp_token', None)
  880. if not all([user_id, uid, time_stamp, time_stamp_token]):
  881. return response.json(444)
  882. try:
  883. # 时间戳token校验
  884. if not CommonService.check_time_stamp_token(time_stamp_token, time_stamp):
  885. return response.json(13)
  886. return response.json(0)
  887. except Exception as e:
  888. return response.json(500, repr(e))
  889. def do_get_device_features(self, request_dict, response):
  890. uid = request_dict.get('uid', None)
  891. if uid:
  892. uid = CommonService.decode_data(uid)
  893. if uid:
  894. uid_qs = UidSetModel.objects.filter(uid=uid)
  895. if uid_qs.exists():
  896. uid_qs = uid_qs.values('is_alexa', 'is_human', 'is_custom_voice', 'double_wifi', 'mobile_4g')
  897. return response.json(0, uid_qs[0])
  898. else:
  899. return response.json(173)
  900. else:
  901. return response.json(444)
  902. else:
  903. return response.json(444)