EquipmentManagerV3.py 19 KB

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