EquipmentManagerV3.py 18 KB

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