Explorar o código

传感器家庭管理接口

zhangdongming %!s(int64=3) %!d(string=hai) anos
pai
achega
3d79eb2db8
Modificáronse 1 ficheiros con 258 adicións e 0 borrados
  1. 258 0
      Controller/EquipmentManager/EquipmentManagerV4.py

+ 258 - 0
Controller/EquipmentManager/EquipmentManagerV4.py

@@ -0,0 +1,258 @@
+# -*- encoding: utf-8 -*-
+"""
+@File    : EquipmentManagerV4.py
+@Time    : 2022/5/13 8:31
+@Author  : stephen
+@Email   : zhangdongming@asj6.wecom.work
+@Software: PyCharm
+"""
+import json
+import re
+import threading
+import time
+
+import base64
+import oss2
+import requests
+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
+from Controller.CheckUserData import RandomStr
+from Controller.DeviceConfirmRegion import Device_Region
+from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidChannelSetModel, \
+    Device_User, iotdeviceInfoModel, UIDCompanySerialModel, UIDModel
+from Object.ResponseObject import ResponseObject
+from Object.TokenObject import TokenObject
+from Service.CommonService import CommonService
+from Service.ModelService import ModelService
+
+
+class EquipmentManagerV4(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:
+            return response.json(tko.code)
+        response.lang = tko.lang
+        userID = tko.userID
+        # 手机端添加设备,查询,修改
+        if operation == 'add':
+            return self.do_add(userID, request_dict, response, request)
+        else:
+            return response.json(414)
+
+    def do_add(self, userID, request_dict, response, request):
+        device_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("准备解密")
+        View_Password = self.decode_pwd(View_Password)
+        Type = request_dict.get('Type', None)
+        ChannelIndex = request_dict.get('ChannelIndex', None)
+        version = request_dict.get('version', '')
+        isCheckMainUser = request_dict.get('isCheckMainUser', None)
+
+        if not all([device_uid, NickName, View_Account, Type, ChannelIndex]):  # Type和ChannelIndex可能为0
+            return response.json(444, {'param': 'UID, NickName, View_Account, Type, ChannelIndex'})
+
+        Type = int(Type)
+        ChannelIndex = int(ChannelIndex)
+
+        re_uid = re.compile(r'^[A-Za-z0-9]{14,20}$')
+        if not re_uid.match(device_uid):
+            return response.json(444, {'param': 'UID'})
+
+        device_info_qs = Device_Info.objects.filter(UID=device_uid, userID_id=userID)
+        if device_info_qs:
+            # 判断设备是否已存在
+            if device_info_qs[0].isExist == 1:
+                return response.json(174)
+            else:
+                device_info_qs.delete()
+
+        id = CommonService.getUserID(getUser=False)
+        userName = Device_User.objects.get(userID=userID).username
+        main_exist = Device_Info.objects.filter(UID=device_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=device_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': device_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': '', 'vod': [
+                    {
+                        "status": 1,
+                        "channel": ChannelIndex,
+                        "endTime": '',
+                        "bucket__content": '',
+                        "uid": device_uid
+                    }
+                ], 'isMainUserExists': 1}
+            return response.json(0, res)
+
+        try:
+            # 判断是否有用户绑定
+            nowTime = int(time.time())
+            us_qs = UidSetModel.objects.filter(uid=device_uid)
+            if us_qs.exists():
+                us_qs.update(nickname=NickName)
+                UidSet_id = us_qs.first().id
+            else:
+                ip = CommonService.get_ip_address(request)
+                region_id = Device_Region().get_device_region(ip)
+                region_alexa = 'CN' if region_id == 1 else 'ALL'
+                uid_set_create_dict = {
+                    'uid': device_uid,
+                    'addTime': nowTime,
+                    'updTime': nowTime,
+                    'ip': CommonService.get_ip_address(request_dict),
+                    'channel': ChannelIndex,
+                    'nickname': NickName,
+                    'version': version,
+                    'region_alexa': region_alexa,
+                }
+                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=device_uid, NickName=NickName,
+                                     View_Account=View_Account,
+                                     View_Password=View_Password, Type=Type, ChannelIndex=ChannelIndex, version=version,
+                                     vodPrimaryUserID=vodPrimaryUserID, vodPrimaryMaster=vodPrimaryMaster)
+            userDevice.save()
+            uid_serial_qs = UIDCompanySerialModel.objects.filter(uid__uid=device_uid)
+            if uid_serial_qs.exists():
+                uid_serial = uid_serial_qs[0]
+                Device_Info.objects.filter(UID=device_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=device_uid).update(vodPrimaryUserID=vodPrimaryUserID,
+                                                                  vodPrimaryMaster=vodPrimaryMaster)
+
+            if not us_qs.exists():
+                us_qs = UidSetModel.objects.filter(uid=device_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': device_uid, 'uid_nick': uid_channel_set['channel_name'],
+                                 'channel': uid_channel_set['channel'], 'password': encrypt_pass})
+                else:
+                    data_list = [{'userID': userID, 'UID': device_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=device_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
+                }
+            return response.json(0, res)
+
+        # 解密
+
+    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