Răsfoiți Sursa

Merge branch 'dev'

# Conflicts:
#	Ansjer/urls.py
#	Controller/DetectController.py
#	Controller/UidUser.py
tanghongbin 5 ani în urmă
părinte
comite
39758f001b

+ 31 - 0
Ansjer/config.py

@@ -126,3 +126,34 @@ FCM_CONFIG = {
     'com.ansjer.accloud_a': 'AAAAb9YP3rk:APA91bFm06w8b9OKQ0gz0iaWFuRqRIkvgAz6z7Gp3dBU_X-LNGJQd1hc1QR2W7QzBglF8SHtERA45a2lbdLRa5qv7hxfd6W_sJLBK7dA8jklsOQBvy505oUzTwMKWy4TwH-exps9KrhO',
     'com.ansjer.zccloud_ab': 'AAAAb9YP3rk:APA91bHu8u-CTpcd0g6lKPo0WNVqCi8jZub1cPPbSAY9AucT1HxlF65ZDUko9iG8q2ch17bwu9YWHpK1xI1gHSRXCslLvZlXEmHZC0AG3JKg15XuUvlFKACIajUFV-pOeGRT8tM6-31I',
 }
+
+DEVICE_TYPE = {
+    0: 'UNKOWN',
+    1: 'DVR',
+    2: 'NVR',
+    3: 'POENVR',
+    4: 'WIRELESSNVR',
+    5: 'POEIPC',
+    6: 'BOLTIPC',
+    7: 'IPC',
+    8: 'KAPIANJI',
+    9: 'FISHEYE',
+    10: 'C512',
+    11: 'C611',
+    12: 'C612',
+    13: 'C199',
+    14: 'C190',
+    15: 'C199_PRO',
+    10001: 'DVRPTZ'
+}
+
+APP_FREQUENT = {
+    0: 'UNKOWN',
+    1: '每天',
+    2: '三天',
+    3: '一周',
+    4: '两周',
+    5: '一个月',
+    6: '一个月以上',
+
+}

+ 2 - 2
Ansjer/config_test.py

@@ -30,8 +30,8 @@ PAYPAL_CRD = {
     # "client_id": "AeuhR7FHisO-lOd2OwtzyDu7PSLMmDZoDLgmzuEQ12WCtTu_8Z1AzcD4gG5SnymnuvJs-n5KBB8H9Z_G",
     # "client_secret": "EGkMCB3RWTcUGJGDYahJ9mCO0AQzEn2AvFfx1GAFjfyyn7-8a0NObcZks89QorlFpvNWTsDXVa2INRNM"
     "mode": "sandbox",  # sandbox or live
-    "client_id": "AfnfDqezODOoWGS-W2Itu-Zl1ay1R95IsGlMqPghPA3KGhkPndNMnQT0bdEewvSv92XAFIfLiinmyhBL",
-    "client_secret": "EErLskwYA1xXY3890mHx5OhzgK83B2rNc57zIozGNyKc8i6RJuhPTF9WyhhdZgyDEih0heo1MH9Jk1lj"
+    "client_id": "AVLoQVq3xHZ6FrF4mxHwlCPgVBAw4Fw5RtMkuxmYd23SkUTIY643n2g3KdK-Al8wV05I28lza5uoQbAA",
+    "client_secret": "EO8kRc8yioDk0i2Qq-QMcVFfwkmyMJorTvBSLDTnxDJJ_wb9VoM_0jkUY9iEng2Flp1ze8wQOGpH5nB2"
 }
 DETECT_PUSH_DOMAIN = 'http://test.push.dvema.com/'
 # 数据库dyanamo品牌日志数据库

+ 1 - 1
Ansjer/formal_settings.py

@@ -39,7 +39,7 @@ AUTHENTICATION_BACKENDS = (
 )
 
 ADDR_URL = []
-ANONYMOUS_USER_ID = -1  # 支持匿名用户.....
+ANONYMOUS_USER_ID = -1  # 支持匿名用户.
 
 STATIC_URL = '/static/'
 

+ 8 - 3
Ansjer/urls.py

@@ -3,12 +3,13 @@ from django.urls import path, re_path
 
 from Controller import FeedBack, EquipmentOTA, EquipmentInfo, AdminManage, AppInfo, \
     AccessLog, DynamoDBLog, Test, MealManage, DeviceManage, EquipmentStatus, SysManage, DeviceLog, LogAccess, \
-    AppColophon, DateController,\
+    AppColophon, DateController, \
     EquipmentManager, LogManager, PermissionManager, OTAEquipment, shareUserPermission, UidSetController, \
     UserManger, CheckUserData, \
     UserController, CloudVod, OrderContrller, VodBucket, DetectController, DeviceShare, UserBrandController, \
-    StsOssController, UIDPreview, OssCrd, SysMsg, UidUser, EquipmentManagerV2,EquipmentManagerV3, PushDeploy, AppSetController,\
-    ApplicationController, UserExController, CloudStorage
+    StsOssController, UIDPreview, OssCrd, SysMsg, UidUser, EquipmentManagerV2, EquipmentManagerV3, PushDeploy, \
+    AppSetController, \
+    ApplicationController, UserExController, CloudStorage, TestApi, UserBrandControllerV2
 
 urlpatterns = [
 
@@ -202,6 +203,10 @@ urlpatterns = [
     url(r'^date/(?P<operation>.*)$', DateController.DateConView.as_view()),
 
     url(r'^equipment/flow_test$', EquipmentManager.uid_status_test),
+    url(r'^equipment/flow_test$', EquipmentManager.uid_status_test),
+    url(r'^account/appFrequency/(?P<operation>.*)$', UserController.UserAppFrequencyView.as_view()),
+    url(r'^v2/userbrand/(?P<operation>.*)$', UserBrandControllerV2.UserBrandV2.as_view()),
+    url(r'^testApi/(?P<operation>.*)$', TestApi.testView.as_view()),
     # app 设备消息模板
     # 路由加参数参考
     # url(r'^(?P<path>.*)/(?P<UID>.*)/lls$', Test.Test.as_view(), name=u'gg'),

+ 127 - 2
Controller/AdminManage.py

@@ -1,16 +1,17 @@
 # -*- coding: utf-8 -*-
+from django.db.models import Count
 from django.views.decorators.csrf import csrf_exempt
 from django.views.generic import TemplateView
 from django.utils.decorators import method_decorator
 from django.contrib.auth.hashers import make_password  # 对密码加密模块
-from Model.models import Device_Info, Role, UserExModel
+from Model.models import Device_Info, Role, UserExModel, User_Brand, UidSetModel
 from Service.ModelService import ModelService
 from django.utils import timezone
 from Model.models import Access_Log, Device_User
 from django.views.decorators.http import require_http_methods
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
-from Ansjer.config import OFF_LINE_TIME_DELTA
+from Ansjer.config import OFF_LINE_TIME_DELTA, DEVICE_TYPE
 import datetime, simplejson as json
 from Service.CommonService import CommonService
 from Object.RedisObject import RedisObject
@@ -64,6 +65,12 @@ class AdminManage(TemplateView):
             return self.getAllUID(userID, response)
         if operation == 'getAllDeviceArea':
             return self.getAllDeviceArea(userID, response)
+        if operation == 'getUserBrand':
+            return self.getUserBrand(userID, response)
+        if operation == 'getAreaDeviceType':
+            return self.getAreaDeviceType(userID, response)
+        if operation == 'getDeviceType':
+            return self.getDeviceType(userID, response)
 
     def resetUserPwd(self, request_dict, userID, response):
         own_permission = ModelService.check_perm(userID=userID, permID=50)
@@ -213,6 +220,124 @@ class AdminManage(TemplateView):
             res = {'count': uid_list.count(), 'uid_list': list(uid_list)}
         return response.json(0, res)
 
+    def getUserBrand(self, userID, response):
+        own_permission = ModelService.check_perm(userID=userID, permID=30)
+        if own_permission is not True:
+            return response.json(404)
+        # 手机型号统计
+        print('手机型号统计:')
+        ub_qs = User_Brand.objects.values('deviceSupplier', 'deviceModel').annotate(value=Count('id')).order_by()
+        res = {
+            'value': 0,
+            'data': []
+        }
+        data = res['data']
+        tmpDict = {}
+        for ub in ub_qs:
+            deviceSupplier = ub['deviceSupplier']
+            if not tmpDict.__contains__(deviceSupplier):
+                tmpDict[deviceSupplier] = {
+                    'name': deviceSupplier,
+                    'value': 0,
+                    'children': []
+                }
+
+            item = tmpDict[deviceSupplier]
+            item['value'] = item['value'] + ub['value']
+            res['value'] = res['value'] + item['value']
+            model = {
+                'name': ub['deviceModel'],
+                'value': ub['value']
+            }
+            item['children'].append(model)
+
+        for k, v in tmpDict.items():
+            data.append(v)
+
+        print(res)
+        return response.json(0, res)
+
+    def getAreaDeviceType(self, userID, response):
+        own_permission = ModelService.check_perm(userID=userID, permID=30)
+        if own_permission is not True:
+            return response.json(404)
+        print('区域设备类型统计:')
+        di_qs = Device_Info.objects.values('area', 'Type').annotate(value=Count('UID', distinct=True)).order_by()
+        res = {
+            'quantity': 0,
+            'data': []
+        }
+        data = res['data']
+        tmpDict = {}
+        tmpDict['null'] = {
+            'area': '未知',
+            'quantity': 0,
+            'models': []
+        }
+        for di in di_qs:
+            area = di['area']
+            if area is None or area == '':
+                area = 'null'
+
+            if not tmpDict.__contains__(area):
+                tmpDict[area] = {
+                    'area': area,
+                    'quantity': 0,
+                    'models': []
+                }
+
+            item = tmpDict[area]
+            item['quantity'] = item['quantity'] + di['value']
+            res['quantity'] = res['quantity'] + item['quantity']
+            model = {
+                'model': DEVICE_TYPE[di['Type']],
+                'quantity': di['value']
+            }
+            item['models'].append(model)
+
+        for k, v in tmpDict.items():
+            data.append(v)
+        return response.json(0, res)
+
+    def getDeviceType(self, userID, response):
+        own_permission = ModelService.check_perm(userID=userID, permID=30)
+        if own_permission is not True:
+            return response.json(404)
+        # 设备类型统计
+        di_qs = Device_Info.objects.values('Type').annotate(quantity=Count('UID', distinct=True)).order_by()
+
+        # 设备型号统计
+        us_qs = UidSetModel.objects.values('deviceModel').annotate(quantity=Count('id')).order_by()
+
+        res = {
+            'type_data': {
+                'quantity': 0,
+                'data': []
+            },
+            'model_data': {
+                'quantity': 0,
+                'data': []
+            }
+        }
+        type_data = res['type_data']
+        data = type_data['data']
+        quantity = 0
+        for di in di_qs:
+            di['Type'] = DEVICE_TYPE[di['Type']]
+            quantity += di['quantity']
+            data.append(di)
+        type_data['quantity'] = quantity
+
+        model_data = res['model_data']
+        data = model_data['data']
+        quantity = 0
+        for us in us_qs:
+            data.append(us)
+            quantity += us['quantity']
+        model_data['quantity'] = quantity
+
+        return response.json(0, res)
+
 
 @require_http_methods(["GET"])
 def getUserIds(request):

+ 4 - 1
Controller/CloudVod.py

@@ -18,6 +18,7 @@ import urllib
 from Object.AliPayObject import AliPayObject
 import oss2
 import paypalrestsdk
+import logging
 from aliyunsdkcore import client
 from aliyunsdksts.request.v20150401 import AssumeRoleRequest
 from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
@@ -195,6 +196,7 @@ class CloudVodView(View):
             return HttpResponseRedirect(red_url)
         return response.json(0, signature)
 
+    #发起支付宝支付
     def do_pay_by_ali(self, request_dict, userID, response):
         uid = request_dict.get('uid', None)
         rank = request_dict.get('rank', None)
@@ -247,7 +249,7 @@ class CloudVodView(View):
             redirectUrl = aliPayObj.alipay_prefix + order_string
             Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID, desc=content,
                                        price=price, currency=currency, addTime=nowTime, updTime=nowTime,
-                                       endTime=nowTime + int(day) * 3600 * 24, rank_id=rank, paypal='', payType=1)
+                                       endTime=nowTime + int(day) * 3600 * 24, rank_id=rank, payType=1)
             return JsonResponse(status=200,
                                 data={'result_code': 0, 'reason': 'success',
                                       'result': {"redirectUrl": redirectUrl, "orderID": orderID},
@@ -606,6 +608,7 @@ class CloudVodView(View):
                 else:
                     return response.json(10, '生成订单错误')
 
+    # 发起paypal支付
     def do_create_order(self, request_dict, userID, response):
         uid = request_dict.get('uid', None)
         rank = request_dict.get('rank', None)

+ 3 - 0
Controller/DetectController.py

@@ -170,6 +170,7 @@ class DetectControllerView(View):
         lang = request_dict.get('lang', 'en')
         tz = request_dict.get('tz', '0')
         # 消息提醒功能新增
+
         # 如果传空上来,就默认为0
         if tz=='':
             tz=0
@@ -208,6 +209,8 @@ class DetectControllerView(View):
 
         nowTime = int(time.time())
         if dvqs.exists():
+            # 修改状态
+            dvqs.update(NotificationMode=status)
             uid_set_qs = UidSetModel.objects.filter(uid=uid)
             # uid配置信息是否存在
 

+ 2 - 0
Controller/DeviceShare.py

@@ -167,6 +167,8 @@ class DeviceShareView(View):
                     sharerDvqs.primaryMaster = primaryMaster
                     sharerDvqs.data_joined = None
                     sharerDvqs.save()
+                    redisObj = RedisObject(db=8)
+                    redisObj.del_data(key='uid_qs_' + userID)
                 except Exception as e:
                     return response.json(10, repr(e))
                 else:

+ 104 - 4
Controller/EquipmentManager.py

@@ -224,6 +224,8 @@ def modifyUserEquipmentInterface(request):
                 }
                 UidSetModel.objects.create(**uid_set_create_dict)
             Device_Info.objects.filter(UID=uid).update(NickName=nickname)
+            redisObj = RedisObject(db=8)
+            redisObj.del_data(key='uid_qs_' + userID)
         return response.json(0, res)
 
 
@@ -369,6 +371,8 @@ def addInterface(request):
                             'nickname': NickName,
                         }
                         UidSetModel.objects.create(**uid_set_create_dict)
+                    else:
+                        us_qs.update(nickname=NickName)
                     pk = CommonService.getUserID(getUser=False)
                     userDevice = Device_Info(id=pk, userID_id=userID, UID=UID,
                                              NickName=NickName, View_Account=View_Account,
@@ -771,14 +775,28 @@ def uid_status(request):
     if tko.code != 0:
         return response.json(tko.code)
     userID = tko.userID
+
+    # 调试
+    logger = logging.getLogger('django')
+    debugOne = int(time.time())
+
     # 判断用户是否绑定设备
     qs = UidSetModel.objects.filter(uid=uid).values('uid', 'detect_status', 'detect_interval', 'version', 'ucode',
                                                     'p2p_region', 'tz', 'video_code', 'channel', 'cloud_vod', 'id',
                                                     'detect_group', 'is_alexa', 'region_alexa')
+
+    # 调试
+    debugOnes = int(time.time())
+    logger.error('————————debugOne_sec:', debugOnes - debugOne)
+
     # 判断uid配置表信息是否存在
     if qs.exists():
         # 获取uid推送是否添加过
         us_id = qs[0]['id']
+
+        # 调试
+        debugTwo = int(time.time())
+
         if UidPushModel.objects.filter(uid_set_id=us_id, userID_id=userID).exists():
             detect_status = qs[0]['detect_status']
         else:
@@ -797,9 +815,22 @@ def uid_status(request):
             'is_alexa': qs[0]['is_alexa'],  # 推送组
             'region_alexa': qs[0]['region_alexa'],  # 推送组
         }
+
+        # 调试
+        debugTwos = int(time.time())
+        logger.error('————————debugTwo_sec:', debugTwos - debugTwo)
+
+        # 调试
+        debugThere = int(time.time())
+
         # 查询云存储相关信息
         ubqs = UID_Bucket.objects.filter(uid=uid). \
             values('bucket__content', 'status', 'channel', 'endTime', 'uid')
+
+        # 调试
+        debugTheres = int(time.time())
+        logger.error('————————debugTheres_sec:', debugTheres - debugThere)
+
         nowTime = int(time.time())
         if ubqs.exists():
             if ubqs[0]['endTime'] > nowTime:
@@ -808,6 +839,63 @@ def uid_status(request):
     else:
         return response.json(0)
 
+def uid_status_test(request):
+    request.encoding = 'utf-8'
+    response = ResponseObject()
+    if request.method == 'POST':
+        request_dict = request.POST
+    elif request.method == 'GET':
+        request_dict = request.GET
+    else:
+        return response.json(444)
+    token = request_dict.get('token', None)
+    uid = request_dict.get('uid', None)
+    tko = TokenObject(token)
+    response.lang = tko.lang
+    if tko.code != 0:
+        return response.json(tko.code)
+    userID = tko.userID
+    # 判断用户是否绑定设备
+    print(100000000000)
+    qs = UidSetModel.objects.filter(uid=uid).values('uid', 'detect_status', 'detect_interval', 'version', 'ucode',
+                                                    'p2p_region', 'tz', 'video_code', 'channel', 'cloud_vod', 'id',
+                                                    'detect_group', 'is_alexa', 'region_alexa')
+    # 判断uid配置表信息是否存在
+    if qs.exists():
+        # 获取uid推送是否添加过
+        print(1111111111111)
+        us_id = qs[0]['id']
+        if UidPushModel.objects.filter(uid_set_id=us_id, userID_id=userID).exists():
+            detect_status = qs[0]['detect_status']
+        else:
+            detect_status = 0
+        data = {
+            'push_status': detect_status,  # 推送状态
+            'push_interval': qs[0]['detect_interval'],  # 推送间隔
+            'ucode': qs[0]['ucode'],
+            'version': qs[0]['version'],
+            'p2p_region': qs[0]['p2p_region'],
+            'tz': qs[0]['tz'],
+            'video_code': qs[0]['video_code'],
+            'channel': qs[0]['channel'],
+            'cloud_vod': qs[0]['cloud_vod'],
+            'detect_group': qs[0]['detect_group'],  # 推送组
+            'is_alexa': qs[0]['is_alexa'],  # 推送组
+            'region_alexa': qs[0]['region_alexa'],  # 推送组
+        }
+        print(22222222222)
+        # 查询云存储相关信息
+        ubqs = UID_Bucket.objects.filter(uid=uid). \
+            values('bucket__content', 'status', 'channel', 'endTime', 'uid')
+        nowTime = int(time.time())
+        if ubqs.exists():
+            if ubqs[0]['endTime'] > nowTime:
+                data['vod'] = list(ubqs)
+        print(3333333333333)
+        return response.json(0, data)
+    else:
+        return response.json(0)
+
 def uid_status_test(request):
     request.encoding = 'utf-8'
     response = ResponseObject()
@@ -864,6 +952,7 @@ def uid_status_test(request):
     else:
         return response.json(0)
 
+
 def update_uid_set(request):
     request.encoding = 'utf-8'
     response = ResponseObject()
@@ -925,9 +1014,10 @@ def update_device_shadow(request):
         request_dict = request.GET
     else:
         return response.json(444)
-    etk = request_dict.get('etk', None)
-    eto = ETkObject(etk)
-    uid = eto.uid
+    # etk = request_dict.get('etk', None)
+    # eto = ETkObject(etk)
+    # uid = eto.uid
+    uid = request_dict.get('uid', None)
     if uid:
         # 重置按钮
         is_reset = request_dict.get('is_reset', None)
@@ -935,7 +1025,17 @@ def update_device_shadow(request):
         if is_reset == '1':
             UidSetModel.objects.filter(uid=uid).delete()
             # 重置设备,判断设备为已删除
-            Device_Info.objects.filter(UID=uid).update(isExist=2)
+            di_qs = Device_Info.objects.filter(UID=uid)
+            di_qs.update(isExist=2)
+            # 清除redis缓存
+            data = di_qs.values()
+            redisObj = RedisObject(db=8)
+            for di in data:
+                key = 'uid_qs_' + di['userID_id']
+                redis_value = redisObj.get_data(key=key)
+                if redis_value is not False:
+                    redisObj.del_data(key)
+
         ucode = request_dict.get('ucode', None)
         version = request_dict.get('version', None)
         p2p_region = request_dict.get('p2p_region', None)

+ 2 - 0
Controller/EquipmentManagerV2.py

@@ -86,6 +86,8 @@ class EquipmentManagerV2(View):
                                 'nickname': NickName,
                             }
                             UidSetModel.objects.create(**uid_set_create_dict)
+                        else:
+                            us_qs.update(nickname=NickName)
                         pk = CommonService.getUserID(getUser=False)
                         userDevice = Device_Info(id=pk, userID_id=userID, UID=UID,
                                                  NickName=NickName, View_Account=View_Account,

+ 118 - 40
Controller/EquipmentManagerV3.py

@@ -8,7 +8,7 @@ from django.db.models import Q
 from django.views.generic.base import View
 from Object.RedisObject import RedisObject
 from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY
-from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidPushModel
+from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidPushModel, UidChannelSetModel
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
 from Service.CommonService import CommonService
@@ -89,6 +89,8 @@ class EquipmentManagerV3(View):
                                 'nickname': NickName,
                             }
                             UidSetModel.objects.create(**uid_set_create_dict)
+                        else:
+                            us_qs.update(nickname=NickName)
                         pk = CommonService.getUserID(getUser=False)
                         userDevice = Device_Info(id=pk, userID_id=userID, UID=UID,
                                                  NickName=NickName, View_Account=View_Account,
@@ -135,8 +137,9 @@ class EquipmentManagerV3(View):
             return response.json(309)
         try:
             deviceData = json.loads(deviceContent)
-            print(deviceData['View_Password'])
-            deviceData['View_Password'] = self.decode_pwd(deviceData['View_Password'])
+            # print(deviceData['View_Password'])
+            if deviceData.__contains__('View_Password'):
+                deviceData['View_Password'] = self.decode_pwd(deviceData['View_Password'])
             dev_info_qs = Device_Info.objects.filter(userID_id=userID, id=id)
             dev_info_qs.update(**deviceData)
         except Exception as e:
@@ -164,9 +167,10 @@ class EquipmentManagerV3(View):
                     }
                     UidSetModel.objects.create(**uid_set_create_dict)
                 Device_Info.objects.filter(UID=uid).update(NickName=nickname)
-                redisObj = RedisObject(db=8)
-                redisObj.del_data(key='uid_qs_' + userID)
+            redisObj = RedisObject(db=8)
+            redisObj.del_data(key='uid_qs_' + userID)
             return response.json(0, res)
+
     # 新查询设备字段
     def do_query(self, userID, request_dict, response):
         token = request_dict.get('token', None)
@@ -183,6 +187,7 @@ class EquipmentManagerV3(View):
         if tko.code == 0:
             redisObj = RedisObject(db=8)
             redis_value = redisObj.get_data(key='uid_qs_'+userID)
+            result = []
             if redis_value == False:
                 # print('缓存不存在就开始添加到缓存')
                 userID = tko.userID
@@ -192,8 +197,7 @@ class EquipmentManagerV3(View):
                 dvql = dvqs.values('id', 'userID', 'NickName', 'UID', 'View_Account',
                            'View_Password', 'ChannelIndex', 'Type', 'isShare',
                            'primaryUserID', 'primaryMaster', 'data_joined',
-                           'version',
-                           'isVod', 'isExist', 'NotificationMode')
+                           'version', 'isVod', 'isExist', 'NotificationMode')
                 dvls = CommonService.qs_to_list(dvql)
                 uid_list = []
                 for dvl in dvls:
@@ -206,10 +210,57 @@ class EquipmentManagerV3(View):
                 nowTime = int(time.time())
                 data = []
                 # 设备拓展信息表
-                us_qs = UidSetModel.objects.filter(uid__in=uid_list).values('uid', 'version', 'nickname','ucode')
+                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']}
+                    uv_dict[us['uid']] = {
+                        'version': us['version'],
+                        'nickname': us['nickname'],
+                        'ucode': us['ucode'],
+                        'detect_interval': us['detect_interval'],
+                        'detect_group': us['detect_group'],
+                        'detect_status': us['detect_status'],
+                        'region_alexa': us['region_alexa'],
+                        'is_alexa': us['is_alexa'],
+                        'deviceModel': us['deviceModel'],
+                        'TimeZone': us['TimeZone'],
+                        'TimeStatus': us['TimeStatus'],
+                        'SpaceUsable': us['SpaceUsable'],
+                        'SpaceSum': us['SpaceSum'],
+                        'MirrorType': us['MirrorType'],
+                        'RecordType': us['RecordType'],
+                        'OutdoorModel': us['OutdoorModel'],
+                        'WIFIName': us['WIFIName'],
+                        'isDetector': us['isDetector'],
+                        'DetectorRank': us['DetectorRank']
+                    }
+                    # 从uid_channel里面取出通道配置信息
+                    ucs_qs = UidChannelSetModel.objects.filter(uid__id=us['id']).values()
+                    channels = []
+                    for ucs in ucs_qs:
+                        channel = {
+                            'channel': ucs['channel'],
+                            'pir_audio': ucs['pir_audio'],
+                            'mic_audio': ucs['mic_audio'],
+                            'battery_status': ucs['battery_status'],
+                            'battery_level': ucs['battery_level'],
+                            'sleep_status': ucs['sleep_status'],
+                            'sleep_time': ucs['sleep_time'],
+                            'light_night_model': ucs['light_night_model'],
+                            'light_alarm_type': ucs['light_alarm_type'],
+                            'light_alarm_level': ucs['light_alarm_level'],
+                            'light_alarm_man_en': ucs['light_alarm_man_en'],
+                            'light_alarm_vol': ucs['light_alarm_vol'],
+                            'light_long_light': ucs['light_long_light']
+                        }
+                        channels.append(channel)
+                    uv_dict[us['uid']]['channels'] = channels
+
                 for p in dvls:
                     p['vod'] = []
                     for dm in ubqs:
@@ -227,6 +278,23 @@ class EquipmentManagerV3(View):
                         # 设备版本号
                         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']
@@ -237,52 +305,62 @@ class EquipmentManagerV3(View):
                     data.append(p)
                 # 缓存时间为一个钟
                 redisObj.set_data(key='uid_qs_'+userID, val=data, expire=3600)
+                result = data
                 print('分页')
-                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)
+                # 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)
             else:
                 # print('去缓存找数据')
                 redis_value = redis_value.replace("'", '"')
                 redis_value = redis_value.replace('"isShare": True', '"isShare": true')
                 redis_value = redis_value.replace('"isShare": False', '"isShare": false')
+                redis_value = redis_value.replace('"isDetector": False', '"isDetector": false')
+                redis_value = redis_value.replace('"isDetector": True', '"isDetector": true')
                 redis_value = redis_value.replace('"version": None', '"version": ""')
                 try:
                     redis_value = json.loads(redis_value)
                 except Exception as e:
                     print(repr(e))
                     return response.json(0, {'data': redis_value})
-                if NickName:
-                    # print('NickName搜索缓存')
-                    for index, item in enumerate(redis_value):
-                        if NickName ==item['NickName']:
-                            # 加密
-                            item['View_Password'] = self.encrypt_pwd(item['View_Password'])
-                            return response.json(0, item)
-                if uid:
-                    # print('uid搜索缓存')
-                    for index, item in enumerate(redis_value):
-                        if uid == item['UID']:
-                            # 加密
-                            item['View_Password'] = self.encrypt_pwd(item['View_Password'])
-                            return response.json(0, item)
-                items = []
-                # print('缓存分页')
-                for index, item in enumerate(redis_value):
-                    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)
+                result = redis_value
+
+            if NickName:
+                # print('NickName搜索缓存')
+                data = []
+                for index, item in enumerate(result):
+                    if NickName == item['NickName']:
+                        # 加密
+                        item['View_Password'] = self.encrypt_pwd(item['View_Password'])
+                        data.append(item)
+                        return response.json(0, data)
+            if uid:
+                # print('uid搜索缓存')
+                data = []
+                for index, item in enumerate(result):
+                    if uid == item['UID']:
+                        # 加密
+                        item['View_Password'] = self.encrypt_pwd(item['View_Password'])
+                        data.append(item)
+                        return response.json(0, data)
+            items = []
+            # print('缓存分页')
+            for index, item in enumerate(result):
+                if (page - 1) * line <= index:
+                    if index < page * line:
+                        # 加密
+                        item['View_Password'] = self.encrypt_pwd(item['View_Password'])
+                        print(item)
+                        items.append(item)
+            print(items)
+            return response.json(0, items)
         else:
             return response.json(tko.code)
 
-
     # 加密
     def encrypt_pwd(self,userPwd):
         for i in range(1, 4):

+ 674 - 0
Controller/TestApi.py

@@ -0,0 +1,674 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
+@AUTHOR: ASJRD018
+@NAME: Ansjer
+@software: PyCharm
+@DATE: 2018/5/22 13:58
+@Version: python3.6
+@MODIFY DECORD:ansjer dev
+@file: Test.py
+@Contact: chanjunkai@163.com
+"""
+from django.views.generic.base import View
+import os
+
+'''
+http://192.168.136.40:8077/Test
+'''
+import json
+import math
+import time
+import urllib
+from Object.AliPayObject import AliPayObject
+import logging
+import boto3
+from boto3.session import Session
+from botocore.exceptions import ClientError
+import oss2
+import paypalrestsdk
+import logging
+from aliyunsdkcore import client
+from aliyunsdksts.request.v20150401 import AssumeRoleRequest
+from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
+from django.utils.decorators import method_decorator
+from django.views.decorators.csrf import csrf_exempt
+from django.views.generic.base import View
+
+from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, OSS_ROLE_ARN, SERVER_DOMAIN, PAYPAL_CRD, \
+    SERVER_DOMAIN_SSL
+from Model.models import Device_Info, Order_Model, Store_Meal, VodHlsModel, OssCrdModel, UID_Bucket
+from Object.ResponseObject import ResponseObject
+from Object.TokenObject import TokenObject
+from Object.UidTokenObject import UidTokenObject
+from Service.CommonService import CommonService
+from Service.ModelService import ModelService
+from Object.m3u8generate import PlaylistGenerator
+from Model.models import Device_User, Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidPushModel
+
+
+
+SERVER_DOMAIN = 'http://test.dvema.com/'
+ACCESS_KEY = "AKIA2E67UIMD3CYTIWPA"
+SECRET_KEY = "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"
+
+
+# 测试接口sdk
+class testView(View):
+    @method_decorator(csrf_exempt)
+    def dispatch(self, *args, **kwargs):
+        return super(testView, self).dispatch(*args, **kwargs)
+
+    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()
+        # operation => cloudVod/path
+        if operation is None:
+            return response.json(444, 'error path')
+        elif operation == 'tests':
+            userID  = '158943594633713800138000'
+            return self.do_filter_playlist(request_dict, userID, response)
+        elif operation == 'cbu':
+            return self.createBucket()
+        elif operation == 'vodList':
+            ip = CommonService.get_ip_address(request)
+            userID = '158943594633713800138000'
+            return self.do_test_query_vod_list(userID, ip, request_dict, response)
+        elif operation == 'signplaym3u8':
+            return self.do_sign_play_m3u8(request_dict, response)
+        elif operation == 'get_sign_sts':
+            ip = CommonService.get_ip_address(request)
+            return self.do_test_get_sign_sts(request_dict, ip, response)
+        elif operation == 'eqi_query':
+            userID = '158943594633713800138000'
+            return self.queryInterface(request_dict, userID, response)
+        else:
+            return 12344444
+
+    def createBucket(self):
+
+
+        #查看桶列表
+        # url = "https://azvod1.s3-ap-northeast-1.amazonaws.com"
+        # session = Session(ACCESS_KEY, SECRET_KEY)
+        # s3_client = session.client('s3', endpoint_url=url)
+        # results = s3_client.list_buckets()
+        # return JsonResponse(status=200, data={'code': 200, 'msg': results['Buckets']})
+
+        # Create bucket
+        session = Session(ACCESS_KEY, SECRET_KEY)
+        s3_client = session.client('s3')
+
+        #上传
+        # s3_client.put_object(Bucket="azvod1", Key="file/rule.txt", Body=open(r"E:\download\Shadowsocks-4.1.10.0\user-rule.txt", 'rb').read())
+
+        #下载
+        resp = s3_client.get_object(Bucket="azvod1", Key="file/rule.txt")
+        with open('local.txt', 'wb') as f:
+            f.write(resp['Body'].read())
+
+    # 新查询设备字段
+    def queryInterface(self, request_dict, userID, response):
+        page = request_dict.get('page', None)
+        line = request_dict.get('line', None)
+        NickName = request_dict.get('NickName', None)
+        uid = request_dict.get('uid', None)
+        page = int(page)
+        line = int(line)
+        response.lang = 'cn'
+        userID = userID
+        dvqs = Device_Info.objects.filter(userID_id=userID)
+        # # 已重置的设备
+        # dvqs = dvqs.filter(~Q(isExist=2))
+        if NickName:
+            dvqs = dvqs.filter(NickName__icontains=NickName)
+        if uid:
+            dvqs = dvqs.filter(UID=uid)
+        # count = dvqs.count()
+        #分页
+        dvql = dvqs[(page - 1) * line:page * line].values('id', 'userID', 'NickName', 'UID', 'View_Account',
+                                                          'View_Password', 'ChannelIndex', 'Type', 'isShare',
+                                                          'primaryUserID', 'primaryMaster', 'data_joined',
+                                                          'version',
+                                                          'isVod', 'isExist', 'NotificationMode')
+        dvls = CommonService.qs_to_list(dvql)
+        uid_list = []
+        for dvl in dvls:
+            uid_list.append(dvl['UID'])
+            # if dvl['isShare'] is False:
+            #     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('uid', 'version', 'nickname', 'detect_interval')
+        uv_dict = {}
+        for us in us_qs:
+            uv_dict[us['uid']] = {'version': us['version'],
+                                  'nickname': us['nickname'],
+                                  'detect_interval': us['detect_interval']}
+        for p in dvls:
+            p['vod'] = []
+            for dm in ubqs:
+                if p['UID'] == dm['uid']:
+                    if dm['endTime'] > nowTime:
+                        p['vod'].append(dm)
+            p['preview'] = []
+            for up in upqs:
+                if p['UID'] == up['uid']:
+                    obj = 'uid_preview/{uid}/channel_{channel}.png'. \
+                        format(uid=up['uid'], channel=up['channel'])
+                    img_sign = bucket.sign_url('GET', obj, 300)
+                    p['preview'].append(img_sign)
+            p_uid = p['UID']
+            if p_uid in uv_dict:
+                # 设备版本号
+                p['uid_version'] = uv_dict[p_uid]['version']
+                p['detect_interval'] = uv_dict[p_uid]['detect_interval']
+                # 设备昵称 调用影子信息昵称,先阶段不可
+                if uv_dict[p_uid]['nickname']:
+                    p['NickName'] = uv_dict[p_uid]['nickname']
+            else:
+                # 设备版本号
+                p['uid_version'] = ''
+            data.append(p)
+        return response.json(0, data)
+
+
+    #获取播放列表
+    def do_test_query_vod_list(self, userID, ip, request_dict, response):
+        uid = 'GZL2PEFJPLY7W6BG111A'
+        channel = 2
+        userID = '158943594633713800138000'
+        dv_qs = Device_Info.objects.filter(UID=uid, userID_id=userID, isShare=False)
+        if not dv_qs.exists():
+            return response.json(12)
+        vod_play_list = []
+        bucket_name = 'azvod1'
+        aws_access_key_id = 'AKIA2E67UIMD45Y3HL53'
+        aws_secret_access_key = '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'
+        session = Session(
+            aws_access_key_id=aws_access_key_id,
+            aws_secret_access_key=aws_secret_access_key,
+            region_name='ap-northeast-1'
+        )
+        conn = session.client('s3')
+        thumbspng = '{uid}/vod{channel}/{time}/thumbs.png'. \
+            format(uid=uid, channel=channel, time=1590485548)
+        response_url = conn.generate_presigned_url(
+            'get_object',
+            Params={
+                'Bucket': bucket_name,
+                'Key': thumbspng
+            },
+            ExpiresIn=3600
+        )
+        # m3u8 = '{uid}/vod{channel}/{time}/{time}.m3u8'. \
+        #     format(uid=uid, channel=channel, time=vod['time'])
+        thumb_url = response_url
+        vod_url = 'http://192.168.136.191:8000/testApi/signplaym3u8?' \
+                  'uid={uid}&channel={channel}&time={time}&sign=tktktktk'. \
+            format(ip=ip, uid=uid, channel=channel, time=1590485548)
+        vod_play_list.append({
+            'name': 1590485548,
+            'sign_url': vod_url,
+            'thumb': thumb_url,
+            'sec': 12})
+        return response.json(0, vod_play_list)
+
+    #生成m3u8列表
+    def do_sign_play_m3u8(self, request_dict, response):
+        uid = 'GZL2PEFJPLY7W6BG111A'
+        channel = 2
+        storeTime = 1591344070
+        fg = 6
+        bucket__region = 'ap-northeast-1'
+        bucket_name = 'azvod1'
+        aws_access_key_id = 'AKIA2E67UIMD45Y3HL53'
+        aws_secret_access_key = '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'
+        session = Session(
+            aws_access_key_id=aws_access_key_id,
+            aws_secret_access_key=aws_secret_access_key,
+            region_name=bucket__region
+        )
+        '''
+            http://test.dvema.com/cloudstorage/signplaym3u8?uid=VVDHCVBYDKFMJRWA111A&channel=1&time=1586940120&sign=tktktktk
+        '''
+        conn = session.client('s3')
+        playlist_entries = []
+
+        for i in range(fg):
+            thumbspng = '{uid}/vod{channel}/{time}/ts{i}.ts'. \
+                format(uid=uid, channel=channel, time=storeTime, i=i)
+            response_url = conn.generate_presigned_url(
+                'get_object',
+                Params={
+                    'Bucket': bucket_name,
+                    'Key': thumbspng
+                },
+                ExpiresIn=86400
+            )
+            # m3u8 = '{uid}/vod{channel}/{time}/{time}.m3u8'. \
+            #     format(uid=uid, channel=channel, time=vod['time'])
+            playlist_entries.append({
+                'name': response_url,
+                'duration': 10,
+            })
+        playlist = PlaylistGenerator(playlist_entries).generate()
+        response = HttpResponse(playlist)
+        response['Content-Type'] = 'application/octet-stream'
+        response['Content-Disposition'] = 'attachment;filename="play.m3u8"'
+        return response
+
+        # return HttpResponse(playlist)
+        # response = HttpResponse(playlist, content_type="application/vnd.apple.mpegurl")
+        # # response = HttpResponse(playlist, content_type="application/octet-stream")
+        # return response
+        # return HttpResponse(status=200, content=playlist)
+
+    def do_test_get_sign_sts(self, request_dict, ip, response):
+        # uid = 'GZL2PEFJPLY7W6BG111A'
+        # channel = 2
+        uid = 'VVDHCVBYDKFMJRWA111A'
+        channel = 1
+        now_time = int(time.time())
+        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)
+            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)]
+                        }
+                    ]
+                }
+                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")
+
+    def do_get_sign_sts(self, request_dict, ip, response):
+        # uid = 'GZL2PEFJPLY7W6BG111A'
+        # channel = 2
+        uid = 'VVDHCVBYDKFMJRWA111A'
+        channel = 1
+        now_time = int(time.time())
+        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)
+            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)]
+                        }
+                    ]
+                }
+                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")
+
+
+
+
+    def do_pay_by_ali(self, request_dict, userID, response):
+        uid = request_dict.get('uid', None)
+        rank = request_dict.get('rank', None)
+        channel = request_dict.get('channel', None)
+        qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False)
+        if not qs.exists():
+            return response.json(12)
+        if not channel or not rank:
+            return response.json(444, 'channel,rank')
+        smqs = Store_Meal.objects.filter(id=rank). \
+            values("currency", "price", "content", "day", "bucket__storeDay", "bucket__region", "type")
+        if not smqs.exists():
+            # 套餐不存在
+            return response.json(173)
+        if smqs[0]['type'] != 1:
+            return response.json(10, '不支持支付宝支付')
+        currency = smqs[0]['currency']
+        price = smqs[0]['price']
+        content = smqs[0]['content']
+        day = smqs[0]['day']
+        nowTime = int(time.time())
+        ubqs = UID_Bucket.objects.filter(uid=uid, channel=channel, endTime__gte=nowTime). \
+            values("bucket__storeDay", "bucket__region")
+        if ubqs.exists():
+            if ubqs[0]['bucket__region'] != smqs[0]['bucket__region']:
+                return response.json(712)  # 区域不一致
+            elif ubqs[0]['bucket__storeDay'] != smqs[0]['bucket__storeDay']:
+                return response.json(713)  # 不可更改套餐
+            # 续费流程
+        nowTime = int(time.time())
+        # 新增流程
+        orderID = CommonService.createOrderID()
+
+        try:
+            aliPayObj = AliPayObject()
+            alipay = aliPayObj.conf()
+            order_string = alipay.api_alipay_trade_wap_pay(
+                out_trade_no=orderID,
+                total_amount=price,
+                subject="测试哟",
+                return_url="{SERVER_DOMAIN_SSL}cloudVod/payOK".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL),
+                notify_url="{SERVER_DOMAIN_SSL}cloudVod/aliPayCallback".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
+                # return_url="http://192.168.136.40/cloudVod/payOK",
+                # notify_url="http://192.168.136.40/cloudVod/aliPayCallback"
+            )
+        except Exception as e:
+            print(repr(e))
+            return response.json(10, repr(e))
+        if order_string:
+            redirectUrl = aliPayObj.alipay_prefix + order_string
+            Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID, desc=content,
+                                       price=price, currency=currency, addTime=nowTime, updTime=nowTime,
+                                       endTime=nowTime + int(day) * 3600 * 24, rank_id=rank, payType=1)
+            return JsonResponse(status=200,
+                                data={'result_code': 0, 'reason': 'success',
+                                      'result': {"redirectUrl": redirectUrl, "orderID": orderID},
+                                      'error_code': 0})
+        else:
+            return response.json(10, '生成订单错误')
+
+    def do_filter_playlist(self, request_dict, userID, response):
+        startTime = int(request_dict.get('startTime', None))
+        endTime = int(request_dict.get('endTime', None))
+        uid = request_dict.get('uid', None)
+        channel = request_dict.get('channel', None)
+        dvqs = Device_Info.objects.filter(UID=uid, userID_id=userID, isShare=False)
+        if not dvqs.exists():
+            return response.json(12)
+        ubqs = UID_Bucket.objects.filter(uid=uid, channel=channel).values('status')
+        if not ubqs.exists():
+            return response.json(10, '设备未购买')
+        nowTime = int(time.time())
+        # vodqs = VodHlsModel.objects.filter(uid=uid, channel=channel, time__range=(startTime, endTime),
+        #                                    endTime__gte=nowTime) \
+        #     .values("time", "sec", "bucket__bucket", "bucket__endpoint", "bucket__region")
+        vodqs = VodHlsModel.objects.filter(uid=uid, channel=channel) \
+            .values("time", "sec", "bucket__bucket", "bucket__endpoint", "bucket__region")
+        vod_play_list = []
+        print(vodqs)
+        auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
+        for vod in vodqs:
+            bucket_name = vod["bucket__bucket"]
+            endpoint = vod["bucket__endpoint"]
+            bucket = oss2.Bucket(auth, endpoint, bucket_name)
+            m3u8 = '{uid}/vod{channel}/{time}/{time}.m3u8'. \
+                format(uid=uid, channel=channel, time=vod['time'])
+            ts = '{uid}/vod{channel}/{time}/ts0.ts'. \
+                format(uid=uid, channel=channel, time=vod['time'])
+            url = bucket.sign_url('GET', m3u8, 3600, params={'x-oss-process': 'hls/sign'})
+            urllst = url.split('?')
+            url_start = urllib.parse.unquote(urllst[0])
+            url_end = urllst[1]
+            vod_play_url = '{url_start}?{url_end}'. \
+                format(url_start=url_start, url_end=url_end)
+            thumb = bucket.sign_url('GET', ts, 3600,
+                                    params={'x-oss-process': 'video/snapshot,t_10000,m_fast,w_300'})
+            vod_play_list.append({'name': vod['time'], 'sign_url': vod_play_url, 'thumb': thumb, 'sec': vod['sec']})
+        return response.json(0, vod_play_list)
+
+

+ 146 - 9
Controller/UidSetController.py

@@ -13,6 +13,9 @@
 """
 import time
 import traceback
+
+from django.db.models import Count
+
 from Object.RedisObject import RedisObject
 import simplejson as json
 from django.utils.decorators import method_decorator
@@ -20,7 +23,7 @@ from django.views.decorators.csrf import csrf_exempt
 from django.views.generic.base import View
 
 from Model.models import UidSetModel, Device_User, Device_Info, UidPushModel, Equipment_Info, UID_Preview, UID_Bucket, \
-    VodHlsModel, Order_Model, OssCrdModel,UidUserModel
+    VodHlsModel, Order_Model, OssCrdModel, UidUserModel, UidChannelSetModel, User_Brand
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
 from Service.CommonService import CommonService
@@ -80,6 +83,12 @@ class UidSetView(View):
             return self.do_admin_update(request_dict, userID, response)
         elif operation == 'update':
             return self.do_update(request_dict, response)
+        elif operation == 'updateSet':
+            return self.do_update_set(request, request_dict, response)
+        elif operation == 'updateChannel':
+            return self.do_update_channel_set(request_dict, response)
+        # elif operation == 'test':
+        #     return self.do_test(response)
         else:
             return response.json(444, 'error path')
 
@@ -190,16 +199,16 @@ class UidSetView(View):
                     else:
                         val = val + 1
                         print('UidUserModel表没有数据')
-                #有后台管理 设备配置表UidSetModel ---uid --本身,
-                #有后台管理 设备关联用户推送表Equipment_Info --devUid --独立没有儿子的,
-                #有后台管理             设备预览图表UID_Preview ---uid---孤立,
-                #有后台管理 设备关联套餐表UID_Bucket ---uid---孤立,
-                #有后台管理            云存回放信息表VodHlsModel ---uid---孤立,
-                #有后台管理 订单信息表Order_Model --UID----独立没有儿子的,
-                #有后台管理 用户设备信息表(最多信息量的表)Device_Info ---UID---孤立,
+                # 有后台管理 设备配置表UidSetModel ---uid --本身,
+                # 有后台管理 设备关联用户推送表Equipment_Info --devUid --独立没有儿子的,
+                # 有后台管理             设备预览图表UID_Preview ---uid---孤立,
+                # 有后台管理 设备关联套餐表UID_Bucket ---uid---孤立,
+                # 有后台管理            云存回放信息表VodHlsModel ---uid---孤立,
+                # 有后台管理 订单信息表Order_Model --UID----独立没有儿子的,
+                # 有后台管理 用户设备信息表(最多信息量的表)Device_Info ---UID---孤立,
                 #           设备证书OssCrdModel ---uid---孤立
                 # 有后台管理 设备ap表 UidUserModel
-                #设备绑定UidPushModel---关联表---设备配置表UidSetModel---配置表的详情有显示
+                # 设备绑定UidPushModel---关联表---设备配置表UidSetModel---配置表的详情有显示
 
                 # raise DatabaseError     #测试用,检测是否能捕捉错误
                 if val == 9:
@@ -312,3 +321,131 @@ class UidSetView(View):
         except Exception:
             errorInfo = traceback.format_exc()
             return response.json(500, {'details': errorInfo})
+
+    def do_update_set(self, request, request_dict, response):
+        uid = request_dict.get('uid', None)
+        deviceContent = request_dict.get('content', None)
+        token = request_dict.get('token', None)
+        # print(deviceContent)
+        if not deviceContent or not uid:
+            return response.json(444, 'content,uid')
+        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:
+            redisObj = RedisObject(db=8)
+            redisObj.del_data(key='uid_qs_' + userID)
+            deviceData = json.loads(deviceContent)
+            uid_set_qs = UidSetModel.objects.filter(uid=uid)
+            if not uid_set_qs.exists():
+                # 由于uid_set表和device_info表设备数量不一致,所以添加以下逻辑把device_info表中的相关信息保存到uid_set表
+                di_qs = Device_Info.objects.filter(UID=uid, userID=userID)
+                if di_qs.exists():
+                    di = di_qs[0]
+                    nowTime = int(time.time())
+                    uid_set_create_dict = {
+                        'uid': di.UID,
+                        'addTime': nowTime,
+                        'updTime': nowTime,
+                        'ip': CommonService.get_ip_address(request),
+                        'channel': di.ChannelIndex,
+                        'nickname': di.NickName,
+                    }
+                    for k, v in deviceData.items():
+                        uid_set_create_dict[k] = v
+                    UidSetModel.objects.create(**uid_set_create_dict)
+                else:
+                    return response.json(177)
+            else:
+                uid_set_qs.update(**deviceData)
+            print('update success')
+        except Exception as e:
+            return response.json(177, repr(e))
+        else:
+            return response.json(0)
+
+    def do_update_channel_set(self, request_dict, response):
+        uid = request_dict.get('uid', None)
+        channel = request_dict.get('channel', None)
+        channelContent = request_dict.get('content', None)
+        token = request_dict.get('token', None)
+        print(channelContent)
+        if not channelContent or not uid or not channel:
+            return response.json(444, 'content,uid, chan')
+        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)
+
+        channel = int(channel)
+        if channel < 1:
+            return response.json(444, 'channel')
+        try:
+            redisObj = RedisObject(db=8)
+            redisObj.del_data(key='uid_qs_' + userID)
+            deviceData = json.loads(channelContent)
+            uid_channel_set_qs = UidChannelSetModel.objects.filter(uid__uid=uid, channel=channel)
+            if not uid_channel_set_qs.exists():
+                uidObject = UidSetModel.objects.filter(uid=uid)
+                ucs = {
+                    'channel': channel,
+                    'uid': uidObject[0]
+                }
+                keys = deviceData.keys()
+                for key in keys:
+                    ucs[key] = deviceData[key]
+                UidChannelSetModel.objects.create(**ucs)
+            else:
+                uid_channel_set_qs.update(**deviceData)
+
+        except Exception as e:
+            return response.json(177, repr(e))
+        else:
+            return response.json(0)
+
+    # def do_test(self, response):
+    #     di_qs = Device_Info.objects.values('Type').annotate(c=Count('UID', distinct=True)).order_by()
+    #     for di in di_qs:
+    #         print(di)
+    #
+    #     # 设备总数量
+    #     count = Device_Info.objects.values('UID').distinct().count()
+    #     print('设备总数量:' + str(count))
+    #
+    #     # 设备型号统计
+    #     print('设备型号统计:')
+    #     us_qs = UidSetModel.objects.values('deviceModel').annotate(c=Count('id')).order_by()
+    #     for us in us_qs:
+    #         print(us)
+    #
+    #     # 手机品牌类型统计
+    #     print('手机品牌类型统计:')
+    #     ub_qs = User_Brand.objects.values('deviceSupplier').annotate(c=Count('id')).order_by()
+    #     for ub in ub_qs:
+    #         print(ub)
+    #
+    #     # 手机型号统计
+    #     print('手机型号统计:')
+    #     ub_qs = User_Brand.objects.values('deviceSupplier', 'deviceModel').annotate(c=Count('id')).order_by()
+    #     for ub in ub_qs:
+    #         print(ub)
+    #
+    #     # 区域统计
+    #     print('区域统计:')
+    #     di_qs = Device_Info.objects.values('area').annotate(c=Count('UID', distinct=True)).order_by()
+    #     for di in di_qs:
+    #         print(di)
+    #
+    #     # 区域设备类型统计
+    #     print('区域设备类型统计:')
+    #     di_qs = Device_Info.objects.values('area', 'Type').annotate(c=Count('UID', distinct=True)).order_by()
+    #     for di in di_qs:
+    #         print(di)
+    #     return response.json(0)

+ 88 - 0
Controller/UserBrandControllerV2.py

@@ -0,0 +1,88 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+from django.utils.decorators import method_decorator
+from django.views.decorators.csrf import csrf_exempt
+from django.views.generic.base import View
+
+from Model.models import User_Brand, Device_User
+from Object.ResponseObject import ResponseObject
+from Object.TokenObject import TokenObject
+
+
+class UserBrandV2(View):
+    @method_decorator(csrf_exempt)
+    def dispatch(self, *args, **kwargs):
+        return super(UserBrandV2, self).dispatch(*args, **kwargs)
+
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation')
+        request_dict = request.GET
+        return self.validate(request_dict, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation')
+        request_dict = request.POST
+        return self.validate(request_dict, operation)
+
+    def validate(self, request_dict, operation):
+        token = request_dict.get('token', None)
+
+        response = ResponseObject()
+        token = TokenObject(token)
+
+        if token.code != 0:
+            return response.json(token.code)
+
+        if operation == 'add':
+            return self.do_add(token.userID, request_dict, response)
+        elif operation == 'query':
+            return self.do_query(token.userID, request_dict, response)
+        else:
+            return response.json(404)
+
+    def do_add(self, userID, request_dict, response):
+        deviceSupplier = request_dict.get('deviceSupplier', None)
+        deviceModel = request_dict.get('deviceModel', None)
+        osType = request_dict.get('osType', None)
+        osVersion = request_dict.get('osVersion', None)
+
+        if userID and deviceSupplier and deviceModel and osType and osVersion:
+            ub_qs = User_Brand.objects.filter(userID=userID)
+            if ub_qs.exists():
+                update = {
+                    'deviceSupplier': deviceSupplier,
+                    'deviceModel': deviceModel,
+                    'osType': osType,
+                    'osVersion': osVersion
+                }
+                ub_qs.update(**update)
+                return response.json(0)
+            else:
+                user = Device_User.objects.filter(userID=userID)
+                if not user.exists():
+                    return response.json(104)
+                data = {
+                    'userID': user[0],
+                    'deviceSupplier': deviceSupplier,
+                    'deviceModel': deviceModel,
+                    'osType': osType,
+                    'osVersion': osVersion
+                }
+                User_Brand.objects.create(**data)
+                return response.json(0)
+        else:
+            return response.json(444)
+
+    def do_query(self, userID, request_dict, response):
+
+        if not userID:
+            return response.json(444)
+        else:
+            ub_qs = User_Brand.objects.filter(userID=userID)
+            data = None
+            if ub_qs.exists():
+                data = ub_qs.values('id', 'deviceSupplier', 'deviceModel', 'osType', 'osVersion')[0]
+
+            return response.json(0, {'data': data})

+ 75 - 1
Controller/UserController.py

@@ -27,7 +27,8 @@ from ratelimit.decorators import ratelimit
 
 from Ansjer.config import AuthCode_Expire, SERVER_DOMAIN, APNS_CONFIG, JPUSH_CONFIG, FCM_CONFIG, TUTK_PUSH_DOMAIN
 from Controller.CheckUserData import DataValid, date_handler, RandomStr
-from Model.models import Device_User, Role, UidPushModel, UserOauth2Model, UserExModel, Device_Info,UidSetModel
+from Model.models import Device_User, Role, UidPushModel, UserOauth2Model, UserExModel, Device_Info, UidSetModel, \
+    UserAppFrequencyModel
 from Object.AWS.SesClassObject import SesClassObject
 from Object.AliSmsObject import AliSmsObject
 from Object.RedisObject import RedisObject
@@ -2930,8 +2931,81 @@ class Image_Code_RegisterView(TemplateView):
         return response.json(0, res)
 
 
+class UserAppFrequencyView(TemplateView):
+    @method_decorator(csrf_exempt)
+    def dispatch(self, *args, **kwargs):
+        return super(UserAppFrequencyView, self).dispatch(*args, **kwargs)
 
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.POST
+        operation = kwargs.get('operation')
+        return self.validates(request_dict, operation)
 
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        request_dict = request.GET
+        operation = kwargs.get('operation')
+        return self.validates(request_dict, operation)
+
+    def validates(self, request_dict, operation):
+        token = request_dict.get('token', None)
+        response = ResponseObject()
+
+        token = TokenObject(token)
+        if token.code != 0:
+            return response.json(token.code)
+
+        if operation == 'refresh':
+            return self.do_refresh(request_dict, token.userID, response)
+        else:
+            return response.json(404)
+
+    def do_refresh(self, request_dict, userID, response):
+        # return response.json(0)
+        type = request_dict.get('type', None)
+        month = request_dict.get('month', None)
+        if not type or not month:
+            return response.json(444, 'type')
+        else:
+            type = int(type)
+            now_time = int(time.time())
+            month = int(month)
+            uaf_qs = UserAppFrequencyModel.objects.filter(user__userID=userID)
+
+            if not uaf_qs.exists():
+                user = Device_User.objects.filter(userID=userID)[0]
+                data = {
+                    'user': user,
+                    'type': type,
+                    'data_time': month,
+                    'add_time': now_time,
+                    'update_time': now_time,
+                }
+                UserAppFrequencyModel.objects.create(**data)
+                return response.json(0)
+            else:
+                updateMonth = time.strftime('%m', time.localtime(month))
+                uaf = uaf_qs.values('id', 'type', 'data_time')[0]
+                dbMonth = time.strftime('%m', time.localtime(int(uaf['data_time'])))
+                print('update month is ' + updateMonth)
+                print('db month is ' + dbMonth)
+                if updateMonth == dbMonth:
+                    UserAppFrequencyModel.objects.filter(id=uaf['id']).update(type=type)
+                    return response.json(0)
+                elif updateMonth > dbMonth:
+                    user = Device_User.objects.filter(userID=userID)[0]
+                    data = {
+                        'user': user,
+                        'type': type,
+                        'data_time': month,
+                        'add_time': now_time,
+                        'update_time': now_time,
+                    }
+                    UserAppFrequencyModel.objects.create(**data)
+                    return response.json(0)
+                else:
+                    return response.json(444, 'month')
 
 
 

+ 56 - 12
Model/models.py

@@ -201,6 +201,7 @@ class Device_User(AbstractBaseUser):
 
 
 # 设备表是建项目开发者设计的,自己看着办
+# 谢谢提醒!我选择凉拌。
 class Device_Info(models.Model):
     id = models.CharField(blank=True, max_length=32, primary_key=True)
     userID = models.ForeignKey(Device_User, blank=True, to_field='userID', on_delete=models.CASCADE)
@@ -230,17 +231,7 @@ class Device_Info(models.Model):
     area = models.CharField(blank=True, max_length=100, default='', verbose_name=u'设备区域area')
     # ios要求新增字段
     version = models.CharField(blank=True, max_length=20, default='', verbose_name=u'版本号')
-    SpaceUsable = models.CharField(blank=True, max_length=20, default='', verbose_name=u'可用空间')
-    SpaceSum = models.CharField(blank=True, max_length=20, default='', verbose_name=u'总空间')
-    WIFIName = models.CharField(blank=True, max_length=50, default='', verbose_name=u'无线名称')
-    WIFIIP = models.CharField(blank=True, max_length=20, default='', verbose_name=u'无线ip')
-    WIFIPwd = models.CharField(blank=True, max_length=50, default='', verbose_name=u'无线密码')
-    isDetector = models.BooleanField(blank=True, verbose_name=u'侦测开关0:关闭,1:开启)', default=False)
-    DetectorRank = models.IntegerField(blank=True, default=0, verbose_name=u'侦测灵敏度 1:低,2:中,3:高4:最高')
     iSNotification = models.BooleanField(blank=True, verbose_name=u'报警通知 0:关闭,1:开启)', default=False)
-    MirrorType = models.IntegerField(blank=True, default=0, verbose_name=u'镜像类型 0:关闭镜像,1:上下镜像,2:左右镜像,3:上下左右镜像')
-    RecordType = models.IntegerField(blank=True, default=0, verbose_name=u'录像模式(0:关闭,1:全是录像,3:报警录像)')
-    TimeZone = models.CharField(blank=True, max_length=50, default='', verbose_name=u'时区')
     isVod = models.SmallIntegerField(blank=True, default=0, verbose_name='是否支持云存')  # 是否支持云存设备
     isExist = models.SmallIntegerField(blank=True, default=1, verbose_name='是否被删除')  # 是否被删除了(需主用户交互) 1存在,0不存在,2设备被重置
     ###
@@ -528,13 +519,15 @@ class Order_Model(models.Model):
     endTime = models.IntegerField(verbose_name='结束时间', default=0)
     status = models.SmallIntegerField(default=0, verbose_name='付款状态')  # 0:否,1:成功
     payType = models.SmallIntegerField(default=0, verbose_name='付款类型0:paypal,1:alipay')
-
     payTime = models.IntegerField(verbose_name='支付成功时间', default=0)
+    rank = models.ForeignKey(Store_Meal, to_field='id', default='', on_delete=models.CASCADE, verbose_name='套餐类型')
     nickname = models.CharField(default='', max_length=64, verbose_name='设备昵称')
     uid_bucket_id = models.IntegerField(default=0, verbose_name='关联uid_bucket的字段')
     commodity_type = models.SmallIntegerField(default=0, verbose_name='云存储套餐类型')
     commodity_code = models.CharField(default='', max_length=32, verbose_name='套餐规格码')
-    pay_url = models.CharField(max_length=500,default='', verbose_name='支付url')
+    pay_url = models.CharField(max_length=500, default='', verbose_name='支付url')
+    paypal = models.CharField(max_length=500, null=True, blank=True, verbose_name='支付批准url')
+
 
     def __str__(self):
         return self.orderID
@@ -678,6 +671,17 @@ class UidSetModel(models.Model):
     pwd = models.CharField(max_length=32, default='', verbose_name=u'设备密码') # 暂时是预留字段
     resetTime = models.IntegerField(default=0, verbose_name='设备重置时间')
     region_alexa = models.CharField(max_length=8, verbose_name='设备alexa区域', default='ALL')  # ALL CN EU US
+    deviceModel = models.CharField(blank=True, max_length=64, default='', verbose_name=u'设备型号')
+    TimeZone = models.CharField(blank=True, max_length=50, default='', verbose_name=u'时区')
+    TimeStatus = models.SmallIntegerField(default=0, verbose_name='同步手机时间开关。0:关闭,1:开启')
+    SpaceUsable = models.CharField(blank=True, max_length=20, default='', verbose_name=u'可用空间')
+    SpaceSum = models.CharField(blank=True, max_length=20, default='', verbose_name=u'总空间')
+    MirrorType = models.IntegerField(blank=True, default=0, verbose_name=u'镜像类型 0:关闭镜像,1:上下镜像,2:左右镜像,3:上下左右镜像')
+    RecordType = models.IntegerField(blank=True, default=0, verbose_name=u'录像模式(0:关闭,1:全是录像,3:报警录像)')
+    OutdoorModel = models.IntegerField(blank=True, default=0, verbose_name=u'室外模式 0:关闭,1:开启')
+    WIFIName = models.CharField(blank=True, max_length=50, default='', verbose_name=u'无线名称')
+    isDetector = models.SmallIntegerField(default=0, verbose_name=u'侦测开关0:关闭,1:开启')
+    DetectorRank = models.IntegerField(default=0, verbose_name=u'侦测灵敏度 0:低,1:中,2:高,3:最高')
 
     class Meta:
         db_table = 'uid_set'
@@ -708,6 +712,31 @@ class UidPushModel(models.Model):
         ordering = ('-id',)
 
 
+# 设备通道配置
+class UidChannelSetModel(models.Model):
+    id = models.AutoField(primary_key=True, verbose_name='自增id')
+    uid = models.ForeignKey(UidSetModel, to_field='id', on_delete=models.CASCADE)
+    channel = models.IntegerField(default=1, verbose_name='通道号')
+    pir_audio = models.SmallIntegerField(default=0, verbose_name='pir声音。0:关闭,1:开启')
+    mic_audio = models.SmallIntegerField(default=0, verbose_name='mic声音。0:关闭,1:开启')
+    battery_status = models.SmallIntegerField(default=0, verbose_name='低电量提醒状态。0:关闭,1:开启')
+    battery_level = models.SmallIntegerField(default=0, verbose_name='低电量提醒级别。0: 低于10%;1:低于25%;2:低于50%;3:低于75%')
+    sleep_status = models.SmallIntegerField(default=0, verbose_name='是否开启【休眠通知】。0:关闭;1:开启')
+    sleep_time = models.SmallIntegerField(default=0, verbose_name='摄像机进入休眠时间。0:不休眠;1:10秒;2:20秒;3:30秒')
+    light_night_model = models.IntegerField(default=0, verbose_name='夜视模式')  # 0:全彩模式,1:黑白模式,2:智能夜视模式
+    light_alarm_type = models.IntegerField(default=0, verbose_name='警报人形类型')  # 0为人形,1为移动,3是人形和移动侦测0x0f
+    light_alarm_level = models.IntegerField(default=0,
+                                            verbose_name='声光报警级别')  # 0: 关闭,1:强烈声光告警,2:轻微声光告警,3: 强烈声告警,4:轻微声告警,5:强烈光告警
+    light_alarm_man_en = models.IntegerField(default=0, verbose_name='人为告警状态')  # 0:关,1:开
+    light_alarm_vol = models.IntegerField(default=0, verbose_name='报警音量')  # 音量值0-100
+    light_long_light = models.IntegerField(default=0, verbose_name='长亮')
+
+    class Meta:
+        db_table = 'uid_channel'
+        verbose_name = '设备通道设置'
+        verbose_name_plural = verbose_name
+
+
 # oauth2 第三方登录补全信息
 class UserExModel(models.Model):
     id = models.AutoField(primary_key=True, verbose_name='自增id')
@@ -879,3 +908,18 @@ class GrantCodeModel(models.Model):
         ordering = ('-add_time',)
         verbose_name = u'授权码表'
         db_table = 'oauth_grant_code'
+
+
+class UserAppFrequencyModel(models.Model):
+    id = models.AutoField(primary_key=True)
+    user = models.ForeignKey(Device_User, to_field='userID', on_delete=models.CASCADE, verbose_name='关联设备用户表')
+    type = models.SmallIntegerField(default=0, verbose_name='使用频率类型') # 1:每天,2:三天,3:一周,4:两周,5:一个月,6:一个月以上
+    data_time = models.IntegerField(default=0, verbose_name='数据时间')
+    add_time = models.IntegerField(default=0, verbose_name='添加时间')
+    update_time = models.IntegerField(default=0, verbose_name='更新时间')
+
+    class Meta:
+        verbose_name = '用户使用APP频率表'
+        verbose_name_plural = verbose_name
+        db_table = 'user_app_frequency'
+        ordering = ('-add_time',)

+ 1 - 1
Object/TokenObject.py

@@ -115,7 +115,7 @@ class TokenObject:
             userID = res.get('userID', '')
             user = res.get('user', '')
             lang = self.lang
-            refreshRes = self.generate(data={'userID': userID, 'lang':lang , 'user': user})
+            refreshRes = self.generate(data={'userID': userID, 'lang': lang, 'user': user})
             return refreshRes
 
 # import jwt

+ 4 - 0
Service/TemplateService.py

@@ -75,6 +75,10 @@ class TemplateService:
             'v3/account/login',
             'detect/queryInfo',
             'sysmsg/query',
+            'v3/account/register',
+            'v3/account/changePwd',
+            'v3/account/resetPwdByCode',
+            'account/appFrequency',
         ]
         return apiList