#!/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
import datetime
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
import requests
import hashlib
import hmac
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 django.contrib.auth.hashers import make_password, check_password  # 对密码加密模块
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, CompanySerialModel, SerialNumberModel, CompanyModel, VPGModel
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':
            res = make_password(123456)
            return JsonResponse(status=200, data=res,safe=False)
        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)
        elif operation == 'getAlexa':
            userID = '158943594633713800138000'
            return self.queryInterface(request_dict, userID, response)
        elif operation == 'generateToken':
            userID = '158943604783713800138000'
            return self.generate_token(request_dict,userID)
        elif operation == 'test_upload_s3':
            userID = '158943604783713800138000'
            return self.test_upload_s3(request_dict)
        elif operation == 'test_request':
            userID = '158943604783713800138000'
            return self.testRequest(request,request_dict)
        else:
            return 123

    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 = '86YC8Z192VB1VMKU111A'
        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)

    def generate_token(self,request_dict,userID):
        # UserIdToken
        tko = TokenObject()
        res = tko.generate(
            data={'userID': 158943594633713800138000, 'lang': 'cn', 'user': '597471180@qq.com', 'm_code': '123413243214'})
        #uidToken
        # utko = UidTokenObject()
        # res = utko.generate(data={'uid': 'XKWZSC5FCJYT19B7111A','channel': 1})
        return JsonResponse(status=200, data=res,safe=False)


    def test_upload_s3(self,request_dict):
        res = CompanyModel.objects.filter(id=3).delete()
        exit(res)

        testd = hmac.new('AWS4rf/xnQ3jIgY8bj7Sz4An4KbYct2sq2MbrfmP8rVV'.encode("utf-8"), '20210223'.encode("utf-8"), hashlib.sha256).digest()
        region_sign = hmac.new(testd, 'cn-northwest-1'.encode("utf-8"), hashlib.sha256).hexdigest()
        exit(region_sign)
        kService = sign(kRegion, 's3')
        kSigning = sign(kService, 'aws4_request')

        # exit(CommonService.getIpIpInfo("120.197.196.156",'CN'))
        aws_key = "ASIA2MMWBR4DUPTFDTOJ" #【你的 aws_access_key】
        aws_secret = "tTFZ9wpxFadeufhfaJ1erErv4U1bJ+TS/SJwTptx" #【你的 aws_access_key】
        aws_session_token = "IQoJb3JpZ2luX2VjEJT//////////wEaDmNuLW5vcnRod2VzdC0xIkYwRAIgenLaMN6NdFji0x18OuaUTPvvtRBAWwjdEYdBTCMh0ywCIEzntAbgRPmwS+YFuNg+F31z60I4J1IoqmrQHR7wmPzVKtsCCML//////////wEQABoMNzEzODE2MTE2OTk5IgyJTmdtNJ319TtNORAqrwLPG6Px0z5CsEQpFt/TCbSSMRtYqBU+x5Ll9hZIuTvg8H+56H02/cr0nSCNiy05z7dSrSWMFoMhVKvHq7as5TRvVXkvMbbYPQuQxxPFr7EswaB+XITeDpdGBI6N7mqnt6h4YJbhk2dNRa2/4Ypr1DuyGnhVV6NxNHA5INtY7apLi3UTcNKwKSQRVzUWZBpoj86wG3j77KOZg18I9P8UWBpA9fpz/Wiv4xrzZSexrUnq5svTLEqMfTYCPBXkxrJBjNrwVjvkBkgeIfQZPz+A5X97p7wXbPf0Jo5aHHRDefbAmBuXYoSfpHjiFWindkcvCaMxQzUiHVLvnN/5SvgQEzN3pLUAAioepRZIZQLaky1aRmYYm1wOCjzgsg9V+GV6gKTE+ipFG/6Nv03Vh++Hv+YwyamJgQY6mgEmxhOhncek0PgQeExx2EXk73olY/6L15eDyHbSWoEKBMTmdlmpYD9Cj3qP4aUUW6UT6V5Tql/s5eBEsYwY+hzgtQiTmd7vjytXxae+dpN9VsWGW4AJ9P+/LgBe6zExUx2MOVst0+hb+dd8bg/qkz7UBYNQAmU+BEoL2Cd7lNXdrv56Gboapo+BosQO49GT8u1k5EheQ9JKHCqv"
        session = Session(aws_access_key_id=aws_key,
                          aws_secret_access_key=aws_secret,
                          aws_session_token=aws_session_token,
                          region_name="cn-northwest-1") # 此处根据自己的 s3 地区位置改变
        s3 = session.resource("s3")
        # client = session.client("s3")
        bucket = "7cdk" # 【你 bucket 的名字】 # 首先需要保.证 s3 上已经存在该存储桶，否则报错
        upload_data = open("./././static/log/test.log", "rb")
        upload_key = "XKWZSC5FCJYT19B7111A/test/test6/test.log"
        file_obj = s3.Bucket(bucket).put_object(Key=upload_key, Body=upload_data)
        print('---------------------')
        print(file_obj)
        print(8/0)
        exit()


    def testRequest(self,request,request_dict):
        ip = CommonService.get_ip_address(request)
        ipInfo = CommonService.getIpIpInfo(ip,"CN")
        # print(type(ipInfo))
        # exit(ipInfo)
        addr = CommonService.getAddr(ip)
        dicts = {
            'ipInfo':ipInfo,
            'addr':addr,
        }
        return HttpResponse(json.dumps(dicts, ensure_ascii=False),
                            content_type="application/json,charset=utf-8")




