EquipmentManagerV3.py 18 KB

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