EquipmentManagerV3.py 19 KB

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