EquipmentManagerV3.py 19 KB

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