EquipmentManagerV3.py 19 KB

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