Browse Source

Merge branch 'dev' of http://192.168.136.45:3000/SERVER/AnsjerServer into dev

pengzhibo168 5 years ago
parent
commit
f0fc45d920

+ 1 - 0
.gitignore

@@ -13,3 +13,4 @@
 /Ansjer/test/__init__.py
 /sdk_install
 /DB/mydata4vipday2.ipdb
+/venv

+ 1 - 1
Ansjer/local_settings.py

@@ -117,7 +117,7 @@ USE_TZ = True
 # 跨域增加忽略
 CORS_ALLOW_CREDENTIALS = True
 CORS_ORIGIN_ALLOW_ALL = True
-CORS_ORIGIN_WHITELIST = ('*')
+# CORS_ORIGIN_WHITELIST = ('*')
 
 CORS_ALLOW_METHODS = (
     'DELETE',

+ 33 - 0
Ansjer/test/postest.py

@@ -0,0 +1,33 @@
+#!/usr/bin/env python3  
+# -*- coding: utf-8 -*-  
+"""
+@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
+@AUTHOR: ASJRD018
+@NAME: AnsjerFormal
+@software: PyCharm
+@DATE: 2020/3/20 14:36
+@Version: python3.6
+@MODIFY DECORD:ansjer dev
+@file: postest.py
+@Contact: chanjunkai@163.com
+"""
+import requests
+
+data = {}
+data['push_type'] = 2
+data['token_val'] = '1a0018970a332cca935'
+data['appBundleId'] = 'com.ansjer.zccloud_ab'
+data['tz'] = '+08.00'
+data['uid'] = 'HLK7EJ2VYLNHHUMG111A'
+data['status'] = '1'
+data['m_code'] = 'AN02000025070000001207.zccloud_ab'
+data['token'] = 'local'
+data['lang'] = 'cn'
+data['app_type'] = '2'
+# 新增传值
+data['interval'] = '3600'
+data['detect_group'] = '57,58,59'
+
+res = requests.post(url='http://192.168.136.140:8077/detect/changeStatus',data=data)
+
+print(res.json())

+ 230 - 0
Ansjer/test/s3boto3signpost.py

@@ -0,0 +1,230 @@
+#!/usr/bin/env python3  
+# -*- coding: utf-8 -*-  
+"""
+@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
+@AUTHOR: ASJRD018
+@NAME: AnsjerFormal
+@software: PyCharm
+@DATE: 2020/3/9 11:47
+@Version: python3.6
+@MODIFY DECORD:ansjer dev
+@file: s3boto3signpost.py
+@Contact: chanjunkai@163.com
+"""
+# from Ansjer.config import *
+from boto3.session import Session
+import simplejson as json
+import boto3
+from botocore.client import Config
+import requests
+
+
+def upload():
+    data = {'url': 'https://azvod1.s3.amazonaws.com/', 'fields': {'key': 'putkey/${filename}', 'AWSAccessKeyId': 'AKIA2E67UIMDUR3B3OOO', 'policy': 'eyJleHBpcmF0aW9uIjogIjIwMjAtMDMtMTNUMDI6NTI6MTlaIiwgImNvbmRpdGlvbnMiOiBbeyJidWNrZXQiOiAiYXp2b2QxIn0sIFsic3RhcnRzLXdpdGgiLCAiJGtleSIsICJwdXRrZXkvIl1dfQ==', 'signature': 'ZDucTfYayCVxKQ2CuCLlUY861Nw='}}
+
+    file_path = 'D:/devcode/AnsjerFormal/Ansjer/test/oss.py'
+    # files = {'file': open(file_path,'rb')}
+    files = {'file': ('wwww/report.xls', open(file_path, 'rb')),'filename':'xxxooo'}
+    res = requests.post(url=data['url'],data=data['fields'],files=files)
+    print(res.text)
+
+upload()
+exit()
+
+
+
+AWS_ACCESS_ID = 'AKIA2E67UIMDUR3B3OOO'
+AWS_ACCESS_SECRET = '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'
+AWS_ACCESS_REGION = 'ap-northeast-1'
+AWS_BUCKET = 'azvod1'
+session = Session(
+    aws_access_key_id=AWS_ACCESS_ID,
+    aws_secret_access_key=AWS_ACCESS_SECRET,
+    region_name=AWS_ACCESS_REGION
+)
+s3conn = session.client('s3')
+ss = s3conn.generate_presigned_post(
+    Key='putkey/${filename}',
+    ExpiresIn=3600,
+    Bucket=AWS_BUCKET
+)
+print(ss)
+exit()
+
+
+def put_object(self, body, key, bucket=''):
+    if bucket == '':
+        bucket = self.bucket
+    s3_client = self.conn
+    response = s3_client.put_object(
+        Body=body,
+        Key=key,
+        Bucket=bucket,
+        # Expires=datetime()
+    )
+    return response
+
+
+def download_file(self, file_name):
+    s3_client = self.conn
+    try:
+        s3_client.download_file(
+            self.bucket,
+            file_name,
+        )
+        return file_name
+    except:
+        print('Cannot download file', file_name)
+        return
+
+
+def get_all_object(self, prefix):
+    paginator = self.conn.get_paginator('list_objects')
+    s3_results = paginator.paginate(
+        Bucket=self.bucket,
+        Prefix=prefix,
+        PaginationConfig={'PageSize': 1000}
+    )
+    bucket_object_list = []
+    for page in s3_results:
+        if "Contents" in page:
+            for key in page["Contents"]:
+                s3_file_name = key['Key'].split('/')[-1]
+                bucket_object_list.append(s3_file_name)
+    return bucket_object_list
+
+
+def get_prefix_obj(self, prefix, bucket):
+    paginator = self.conn.get_paginator('list_objects')
+    s3_results = paginator.paginate(
+        Bucket=bucket,
+        Prefix=prefix,
+        # PaginationConfig={'PageSize': 1000}
+    )
+    bucket_object_list = []
+    for page in s3_results:
+        if "Contents" in page:
+            for key in page["Contents"]:
+                s3_file_name = key['Key'].split('/')[-1]
+                bucket_object_list.append(s3_file_name)
+    return bucket_object_list
+
+
+def delete_object(self, key):
+    response = self.conn.delete_object(
+        Bucket=self.bucket,
+        Key=key,
+    )
+    return response
+
+
+def get_object(self, key):
+    response = self.conn.get_object(
+        Bucket=self.bucket,
+        Key=key,
+    )
+    return response
+
+
+def del_list_object(self, keydict):
+    keylist = json.loads(keydict)['keylist']
+    del_list = []
+    for i in keylist:
+        del_list.append({'Key': i})
+    response = self.conn.delete_objects(
+        Bucket=self.bucket,
+        Delete={'Objects': del_list}
+    )
+    print(response)
+    return response
+
+
+def del_object_list(self, keylist):
+    del_list = []
+    for i in keylist:
+        del_list.append({'Key': i})
+    response = self.conn.delete_objects(
+        Bucket=self.bucket,
+        Delete={'Objects': del_list}
+    )
+    print(response)
+    return response
+
+
+def get_download_url(self, key):
+    self.conn.generate_presigned_url(
+        'get_object',
+        Params={
+            'Bucket': 'www.mybucket.com',
+            'Key': key
+        },
+        ExpiresIn=100)
+    return
+
+
+# 推mp4到s3,且设置为html5播放
+def put_mp4_object(self, body, key):
+    s3_client = self.conn
+    response = s3_client.put_object(
+        Body=body,
+        Key=key,
+        Bucket=self.bucket,
+        ContentType='video/mp4'
+    )
+    return response
+
+
+def get_generate_vod_url(self, key):
+    response_url = self.conn.generate_presigned_url(
+        'get_object',
+        Params={
+            'Bucket': self.bucket,
+            'Key': key
+        },
+        ExpiresIn=3600
+    )
+    return response_url
+
+
+def sign_put_object(self, key, bucket_meal):
+    s3_con = boto3.client('s3',
+                          aws_access_key_id=AWS_ACCESS_ID,
+                          aws_secret_access_key=AWS_ACCESS_SECRET,
+                          config=Config(signature_version='s3v4'),
+                          region_name=AWS_ACCESS_ID,
+                          )
+    try:
+        url = s3_con.generate_presigned_url(
+            'put_object',
+            Params={
+                'Bucket': bucket_meal,
+                'Key': key,
+            },
+            ExpiresIn=60,
+            HttpMethod='PUT'
+        )
+    except Exception as e:
+        print(repr(e))
+        return False
+    else:
+        return url
+
+
+def sign_post_object(self, key, bucket_meal):
+    s3_con = boto3.client('s3',
+                          aws_access_key_id=AWS_ACCESS_ID,
+                          aws_secret_access_key=AWS_ACCESS_SECRET,
+                          config=Config(signature_version='s3v4'),
+                          region_name=AWS_ACCESS_REGION,
+                          )
+    try:
+        data = s3_con.generate_presigned_post(
+            Key=key,
+            ExpiresIn=60,
+            Bucket=bucket_meal
+        )
+    except Exception as e:
+        print(repr(e))
+        return False
+    else:
+        return data

+ 39 - 40
Ansjer/test/s3sts.py

@@ -11,87 +11,86 @@
 @file: s3sts.py
 @Contact: chanjunkai@163.com
 """
-
-def getCredentials():
+def test_get_credential():
     import boto3
     REGION_NAME = 'us-east-1'  # e.g
     import json
-
-    sts = boto3.client(
+    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": "kinesisvideo:*", "Resource": ["arn:aws:kinesisvideo:us-east-1:697864307463:stream/wpy_stream/1573460250304"]}]}
-    credentials = sts.get_federation_token(
-        Name='chanjunkai@163.com',  # or any unique text related to user
+    Policy = {"Version": "2012-10-17", "Statement": [
+        {"Effect": "Allow", "Action": "s3:*", "Resource": ["arn:aws:s3:::azvod1/*"]}]}
+    response = boto3_sts.get_federation_token(
+        Name='chanjunkai@166.com',
         Policy=json.dumps(Policy),
-        DurationSeconds=3600,
-    )
-
-    print(credentials)
-    access_key_id = credentials['Credentials']['AccessKeyId']
-    session_token = credentials['Credentials']['SessionToken']
-    secret_access_key = credentials['Credentials']['SecretAccessKey']
 
-getCredentials()
+        DurationSeconds=7200
+    )
+    print(response)
 
-exit()
+# test_get_credential()
 # exit()
-def getCredentialsTemplate():
+
+def getCredentials():
     import boto3
     REGION_NAME = 'us-east-1'  # e.g
+    import json
 
     sts = boto3.client(
         'sts',
-        aws_access_key_id='AKIAIXAA4C3QCK7ZNUOA',
-        aws_secret_access_key='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',
+        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:::<your-bucket>/<key-folder>/*"]}]}
+    Policy = {"Version": "2012-10-17",
+              "Statement": [{"Effect": "Allow", "Action": "kinesisvideo:*", "Resource": [
+                  "arn:aws:kinesisvideo:us-east-1:697864307463:stream/wpy_stream/1573460250304"]}]}
     credentials = sts.get_federation_token(
-        Name='12132@qq.com',  # or any unique text related to user
-        Policy={},
+        Name='chanjunkai@163.com',  # or any unique text related to user
+        Policy=json.dumps(Policy),
         DurationSeconds=3600,
-        # minimum is 200 which is enough as token is just for start of request and necessarily need not live throughout the life of the whole upload.
     )
+
+    print(credentials)
     access_key_id = credentials['Credentials']['AccessKeyId']
     session_token = credentials['Credentials']['SessionToken']
     secret_access_key = credentials['Credentials']['SecretAccessKey']
-    print(credentials)
+    res = {
+        'access_key_id': access_key_id,
+        'session_token': session_token,
+        'secret_access_key': secret_access_key,
+    }
+    print(res)
+
+# getCredentials()
+
 
 def test():
     print('test')
     import boto3
     REGION_NAME = 'us-east-1'  # e.g
     import json
-    # crd = {'Credentials': {'AccessKeyId': 'ASIA2E67UIMDZEZW7F56', 'SecretAccessKey': '2XE3bxqUlt7RTwojtsOxAQdp25dXlPSOGJr4PJ9l', 'SessionToken': 'FQoGZXIvYXdzEHIaDNE8Ddu2SeUjFQB3ICL7AVZuoryvjuDgFFkNuB81R2tO+jo5xbH3mecUN9SygDRWccfGqUkZZli8h9oF9nxht3LzawpTzR8Xsk3Zcq7hXZ4n69nNjCzO5iRAqNU5OSA5QdS70xcJyGBvMz5QX+QL6T8nTUf0qImvgTgzHl1U7dhPDkpR2TTpuFkoCxPjPDDmljA45TzOzDPkZ9P48njKF0ijJsWKUIJSOOXpixn7QZHE0+WzCrl4OQdr4gyYBDufYQl4Hc/jhG1W40FE9KARRClOFQk01gc8RZR07K26+bDUfLdhT4uBpwZ64xR64VQX0OKVu0e9hjPFEePDheSIwdzS7htJomuF5Vq7KIGuk98F', 'Expiration': datetime.datetime(2018, 11, 9, 1, 38, 25, tzinfo=tzutc())}, 'FederatedUser': {'FederatedUserId': '697864307463:chanjunkai@163.com', 'Arn': 'arn:aws:sts::697864307463:federated-user/chanjunkai@163.com'}, 'PackedPolicySize': 11, 'ResponseMetadata': {'RequestId': 'c4e67d2b-e3b7-11e8-b1b0-bfa03e244fac', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'c4e67d2b-e3b7-11e8-b1b0-bfa03e244fac', 'content-type': 'text/xml', 'content-length': '1151', 'date': 'Fri, 09 Nov 2018 00:38:24 GMT'}, 'RetryAttempts': 0}}
-    crd = {'AccessKeyId': 'ASIA2E67UIMD2KA76ZX3', 'SecretAccessKey': 'HbbZPLKcdr1vh81fUH5M8bGzhobPJ9/7SjOBqLNB', 'SessionToken': 'FQoGZXIvYXdzEOz//////////wEaDOT/uGl4KlSpHcQk1SL7AZW+0TxQFvhBp+UtPACl1L7WXftaHv7R5AozWYO/MmDHU1IDSQw0JNbK6v5xhOtxgdE2aSmN0UGq9g5SyI5+EX8xDrwuSg6b8fgUJ6Z9N62xO1e5qnY5wYI1R6xbmRHqCfIN+uBg/PzeKKcSLiLfK49nPbxTsgXn3drW+pQ4kjvyTDQlNVqwCk61eNTrt+WIqKz7e71BUV5I0vlERivyknWve5uoBrBGesYRSxAYT5/9MqvvGMc8k8lfDStlJOwANPqcXFyQFg8heU3pnenjJZOQ+vMHzEHxL7yZseq6SoadjkWT6xm4VyDLGPGr4IdUaoP1V9FFDdGbVHwzKM6crt8F'}
-
+    crd = {'Credentials': {'AccessKeyId': 'ASIA2E67UIMDZ3G2JTGG', 'SecretAccessKey': 'hZLPMgOiOUR08uZhEorG7Hf2KURo+U62n8pz4h9J', 'SessionToken': 'FwoGZXIvYXdzEEsaDFDNHGJymzOcRe21LiLFARGel4C5k3cqtnon8+yrpzZW5+tTsUONkQlBVeM6XjIgn9LUmlwroGktRBAOLuNb++licd8bUugeCU9+XMoWivJi7c3B3G5LVbofxPqs6MPfXdx4XXVa7PtMZPCyqjIhoIWcbrNuY21j3j3Mj1oggdLxPF1qPiAL1auVW8cTvygaRr6X5wgGGl0dOvBLOfGJzyCIOyLQ4BjwNCFaT4awgfrfK7rYnKvBGUWcM5UEkJ6O6dIkCHb+eHCV9RwqosXBcSE4KNk6KLKtpvMFMin3p5wPsYYvAAJVwDmFUoPyRuKom8HL8mlya7/aCnAbIM5u5lPO7TionA==', 'Expiration': 3600}, 'FederatedUser': {'FederatedUserId': '697864307463:chanjunkai@166.com', 'Arn': 'arn:aws:sts::697864307463:federated-user/chanjunkai@166.com'}, 'PackedPolicySize': 8, 'ResponseMetadata': {'RequestId': '65904087-9678-4c25-9042-fbb1b165a928', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '65904087-9678-4c25-9042-fbb1b165a928', 'content-type': 'text/xml', 'content-length': '1138', 'date': 'Thu, 12 Mar 2020 01:56:02 GMT'}, 'RetryAttempts': 0}}
 
 
     # s3_resource = boto3.resource(
     s3_resource = boto3.client(
         's3',
-        aws_access_key_id=crd['AccessKeyId'],
-        aws_secret_access_key=crd['SecretAccessKey'],
-        aws_session_token=crd['SessionToken'],
+        aws_access_key_id=crd['Credentials']['AccessKeyId'],
+        aws_secret_access_key=crd['Credentials']['SecretAccessKey'],
+        aws_session_token=crd['Credentials']['SessionToken'],
     )
     response = s3_resource.put_object(
         Body='xxxxx',
-        Key='test',
-        Bucket='ansjerfilemanager',
+        Key='test1111111111111.log',
+        Bucket='azvod1',
         # Expires=datetime()
     )
-    # response = s3_resource.get_object(
-    #     Bucket='ansjerfilemanager',
-    #     Key='face.jpg',
-    # )
     print(response)
 
-test()
+
+test()

+ 3 - 1
Ansjer/urls.py

@@ -45,6 +45,7 @@ urlpatterns = [
     url(r'^equipment/admin_modify', EquipmentManager.admin_modifyInterface),
 
     url(r'^equipment/query', EquipmentManager.queryInterface),
+    # 获取设备影子信息接口
     url(r'^equipment/flow$', EquipmentManager.uid_status),
 
     url(r'^OTA/uploads$', OTAEquipment.getUploadFiletoDirView.as_view()),
@@ -113,7 +114,8 @@ urlpatterns = [
     # 重置密码验证码校验
     url(r'^v2/authcode/verify$', UserController.verifyAuthcode.as_view()),
     url(r'^v2/account/logout$', UserController.V2LogoutView.as_view()),
-
+    # 新增
+    url(r'^detect/detect_group_push$',DetectController.NotificationView.detect_group_push),
     url(r'^detect/add$', DetectController.PushNotificationView.as_view()),
     url(r'^detect/(?P<operation>.*)$', DetectController.DetectControllerView.as_view()),
     url(r'^notify/push$', DetectController.NotificationView.as_view()),

+ 180 - 13
Controller/DetectController.py

@@ -37,6 +37,9 @@ http://push.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
 
 http://www.dvema.com/detect/changeStatus?push_type=2&token_val=1a0018970a332cca935&appBundleId=com.ansjer.zccloud_ab&tz=+08.00&uid=HLK7EJ2VYLNHHUMG111A&status=1&m_code=AN02000025070000001207.zccloud_ab&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiMTMxMTk2NTc3MTMiLCJsYW5nIjoiZW4iLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJ1c2VySUQiOiIxNTQ0ODM4MjMyOTczMTM4MDAxMzgwMDAiLCJleHAiOjE1ODQxNDc0NjN9.NjK91B26jZDtdmq8tW-8hXNQPqqDfo9Zwf_Jg6Uf7co&lang=cn&app_type=2
 
+http://127.0.0.1:8077/detect/changeStatus?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTg0MzUxODk2MjgyMTM4MDAxMzgwMDAiLCJsYW5nIjoiZW4iLCJ1c2VyIjoiMTM2ODAzMTc1OTYiLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJleHAiOjE1ODcyNjEzODN9.H87931EDg6PGZK63EAsvY1FRJov9qo_S70mBKvpZeQM&push_type=2&token_val=token_val&appBundleId=appBundleId&tz=0&uid=158440619973313800138000&status=1&m_code&lang=cn&app_type=0&start_status=1&interval=60&eventType=60
+http://192.168.136.140:8077/detect/changeStatus?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTg0MzUxODk2MjgyMTM4MDAxMzgwMDAiLCJsYW5nIjoiZW4iLCJ1c2VyIjoiMTM2ODAzMTc1OTYiLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJleHAiOjE1ODcyNjEzODN9.H87931EDg6PGZK63EAsvY1FRJov9qo_S70mBKvpZeQM&push_type=2&token_val=token_val&appBundleId=appBundleId&tz=0&uid=158440619973313800138000&status=1&m_code&lang=cn&app_type=0&start_status=1&interval=60&eventType=60
+detect/changeStatus
 
 '''
 
@@ -65,6 +68,7 @@ class DetectControllerView(View):
             userID = tko.userID
             # 修改推送设置
             if operation == 'changeStatus':
+                print("进入changeStatus")
                 return self.do_change_status(userID, request_dict, response)
             # 查询推送信息
             elif operation == 'queryInfo':
@@ -266,24 +270,28 @@ class DetectControllerView(View):
         else:
             return response.json(14)
 
-    def do_change_status(self, userID, request_dict, response):
-        uid = request_dict.get('uid', None)
+    def do_change_status11(self, userID, request_dict, response):
         token_val = request_dict.get('token_val', None)
         appBundleId = request_dict.get('appBundleId', None)
         app_type = request_dict.get('app_type', None)
         push_type = request_dict.get('push_type', None)
         status = request_dict.get('status', None)
         m_code = request_dict.get('m_code', None)
+        uid = request_dict.get('uid', None)
+        detect_group = request_dict.get('eventType', None)
         # 设备语言
         lang = request_dict.get('lang', 'en')
         tz = request_dict.get('tz', '0')
+        start_status = request_dict.get('start_status', None)
         # interval = request_dict.get('interval', None)
         if not status:
             return response.json(444, 'status')
+        print("111")
         # 关闭推送
         if not all([appBundleId, app_type, token_val, uid, m_code]):
             return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
         # 判断推送类型对应key是否存在
+        print('push_type:', push_type)
         if push_type == '0':
             if appBundleId not in APNS_CONFIG.keys():
                 return response.json(904)
@@ -295,7 +303,23 @@ class DetectControllerView(View):
                 return response.json(904)
         else:
             return response.json(173)
+
         dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
+        # 新增a
+        if start_status == "1":
+            interval = request_dict.get('interval', None)
+            # 设备表,用于判断这台设备是否存在
+            dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
+            if dvqs.exists():
+                uid_set_qs = UidSetModel.objects. \
+                    filter(uid=uid, uidpushmodel__userID_id=userID)
+                if uid_set_qs.exists():
+                    uid_set_qs.update(detect_interval=int(interval))
+                else:
+                    return response.json(173)
+            # 移动侦测  evenType为字符串0,将detect_group设置进数据库
+            UidSetModel.objects.filter(uid=uid, uidpushmodel__userID_id=userID).update(detect_group=detect_group)
+            # /新增a
         status = int(status)
         # 获取用户区域
         # ip = self.ip
@@ -326,7 +350,135 @@ class DetectControllerView(View):
                 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 = RedisObject(db=6, SERVER_HOST='push.dvema.com')
+                redisObj.del_data(key=ykey)
+                return response.json(0)
+            elif status == 1:
+                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_set_id = uid_set_qs[0].id
+                    uid_push_create_dict = {
+                        'uid_set_id': uid_set_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)
+                # utko = UidTokenObject()
+                # # right
+                # utko.generate(data={'uid': uid})
+                etkObj = ETkObject(etk='')
+                etk = etkObj.encrypt(uid)
+                detectUrl = "{DETECT_PUSH_DOMAIN}notify/push?etk={etk}". \
+                    format(etk=etk, DETECT_PUSH_DOMAIN=DETECT_PUSH_DOMAIN)
+                return response.json(0, {'detectUrl': detectUrl})
+        else:
+            return response.json(14)
+
+    def do_change_status(self, userID, request_dict, response):
+        token_val = request_dict.get('token_val', None)
+        appBundleId = request_dict.get('appBundleId', None)
+        app_type = request_dict.get('app_type', None)
+        push_type = request_dict.get('push_type', None)
+        status = request_dict.get('status', None)
+        m_code = request_dict.get('m_code', None)
+        uid = request_dict.get('uid', None)
+        # 设备语言
+        lang = request_dict.get('lang', 'en')
+        tz = request_dict.get('tz', '0')
+        # 消息提醒功能新增
+        detect_group = request_dict.get('detect_group', None)
+        interval = request_dict.get('interval', None)
+        if not status:
+            return response.json(444, 'status')
+        print("111")
+        # 关闭推送
+        if not all([appBundleId, app_type, token_val, uid, m_code]):
+            return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
+        # 判断推送类型对应key是否存在
+        print('push_type:', push_type)
+
+        if push_type == '0':
+            if appBundleId not in APNS_CONFIG.keys():
+                return response.json(904)
+        elif push_type == '1':
+            if appBundleId not in FCM_CONFIG.keys():
+                return response.json(904)
+        elif push_type == '2':
+            if appBundleId not in JPUSH_CONFIG.keys():
+                return response.json(904)
+        else:
+            return response.json(173)
+        dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
+        status = int(status)
+        # 获取用户区域
+        # ip = self.ip
+        # ipInfo = CommonService.getIpIpInfo(ip=ip, lang='EN')
+        # area = ipInfo['country_name']
+        # if area == 'China':
+        #     DETECT_PUSH_DOMAIN = 'cn.push.dvema.com'
+        # else:
+        #     DETECT_PUSH_DOMAIN = 'en.push.dvema.com'
+
+
+        nowTime = int(time.time())
+        if dvqs.exists():
+            uid_set_qs = UidSetModel.objects.filter(uid=uid)
+            # uid配置信息是否存在
+
+            if uid_set_qs.exists():
+                uid_set_id = uid_set_qs[0].id
+                qs_data = {
+                    'detect_status': status,
+                    'updTime': nowTime,
+                }
+                if interval:
+                    qs_data['detect_interval'] = int(interval)
+                if detect_group:
+                    qs_data['detect_group'] = detect_group
+                print(qs_data)
+                uid_set_qs.update(**qs_data)
+
+            else:
+                qs_data = {
+                    'uid': uid,
+                    'addTime': nowTime,
+                    'updTime': nowTime,
+                    'detect_status': status,
+                }
+                if interval:
+                    qs_data['detect_interval'] = int(interval)
+                if detect_group:
+                    qs_data['detect_group'] = detect_group
+                # 添加设备配置
+                uid_set_qs = UidSetModel.objects.create(**qs_data)
+
+                uid_set_id = uid_set_qs.id
+
+            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)
                 return response.json(0)
             elif status == 1:
@@ -423,16 +575,30 @@ class NotificationView(View):
             uid = utko.UID
         # utko = UidTokenObject(uidToken)
         # uid = utko.UID
+        detect_group = UidSetModel.objects.filter(uid=uid). \
+            values('detect_group')
+        event_type = detect_group
+        # 新增 移动侦测
+        if event_type == '0':
+            self.detect_group_push(self, request_dict, uid, response, channel, n_time, event_type, is_st)
+        # 新增 pir侦测
+        if event_type == '1':
+            self.detect_group_push(self, request_dict, uid, response, channel, n_time, event_type, is_st)
+        # 新增 移动侦测和pir侦测
+        if event_type == '01':
+            self.detect_group_push(self, request_dict, uid, response, channel, n_time, event_type, is_st)
+
+    # 新增 把代码封装以便后面分侦测类型
+    def detect_group_push(self, request_dict, uid, response, channel, n_time, event_type, is_st):
         redisObj = RedisObject(db=6)
-        # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
-        pkey = '{uid}_ptl'.format(uid=uid)
+        pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
         if redisObj.get_data(key=pkey):
             res_data = {'code': 0, 'msg': 'success,!'}
             return JsonResponse(status=200, data=res_data)
         else:
             # 设置推送间隔60秒一次
             redisObj.set_data(key=pkey, val=1, expire=60)
-        uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid,uid_set__detect_status=1). \
+        uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
             values('token_val', 'app_type', 'appBundleId',
                    'push_type', 'userID_id', 'userID__NickName',
                    'lang', 'tz', 'uid_set__nickname')
@@ -451,11 +617,11 @@ class NotificationView(View):
                 # android gcm
                 elif push_type == 1:
                     self.do_fcm(request_dict, up, response, uid, channel, nickname)
-                    # self.do_gmc(request_dict, up, response, uid, channel,nickname)
+                # self.do_gmc(request_dict, up, response, uid, channel,nickname)
                 # android jpush
                 elif push_type == 2:
                     self.do_jpush(request_dict, up, response, uid, channel, nickname)
-                # self.do_save_equipment_info(ua, n_time, channel, event_type, is_st)
+            # self.do_save_equipment_info(ua, n_time, channel, event_type, is_st)
             # 需求不一样,所以这么做的
             self.do_bulk_create_info(uid_push_qs, n_time, channel, event_type, is_st, uid)
             if is_st == '0' or is_st == '2':
@@ -502,7 +668,7 @@ class NotificationView(View):
         push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
                      "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
         message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
-        send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz,event_type=event_type)
+        send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)
         android = jpush.android(alert=send_text, priority=1, style=1, alert_type=7,
                                 big_text=send_text, title=message_title,
                                 extras=push_data)
@@ -565,7 +731,7 @@ class NotificationView(View):
         push_service = FCMNotification(api_key=serverKey)
         registration_id = token_val
         message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
-        send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz,event_type=event_type)
+        send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)
         data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
                 "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
         result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title,
@@ -586,7 +752,7 @@ class NotificationView(View):
         appBundleId = uaql['appBundleId']
         tz = uaql['tz']
         message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
-        send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz,event_type=event_type)
+        send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)
         try:
             print('---')
 
@@ -679,8 +845,9 @@ class PushNotificationView(View):
                 return JsonResponse(status=200, data=res_data)
             else:
                 redisObj.set_data(key=pkey, val=1, expire=60)
-            uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid,uid_set__detect_status=1).\
-                values('token_val', 'app_type', 'appBundleId', 'push_type','userID_id', 'userID__NickName', 'lang', 'tz', 'uid_set__nickname')
+            uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
+                values('token_val', 'app_type', 'appBundleId', 'push_type', 'userID_id', 'userID__NickName', 'lang',
+                       'tz', 'uid_set__nickname')
             if uid_push_qs.exists():
                 auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
                 bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')

+ 3 - 1
Controller/EquipmentManager.py

@@ -753,7 +753,8 @@ def uid_status(request):
     userID = tko.userID
     # 判断用户是否绑定设备
     qs = UidSetModel.objects.filter(uid=uid).values('uid', 'detect_status', 'detect_interval', 'version', 'ucode',
-                                                    'p2p_region', 'tz', 'video_code', 'channel', 'cloud_vod', 'id')
+                                                    'p2p_region', 'tz', 'video_code', 'channel', 'cloud_vod', 'id',
+                                                    'detect_group')
     # 判断uid配置表信息是否存在
     if qs.exists():
         # 获取uid推送是否添加过
@@ -772,6 +773,7 @@ def uid_status(request):
             'video_code': qs[0]['video_code'],
             'channel': qs[0]['channel'],
             'cloud_vod': qs[0]['cloud_vod'],
+            'detect_group': qs[0]['detect_group'],  # 推送组
         }
         # 查询云存储相关信息
         ubqs = UID_Bucket.objects.filter(uid=uid). \

+ 9 - 8
Controller/OTAEquipment.py

@@ -498,14 +498,15 @@ def getNewVerInterface(request):
             # 创建url的token
             tko = UrlTokenObject()
             file_path = tko.generate(data={'Url': "ansjer/" + CommonService.RandomStr(6) + "/" + file_path})
-            if SERVER_TYPE == 'Ansjer.formal_settings':
-                url = SERVER_DOMAIN + 'dlotapack/' + file_path
-            else:
-                # 这里调用国内服务器进行下载,防止下载bug
-                if code == '18E201200CA' or code == '18E201200CZ':
-                    url = 'http://www.zositech.xyz/dlotapack/' + file_path
-                else:
-                    url = SERVER_DOMAIN + 'dlotapack/' + file_path
+            url = SERVER_DOMAIN + 'dlotapack/' + file_path
+            # if SERVER_TYPE == 'Ansjer.formal_settings':
+            #     url = SERVER_DOMAIN + 'dlotapack/' + file_path
+            # else:
+            #     这里调用国内服务器进行下载,防止下载bug
+                # if code == '18E201200CA' or code == '18E201200CZ':
+                #     url = 'http://www.zositech.xyz/dlotapack/' + file_path
+                # else:
+                #     url = SERVER_DOMAIN + 'dlotapack/' + file_path
             return response.json(0, {
                 'ver': ver,
                 'url': url,

+ 23 - 3
Controller/Test.py

@@ -23,6 +23,7 @@ import json
 from alipay import AliPay
 import time
 import apns2
+from django.http import JsonResponse
 
 
 # 测试接口sdk
@@ -31,9 +32,6 @@ class Test(View):
     def get(self, request, *args, **kwargs):
 
         request_dict = request.GET
-        op = request_dict.get('op',None)
-        if op:
-            return self.do_get_aws_kinesis_vidoe()
         test_push_type = request_dict.get('test_push_type')
         if test_push_type == 'jpush':
             return self.jgPush(request)
@@ -41,9 +39,31 @@ class Test(View):
             return self.do_fcm_push(request)
         elif test_push_type == 'apns':
             return self.do_apns(request.GET)
+        elif test_push_type == 's3sts':
+            return self.do_get_s3_sts()
         return self.do_gcm_push(request)
         return self.do_alipay_query_status()
 
+    def do_get_s3_sts(self):
+        import boto3
+        REGION_NAME = 'us-east-1'  # e.g
+        import json
+        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/*"]}]}
+        response = boto3_sts.get_federation_token(
+            Name='chanjunkai@166.com',
+            Policy=json.dumps(Policy),
+            DurationSeconds=7200
+        )
+        return JsonResponse(status=200, data=response)
+
+
     def do_get_aws_kinesis_vidoe(self):
         import boto3
         REGION_NAME = 'us-east-1'  # e.g

+ 1 - 1
Controller/VodBucket.py

@@ -140,7 +140,7 @@ class UidBucketView(View):
         if operation == 'add':
             return self.do_add(request_dict, response, userID)
         elif operation == 'delete':
-            return self.do_delete(request_dict, respons, userIDe)
+            return self.do_delete(request_dict, response, userID)
         elif operation == 'update':
             return self.do_update(request_dict, response,userID)
         elif operation == 'query':

+ 3 - 3
Model/models.py

@@ -641,11 +641,11 @@ class UidSetModel(models.Model):
     video_code = models.SmallIntegerField(default=0, verbose_name='编码类型')  # 0:264,1:265
     nickname = models.CharField(default='', max_length=64, verbose_name='设备昵称')
     ip = models.CharField(max_length=20, default='', verbose_name=u'设备ip')
-    pwd = models.CharField(max_length=32, default='', verbose_name=u'设备密码')
     # 设备重置后第一次启动时间
-    resetTime = models.IntegerField(default=0, verbose_name='设备重置时间')
     is_alexa = models.IntegerField(default=0, verbose_name='会否支持alexa') # 0:否,1:是
-    # is_azpush = models.IntegerField(default=0, verbose_name='会否自家推送服务') # 0:否,1:是
+    detect_group = models.CharField(default='',max_length=32,verbose_name=u'检测类型')
+    pwd = models.CharField(max_length=32, default='', verbose_name=u'设备密码')
+    resetTime = models.IntegerField(default=0, verbose_name='设备重置时间')
     detect_group = models.CharField(default='', max_length=10, verbose_name=u'检测类型')
     class Meta:
         db_table = 'uid_set'

+ 2 - 1
Object/TokenObject.py

@@ -21,7 +21,7 @@ class TokenObject:
 
     def __init__(self, token=None):
         if token == 'local':
-            token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTQzOTA5MDUwNDEzMTM4MDAxMzgwMDAiLCJsYW5nIjoiZW4iLCJ1c2VyIjoiMTM4MDAxMzgwMDEiLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJleHAiOjE1NzY0NzY2NDR9.ZksD1AGi5sCI2HRQ_sPfS1Qgj-0Cm5soYEMqhx-H1Ew'
+            token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTg0MzUxODk2MjgyMTM4MDAxMzgwMDAiLCJsYW5nIjoiZW4iLCJ1c2VyIjoiMTM2ODAzMTc1OTYiLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJleHAiOjE1ODcyNzcwNjB9.c0LV_XyxwbzUlYqMJqx7vw9f19Jv-0kGnUHuu_go-mo'
         if token == 'test':
             token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiMTM4MDAxMzgwMDEiLCJleHAiOjE1Njk5OTg4OTYsInVzZXJJRCI6IjE1MTU2NDI2MjMzNzkzOTUxMzgwMDEzODAwMSIsImxhbmciOiJlbiIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCJ9.VAQtT9AbCCfXcrNj9DL5cvVasMDoI7AP8ptgU1GoMu8'
         self.token = token
@@ -29,6 +29,7 @@ class TokenObject:
         self.userID = None
         self.user = ''
         self.code = 0
+        # 令牌校验
         self.valid()
 
     def valid(self):

+ 11 - 5
requirements.txt

@@ -1,4 +1,4 @@
-Django > 2
+Django==2
 
 django-cors-headers
 django-imagekit
@@ -18,13 +18,19 @@ ffmpy
 xmltodict
 var_dump
 django-middleware-global-request
-oss2
-aliyun-python-sdk-sts
 jpush
 pyipip
 boto
 django-ratelimit
 paypalrestsdk
 pymongo
-apns2-client
-pyfcm
+image
+pyfcm
+pillow
+oss2
+redis
+ipip-ipdb
+alipay-sdk-python
+https://www.cnblogs.com/victorwu/p/8505336.html
+apns2
+aliyun-python-sdk-sts