EquipmentManagerV3.py 54 KB

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