Pārlūkot izejas kodu

Merge branch 'test' of 13.56.215.252:/web/rpo/AnsjerFormal into test

Ansjer 4 gadi atpakaļ
vecāks
revīzija
ba39a7740b

+ 2 - 0
Controller/CloudStorage.py

@@ -78,6 +78,7 @@ class CloudStorageView(View):
         elif operation == 'getsignsts':
             ip = CommonService.get_ip_address(request)
             return self.do_get_sign_sts(request_dict, ip, response)
+            # return self.do_get_sign_sts_test(request_dict, ip, response)
         elif operation == 'storeplaylist':
             return self.do_store_playlist(request_dict, response)
         elif operation == 'signplaym3u8':
@@ -105,6 +106,7 @@ class CloudStorageView(View):
             else:
                 return response.json(414)
 
+
     def do_test_play_m3u8(self, request_dict, response):
         playlist_entries = [
             {

+ 224 - 75
Controller/CloudVod.py

@@ -387,7 +387,7 @@ class CloudVodView(View):
     		color : green
     	}
     	.content_img{
-    		width: 60px; 
+    		width: 60px;
     		height: 60px;
     	}
     	.bottom{
@@ -427,7 +427,7 @@ class CloudVodView(View):
     function payOKButton() {
         // 复杂数据
         console.log('success')
-        window.webkit.messageHandlers.jsCallOC.postMessage({"status": 1});
+        window.location.href="https://test.dvema.com/closePage";
     }
 	</script>
 </body> 
@@ -690,89 +690,238 @@ class CloudVodView(View):
                 return response.json(0, {"redirectUrl": approval_url, "orderID": orderID})
         return response.json(10, 'generate_order_false')
 
-    #  生成设备sts上传授权
+
     def do_getSts(self, request_dict, ip, response):
         uidToken = request_dict.get('uidToken', None)
         utko = UidTokenObject(uidToken)
         if utko.flag is False:
             return response.json(444, 'uidToken')
-        UID = utko.UID
+        uid = utko.UID
         channel = utko.channel
         print(channel)
-        print(UID)
-        ubqs = UID_Bucket.objects.filter(uid=UID, channel=channel, status=1). \
-            values('channel', 'bucket__bucket', 'bucket__endpoint', 'bucket__region', 'endTime')
+        print(uid)
         now_time = int(time.time())
-        if not ubqs.exists():
-            res = {'code': 404, 'msg': '未购买'}
-            return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
-        elif ubqs[0]['endTime'] < now_time:
-            res = {'code': 404, 'msg': '过期'}
-            return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
-        oc_qs = OssCrdModel.objects.filter(uid=UID, channel=channel).values("addTime", "data")
-        if oc_qs.exists():
-            endTime = int(oc_qs[0]["addTime"]) + 3500
-            if endTime > now_time:
-                print(endTime)
-                print(now_time)
-                res = json.loads(oc_qs[0]["data"])
+        ubqs = UID_Bucket.objects.filter(uid=uid, channel=channel, endTime__gte=now_time). \
+            values("bucket__mold", "bucket__bucket", "bucket__endpoint", "bucket__region", "endTime")
+        if ubqs.exists():
+            if ubqs[0]["bucket__mold"] == 0:
+                # 阿里云 oss sts
+                oc_qs = OssCrdModel.objects.filter(uid=uid, channel=channel). \
+                    values("addTime", "data")
+                if oc_qs.exists():
+                    endTime = int(oc_qs[0]["addTime"]) + 3500
+                    if endTime > now_time:
+                        print(endTime)
+                        print(now_time)
+                        res = json.loads(oc_qs[0]["data"])
+                        return JsonResponse(status=200, data=res)
+                # 套餐id
+                storage = '{uid}/vod{channel}/'.format(uid=uid, channel=channel)
+                bucket_name = ubqs[0]['bucket__bucket']
+                endpoint = ubqs[0]['bucket__endpoint']
+                access_key_id = OSS_STS_ACCESS_KEY
+                access_key_secret = OSS_STS_ACCESS_SECRET
+                region_id = ubqs[0]['bucket__region']
+                role_arn = OSS_ROLE_ARN
+                clt = client.AcsClient(access_key_id, access_key_secret, region_id)
+                req = AssumeRoleRequest.AssumeRoleRequest()
+                # 设置返回值格式为JSON。
+                req.set_accept_format('json')
+                req.set_RoleArn(role_arn)
+                req.set_RoleSessionName(uid + '_' + channel)
+                req.set_DurationSeconds(3600)
+                Resource_access = "acs:oss:*:*:{bucket_name}/{uid_channel}*". \
+                    format(bucket_name=bucket_name, uid_channel=storage)
+                print(Resource_access)
+                policys = {
+                    "Version": "1",
+                    "Statement": [
+                        {
+                            "Action": ["oss:PutObject", "oss:DeleteObject", ],
+                            "Resource": [Resource_access],
+                            "Effect": "Allow",
+                            "Condition": {
+                                "IpAddress": {"acs:SourceIp": ip}
+                                # "IpAddress": {"acs:SourceIp": "120.237.157.184"}
+                                # "IpAddress": {"acs:SourceIp": "*"}
+                            }
+                        }
+                    ]
+                }
+                req.set_Policy(Policy=json.dumps(policys))
+                body = clt.do_action(req)
+                # 使用RAM账号的AccessKeyId和AccessKeySecret向STS申请临时token。
+                token = json.loads(body.decode('utf-8'))
+                print(token)
+                res = {
+                    'AccessKeyId': token['Credentials']['AccessKeyId'],
+                    'AccessKeySecret': token['Credentials']['AccessKeySecret'],
+                    'SecurityToken': token['Credentials']['SecurityToken'],
+                    'Expiration': token['Credentials']['Expiration'],
+                    'expire': '3600',
+                    'endpoint': endpoint,
+                    'bucket_name': bucket_name,
+                    'arn': token['AssumedRoleUser']['Arn'],
+                    'code': 0,
+                    'storage': storage,
+                    'endTime': ubqs[0]['endTime'],
+                    'ip': ip}
+                if oc_qs.exists():
+                    oc_qs.update(data=json.dumps(res), addTime=now_time)
+                else:
+                    OssCrdModel.objects.create \
+                        (uid=uid, channel=channel, data=json.dumps(res), addTime=now_time)
                 return JsonResponse(status=200, data=res)
-        # 套餐id
-        storage = '{uid}/vod{channel}/'.format(uid=UID, channel=channel)
-        bucket_name = ubqs[0]['bucket__bucket']
-        endpoint = ubqs[0]['bucket__endpoint']
-        access_key_id = OSS_STS_ACCESS_KEY
-        access_key_secret = OSS_STS_ACCESS_SECRET
-        region_id = ubqs[0]['bucket__region']
-        role_arn = OSS_ROLE_ARN
-        clt = client.AcsClient(access_key_id, access_key_secret, region_id)
-        req = AssumeRoleRequest.AssumeRoleRequest()
-        # 设置返回值格式为JSON。
-        req.set_accept_format('json')
-        req.set_RoleArn(role_arn)
-        req.set_RoleSessionName(UID)
-        req.set_DurationSeconds(3600)
-        Resource_access = "acs:oss:*:*:{bucket_name}/{uid_channel}*".format(bucket_name=bucket_name,
-                                                                            uid_channel=storage)
-        print(Resource_access)
-        policys = {
-            "Version": "1",
-            "Statement": [
-                {
-                    "Action": ["oss:PutObject", "oss:DeleteObject", ],
-                    "Resource": [Resource_access],
-                    "Effect": "Allow",
-                    "Condition": {
-                        "IpAddress": {"acs:SourceIp": ip}
-                        # "IpAddress": {"acs:SourceIp": "120.237.157.184"}
-                        # "IpAddress": {"acs:SourceIp": "*"}
-                    }
+            elif ubqs[0]["bucket__mold"] == 1:
+                # 亚马逊 s3 sts
+                sts_qs = StsCrdModel.objects.filter(uid=uid, channel=channel). \
+                    values("addTime", "data")
+                if sts_qs.exists():
+                    endTime = int(sts_qs[0]["addTime"]) + 3500
+                    if endTime > now_time:
+                        print(endTime)
+                        print(now_time)
+                        res = json.loads(sts_qs[0]["data"])
+                        return JsonResponse(status=200, data=res)
+                    # 套餐id
+                storage = '{uid}/vod{channel}/'.format(uid=uid, channel=channel)
+                bucket_name = ubqs[0]['bucket__bucket']
+                endpoint = ubqs[0]['bucket__endpoint']
+                region_id = ubqs[0]['bucket__region']
+
+                ###############
+                REGION_NAME = region_id
+                boto3_sts = boto3.client(
+                    'sts',
+                    aws_access_key_id='AKIA2E67UIMD45Y3HL53',
+                    aws_secret_access_key='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',
+                    region_name=REGION_NAME
+                )
+                Policy = {
+                    "Version": "2012-10-17",
+                    "Statement": [
+                        {
+                            "Effect": "Allow",
+                            "Action": "s3:*",
+                            "Resource": ["arn:aws:s3:::azvod1/{uid_channel}/*".
+                                             format(uid_channel=storage)]
+                        }
+                    ]
                 }
-            ]
-        }
-        req.set_Policy(Policy=json.dumps(policys))
-        body = clt.do_action(req)
-        # 使用RAM账号的AccessKeyId和AccessKeySecret向STS申请临时token。
-        token = json.loads(body.decode('utf-8'))
-        print(token)
-        res = {
-            'AccessKeyId': token['Credentials']['AccessKeyId'],
-            'AccessKeySecret': token['Credentials']['AccessKeySecret'],
-            'SecurityToken': token['Credentials']['SecurityToken'],
-            'Expiration': token['Credentials']['Expiration'],
-            'expire': '3600',
-            'endpoint': endpoint,
-            'bucket_name': bucket_name,
-            'arn': token['AssumedRoleUser']['Arn'],
-            'code': 0,
-            'storage': storage,
-            'endTime': ubqs[0]['endTime'],
-            'ip': ip}
-        if oc_qs.exists():
-            oc_qs.update(data=json.dumps(res), addTime=now_time)
-        else:
-            OssCrdModel.objects.create(uid=UID, channel=channel, data=json.dumps(res), addTime=now_time)
-        return JsonResponse(status=200, data=res)
+                response = boto3_sts.get_federation_token(
+                    Name='{role_name}'.format(role_name=uid + '_' + channel),
+                    Policy=json.dumps(Policy),
+                    DurationSeconds=7200
+                )
+                ###############
+                res = {
+                    'AccessKeyId': response['Credentials']['AccessKeyId'],
+                    'AccessKeySecret': response['Credentials']['SecretAccessKey'],
+                    'SessionToken': response['Credentials']['SessionToken'],
+                    'Expiration': response['Credentials']['Expiration'],
+                    'expire': '3600',
+                    'endpoint': endpoint,
+                    'bucket_name': bucket_name,
+                    'arn': response['FederatedUser']['Arn'],
+                    'code': 0,
+                    'storage': storage,
+                    'endTime': ubqs[0]['endTime'],
+                    'ip': ip,
+                }
+                if sts_qs.exists():
+                    sts_qs.update(data=json.dumps(res,default=str), addTime=now_time)
+                else:
+                    StsCrdModel.objects.create(uid=uid, channel=channel, data=json.dumps(res, default=str),
+                                               addTime=now_time, type=1)
+                return JsonResponse(status=200, data=res)
+            else:
+                res = {'code': 404, 'msg': 'data not exists!'}
+                return HttpResponse(json.dumps(res, ensure_ascii=False),
+                                    content_type="application/json,charset=utf-8")
+
+    #  生成设备sts上传授权
+    # def do_getSts(self, request_dict, ip, response):
+    #     uidToken = request_dict.get('uidToken', None)
+    #     utko = UidTokenObject(uidToken)
+    #     if utko.flag is False:
+    #         return response.json(444, 'uidToken')
+    #     UID = utko.UID
+    #     channel = utko.channel
+    #     print(channel)
+    #     print(UID)
+    #     ubqs = UID_Bucket.objects.filter(uid=UID, channel=channel, status=1). \
+    #         values('channel', 'bucket__bucket', 'bucket__endpoint', 'bucket__region', 'endTime')
+    #     now_time = int(time.time())
+    #     if not ubqs.exists():
+    #         res = {'code': 404, 'msg': '未购买'}
+    #         return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
+    #     elif ubqs[0]['endTime'] < now_time:
+    #         res = {'code': 404, 'msg': '过期'}
+    #         return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
+    #     oc_qs = OssCrdModel.objects.filter(uid=UID, channel=channel).values("addTime", "data")
+    #     if oc_qs.exists():
+    #         endTime = int(oc_qs[0]["addTime"]) + 3500
+    #         if endTime > now_time:
+    #             print(endTime)
+    #             print(now_time)
+    #             res = json.loads(oc_qs[0]["data"])
+    #             return JsonResponse(status=200, data=res)
+    #     # 套餐id
+    #     storage = '{uid}/vod{channel}/'.format(uid=UID, channel=channel)
+    #     bucket_name = ubqs[0]['bucket__bucket']
+    #     endpoint = ubqs[0]['bucket__endpoint']
+    #     access_key_id = OSS_STS_ACCESS_KEY
+    #     access_key_secret = OSS_STS_ACCESS_SECRET
+    #     region_id = ubqs[0]['bucket__region']
+    #     role_arn = OSS_ROLE_ARN
+    #     clt = client.AcsClient(access_key_id, access_key_secret, region_id)
+    #     req = AssumeRoleRequest.AssumeRoleRequest()
+    #     # 设置返回值格式为JSON。
+    #     req.set_accept_format('json')
+    #     req.set_RoleArn(role_arn)
+    #     req.set_RoleSessionName(UID)
+    #     req.set_DurationSeconds(3600)
+    #     Resource_access = "acs:oss:*:*:{bucket_name}/{uid_channel}*".format(bucket_name=bucket_name,
+    #                                                                         uid_channel=storage)
+    #     print(Resource_access)
+    #     policys = {
+    #         "Version": "1",
+    #         "Statement": [
+    #             {
+    #                 "Action": ["oss:PutObject", "oss:DeleteObject", ],
+    #                 "Resource": [Resource_access],
+    #                 "Effect": "Allow",
+    #                 "Condition": {
+    #                     "IpAddress": {"acs:SourceIp": ip}
+    #                     # "IpAddress": {"acs:SourceIp": "120.237.157.184"}
+    #                     # "IpAddress": {"acs:SourceIp": "*"}
+    #                 }
+    #             }
+    #         ]
+    #     }
+    #     req.set_Policy(Policy=json.dumps(policys))
+    #     body = clt.do_action(req)
+    #     # 使用RAM账号的AccessKeyId和AccessKeySecret向STS申请临时token。
+    #     token = json.loads(body.decode('utf-8'))
+    #     print(token)
+    #     res = {
+    #         'AccessKeyId': token['Credentials']['AccessKeyId'],
+    #         'AccessKeySecret': token['Credentials']['AccessKeySecret'],
+    #         'SecurityToken': token['Credentials']['SecurityToken'],
+    #         'Expiration': token['Credentials']['Expiration'],
+    #         'expire': '3600',
+    #         'endpoint': endpoint,
+    #         'bucket_name': bucket_name,
+    #         'arn': token['AssumedRoleUser']['Arn'],
+    #         'code': 0,
+    #         'storage': storage,
+    #         'endTime': ubqs[0]['endTime'],
+    #         'ip': ip}
+    #     if oc_qs.exists():
+    #         oc_qs.update(data=json.dumps(res), addTime=now_time)
+    #     else:
+    #         OssCrdModel.objects.create(uid=UID, channel=channel, data=json.dumps(res), addTime=now_time)
+    #     return JsonResponse(status=200, data=res)
 
     def do_paypal_execute(self, request_dict, response):
         paymentId = request_dict.get('paymentId', None)

+ 26 - 6
Controller/DetectController.py

@@ -246,15 +246,14 @@ class DetectControllerView(View):
             if status == 0:
                 UidPushModel.objects.filter(uid_set__uid=uid).delete()
                 # 状态为0的时候删除redis缓存数据
-                ykey = '{uid}_redis_qs'.format(uid=uid)
-                redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')
-                redisObj.del_data(key=ykey)
+                self.do_delete_redis(uid)
                 return response.json(0)
             elif status == 1:
                 uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
-                ykey = '{uid}_redis_qs'.format(uid=uid)
-                redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')
-                redisObj.del_data(key=ykey)
+                # ykey = '{uid}_redis_qs'.format(uid=uid)
+                # redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')
+                # redisObj.del_data(key=ykey)
+
                 if uid_push_qs.exists():
                     uid_push_update_dict = {
                         'appBundleId': appBundleId,
@@ -283,6 +282,11 @@ class DetectControllerView(View):
                     }
                     # 绑定设备推送
                     UidPushModel.objects.create(**uid_push_create_dict)
+
+                if interval:
+                    self.do_delete_redis(uid, int(interval))
+                else:
+                    self.do_delete_redis(uid)
                 # utko = UidTokenObject()
                 # # right
                 # utko.generate(data={'uid': uid})
@@ -294,6 +298,22 @@ class DetectControllerView(View):
         else:
             return response.json(14)
 
+    def do_delete_redis(self, uid, detect_interval=0):
+        keyPattern = '{uid}*'.format(uid=uid)
+        redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')
+        keys = redisObj.get_keys(keyPattern)
+        if keys:
+            for key in keys:
+                key = key.decode()
+                if detect_interval == 0:
+                    redisObj.del_data(key=key)
+                elif key.find('plt') != -1:
+                    continue
+                elif key.find('flag') != -1:
+                    redisObj.set_data(key=key, val=1, expire=detect_interval)
+                else:
+                    redisObj.del_data(key=key)
+
     def do_update_interval(self, userID, request_dict, response):
         uid = request_dict.get('uid', None)
         interval = request_dict.get('interval', None)

+ 17 - 18
Controller/EquipmentManager.py

@@ -2,8 +2,7 @@ import re
 import time
 import traceback
 import threading
-
-import requests
+import logging
 import simplejson as json
 from django.utils import timezone
 from Model.models import Device_User, Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidPushModel
@@ -17,7 +16,6 @@ from Object.ETkObject import ETkObject
 import oss2
 from django.http import JsonResponse
 from Object.RedisObject import RedisObject
-import logging
 
 
 #     查询用户设备
@@ -101,8 +99,6 @@ def addNewUserEquipmentInterface(request):
                                            args=(CommonService.get_ip_address(request), userID, 'addV0'))
                     asy.start()
 
-
-
                 # is_bind = Device_Info.objects.filter(UID=UID, isShare=False)
                 # # 判断是否有已绑定用户
                 # if not is_bind.exists():
@@ -164,7 +160,7 @@ def delUserEquipmentInterface(request):
         # redisObj.del_data(key='uid_qs_' + userID)
         if dv_qs.exists():
             uid = dv_qs[0].UID
-            asy = threading.Thread(target=ModelService.delete_log, args=(CommonService.get_ip_address(request), userID, 'deleteV0', uid))
+            asy = threading.Thread(target=ModelService.add_log, args=(CommonService.get_ip_address(request), userID, 'deleteV1'))
             asy.start()
 
             print('删除')
@@ -210,6 +206,16 @@ def modifyUserEquipmentInterface(request):
         return response.json(309)
     try:
         deviceData = json.loads(deviceContent)
+
+        if deviceData.__contains__('userID_id'):
+            asy = threading.Thread(target=ModelService.update_log,
+                                   args=(CommonService.get_ip_address(request), userID, 'modifyV0', deviceData, id))
+            asy.start()
+            return response.json(10, '110')
+
+        if deviceData.__contains__('UID'):
+            del deviceData['UID']
+
         dev_info_qs = Device_Info.objects.filter(userID_id=userID, id=id)
         dev_info_qs.update(**deviceData)
     except Exception as e:
@@ -220,14 +226,9 @@ def modifyUserEquipmentInterface(request):
         if qs.exists():
             uid = qs[0].UID
             if uid == '98UXAA8BRPA35VAL111A':
-                file_path = '/'.join((BASE_DIR, 'static/add_device.log'))
-                file = open(file_path, 'a+')
-                file.write(
-                    CommonService.get_ip_address(request) + "; username:" + userID + "; time:" + time.strftime(
-                        "%Y-%m-%d %H:%M:%S", time.localtime()) + "; modifyV1")
-                file.write('\n')
-                file.flush()
-                file.close()
+                asy = threading.Thread(target=ModelService.update_log,
+                                       args=(CommonService.get_ip_address(request), userID, 'modifyV0', deviceContent, id))
+                asy.start()
             nickname = qs[0].NickName
             # 增加设备影子信息修改昵称 start
             us_qs = UidSetModel.objects.filter(uid=uid)
@@ -374,12 +375,11 @@ def addInterface(request):
                         return response.json(174)
                     else:
                         is_exist.delete()
-
                 if UID == '98UXAA8BRPA35VAL111A':
                     asy = threading.Thread(target=ModelService.add_log,
                                            args=(CommonService.get_ip_address(request), userID, 'addV1'))
                     asy.start()
-
+                    return response.json(10, 'illegal uid: {uid}'.format(uid=UID))
                 pass
                 # is_bind = Device_Info.objects.filter(UID=UID, isShare=False)
                 # # 判断是否有已绑定用户
@@ -681,9 +681,8 @@ def deleteInterface(request):
         if dv_qs.exists():
             uid = dv_qs[0].UID
             asy = threading.Thread(target=ModelService.delete_log,
-                                   args=(CommonService.get_ip_address(request), userID, 'deleteV1', uid))
+                                   args=(CommonService.get_ip_address(request), userID, 'deleteV2', uid))
             asy.start()
-
             if dv_qs[0].isShare:
                 dv_qs.delete()
             else:

+ 21 - 6
Controller/EquipmentManagerV3.py

@@ -81,7 +81,7 @@ class EquipmentManagerV3(View):
                         asy = threading.Thread(target=ModelService.add_log,
                                                args=(CommonService.get_ip_address(request), userID, 'addV3'))
                         asy.start()
-
+                        return response.json(10, 'illegal uid: {uid}'.format(uid=UID))
                     # is_bind = Device_Info.objects.filter(UID=UID, isShare=False)
                     # # 判断是否有已绑定用户
                     # if is_bind:
@@ -107,8 +107,14 @@ class EquipmentManagerV3(View):
                                                  NickName=NickName, View_Account=View_Account,
                                                  View_Password=View_Password, Type=Type, ChannelIndex=ChannelIndex)
                         userDevice.save()
-                        asy = threading.Thread(target=ModelService.notify_alexa_add, args=(UID, userID, NickName))
-                        asy.start()
+
+                        if not us_qs.exists():
+                            us_qs = UidSetModel.objects.filter(uid=UID)
+
+                        if us_qs.exists() and us_qs[0].is_alexa == 1:
+                            asy = threading.Thread(target=ModelService.notify_alexa_add, args=(UID, userID, NickName))
+                            asy.start()
+
                         # redisObj = RedisObject(db=8)
                         # redisObj.del_data(key='uid_qs_' + userID)
                     except Exception as e:
@@ -153,6 +159,16 @@ class EquipmentManagerV3(View):
         try:
             # deviceData = json.loads(deviceContent)
             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'):
                 deviceData['View_Password'] = self.decode_pwd(deviceData['View_Password'])
@@ -167,10 +183,9 @@ class EquipmentManagerV3(View):
             if qs.exists():
                 uid = qs[0].UID
                 if uid == '98UXAA8BRPA35VAL111A':
-                    asy = threading.Thread(target=ModelService.add_log,
-                                           args=(CommonService.get_ip_address(request), userID, 'modifyV3'))
+                    asy = threading.Thread(target=ModelService.update_log,
+                                           args=(CommonService.get_ip_address(request), userID, 'modifyV3', deviceData, id))
                     asy.start()
-
                 nickname = qs[0].NickName
                 # 增加设备影子信息修改昵称 start
                 us_qs = UidSetModel.objects.filter(uid=uid)

+ 14 - 2
Controller/TestApi.py

@@ -77,8 +77,8 @@ class testView(View):
         if operation is None:
             return response.json(444, 'error path')
         elif operation == 'tests':
-             res = make_password(123456)
-             return JsonResponse(status=200, data=res,safe=False)
+            res = make_password(123456)
+            return JsonResponse(status=200, data=res,safe=False)
         elif operation == 'cbu':
             return self.createBucket()
         elif operation == 'vodList':
@@ -96,6 +96,9 @@ class testView(View):
         elif operation == 'getAlexa':
             userID = '158943594633713800138000'
             return self.queryInterface(request_dict, userID, response)
+        elif operation == 'generateToken':
+            userID = '158943604783713800138000'
+            return self.generate_token(request_dict,userID)
         else:
             return 12344444
 
@@ -674,4 +677,13 @@ class testView(View):
             vod_play_list.append({'name': vod['time'], 'sign_url': vod_play_url, 'thumb': thumb, 'sec': vod['sec']})
         return response.json(0, vod_play_list)
 
+    def generate_token(self,request_dict,userID):
+        #UserIdToken
+        # tko = TokenObject()
+        # res = tko.generate(
+        #     data={'userID': 158943604783713800138000, 'lang': 'cn', 'user': '13527261476', 'm_code': '123413243214'})
 
+        #uidToken
+        utko = UidTokenObject()
+        res = utko.generate(data={'uid':'86YC8Z192VB1VMKU111A','channel':1})
+        return JsonResponse(status=200, data=res,safe=False)

+ 1 - 1
Controller/UidUser.py

@@ -540,7 +540,7 @@ def v3queryInterface(request):
     else:
         return response.json(tko.code)
 
-# 加密
+# #加密
 def encrypt_pwd(userPwd):
     for i in range(1, 4):
         if i == 1:

+ 7 - 0
Object/RedisObject.py

@@ -84,3 +84,10 @@ class RedisObject:
             return ttl
         else:
             return 0
+
+    def get_keys(self, key):
+        keys = self.CONN.keys(key)
+        if keys:
+            return keys
+        else:
+            return False

+ 15 - 3
Service/ModelService.py

@@ -159,6 +159,7 @@ class ModelService:
         uid_list = Device_Info.objects.filter(userID_id=userID).values_list('UID', flat=True)
         return list(uid_list)
 
+
     @staticmethod
     def notify_alexa_add(uid, userID, nickname):
         url = 'https://www.zositech.xyz/deviceStatus/addOrUpdate'
@@ -168,7 +169,7 @@ class ModelService:
             'uid_nick': nickname
         }
         try:
-            requests.post(url, data=data, timeout=5)
+            res = requests.post(url, data=data, timeout=10)
         except Exception as e:
             print(repr(e))
 
@@ -177,7 +178,18 @@ class ModelService:
         file_path = '/'.join((BASE_DIR, 'static/add_device.log'))
         file = open(file_path, 'a+')
         file.write(ip + "; username:" + userID + "; time:" + time.strftime(
-                "%Y-%m-%d %H:%M:%S", time.localtime()) + "; " + operation)
+            "%Y-%m-%d %H:%M:%S", time.localtime()) + "; " + operation)
+        file.write('\n')
+        file.flush()
+        file.close()
+
+    @staticmethod
+    def update_log(ip, userID, operation, content, id):
+        content['xid'] = id
+        file_path = '/'.join((BASE_DIR, 'static/update_device.log'))
+        file = open(file_path, 'a+')
+        file.write(ip + "; username:" + userID + "; time:" + time.strftime(
+            "%Y-%m-%d %H:%M:%S", time.localtime()) + "; content:" + json.dumps(content) + "; " + operation)
         file.write('\n')
         file.flush()
         file.close()
@@ -187,7 +199,7 @@ class ModelService:
         file_path = '/'.join((BASE_DIR, 'static/delete_device.log'))
         file = open(file_path, 'a+')
         file.write(ip + "; username:" + userID + "; time:" + time.strftime(
-            "%Y-%m-%d %H:%M:%S", time.localtime()) + "; " + operation + "; uid:"+UID)
+            "%Y-%m-%d %H:%M:%S", time.localtime()) + "; " + operation + "; uid:" + UID)
         file.write('\n')
         file.flush()
         file.close()