123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378 |
- import re
- import threading
- import time
- import traceback
- from Controller.CheckUserData import RandomStr
- import oss2, base64
- from django.db.models import Q
- from django.views.generic.base import View
- from Object.RedisObject import RedisObject
- from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY
- from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidPushModel, UidChannelSetModel
- from Object.ResponseObject import ResponseObject
- from Object.TokenObject import TokenObject
- from Service.CommonService import CommonService
- from Service.ModelService import ModelService
- import time,json
- class EquipmentManagerV3(View):
- def get(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- operation = kwargs.get('operation')
- return self.validation(request.GET, request, operation)
- def post(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- operation = kwargs.get('operation')
- return self.validation(request.POST, request, operation)
- def validation(self, request_dict, request, operation):
- response = ResponseObject()
- token = request_dict.get('token', None)
- # 设备主键uid
- tko = TokenObject(token)
- if tko.code == 0:
- response.lang = tko.lang
- userID = tko.userID
- # 手机端添加设备,查询,修改
- if operation == 'add':
- return self.do_add(userID, request_dict, response, request)
- elif operation == 'query':
- return self.do_query(userID, request_dict, response)
- elif operation == 'modify':
- return self.do_modify(userID, request_dict, response)
- else:
- return response.json(414)
- else:
- return response.json(tko.code)
- def do_add(self, userID, request_dict, response, request):
- token = request_dict.get('token', None)
- UID = request_dict.get('UID', None)
- NickName = request_dict.get('NickName', None)
- View_Account = request_dict.get('View_Account', None)
- View_Password = request_dict.get('View_Password', '')
- print("准备解密")
- View_Password = self.decode_pwd(View_Password)
- Type = request_dict.get('Type', None)
- ChannelIndex = request_dict.get('ChannelIndex', None)
- if all([UID, NickName, View_Account, Type, ChannelIndex]):
- tko = TokenObject(token)
- response.lang = tko.lang
- if tko.code == 0:
- userID = tko.userID
- re_uid = re.compile(r'^[A-Za-z0-9]{20}$')
- if re_uid.match(UID):
- is_exist = Device_Info.objects.filter(UID=UID, userID_id=userID)
- if is_exist:
- # 判断设备是否已存在
- if is_exist[0].isExist == 1:
- return response.json(174)
- else:
- is_exist.delete()
- # is_bind = Device_Info.objects.filter(UID=UID, isShare=False)
- # # 判断是否有已绑定用户
- # if is_bind:
- # return response.json(15)
- try:
- # 判断是否有用户绑定
- nowTime = int(time.time())
- us_qs = UidSetModel.objects.filter(uid=UID)
- if not us_qs.exists():
- uid_set_create_dict = {
- 'uid': UID,
- 'addTime': nowTime,
- 'updTime': nowTime,
- 'ip': CommonService.get_ip_address(request_dict),
- 'channel': ChannelIndex,
- 'nickname': NickName,
- }
- UidSetModel.objects.create(**uid_set_create_dict)
- else:
- us_qs.update(nickname=NickName)
- pk = CommonService.getUserID(getUser=False)
- userDevice = Device_Info(id=pk, userID_id=userID, UID=UID,
- NickName=NickName, View_Account=View_Account,
- View_Password=View_Password, Type=Type, ChannelIndex=ChannelIndex)
- userDevice.save()
- # redisObj = RedisObject(db=8)
- # redisObj.del_data(key='uid_qs_' + userID)
- except Exception as e:
- return response.json(10, repr(e))
- else:
- dvqs = Device_Info.objects.filter(id=pk).values('id', 'userID', 'NickName', 'UID',
- 'View_Account',
- 'View_Password', 'ChannelIndex', 'Type',
- 'isShare',
- 'primaryUserID', 'primaryMaster',
- 'data_joined', 'version',
- 'isVod', 'isExist')
- dvql = CommonService.qs_to_list(dvqs)
- ubqs = UID_Bucket.objects.filter(uid=UID). \
- values('bucket__content', 'status', 'channel', 'endTime', 'uid')
- res = dvql[0]
- res['vod'] = list(ubqs)
- return response.json(0, res)
- else:
- return response.json(444, {'param': 'UID'})
- else:
- return response.json(tko.code)
- else:
- return response.json(444, {'param': 'UID,NickName,View_Account,View_Password,Type,ChannelIndex'})
- def do_modify(self, userID, request_dict, response):
- token = request_dict.get('token', None)
- deviceContent = request_dict.get('content', None)
- id = request_dict.get('id', None)
- if not deviceContent or not id:
- return response.json(444, 'content,id')
- tko = TokenObject(token)
- response.lang = tko.lang
- if tko.code != 0:
- return response.json(tko.code)
- userID = tko.userID
- if userID is None:
- return response.json(309)
- try:
- # deviceData = json.loads(deviceContent)
- deviceData = eval(deviceContent)
- # print(deviceData['View_Password'])
- if deviceData.__contains__('View_Password'):
- deviceData['View_Password'] = self.decode_pwd(deviceData['View_Password'])
- dev_info_qs = Device_Info.objects.filter(userID_id=userID, id=id)
- dev_info_qs.update(**deviceData)
- except Exception as e:
- print(e)
- return response.json(177, repr(e))
- else:
- qs = Device_Info.objects.filter(userID_id=userID, id=id)
- res = CommonService.qs_to_dict(qs)
- if qs.exists():
- uid = qs[0].UID
- nickname = qs[0].NickName
- # 增加设备影子信息修改昵称 start
- us_qs = UidSetModel.objects.filter(uid=uid)
- if us_qs.exists():
- us_qs.update(nickname=nickname)
- else:
- ChannelIndex = qs[0].ChannelIndex
- nowTime = int(time.time())
- uid_set_create_dict = {
- 'uid': uid,
- 'addTime': nowTime,
- 'updTime': nowTime,
- # 'ip': CommonService.get_ip_address(request),
- 'channel': ChannelIndex,
- 'nickname': nickname,
- }
- UidSetModel.objects.create(**uid_set_create_dict)
- di_qs = Device_Info.objects.filter(UID=uid)
- di_qs.update(NickName=nickname)
- # redisObj = RedisObject(db=8)
- # redisObj.del_data(key='uid_qs_' + userID)
- return response.json(0, res)
- # 新查询设备字段
- def do_query(self, userID, request_dict, response):
- token = request_dict.get('token', None)
- page = request_dict.get('page', None)
- line = request_dict.get('line', None)
- NickName = request_dict.get('NickName', None)
- if not token or not page or not line:
- return response.json(444)
- page = int(page)
- line = int(line)
- uid = request_dict.get('uid', None)
- tko = TokenObject(token)
- response.lang = tko.lang
- if page <= 0:
- return response.json(0)
- if tko.code == 0:
- userID = tko.userID
- dvqs = Device_Info.objects.filter(userID_id=userID)
- # # 过滤已重置的设备
- dvqs = dvqs.filter(~Q(isExist=2))
- dvql = dvqs.values('id', 'userID', 'NickName', 'UID', 'View_Account',
- 'View_Password', 'ChannelIndex', 'Type', 'isShare',
- 'primaryUserID', 'primaryMaster', 'data_joined',
- 'version', 'isVod', 'isExist', 'NotificationMode')
- dvls = CommonService.qs_to_list(dvql)
- uid_list = []
- for dvl in dvls:
- uid_list.append(dvl['UID'])
- ubqs = UID_Bucket.objects.filter(uid__in=uid_list). \
- values('bucket__content', 'status', 'channel', 'endTime', 'uid')
- upqs = UID_Preview.objects.filter(uid__in=uid_list).order_by('channel').values('id', 'uid', 'channel')
- auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
- bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
- nowTime = int(time.time())
- data = []
- # 设备拓展信息表
- us_qs = UidSetModel.objects.filter(uid__in=uid_list).values('id', 'uid', 'version', 'nickname', 'ucode',
- 'detect_status', 'detect_group',
- 'detect_interval',
- 'region_alexa', 'is_alexa', 'deviceModel',
- 'TimeZone', 'TimeStatus', 'SpaceUsable',
- 'SpaceSum', 'MirrorType', 'RecordType',
- 'OutdoorModel', 'WIFIName', 'isDetector',
- 'DetectorRank')
- uv_dict = {}
- for us in us_qs:
- uv_dict[us['uid']] = {
- 'version': us['version'],
- 'nickname': us['nickname'],
- 'ucode': us['ucode'],
- 'detect_interval': us['detect_interval'],
- 'detect_group': us['detect_group'],
- 'detect_status': us['detect_status'],
- 'region_alexa': us['region_alexa'],
- 'is_alexa': us['is_alexa'],
- 'deviceModel': us['deviceModel'],
- 'TimeZone': us['TimeZone'],
- 'TimeStatus': us['TimeStatus'],
- 'SpaceUsable': us['SpaceUsable'],
- 'SpaceSum': us['SpaceSum'],
- 'MirrorType': us['MirrorType'],
- 'RecordType': us['RecordType'],
- 'OutdoorModel': us['OutdoorModel'],
- 'WIFIName': us['WIFIName'],
- 'isDetector': us['isDetector'],
- 'DetectorRank': us['DetectorRank']
- }
- # 从uid_channel里面取出通道配置信息
- ucs_qs = UidChannelSetModel.objects.filter(uid__id=us['id']).values()
- channels = []
- for ucs in ucs_qs:
- channel = {
- 'channel': ucs['channel'],
- 'pir_audio': ucs['pir_audio'],
- 'mic_audio': ucs['mic_audio'],
- 'battery_status': ucs['battery_status'],
- 'battery_level': ucs['battery_level'],
- 'sleep_status': ucs['sleep_status'],
- 'sleep_time': ucs['sleep_time'],
- 'light_night_model': ucs['light_night_model'],
- 'light_alarm_type': ucs['light_alarm_type'],
- 'light_alarm_level': ucs['light_alarm_level'],
- 'light_alarm_man_en': ucs['light_alarm_man_en'],
- 'light_alarm_vol': ucs['light_alarm_vol'],
- 'light_long_light': ucs['light_long_light']
- }
- channels.append(channel)
- uv_dict[us['uid']]['channels'] = channels
- for p in dvls:
- p['vod'] = []
- for dm in ubqs:
- if p['UID'] == dm['uid']:
- if dm['endTime'] > nowTime:
- p['vod'].append(dm)
- p['preview'] = []
- for up in upqs:
- if p['UID'] == up['uid']:
- obj = 'uid_preview/{uid}/channel_{channel}.png'.format(uid=up['uid'], channel=up['channel'])
- img_sign = bucket.sign_url('GET', obj, 300)
- p['preview'].append(img_sign)
- p_uid = p['UID']
- if p_uid in uv_dict:
- # 设备版本号
- p['uid_version'] = uv_dict[p_uid]['version']
- p['ucode'] = uv_dict[p_uid]['ucode']
- p['detect_interval'] = uv_dict[p_uid]['detect_interval']
- p['detect_status'] = uv_dict[p_uid]['detect_status']
- p['detect_group'] = uv_dict[p_uid]['detect_group']
- p['region_alexa'] = uv_dict[p_uid]['region_alexa']
- p['is_alexa'] = uv_dict[p_uid]['is_alexa']
- p['deviceModel'] = uv_dict[p_uid]['deviceModel']
- p['TimeZone'] = uv_dict[p_uid]['TimeZone']
- p['TimeStatus'] = uv_dict[p_uid]['TimeStatus']
- p['SpaceUsable'] = uv_dict[p_uid]['SpaceUsable']
- p['SpaceSum'] = uv_dict[p_uid]['SpaceSum']
- p['MirrorType'] = uv_dict[p_uid]['MirrorType']
- p['RecordType'] = uv_dict[p_uid]['RecordType']
- p['OutdoorModel'] = uv_dict[p_uid]['OutdoorModel']
- p['WIFIName'] = uv_dict[p_uid]['WIFIName']
- p['isDetector'] = uv_dict[p_uid]['isDetector']
- p['DetectorRank'] = uv_dict[p_uid]['DetectorRank']
- p['channels'] = uv_dict[p_uid]['channels']
- # 设备昵称 调用影子信息昵称,先阶段不可
- if uv_dict[p_uid]['nickname']:
- p['NickName'] = uv_dict[p_uid]['nickname']
- else:
- # 设备版本号
- p['uid_version'] = ''
- p['ucode'] = ''
- data.append(p)
- result = data
- if NickName:
- # print('NickName搜索缓存')
- data = []
- for index, item in enumerate(result):
- if NickName == item['NickName']:
- # 加密
- item['View_Password'] = self.encrypt_pwd(item['View_Password'])
- data.append(item)
- return response.json(0, data)
- if uid:
- # print('uid搜索缓存')
- data = []
- for index, item in enumerate(result):
- if uid == item['UID']:
- # 加密
- item['View_Password'] = self.encrypt_pwd(item['View_Password'])
- data.append(item)
- return response.json(0, data)
- items = []
- # print('缓存分页')
- for index, item in enumerate(result):
- if (page - 1) * line <= index:
- if index < page * line:
- # 加密
- item['View_Password'] = self.encrypt_pwd(item['View_Password'])
- print(item)
- items.append(item)
- print(items)
- return response.json(0, items)
- else:
- return response.json(tko.code)
- # 加密
- def encrypt_pwd(self,userPwd):
- for i in range(1, 4):
- if i == 1:
- userPwd = RandomStr(3, False)+userPwd+RandomStr(3, False)
- userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
- if i == 2:
- userPwd = RandomStr(2, False)+str(userPwd)+RandomStr(2, False)
- userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
- if i == 3:
- userPwd = RandomStr(1, False)+str(userPwd)+RandomStr(1, False)
- userPwd = base64.b64encode(str(userPwd).encode("utf-8")).decode('utf8')
- return userPwd
- # 解密
- def decode_pwd(self, password):
- for i in range(1, 4):
- if i == 1:
- # 第一次先解密
- password = base64.b64decode(password)
- password = password.decode('utf-8')
- # 截去第一位,最后一位
- password = password[1:-1]
- if i == 2:
- # 第2次先解密
- password = base64.b64decode(password)
- password = password.decode('utf-8')
- # 去前2位,后2位
- password = password[2:-2]
- if i == 3:
- # 第3次先解密
- password = base64.b64decode(password)
- password = password.decode('utf-8')
- # 去前3位,后3位
- password = password[3:-3]
- return password
|