EquipmentManagerV3.py 18 KB

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