12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094 |
- import base64
- import json
- import logging
- import re
- import threading
- import time
- import oss2
- import requests
- from django.db import transaction
- from django.db.models import Q
- from django.views.generic.base import View
- from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY, SERVER_DOMAIN_LIST, SERVER_DOMAIN_TEST, \
- SERVER_DOMAIN_CN, SERVER_DOMAIN_US, SERVER_DOMAIN_EUR
- from Controller.CheckUserData import RandomStr
- from Controller.DeviceConfirmRegion import Device_Region
- from Controller.SensorGateway.EquipmentFamilyController import EquipmentFamilyView
- from Controller.UnicomCombo.UnicomComboController import UnicomComboView
- from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidChannelSetModel, \
- Device_User, iotdeviceInfoModel, UIDCompanySerialModel, UnicomDeviceInfo, CountryModel, \
- DeviceCloudPhotoInfo, UidPushModel, ExperienceContextModel
- from Object.ResponseObject import ResponseObject
- from Object.TokenObject import TokenObject
- from Service.CommonService import CommonService
- from Service.EquipmentInfoService import EquipmentInfoService
- from Service.ModelService import ModelService
- from Service.UserDeviceService import UserDeviceService
- LOGGER = logging.getLogger('info')
- 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()
- if operation == 'notLoginMainUserDevice':
- return self.not_login_do_mainUserDevice(request_dict, response)
- elif operation == 'notLoginMainDelDevice':
- return self.test_tool_del_device(request_dict, response)
- token = request_dict.get('token', None)
- tko = TokenObject(token)
- if tko.code != 0:
- return response.json(tko.code)
- response.lang = tko.lang
- userID = tko.userID
- # 手机端添加设备,查询,修改
- if operation == 'add':
- return self.do_add(userID, request_dict, response, request)
- if operation == 'batchAdd':
- return self.do_batch_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, request)
- elif operation == 'modifyChannelName':
- return self.do_modify_channel_name(userID, request_dict, response, request)
- elif operation == 'fuzzyQuery':
- return self.do_fuzzy_query(userID, request_dict, response)
- elif operation == 'mainUserDevice':
- return self.do_mainUserDevice(request_dict, response)
- elif operation == 'getDeviceFeatures':
- return self.do_get_device_features(request_dict, response)
- else:
- return response.json(414)
- def do_add(self, userID, request_dict, response, request):
- 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', '')
- encrypt_pass = View_Password
- print("准备解密")
- Type = request_dict.get('Type', None)
- ChannelIndex = request_dict.get('ChannelIndex', None)
- version = request_dict.get('version', '')
- isCheckMainUser = request_dict.get('isCheckMainUser', None)
- family_id = request_dict.get('familyId', None)
- room_id = request_dict.get('roomId', None)
- m_code = request_dict.get('m_code', None)
- appBundleId = request_dict.get('appBundleId', None)
- app_type = request_dict.get('app_type', None)
- push_type = request_dict.get('push_type', None)
- token_val = request_dict.get('token_val', None)
- lang = request_dict.get('lang', 'en')
- tz = request_dict.get('tz', '0')
- if not NickName:
- NickName = UID[:6]
- if not all([UID, NickName, View_Account, Type, ChannelIndex]): # Type和ChannelIndex可能为0
- return response.json(444, {'param': 'UID, NickName, View_Account, Type, ChannelIndex'})
- if tz == '':
- tz = 0
- else:
- tz = tz.replace("GMT", "")
- Type = int(Type)
- ChannelIndex = int(ChannelIndex)
- re_uid = re.compile(r'^[A-Za-z0-9]{14,20}$')
- if not re_uid.match(UID):
- return response.json(444, {'param': 'UID'})
- device_info_qs = Device_Info.objects.filter(UID=UID, userID_id=userID)
- if device_info_qs:
- # 判断设备是否已存在
- if device_info_qs[0].isExist == 1:
- return response.json(174)
- else:
- device_info_qs.delete()
- dvr_type_list = [1, 2, 3, 4, 10001]
- View_Password = '' if Type in dvr_type_list else 'admin'
- id = CommonService.getUserID(getUser=False)
- device_user_qs = Device_User.objects.filter(userID=userID).values('username')
- if not device_user_qs.exists():
- return response.json(173)
- userName = device_user_qs[0]['username']
- main_exist = Device_Info.objects.filter(UID=UID)
- main_exist = main_exist.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID', 'vodPrimaryMaster')
- vodPrimaryUserID = userID
- vodPrimaryMaster = userName
- primaryUserID = ''
- primaryMaster = ''
- isShare = False
- is_bind = Device_Info.objects.filter(UID=UID, isShare=False).values('userID__userID', 'primaryUserID',
- 'primaryMaster')
- if main_exist.exists():
- vodPrimaryUserID = main_exist[0]['vodPrimaryUserID']
- vodPrimaryMaster = main_exist[0]['vodPrimaryMaster']
- if is_bind.exists():
- primaryUserID = is_bind[0]['primaryUserID']
- primaryMaster = is_bind[0]['primaryMaster']
- isShare = True
- isusermain = False
- if (vodPrimaryUserID != userID and vodPrimaryUserID != '') or (primaryUserID != userID and primaryUserID != ''):
- isusermain = True
- # 判断是否有已绑定用户
- if isCheckMainUser == '1' and isusermain:
- res = {
- 'id': id,
- 'userID': userID,
- 'NickName': NickName,
- 'UID': UID,
- 'View_Account': View_Account,
- 'View_Password': View_Password,
- 'ChannelIndex': ChannelIndex,
- 'Type': Type,
- 'isShare': isShare,
- 'primaryUserID': primaryUserID,
- 'primaryMaster': primaryMaster,
- 'vodPrimaryUserID': vodPrimaryUserID,
- 'vodPrimaryMaster': vodPrimaryMaster,
- 'data_joined': '',
- 'version': version,
- 'isVod': 0,
- 'isExist': 1,
- 'userID__userEmail': ''
- }
- res['vod'] = [
- {
- "status": 1,
- "channel": ChannelIndex,
- "endTime": '',
- "bucket__content": '',
- "uid": UID
- }
- ]
- res['isMainUserExists'] = 1
- return response.json(0, res)
- try:
- # 判断是否有用户绑定
- nowTime = int(time.time())
- us_qs = UidSetModel.objects.filter(uid=UID)
- if us_qs.exists():
- us_qs.update(nickname=NickName, device_type=Type)
- UidSet_id = us_qs.first().id
- else:
- ip = CommonService.get_ip_address(request)
- ipInfo = CommonService.getIpIpInfo(ip, 'CN')
- country_qs = CountryModel.objects.filter(country_code=ipInfo['country_code']).values('id')
- country = country_qs.exists() if country_qs[0]['id'] else 0
- region_id = Device_Region().get_device_region(ip)
- region_alexa = 'CN' if region_id == 1 else 'ALL'
- uid_set_create_dict = {
- 'uid': UID,
- 'addTime': nowTime,
- 'updTime': nowTime,
- 'ip': CommonService.get_ip_address(request_dict),
- 'channel': ChannelIndex,
- 'nickname': NickName,
- 'version': version,
- 'region_alexa': region_alexa,
- 'device_type': Type,
- 'tb_country': country
- }
- UidSet = UidSetModel.objects.create(**uid_set_create_dict)
- UidSet_id = UidSet.id
- if all([token_val, m_code, appBundleId, app_type]):
- uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=UID)
- if uid_push_qs.exists():
- uid_push_update_dict = {
- 'appBundleId': appBundleId,
- 'app_type': app_type,
- 'push_type': push_type,
- 'token_val': token_val,
- 'updTime': nowTime,
- 'lang': lang,
- 'tz': tz
- }
- uid_push_qs.update(**uid_push_update_dict)
- else:
- uid_push_create_dict = {
- 'uid_set_id': UidSet_id,
- 'userID_id': userID,
- 'appBundleId': appBundleId,
- 'app_type': app_type,
- 'push_type': push_type,
- 'token_val': token_val,
- 'm_code': m_code,
- 'addTime': nowTime,
- 'updTime': nowTime,
- 'lang': lang,
- 'tz': tz
- }
- # 绑定设备推送
- UidPushModel.objects.create(**uid_push_create_dict)
- # 查询uid_channel表有无该uid的数据
- uid_channel_set = UidChannelSetModel.objects.filter(uid_id=UidSet_id)
- if not uid_channel_set.exists():
- # 多通道设备设置通道名
- if Type in dvr_type_list:
- UidChannelSet_bulk = []
- for i in range(1, ChannelIndex + 1):
- channel_name = 'channel' + str(i) # channel1,channel2...
- UidChannelSet = UidChannelSetModel(uid_id=UidSet_id, channel=i, channel_name=channel_name)
- UidChannelSet_bulk.append(UidChannelSet)
- UidChannelSetModel.objects.bulk_create(UidChannelSet_bulk)
- userDevice = Device_Info(id=id, userID_id=userID, UID=UID, NickName=NickName, View_Account=View_Account,
- View_Password=View_Password, Type=Type, ChannelIndex=ChannelIndex, version=version,
- vodPrimaryUserID=vodPrimaryUserID, vodPrimaryMaster=vodPrimaryMaster)
- userDevice.save()
- # 添加到家庭房间
- if family_id:
- EquipmentFamilyView.family_room_device_save(family_id, room_id, userDevice.id, Type)
- uid_serial_qs = UIDCompanySerialModel.objects.filter(uid__uid=UID)
- if uid_serial_qs.exists():
- uid_serial = uid_serial_qs[0]
- serial_number = uid_serial.company_serial.serial_number + uid_serial.company_serial.company.mark
- Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
- vodPrimaryMaster=vodPrimaryMaster,
- serial_number=serial_number)
- self.unicom_user_info_save(userID, serial_number)
- else:
- Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
- vodPrimaryMaster=vodPrimaryMaster)
- if not us_qs.exists():
- us_qs = UidSetModel.objects.filter(uid=UID)
- if us_qs.exists() and us_qs[0].is_alexa == 1:
- if us_qs[0].channel > 1:
- data_list = []
- uid_channel_set_qs = UidChannelSetModel.objects.filter(uid_id=us_qs[0].id). \
- values('channel', 'channel_name')
- if uid_channel_set_qs.exists():
- # 多通道设备名为 UidChannelSetModel 的 channel_name
- for uid_channel_set in uid_channel_set_qs:
- data_list.append({'userID': userID, 'UID': UID, 'uid_nick': uid_channel_set['channel_name'],
- 'channel': uid_channel_set['channel'], 'password': encrypt_pass})
- else:
- data_list = [{'userID': userID, 'UID': UID, 'uid_nick': NickName, 'password': encrypt_pass}]
- # 请求Alexa服务器更新事件网关
- data_list = json.dumps(data_list)
- data = {'data_list': data_list}
- url = 'https://www.zositech.xyz/deviceStatus/addOrUpdateV2'
- requests.post(url, data=data, timeout=2)
- except Exception as e:
- return response.json(10, repr(e))
- else:
- dvqs = Device_Info.objects.filter(id=id).values('id', 'userID', 'NickName', 'UID',
- 'View_Account',
- 'View_Password', 'ChannelIndex', 'Type',
- 'isShare',
- 'primaryUserID', 'primaryMaster',
- 'vodPrimaryUserID', 'vodPrimaryMaster',
- 'userID__userEmail',
- 'data_joined', 'version',
- 'isVod', 'isExist', 'isCameraOpenCloud', 'serial_number')
- 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)
- iotqs = iotdeviceInfoModel.objects.filter(serial_number=dvql[0]['serial_number'])
- if iotqs.exists():
- res['iot'] = {
- 'endpoint': iotqs[0].endpoint,
- 'token_iot_number': iotqs[0].endpoint
- }
- # 存在序列号返回完整序列号
- if res['serial_number']:
- res['serial_number'] = CommonService.get_full_serial_number(UID, res['serial_number'], Type)
- return response.json(0, res)
- @classmethod
- def unicom_user_info_save(cls, user_id, serial_number):
- """
- 保存联通与用户信息绑定
- @param user_id: 用户id
- @param serial_number: 序列号
- @return: True | False
- """
- try:
- unicom_device_info_qs = UnicomDeviceInfo.objects.filter(serial_no=serial_number)
- if not unicom_device_info_qs.exists():
- return False
- if not unicom_device_info_qs[0].user_id:
- n_time = int(time.time())
- # 生成4G免费订单
- UnicomComboView.experience_order_4G(unicom_device_info_qs[0].iccid,
- serial_number, user_id, False)
- unicom_device_info_qs.update(user_id=user_id, updated_time=n_time)
- return True
- except Exception as e:
- logging.info('创建体验4G订单异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
- return False
- def do_batch_add(self, userID, request_dict, response, request):
- # 批量添加设备
- uidContent = request_dict.get('uidContent', None)
- family_id = request_dict.get('familyId', None)
- room_id = request_dict.get('roomId', None)
- if not uidContent:
- return response.json(444, {'param': 'uidContent'})
- try:
- deviceNumber = 0 # 添加成功数量
- add_success_flag = False # 添加成功标识
- exception_flag = False # 异常标识
- exists_flag = False # 已存在标识
- uid_content_list = eval(uidContent)
- print('uidContent: ', uid_content_list)
- re_uid = re.compile(r'^[A-Za-z0-9]{14,20}$')
- for uid_content in uid_content_list:
- exception_flag = False # 重置异常标识
- exists_flag = False # 已存在标识
- UID = uid_content['uid']
- NickName = uid_content['nickName']
- Type = uid_content['type']
- ChannelIndex = uid_content['channelIndex']
- version = uid_content['version']
- isCheckMainUser = uid_content['isCheckMainUser']
- View_Account = uid_content['viewAccount']
- encryptPassword = uid_content['encryptPassword']
- View_Password = self.decode_pwd(encryptPassword)
- if not all([UID, NickName, View_Account]): # Type和ChannelIndex可能为0
- return response.json(444, {'param': 'UID, NickName, View_Account'})
- if not re_uid.match(UID): # 检查uid长度
- return response.json(444, {'error uid length': UID})
- device_info_qs = Device_Info.objects.filter(UID=UID, userID_id=userID)
- if device_info_qs:
- # 判断设备是否已存在
- if device_info_qs[0].isExist == 1:
- exists_res = {UID: 'device already exists!'}
- exists_flag = True
- continue
- else:
- device_info_qs.delete()
- id = CommonService.getUserID(getUser=False)
- device_user_qs = Device_User.objects.filter(userID=userID).values('username')
- if not device_user_qs.exists():
- return response.json(173)
- userName = device_user_qs[0]['username']
- main_exist = Device_Info.objects.filter(UID=UID)
- main_exist = main_exist.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID', 'vodPrimaryMaster')
- vodPrimaryUserID = userID
- vodPrimaryMaster = userName
- primaryUserID = ''
- primaryMaster = ''
- isShare = False
- is_bind = Device_Info.objects.filter(UID=UID, isShare=False).values('userID__userID', 'primaryUserID',
- 'primaryMaster', 'Type')
- if main_exist.exists():
- vodPrimaryUserID = main_exist[0]['vodPrimaryUserID']
- vodPrimaryMaster = main_exist[0]['vodPrimaryMaster']
- if is_bind.exists():
- primaryUserID = is_bind[0]['primaryUserID']
- primaryMaster = is_bind[0]['primaryMaster']
- isShare = True
- isusermain = False
- if (vodPrimaryUserID != userID and vodPrimaryUserID != '') or (
- primaryUserID != userID and primaryUserID != ''):
- isusermain = True
- # 判断是否有已绑定用户
- if isCheckMainUser == 1 and isusermain:
- res = {
- 'id': id,
- 'userID': userID,
- 'NickName': NickName,
- 'UID': UID,
- 'View_Account': View_Account,
- 'View_Password': View_Password,
- 'ChannelIndex': ChannelIndex,
- 'Type': Type,
- 'isShare': isShare,
- 'primaryUserID': primaryUserID,
- 'primaryMaster': primaryMaster,
- 'vodPrimaryUserID': vodPrimaryUserID,
- 'vodPrimaryMaster': vodPrimaryMaster,
- 'data_joined': '',
- 'version': version,
- 'isVod': 0,
- 'isExist': 1,
- 'userID__userEmail': ''
- }
- res['vod'] = [
- {
- "status": 1,
- "channel": ChannelIndex,
- "endTime": '',
- "bucket__content": '',
- "uid": UID
- }
- ]
- res['isMainUserExists'] = 1
- continue
- # 判断是否有用户绑定
- nowTime = int(time.time())
- us_qs = UidSetModel.objects.filter(uid=UID)
- if us_qs.exists():
- us_qs.update(nickname=NickName)
- UidSet_id = us_qs.first().id
- else:
- ip = CommonService.get_ip_address(request)
- ipInfo = CommonService.getIpIpInfo(ip, 'CN')
- country_qs = CountryModel.objects.filter(country_code=ipInfo['country_code']).values('id')
- country = country_qs.exists() if country_qs[0]['id'] else 0
- region_id = Device_Region().get_device_region(ip)
- region_alexa = 'CN' if region_id == 1 else 'ALL'
- uid_set_create_dict = {
- 'uid': UID,
- 'addTime': nowTime,
- 'updTime': nowTime,
- 'ip': CommonService.get_ip_address(request_dict),
- 'channel': ChannelIndex,
- 'nickname': NickName,
- 'version': version,
- 'region_alexa': region_alexa,
- 'device_type': is_bind[0]['Type'] if is_bind.exists() else int(Type),
- 'tb_country': country
- }
- UidSet = UidSetModel.objects.create(**uid_set_create_dict)
- UidSet_id = UidSet.id
- # 查询uid_channel表有无该uid的数据
- uid_channel_set = UidChannelSetModel.objects.filter(uid_id=UidSet_id)
- if not uid_channel_set.exists():
- # 多通道设备设置通道名
- multi_channel_list = [1, 2, 3, 4, 10001]
- if Type in multi_channel_list:
- UidChannelSet_bulk = []
- for i in range(1, ChannelIndex + 1):
- channel_name = 'channel' + str(i) # channel1,channel2...
- UidChannelSet = UidChannelSetModel(uid_id=UidSet_id, channel=i, channel_name=channel_name)
- UidChannelSet_bulk.append(UidChannelSet)
- UidChannelSetModel.objects.bulk_create(UidChannelSet_bulk)
- userDevice = Device_Info(id=id, userID_id=userID, UID=UID, NickName=NickName, View_Account=View_Account,
- View_Password=View_Password, Type=Type, ChannelIndex=ChannelIndex,
- version=version,
- vodPrimaryUserID=vodPrimaryUserID, vodPrimaryMaster=vodPrimaryMaster)
- userDevice.save()
- # 添加到家庭房间
- if family_id:
- EquipmentFamilyView.family_room_device_save(family_id, room_id, userDevice.id, Type)
- uid_serial_qs = UIDCompanySerialModel.objects.filter(uid__uid=UID)
- if uid_serial_qs.exists():
- uid_serial = uid_serial_qs[0]
- Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
- vodPrimaryMaster=vodPrimaryMaster,
- serial_number=uid_serial.company_serial.serial_number + uid_serial.company_serial.company.mark)
- else:
- Device_Info.objects.filter(UID=UID).update(vodPrimaryUserID=vodPrimaryUserID,
- vodPrimaryMaster=vodPrimaryMaster)
- if not us_qs.exists():
- us_qs = UidSetModel.objects.filter(uid=UID)
- if us_qs.exists() and us_qs[0].is_alexa == 1:
- if us_qs[0].channel > 1:
- data_list = []
- uid_channel_set_qs = UidChannelSetModel.objects.filter(uid_id=us_qs[0].id). \
- values('channel', 'channel_name')
- if uid_channel_set_qs.exists():
- # 多通道设备名为 UidChannelSetModel 的 channel_name
- for uid_channel_set in uid_channel_set_qs:
- data_list.append(
- {'userID': userID, 'UID': UID, 'uid_nick': uid_channel_set['channel_name'],
- 'channel': uid_channel_set['channel'], 'password': encryptPassword})
- else:
- data_list = [{'userID': userID, 'UID': UID, 'uid_nick': NickName, 'password': encryptPassword}]
- # 请求Alexa服务器更新事件网关
- data_list = json.dumps(data_list)
- data = {'data_list': data_list}
- url = 'https://www.zositech.xyz/deviceStatus/addOrUpdateV2'
- requests.post(url, data=data, timeout=2)
- dvqs = Device_Info.objects.filter(id=id).values('id', 'userID', 'NickName', 'UID',
- 'View_Account',
- 'View_Password', 'ChannelIndex', 'Type',
- 'isShare',
- 'primaryUserID', 'primaryMaster',
- 'vodPrimaryUserID', 'vodPrimaryMaster',
- 'userID__userEmail',
- 'data_joined', 'version',
- 'isVod', 'isExist', 'isCameraOpenCloud',
- 'serial_number')
- dvql = CommonService.qs_to_list(dvqs)
- ubqs = UID_Bucket.objects.filter(uid=UID). \
- values('bucket__content', 'status', 'channel', 'endTime', 'uid')
- success_res = dvql[0]
- success_res['vod'] = list(ubqs)
- iotqs = iotdeviceInfoModel.objects.filter(serial_number=dvql[0]['serial_number'])
- if iotqs.exists():
- success_res['iot'] = {'endpoint': iotqs[0].endpoint, 'token_iot_number': iotqs[0].endpoint}
- deviceNumber += 1
- success_res['deviceNumber'] = deviceNumber
- add_success_flag = True
- except Exception as e:
- LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
- print(e)
- error_res = repr(e)
- exception_flag = True
- pass
- finally:
- if add_success_flag: # 有一台添加成功则返回成功
- return response.json(0, success_res)
- if exists_flag: # 全部设备已存在
- return response.json(174, exists_res)
- if exception_flag:
- return response.json(500, error_res)
- return response.json(0, res)
- def do_modify(self, userID, request_dict, response, request):
- 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 = eval(deviceContent)
- if deviceData.__contains__('userID_id'):
- asy = threading.Thread(target=ModelService.update_log,
- args=(CommonService.get_ip_address(request), userID, 'modifyV3', deviceData, id))
- asy.start()
- return response.json(10, '110')
- if deviceData.__contains__('UID'):
- del deviceData['UID']
- # print(deviceData['View_Password'])
- if deviceData.__contains__('View_Password'):
- encrypt_pwd = deviceData['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():
- if deviceData.__contains__('NickName'):
- us_qs.update(nickname=nickname)
- else:
- ip = CommonService.get_ip_address(request)
- ipInfo = CommonService.getIpIpInfo(ip, 'CN')
- country_qs = CountryModel.objects.filter(country_code=ipInfo['country_code']).values('id')
- country = country_qs.exists() if country_qs[0]['id'] else 0
- 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,
- 'device_type': qs[0].Type,
- 'tb_country': country
- }
- UidSetModel.objects.create(**uid_set_create_dict)
- di_qs = Device_Info.objects.filter(UID=uid)
- di_qs.update(NickName=nickname)
- if deviceData is not None and deviceData.__contains__('NickName') and us_qs[0].is_alexa == 1:
- # 请求Alexa服务器更新事件网关
- url = 'https://www.zositech.xyz/deviceStatus/addOrUpdateV2'
- password = encrypt_pwd if deviceData.__contains__('View_Password') else ''
- data_list = [{'userID': userID, 'UID': uid, 'uid_nick': nickname, 'password': password}]
- data_list = json.dumps(data_list)
- data = {'data_list': data_list}
- requests.post(url, data=data, timeout=2)
- return response.json(0, res)
- # 编辑通道名
- def do_modify_channel_name(self, userID, request_dict, response):
- uid = request_dict.get('uid', None)
- channel = request_dict.get('channel', None)
- channel_name = request_dict.get('channel_name', None)
- if not all([uid, channel, channel_name]):
- return response.json(444)
- # 更新通道名
- UidChannelSetModel.objects.filter(uid__uid=uid).update(channel_name=channel_name)
- return response.json(0)
- def do_query(self, userID, request_dict, response):
- """
- 首页查询设备列表
- @param userID: 用户id
- @param request_dict: 请求参数
- @param 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:
- return response.json(tko.code)
- userID = tko.userID
- # 查询设备列表以及设备uid集合
- dv_list, uid_list = UserDeviceService.query_device_list(userID, uid, NickName, page, line)
- ub_qs = UserDeviceService.query_device_uid_bucket(uid_list) # 根据uid集合查询云存套餐
- up_qs = UserDeviceService.query_device_preview(uid_list) # 根据uid集合查询设备预览图
- 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 = []
- uv_dict = UserDeviceService.query_device_channel(uid_list) # 查询设备uid通道配置属性
- # 遍历设备列表,查询设备关联数据详情
- for p in dv_list:
- p['UID'] = p['UID'].replace('\n', '').replace('\r', '')
- p_uid = p['UID'].upper()
- UserDeviceService.get_sim_by_serial_number(p) # 获取SIM卡属性
- p['cloudPhoto'] = self.get_cloud_photo_status(p['UID'])
- # 获取云存使用状态
- p['vod_use_status'] = self.get_vod_use_status(p_uid, nowTime)
- # 获取iot_deviceInfo表的endpoint和token_iot_number
- p['iot'] = []
- if p['serial_number']: # 存在序列号根据序列号查询
- iotdeviceInfo_qs = iotdeviceInfoModel.objects.filter(serial_number=p['serial_number'][0:6])
- else: # 根据uid查询
- iotdeviceInfo_qs = iotdeviceInfoModel.objects.filter(uid=p_uid)
- if iotdeviceInfo_qs.exists():
- iotdeviceInfo = iotdeviceInfo_qs.values('endpoint', 'token_iot_number')
- p['iot'].append({
- 'endpoint': iotdeviceInfo[0]['endpoint'],
- 'token_iot_number': iotdeviceInfo[0]['token_iot_number']
- })
- p['vod'] = []
- for dm in ub_qs:
- if p_uid == dm['uid']:
- if dm['endTime'] > nowTime:
- p['vod'].append(dm)
- p['preview'] = []
- for up in up_qs:
- 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)
- UserDeviceService.get_uid_info(p, p_uid) # 获取uid初始化信息
- if p_uid in uv_dict:
- # 获取设备信息DTO
- UserDeviceService.get_device_info_dto(p, p_uid, uv_dict, userID)
- else:
- # 设备版本号
- p['uid_version'] = ''
- p['ucode'] = ''
- p['View_Password'] = self.encrypt_pwd(p['View_Password'])
- # 判断设备是否支持4G
- uid_set_qs =UidSetModel.objects.filter(uid=p['UID']).values('mobile_4g')
- if uid_set_qs.exists():
- uid_set_qs = uid_set_qs.first()
- if uid_set_qs['mobile_4g'] == 1:
- p['isCameraOpenCloud'] = 0
- data.append(p)
- result = data
- return response.json(0, result)
- @staticmethod
- def get_vod_use_status(uid, now_time):
- """
- 根据UID获取云存使用状态
- @param uid: 设备uid
- @param now_time: 现在时间戳
- @return: 0:未体验;1:使用中;2:已过期
- """
- experience_context_qs = ExperienceContextModel.objects.filter(uid=uid, experience_type=0)
- if not experience_context_qs.exists():
- return 0
- uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gt=now_time, use_status=1)
- if uid_bucket_qs.exists():
- return 1
- else:
- return 2
- @staticmethod
- def get_cloud_photo_status(uid):
- """
- 根据UID获取云相册开关状态
- @param uid: 设备uid
- @return: 0 or 1
- """
- cloud_photo_qs = DeviceCloudPhotoInfo.objects.filter(uid=uid).values('status')
- if not cloud_photo_qs.exists():
- return 0
- return cloud_photo_qs[0]['status']
- def do_fuzzy_query(self, userID, request_dict, response):
- fuzzy = request_dict.get('fuzzy', None)
- page = request_dict.get('page', None)
- line = request_dict.get('line', None)
- if not all([page, line]):
- return response.json(444)
- page = int(page)
- line = int(line)
- try:
- device_qs = Device_Info.objects.filter(userID=userID)
- device_qs = device_qs.filter(~Q(isExist=2))
- if not device_qs.exists():
- return response.json(0, [])
- if fuzzy:
- device_qs = device_qs.filter(Q(UID__icontains=fuzzy) | Q(NickName__icontains=fuzzy))
- device_qs = device_qs.values('id', 'userID', 'NickName', 'UID', 'View_Account',
- 'View_Password', 'ChannelIndex', 'Type', 'isShare',
- 'primaryUserID', 'primaryMaster', 'data_joined', 'vodPrimaryUserID',
- 'vodPrimaryMaster', 'userID__userEmail',
- 'version', 'isVod', 'isExist', 'NotificationMode', 'isCameraOpenCloud',
- 'serial_number')
- dvls = CommonService.qs_to_list(device_qs)
- 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'],
- 'channel_name': ucs['channel_name'],
- '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:
- # 获取iot_deviceInfo表的endpoint和token_iot_number
- p['iot'] = []
- if p['serial_number']: # 存在序列号根据序列号查询
- # 摄像头设备返回完整序列号
- if p['UID'] != p['serial_number']:
- p['serial_number'] = CommonService.get_full_serial_number(p['UID'], p['serial_number'],
- p['Type'])
- iotdeviceInfo_qs = iotdeviceInfoModel.objects.filter(serial_number=p['serial_number'][0:6])
- else: # 根据uid查询
- iotdeviceInfo_qs = iotdeviceInfoModel.objects.filter(uid=p['UID'])
- if iotdeviceInfo_qs.exists():
- iotdeviceInfo = iotdeviceInfo_qs.values('endpoint', 'token_iot_number')
- p['iot'].append({
- 'endpoint': iotdeviceInfo[0]['endpoint'],
- 'token_iot_number': iotdeviceInfo[0]['token_iot_number']
- })
- 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)
- items = []
- for index, item in enumerate(data):
- if (page - 1) * line <= index:
- if index < page * line:
- # 加密
- item['View_Password'] = self.encrypt_pwd(item['View_Password'])
- items.append(item)
- return response.json(0, items)
- except Exception as e:
- return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
- # 加密
- 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
- @staticmethod
- def do_mainUserDevice(request_dict, response):
- """
- 根据UID获取云存主用户信息
- """
- try:
- UID = request_dict.get('UID')
- dvq = Device_Info.objects.filter(UID=UID)
- dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
- if not dvq.exists():
- return response.json(0, {})
- qs = Device_User.objects.filter(userID=dvq[0]['vodPrimaryUserID']) \
- .values('userID', 'NickName', 'username', 'userEmail', 'phone')
- if not qs.exists():
- return response.json(0, {})
- nickname = qs[0]['username']
- phone = qs[0]['phone']
- username = qs[0]['username']
- qs = CommonService.qs_to_list(qs)
- if nickname == '':
- qs[0]['NickName'] = username
- if phone == '':
- qs[0]['phone'] = nickname
- return response.json(0, qs)
- except Exception as e:
- LOGGER.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
- return response.json(500)
- def not_login_do_mainUserDevice(self, request_dict, response):
- UID = request_dict.get('UID')
- token = request_dict.get('token', None)
- time_stamp = request_dict.get('time_stamp', None)
- if not all([token, time_stamp]):
- return response.json(444)
- # 时间戳token校验
- if not CommonService.check_time_stamp_token(token, time_stamp):
- return response.json(13)
- dvq = Device_Info.objects.filter(UID=UID)
- dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
- qs = {}
- if dvq.exists():
- qs = Device_User.objects.filter(userID=dvq[0]['vodPrimaryUserID']).values('userID', 'NickName', 'username',
- 'userEmail', 'phone')
- NickName = qs[0]['NickName']
- phone = qs[0]['phone']
- username = qs[0]['username']
- qs = CommonService.qs_to_list(qs)
- if NickName == '':
- qs[0]['NickName'] = username
- if phone == '':
- qs[0]['phone'] = NickName
- return response.json(0, qs)
- @staticmethod
- def test_tool_del_device(request_dict, response):
- """
- 测试工具删除设备
- @param request_dict: 请求数据
- @request_dict uid: uid
- @request_dict time_stamp: 时间戳
- @request_dict time_stamp_token: 时间戳token
- @param response: 响应
- @return: response
- """
- uid = request_dict.get('uid')
- time_stamp = request_dict.get('time_stamp', None)
- time_stamp_token = request_dict.get('time_stamp_token', None)
- if not all([uid, time_stamp, time_stamp_token]):
- return response.json(444)
- try:
- # 时间戳token校验
- if not CommonService.check_time_stamp_token(time_stamp_token, time_stamp):
- return response.json(13)
- with transaction.atomic():
- Device_Info.objects.filter(UID=uid).delete()
- # 删除推送消息
- for val in range(1, 8):
- EquipmentInfoService.get_equipment_info_model('', val).filter(device_uid=uid).delete()
- return response.json(0)
- except Exception as e:
- return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
- def do_get_device_features(self, request_dict, response):
- uid = request_dict.get('uid', None)
- if uid:
- uid = CommonService.decode_data(uid)
- if uid:
- uid_qs = UidSetModel.objects.filter(uid=uid)
- if uid_qs.exists():
- uid_qs = uid_qs.values('is_alexa', 'is_human', 'is_custom_voice', 'double_wifi', 'mobile_4g')
- return response.json(0, uid_qs[0])
- else:
- return response.json(173)
- else:
- return response.json(444)
- else:
- return response.json(444)
|