EquipmentManagerV3.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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 Object.RedisObject import RedisObject
  11. from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY, BASE_DIR
  12. from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidPushModel, UidChannelSetModel
  13. from Object.ResponseObject import ResponseObject
  14. from Object.TokenObject import TokenObject
  15. from Service.CommonService import CommonService
  16. from Service.ModelService import ModelService
  17. import time,json
  18. class EquipmentManagerV3(View):
  19. def get(self, request, *args, **kwargs):
  20. request.encoding = 'utf-8'
  21. operation = kwargs.get('operation')
  22. return self.validation(request.GET, request, operation)
  23. def post(self, request, *args, **kwargs):
  24. request.encoding = 'utf-8'
  25. operation = kwargs.get('operation')
  26. return self.validation(request.POST, request, operation)
  27. def validation(self, request_dict, request, operation):
  28. response = ResponseObject()
  29. token = request_dict.get('token', None)
  30. # 设备主键uid
  31. tko = TokenObject(token)
  32. if tko.code == 0:
  33. response.lang = tko.lang
  34. userID = tko.userID
  35. # 手机端添加设备,查询,修改
  36. if operation == 'add':
  37. return self.do_add(userID, request_dict, response, request)
  38. elif operation == 'query':
  39. return self.do_query(userID, request_dict, response)
  40. elif operation == 'modify':
  41. return self.do_modify(userID, request_dict, response, request)
  42. else:
  43. return response.json(414)
  44. else:
  45. return response.json(tko.code)
  46. def do_add(self, userID, request_dict, response, request):
  47. token = request_dict.get('token', None)
  48. UID = request_dict.get('UID', None)
  49. NickName = request_dict.get('NickName', None)
  50. View_Account = request_dict.get('View_Account', None)
  51. View_Password = request_dict.get('View_Password', '')
  52. print("准备解密")
  53. View_Password = self.decode_pwd(View_Password)
  54. Type = request_dict.get('Type', None)
  55. ChannelIndex = request_dict.get('ChannelIndex', None)
  56. if all([UID, NickName, View_Account, Type, ChannelIndex]):
  57. tko = TokenObject(token)
  58. response.lang = tko.lang
  59. if tko.code == 0:
  60. userID = tko.userID
  61. re_uid = re.compile(r'^[A-Za-z0-9]{20}$')
  62. if re_uid.match(UID):
  63. is_exist = Device_Info.objects.filter(UID=UID, userID_id=userID)
  64. if is_exist:
  65. # 判断设备是否已存在
  66. if is_exist[0].isExist == 1:
  67. return response.json(174)
  68. else:
  69. is_exist.delete()
  70. if UID == '98UXAA8BRPA35VAL111A':
  71. asy = threading.Thread(target=ModelService.add_log,
  72. args=(CommonService.get_ip_address(request), userID, 'addV3'))
  73. asy.start()
  74. return response.json(10, 'illegal uid: {uid}'.format(uid=UID))
  75. # is_bind = Device_Info.objects.filter(UID=UID, isShare=False)
  76. # # 判断是否有已绑定用户
  77. # if is_bind:
  78. # return response.json(15)
  79. try:
  80. # 判断是否有用户绑定
  81. nowTime = int(time.time())
  82. us_qs = UidSetModel.objects.filter(uid=UID)
  83. if not us_qs.exists():
  84. uid_set_create_dict = {
  85. 'uid': UID,
  86. 'addTime': nowTime,
  87. 'updTime': nowTime,
  88. 'ip': CommonService.get_ip_address(request_dict),
  89. 'channel': ChannelIndex,
  90. 'nickname': NickName,
  91. }
  92. UidSetModel.objects.create(**uid_set_create_dict)
  93. else:
  94. us_qs.update(nickname=NickName)
  95. pk = CommonService.getUserID(getUser=False)
  96. userDevice = Device_Info(id=pk, userID_id=userID, UID=UID,
  97. NickName=NickName, View_Account=View_Account,
  98. View_Password=View_Password, Type=Type, ChannelIndex=ChannelIndex)
  99. userDevice.save()
  100. if not us_qs.exists():
  101. us_qs = UidSetModel.objects.filter(uid=UID)
  102. if us_qs.exists() and us_qs[0].is_alexa == 1:
  103. asy = threading.Thread(target=ModelService.notify_alexa_add, args=(UID, userID, NickName))
  104. asy.start()
  105. # redisObj = RedisObject(db=8)
  106. # redisObj.del_data(key='uid_qs_' + userID)
  107. except Exception as e:
  108. return response.json(10, repr(e))
  109. else:
  110. dvqs = Device_Info.objects.filter(id=pk).values('id', 'userID', 'NickName', 'UID',
  111. 'View_Account',
  112. 'View_Password', 'ChannelIndex', 'Type',
  113. 'isShare',
  114. 'primaryUserID', 'primaryMaster',
  115. 'data_joined', 'version',
  116. 'isVod', 'isExist')
  117. dvql = CommonService.qs_to_list(dvqs)
  118. ubqs = UID_Bucket.objects.filter(uid=UID). \
  119. values('bucket__content', 'status', 'channel', 'endTime', 'uid')
  120. res = dvql[0]
  121. res['vod'] = list(ubqs)
  122. return response.json(0, res)
  123. else:
  124. return response.json(444, {'param': 'UID'})
  125. else:
  126. return response.json(tko.code)
  127. else:
  128. return response.json(444, {'param': 'UID,NickName,View_Account,View_Password,Type,ChannelIndex'})
  129. def do_modify(self, userID, request_dict, response, request):
  130. token = request_dict.get('token', None)
  131. deviceContent = request_dict.get('content', None)
  132. id = request_dict.get('id', None)
  133. if not deviceContent or not id:
  134. return response.json(444, 'content,id')
  135. tko = TokenObject(token)
  136. response.lang = tko.lang
  137. if tko.code != 0:
  138. return response.json(tko.code)
  139. userID = tko.userID
  140. if userID is None:
  141. return response.json(309)
  142. deviceData = None
  143. dev_info_qs = None
  144. try:
  145. # deviceData = json.loads(deviceContent)
  146. deviceData = eval(deviceContent)
  147. if deviceData.__contains__('userID_id'):
  148. asy = threading.Thread(target=ModelService.update_log,
  149. args=(CommonService.get_ip_address(request), userID, 'modifyV3', deviceData, id))
  150. asy.start()
  151. return response.json(10, '110')
  152. if deviceData.__contains__('UID'):
  153. del deviceData['UID']
  154. # print(deviceData['View_Password'])
  155. if deviceData.__contains__('View_Password'):
  156. deviceData['View_Password'] = self.decode_pwd(deviceData['View_Password'])
  157. dev_info_qs = Device_Info.objects.filter(userID_id=userID, id=id)
  158. dev_info_qs.update(**deviceData)
  159. except Exception as e:
  160. print(e)
  161. return response.json(177, repr(e))
  162. else:
  163. qs = Device_Info.objects.filter(userID_id=userID, id=id)
  164. res = CommonService.qs_to_dict(qs)
  165. if qs.exists():
  166. uid = qs[0].UID
  167. nickname = qs[0].NickName
  168. # 增加设备影子信息修改昵称 start
  169. us_qs = UidSetModel.objects.filter(uid=uid)
  170. if us_qs.exists():
  171. if deviceData.__contains__('NickName'):
  172. us_qs.update(nickname=nickname)
  173. else:
  174. ChannelIndex = qs[0].ChannelIndex
  175. nowTime = int(time.time())
  176. uid_set_create_dict = {
  177. 'uid': uid,
  178. 'addTime': nowTime,
  179. 'updTime': nowTime,
  180. # 'ip': CommonService.get_ip_address(request),
  181. 'channel': ChannelIndex,
  182. 'nickname': nickname,
  183. }
  184. UidSetModel.objects.create(**uid_set_create_dict)
  185. di_qs = Device_Info.objects.filter(UID=uid)
  186. di_qs.update(NickName=nickname)
  187. if deviceData is not None and deviceData.__contains__('NickName') and us_qs[0].is_alexa == 1:
  188. asy = threading.Thread(target=ModelService.notify_alexa_add, args=(uid, userID, nickname))
  189. asy.start()
  190. # redisObj = RedisObject(db=8)
  191. # redisObj.del_data(key='uid_qs_' + userID)
  192. return response.json(0, res)
  193. # 新查询设备字段
  194. def do_query(self, userID, request_dict, response):
  195. token = request_dict.get('token', None)
  196. page = request_dict.get('page', None)
  197. line = request_dict.get('line', None)
  198. NickName = request_dict.get('NickName', None)
  199. if not token or not page or not line:
  200. return response.json(444)
  201. page = int(page)
  202. line = int(line)
  203. uid = request_dict.get('uid', None)
  204. tko = TokenObject(token)
  205. response.lang = tko.lang
  206. if page <= 0:
  207. return response.json(0)
  208. if tko.code == 0:
  209. userID = tko.userID
  210. dvqs = Device_Info.objects.filter(userID_id=userID)
  211. # # 过滤已重置的设备
  212. dvqs = dvqs.filter(~Q(isExist=2))
  213. dvql = dvqs.values('id', 'userID', 'NickName', 'UID', 'View_Account',
  214. 'View_Password', 'ChannelIndex', 'Type', 'isShare',
  215. 'primaryUserID', 'primaryMaster', 'data_joined',
  216. 'version', 'isVod', 'isExist', 'NotificationMode')
  217. dvls = CommonService.qs_to_list(dvql)
  218. uid_list = []
  219. for dvl in dvls:
  220. uid_list.append(dvl['UID'])
  221. ubqs = UID_Bucket.objects.filter(uid__in=uid_list). \
  222. values('bucket__content', 'status', 'channel', 'endTime', 'uid')
  223. upqs = UID_Preview.objects.filter(uid__in=uid_list).order_by('channel').values('id', 'uid', 'channel')
  224. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  225. bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
  226. nowTime = int(time.time())
  227. data = []
  228. # 设备拓展信息表
  229. us_qs = UidSetModel.objects.filter(uid__in=uid_list).values('id', 'uid', 'version', 'nickname', 'ucode',
  230. 'detect_status', 'detect_group',
  231. 'detect_interval',
  232. 'region_alexa', 'is_alexa', 'deviceModel',
  233. 'TimeZone', 'TimeStatus', 'SpaceUsable',
  234. 'SpaceSum', 'MirrorType', 'RecordType',
  235. 'OutdoorModel', 'WIFIName', 'isDetector',
  236. 'DetectorRank')
  237. uv_dict = {}
  238. for us in us_qs:
  239. uv_dict[us['uid']] = {
  240. 'version': us['version'],
  241. 'nickname': us['nickname'],
  242. 'ucode': us['ucode'],
  243. 'detect_interval': us['detect_interval'],
  244. 'detect_group': us['detect_group'],
  245. 'detect_status': us['detect_status'],
  246. 'region_alexa': us['region_alexa'],
  247. 'is_alexa': us['is_alexa'],
  248. 'deviceModel': us['deviceModel'],
  249. 'TimeZone': us['TimeZone'],
  250. 'TimeStatus': us['TimeStatus'],
  251. 'SpaceUsable': us['SpaceUsable'],
  252. 'SpaceSum': us['SpaceSum'],
  253. 'MirrorType': us['MirrorType'],
  254. 'RecordType': us['RecordType'],
  255. 'OutdoorModel': us['OutdoorModel'],
  256. 'WIFIName': us['WIFIName'],
  257. 'isDetector': us['isDetector'],
  258. 'DetectorRank': us['DetectorRank']
  259. }
  260. # 从uid_channel里面取出通道配置信息
  261. ucs_qs = UidChannelSetModel.objects.filter(uid__id=us['id']).values()
  262. channels = []
  263. for ucs in ucs_qs:
  264. channel = {
  265. 'channel': ucs['channel'],
  266. 'pir_audio': ucs['pir_audio'],
  267. 'mic_audio': ucs['mic_audio'],
  268. 'battery_status': ucs['battery_status'],
  269. 'battery_level': ucs['battery_level'],
  270. 'sleep_status': ucs['sleep_status'],
  271. 'sleep_time': ucs['sleep_time'],
  272. 'light_night_model': ucs['light_night_model'],
  273. 'light_alarm_type': ucs['light_alarm_type'],
  274. 'light_alarm_level': ucs['light_alarm_level'],
  275. 'light_alarm_man_en': ucs['light_alarm_man_en'],
  276. 'light_alarm_vol': ucs['light_alarm_vol'],
  277. 'light_long_light': ucs['light_long_light']
  278. }
  279. channels.append(channel)
  280. uv_dict[us['uid']]['channels'] = channels
  281. for p in dvls:
  282. p['vod'] = []
  283. for dm in ubqs:
  284. if p['UID'] == dm['uid']:
  285. if dm['endTime'] > nowTime:
  286. p['vod'].append(dm)
  287. p['preview'] = []
  288. for up in upqs:
  289. if p['UID'] == up['uid']:
  290. obj = 'uid_preview/{uid}/channel_{channel}.png'.format(uid=up['uid'], channel=up['channel'])
  291. img_sign = bucket.sign_url('GET', obj, 300)
  292. p['preview'].append(img_sign)
  293. p_uid = p['UID']
  294. if p_uid in uv_dict:
  295. # 设备版本号
  296. p['uid_version'] = uv_dict[p_uid]['version']
  297. p['ucode'] = uv_dict[p_uid]['ucode']
  298. p['detect_interval'] = uv_dict[p_uid]['detect_interval']
  299. p['detect_status'] = uv_dict[p_uid]['detect_status']
  300. p['detect_group'] = uv_dict[p_uid]['detect_group']
  301. p['region_alexa'] = uv_dict[p_uid]['region_alexa']
  302. p['is_alexa'] = uv_dict[p_uid]['is_alexa']
  303. p['deviceModel'] = uv_dict[p_uid]['deviceModel']
  304. p['TimeZone'] = uv_dict[p_uid]['TimeZone']
  305. p['TimeStatus'] = uv_dict[p_uid]['TimeStatus']
  306. p['SpaceUsable'] = uv_dict[p_uid]['SpaceUsable']
  307. p['SpaceSum'] = uv_dict[p_uid]['SpaceSum']
  308. p['MirrorType'] = uv_dict[p_uid]['MirrorType']
  309. p['RecordType'] = uv_dict[p_uid]['RecordType']
  310. p['OutdoorModel'] = uv_dict[p_uid]['OutdoorModel']
  311. p['WIFIName'] = uv_dict[p_uid]['WIFIName']
  312. p['isDetector'] = uv_dict[p_uid]['isDetector']
  313. p['DetectorRank'] = uv_dict[p_uid]['DetectorRank']
  314. p['channels'] = uv_dict[p_uid]['channels']
  315. # 设备昵称 调用影子信息昵称,先阶段不可
  316. if uv_dict[p_uid]['nickname']:
  317. p['NickName'] = uv_dict[p_uid]['nickname']
  318. else:
  319. # 设备版本号
  320. p['uid_version'] = ''
  321. p['ucode'] = ''
  322. data.append(p)
  323. result = data
  324. if NickName:
  325. # print('NickName搜索缓存')
  326. data = []
  327. for index, item in enumerate(result):
  328. if NickName == item['NickName']:
  329. # 加密
  330. item['View_Password'] = self.encrypt_pwd(item['View_Password'])
  331. data.append(item)
  332. return response.json(0, data)
  333. if uid:
  334. # print('uid搜索缓存')
  335. data = []
  336. for index, item in enumerate(result):
  337. if uid == item['UID']:
  338. # 加密
  339. item['View_Password'] = self.encrypt_pwd(item['View_Password'])
  340. data.append(item)
  341. return response.json(0, data)
  342. items = []
  343. # print('缓存分页')
  344. for index, item in enumerate(result):
  345. if (page - 1) * line <= index:
  346. if index < page * line:
  347. # 加密
  348. item['View_Password'] = self.encrypt_pwd(item['View_Password'])
  349. print(item)
  350. items.append(item)
  351. print(items)
  352. return response.json(0, items)
  353. else:
  354. return response.json(tko.code)
  355. # 加密
  356. def encrypt_pwd(self,userPwd):
  357. for i in range(1, 4):
  358. if i == 1:
  359. userPwd = RandomStr(3, False)+userPwd+RandomStr(3, False)
  360. userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
  361. if i == 2:
  362. userPwd = RandomStr(2, False)+str(userPwd)+RandomStr(2, False)
  363. userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
  364. if i == 3:
  365. userPwd = RandomStr(1, False)+str(userPwd)+RandomStr(1, False)
  366. userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
  367. return userPwd
  368. # 解密
  369. def decode_pwd(self, password):
  370. for i in range(1, 4):
  371. if i == 1:
  372. # 第一次先解密
  373. password = base64.b64decode(password)
  374. password = password.decode('utf-8')
  375. # 截去第一位,最后一位
  376. password = password[1:-1]
  377. if i == 2:
  378. # 第2次先解密
  379. password = base64.b64decode(password)
  380. password = password.decode('utf-8')
  381. # 去前2位,后2位
  382. password = password[2:-2]
  383. if i == 3:
  384. # 第3次先解密
  385. password = base64.b64decode(password)
  386. password = password.decode('utf-8')
  387. # 去前3位,后3位
  388. password = password[3:-3]
  389. return password