#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: AnsjerFormal
@software: PyCharm
@DATE: 2018/12/5 9:30
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: CloudVod.py
@Contact: chanjunkai@163.com
"""
import json
import math
import time
import urllib

import boto3

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
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, StsCrdModel
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

'''
# 获取设备推送hls流 证书
http://192.168.136.40:8077/cloudVod/getSts?uidToken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJGVFNMTDhITTQzN1ozOFdVMTExQSIsImNoYW5uZWwiOiI0In0.HO-PzoRwhQ4CFNkjthqOitf48c-XOvHjtNGCeUmBe9g
# 获取存储的播放文件列表
#修改状态
http://192.168.136.40:8077/cloudVod/status?token=local&uid=xxx&channel=4&status=1
# 回调vod
http://192.168.136.40:8077/cloudVod/storeplaylist?uidToken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJGVFNMTDhITTQzN1ozOFdVMTExQSIsImNoYW5uZWwiOiI0In0.HO-PzoRwhQ4CFNkjthqOitf48c-XOvHjtNGCeUmBe9g&time=1234567891
=============================
# 生成订单
http://test.dvema.com/cloudVod/createOrder?token=test&uid=xxx&channel=4&rank=1
# 修改设备云存状态
http://test.dvema.com/cloudVod/status?uid=xxx&channel=4&token=test&status=1

# 获取指定设备云存关联信息
http://test.dvema.com/cloudVod/details?token=test&uid=xxxx

# 获取回放列表
http://test.dvema.com/cloudVod/getHlsList?uid=xxxx&channel=4&token=test&daytime=2018121001


2设备端
http://test.dvema.com/cloudVod/getSts?uidToken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjaGFubmVsIjoiNCIsInVpZCI6IkZUU0xMOEhNNDM3WjM4V1UxMTFBIn0.wkrwYvIYf5qEukOSTxALSAgSqop-gNBdEvSwScOgYB8
# 支付宝支付
http://192.168.136.40:8077/cloudVod/aliPayCreateOrder?token=local&channel=2&rank=1&uid=OOBDSU9547NTRSMF111A
'''


# 设备信息添加
class CloudVodView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(CloudVodView, 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')
        if operation == 'getSts':
            # 移动侦测获取设备sts证书
            ip = CommonService.get_ip_address(request)
            return self.do_getSts(request_dict, ip, response)
        # 付款完成
        elif operation == 'payExecute':
            return self.do_paypal_execute(request_dict, response)
        elif operation == 'storeplaylist':
            return self.do_store_palylist(request_dict, response)
        elif operation == 'payOK':
            return self.do_pay_ok()
        elif operation == 'payError':
            return self.do_pay_error()
        else:
            token = request_dict.get('token', None)
            # 设备主键uid
            tko = TokenObject(token)
            response.lang = tko.lang
            if tko.code != 0:
                return response.json(tko.code)
            userID = tko.userID
            if operation == 'status':
                return self.do_change_status(request_dict, userID, response)
            elif operation == 'details':
                return self.do_get_details(request_dict, response)
            elif operation == 'filterVod':
                return self.do_filter_playlist(request_dict, userID, response)
            elif operation == 'findVod':
                return self.do_find_playlist(request_dict, userID, response)
            elif operation == 'orderStatus':
                return self.do_pay_status(request_dict, userID, response)
            else:
                return response.json(414)

    def do_get_details(self, request_dict, response):
        uid = request_dict.get('uid', None)
        dvqs = Device_Info.objects.filter(UID=uid, isShare=False)
        if not dvqs.exists():
            return response.json(12)
        ubqs = UID_Bucket.objects.filter(uid=uid). \
            values('bucket__content', 'status', 'channel', 'endTime', 'uid')
        res = []
        if ubqs.exists():
            res = list(ubqs)
        return response.json(0, res)

    def do_pay_error(self):
        response = HttpResponse()
        response.content = '''
<!DOCTYPE html>
<html>
<head>
	<!--浏览器不缓存-->
	<meta http-equiv="Pragma" content="no-cache">
	<meta http-equiv="Cache-Control" content="no-cache">
	<meta http-equiv="Expires" content="0">
	<!--utf-8-->
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <!-- viewport的<meta>标签，这个标签可以修改在大部分的移动设备上面的显示，为了确保适当的绘制和触屏缩放。-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="https://test.dvema.com/web/images/favicon.ico" type="image/x-icon"  charset="utf-8"/>  
    <title>Trading particulars</title>
    <style>
    	.title_head{
    		height: 50px;
    		border-radius: 5px;
    		background-color: #c3c6c7; 
    		text-align: center;
    		line-height: 50px;
    	}
    	.content{
    		text-align: center;
    		margin-top: 50px;
    		font-size: 20px;
    		color : #ec7648
    	}
    	.content_img{
    		width: 60px; 
    		height: 60px;
    	}
    	.bottom{
    		 margin-bottom: 10px; 
    		 margin-top: 250px; 
    		 color : #ec7648
    	}
    	.bottom_div{
    		border: 1px solid #ec7648; 
    		line-height: 38px; 
    		text-align: center; 
    		width: 100px; 
    		height: 38px;
    		border-radius: 5px;
    	}
    	
    	.bottom_div:hover{
    		background-color: #dde4e2;
    	}
    </style>
</head>
<body>
	<div class="title_head">Trading particulars</div>
    <div class="content">
    	<p >
    		<img src="https://test.dvema.com/web/images/failed.jpg" class="content_img">
    		<br />
    		Payment failure
    	</p>
    </div>
    <center class="bottom">
    	<div class="bottom_div" onclick="payOKButton()"> 
    	 Finish
    	</div>
    </center>
    <script> 	    // 点击付款成功按钮
    function payOKButton() {
        // 复杂数据
        console.log('success')
        window.webkit.messageHandlers.jsCallOC.postMessage({"status": 0});
    }
	</script>
</body> 
</html>
                '''
        return response

    def do_pay_ok(self):
        response = HttpResponse()
        response.content = '''

<!DOCTYPE html>
<html>
<head>
	<!--浏览器不缓存-->
	<meta http-equiv="Pragma" content="no-cache">
	<meta http-equiv="Cache-Control" content="no-cache">
	<meta http-equiv="Expires" content="0">
	<!--utf-8-->
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <!-- viewport的<meta>标签，这个标签可以修改在大部分的移动设备上面的显示，为了确保适当的绘制和触屏缩放。-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="https://test.dvema.com/web/images/favicon.ico" type="image/x-icon"  charset="utf-8"/>  
    <title>Trading particulars</title>
    <style>
    	.title_head{
    		height: 50px;
    		border-radius: 5px;
    		background-color: #c3c6c7; 
    		text-align: center;
    		line-height: 50px;
    	}
    	.content{
    		text-align: center;
    		margin-top: 50px;
    		font-size: 20px;
    		color : green
    	}
    	.content_img{
    		width: 60px;
    		height: 60px;
    	}
    	.bottom{
    		 margin-bottom: 10px; 
    		 margin-top: 250px; 
    		 color : green
    	}
    	.bottom_div{
    		border: 1px solid green; 
    		line-height: 38px; 
    		text-align: center; 
    		width: 100px; 
    		height: 38px;
    		border-radius: 5px;
    	}
    	
    	.bottom_div:hover{
    		background-color: #dde4e2;
    	}
    </style>
</head>
<body>
	<div class="title_head">Trading particulars</div>
    <div class="content">
    	<p >
    		<img src="https://test.dvema.com/web/images/timg.jpg" class="content_img">
    		<br />
    		Successful payment
    	</p>
    </div>
    <center class="bottom">
    	<div class="bottom_div" onclick="payOKButton()"> 
    	 Finish
    	</div>
    </center>
    <script> 	    // 点击付款成功按钮
    function payOKButton() {
        // 复杂数据
        console.log('success')
        window.location.href="https://test.dvema.com/closePage";
    }
	</script>
</body> 
</html>
        '''
        return response

    def do_getSts(self, request_dict, ip, response):
        uidToken = request_dict.get('uidToken', None)
        utko = UidTokenObject(uidToken)
        if utko.flag is False:
            return response.json(444, 'uidToken')
        uid = utko.UID
        channel = utko.channel
        print(channel)
        print(uid)
        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")

    #  生成设备sts上传授权
    # def do_getSts(self, request_dict, ip, response):
    #     uidToken = request_dict.get('uidToken', None)
    #     utko = UidTokenObject(uidToken)
    #     if utko.flag is False:
    #         return response.json(444, 'uidToken')
    #     UID = utko.UID
    #     channel = utko.channel
    #     print(channel)
    #     print(UID)
    #     ubqs = UID_Bucket.objects.filter(uid=UID, channel=channel, status=1). \
    #         values('channel', 'bucket__bucket', 'bucket__endpoint', 'bucket__region', 'endTime')
    #     now_time = int(time.time())
    #     if not ubqs.exists():
    #         res = {'code': 404, 'msg': '未购买'}
    #         return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
    #     elif ubqs[0]['endTime'] < now_time:
    #         res = {'code': 404, 'msg': '过期'}
    #         return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
    #     oc_qs = OssCrdModel.objects.filter(uid=UID, channel=channel).values("addTime", "data")
    #     if oc_qs.exists():
    #         endTime = int(oc_qs[0]["addTime"]) + 3500
    #         if endTime > now_time:
    #             print(endTime)
    #             print(now_time)
    #             res = json.loads(oc_qs[0]["data"])
    #             return JsonResponse(status=200, data=res)
    #     # 套餐id
    #     storage = '{uid}/vod{channel}/'.format(uid=UID, channel=channel)
    #     bucket_name = ubqs[0]['bucket__bucket']
    #     endpoint = ubqs[0]['bucket__endpoint']
    #     access_key_id = OSS_STS_ACCESS_KEY
    #     access_key_secret = OSS_STS_ACCESS_SECRET
    #     region_id = ubqs[0]['bucket__region']
    #     role_arn = OSS_ROLE_ARN
    #     clt = client.AcsClient(access_key_id, access_key_secret, region_id)
    #     req = AssumeRoleRequest.AssumeRoleRequest()
    #     # 设置返回值格式为JSON。
    #     req.set_accept_format('json')
    #     req.set_RoleArn(role_arn)
    #     req.set_RoleSessionName(UID)
    #     req.set_DurationSeconds(3600)
    #     Resource_access = "acs:oss:*:*:{bucket_name}/{uid_channel}*".format(bucket_name=bucket_name,
    #                                                                         uid_channel=storage)
    #     print(Resource_access)
    #     policys = {
    #         "Version": "1",
    #         "Statement": [
    #             {
    #                 "Action": ["oss:PutObject", "oss:DeleteObject", ],
    #                 "Resource": [Resource_access],
    #                 "Effect": "Allow",
    #                 "Condition": {
    #                     "IpAddress": {"acs:SourceIp": ip}
    #                     # "IpAddress": {"acs:SourceIp": "120.237.157.184"}
    #                     # "IpAddress": {"acs:SourceIp": "*"}
    #                 }
    #             }
    #         ]
    #     }
    #     req.set_Policy(Policy=json.dumps(policys))
    #     body = clt.do_action(req)
    #     # 使用RAM账号的AccessKeyId和AccessKeySecret向STS申请临时token。
    #     token = json.loads(body.decode('utf-8'))
    #     print(token)
    #     res = {
    #         'AccessKeyId': token['Credentials']['AccessKeyId'],
    #         'AccessKeySecret': token['Credentials']['AccessKeySecret'],
    #         'SecurityToken': token['Credentials']['SecurityToken'],
    #         'Expiration': token['Credentials']['Expiration'],
    #         'expire': '3600',
    #         'endpoint': endpoint,
    #         'bucket_name': bucket_name,
    #         'arn': token['AssumedRoleUser']['Arn'],
    #         'code': 0,
    #         'storage': storage,
    #         'endTime': ubqs[0]['endTime'],
    #         'ip': ip}
    #     if oc_qs.exists():
    #         oc_qs.update(data=json.dumps(res), addTime=now_time)
    #     else:
    #         OssCrdModel.objects.create(uid=UID, channel=channel, data=json.dumps(res), addTime=now_time)
    #     return JsonResponse(status=200, data=res)

    def do_paypal_execute(self, request_dict, response):
        paymentId = request_dict.get('paymentId', None)
        PayerID = request_dict.get('PayerID', None)
        orderID = request_dict.get('orderID', None)
        if not paymentId or not PayerID or not orderID:
            red_url = "{SERVER_DOMAIN}cloudVod/payError".format(SERVER_DOMAIN=SERVER_DOMAIN)
            return HttpResponseRedirect(red_url)
        paypalrestsdk.configure(PAYPAL_CRD)
        # ID of the payment. This ID is provided when creating payment.
        payment = paypalrestsdk.Payment.find(paymentId)
        print(payment)
        payres = payment.execute({"payer_id": PayerID})
        print(payres)
        if not payres:
            red_url = "{SERVER_DOMAIN}cloudVod/payError".format(SERVER_DOMAIN=SERVER_DOMAIN)
            return HttpResponseRedirect(red_url)
        print("Payment execute successfully")
        order_qs = Order_Model.objects.filter(orderID=orderID)
        nowTime = int(time.time())
        order_qs.update(status=1, updTime=nowTime)
        order_list = order_qs.values("UID", "rank_id", "channel")
        rank_id = order_list[0]['rank_id']
        UID = order_list[0]['UID']
        channel = order_list[0]['channel']
        smqs = Store_Meal.objects.filter(id=rank_id).values("day", "bucket_id", "bucket__storeDay")
        bucketId = smqs[0]['bucket_id']
        if not smqs.exists():
            return response.json(0, '套餐已删除')
        addTime = int(smqs[0]["day"]) * 24 * 3600
        ubqs = UID_Bucket.objects.filter(uid=UID, channel=channel).values("bucket_id", "endTime", "bucket__storeDay")
        nowTime = int(time.time())
        if ubqs.exists():
            # 判断是否过期了
            if nowTime > ubqs[0]['endTime']:
                ubqs.update(endTime=nowTime + addTime)
            else:
                # 同一个bucket续费
                if bucketId == ubqs[0]['bucket_id']:
                    ubqs.update(endTime=ubqs[0]['endTime'] + addTime)
                else:
                    if ubqs[0]['bucket__storeDay'] > smqs[0]['bucket__storeDay']:
                        return response.json(10, '不可选低级别套餐')
                    else:
                        # 升级
                        origin_storeDay = int(ubqs[0]['bucket__storeDay'])
                        upgrade_storeDay = int(smqs[0]['bucket__storeDay'])
                        ctcTime = ubqs[0]['endTime'] - nowTime
                        multiple = math.ceil(upgrade_storeDay / origin_storeDay)
                        ubqs.update(endTime=ctcTime / multiple + addTime + ubqs[0]['endTime'], bucket_id=bucketId)
                        # 付款成功把oss token删除
                        OssCrdModel.objects.filter(uid=UID, channel=channel).delete()
        # 新增模式
        else:
            print('create')
            UID_Bucket.objects.create(uid=UID, channel=channel,
                                      bucket_id=bucketId, endTime=nowTime + addTime)
            # return response.json(0)
        red_url = "{SERVER_DOMAIN}cloudVod/payOK".format(SERVER_DOMAIN=SERVER_DOMAIN)
        return HttpResponseRedirect(red_url)

    def do_change_status(self, request_dict, userID, response):
        uid = request_dict.get('uid', None)
        status = request_dict.get('status', None)
        channel = request_dict.get('channel', None)
        if not uid or not status or not channel:
            return response.json(444, 'uid,status,channel')
        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(channel=channel, uid=uid)
        if not ubqs.exists():
            return response.json(10, '未购买')
        now_time = int(time.time())
        if now_time > ubqs[0].endTime:
            return response.json(10, '已过期')
        ubqs.update(status=status)
        if status == 0:
            return response.json(0)
        utko = UidTokenObject()
        utko.generate(data={'uid': uid, 'channel': channel})
        uidTkUrl = "{SERVER_DOMAIN}cloudVod/getSts?uidToken={uidToken}". \
            format(uidToken=utko.token, SERVER_DOMAIN=SERVER_DOMAIN)
        storeHlsUrl = "{SERVER_DOMAIN}cloudVod/storeplaylist?uidToken={uidToken}". \
            format(uidToken=utko.token, SERVER_DOMAIN=SERVER_DOMAIN)
        return response.json(0, {'uidTkUrl': uidTkUrl, 'storeHlsUrl': storeHlsUrl})

    def do_store_palylist(self, request_dict, response):
        uidToken = request_dict.get('uidToken', None)
        storeTime = request_dict.get('time', None)
        sec = request_dict.get('sec', None)
        utko = UidTokenObject(uidToken)
        if utko.flag is False:
            return response.json(444, 'uidToken')
        if not uidToken or not storeTime or not sec:
            return response.json(444, 'uidToken,time,sec')
        UID = utko.UID
        channel = utko.channel
        print(channel)
        print(UID)
        nowTime = int(time.time())
        if not OssCrdModel.objects.filter(uid=UID, channel=channel).exists():
            res = {'code': 404, 'msg': '设备未购买'}
            return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
        qs = UID_Bucket.objects.filter(uid=UID, channel=channel, status=1, endTime__gte=nowTime). \
            values("channel", "bucket__storeDay", "bucket_id")
        if not qs.exists():
            res = {'code': 404, 'msg': '设备未购买'}
            return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
        storeDay = qs[0]['bucket__storeDay']
        bucketID = qs[0]['bucket_id']
        endTime = int(storeTime) + storeDay * 86400
        VodHlsModel.objects.create(uid=UID, channel=channel, time=storeTime,
                                   endTime=endTime, bucket_id=bucketID, sec=sec)
        return response.json(0)

    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")
        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)

    # backend find play list0
    def do_find_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)
        own_perm = ModelService.check_perm(userID, 20)
        if own_perm is False:
            return response.json(404)
        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", "id")
        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_1000,m_fast,w_300'})
            vod_play_list.append(
                {'name': vod['time'], 'sign_url': vod_play_url, 'thumb': thumb, 'sec': vod['sec'], 'id': vod['id']})
        return response.json(0, vod_play_list)

    def do_pay_status(self, request_dict, userID, response):
        orderID = request_dict.get('orderID', None)
        lang = request_dict.get('lang', 'en')
        om_qs = Order_Model.objects.filter(orderID=orderID).values('status')
        # response = HttpResponse()
        # success_pay_content = '''
        #                 '''
        # falil_pay_content = '''
        #
        #                 '''

        status = 0
        url = "{SERVER_DOMAIN}web/paid2/fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)

        if om_qs.exists():
            status = om_qs[0]['status']
            if status == 1:

                url = "{SERVER_DOMAIN}web/paid2/success.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
            else:

                url = "{SERVER_DOMAIN}web/paid2/fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)

        if lang !='cn':
            status = 0
            url = "{SERVER_DOMAIN}web/paid2/en_fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)

            if om_qs.exists():
                status = om_qs[0]['status']
                if status == 1:

                    url = "{SERVER_DOMAIN}web/paid2/en_success.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
                else:

                    url = "{SERVER_DOMAIN}web/paid2/en_fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)

        res = {'status': status, 'url': url}
        return response.json(0, res)

    def query_alipay_order(self, request_dict, userID, response):
        out_trade_no = request_dict.get('out_trade_no', None)

        if out_trade_no is None:
            return response.json(444)

        try:
            aliPayObj = AliPayObject()
            alipay = aliPayObj.conf()
            result = alipay.api_alipay_trade_query(out_trade_no=out_trade_no)
            print(result)
        except Exception as e:
            print(repr(e))
            return response.json(10, repr(e))
        return response.json(0, {'result': result})

    def do_alipay_cancel(self, request_dict, userID, response):
        out_trade_no = request_dict.get('out_trade_no', None)

        if out_trade_no is None:
            return response.json(444)

        order_qs = Order_Model.objects.filter(orderID=out_trade_no)
        if not order_qs.exists():
            return response.json(800)

        order = order_qs[0]

        # 交易状态：
        # WAIT_BUYER_PAY（交易创建，等待买家付款）
        # TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）
        # TRADE_SUCCESS（交易支付成功）
        # TRADE_FINISHED（交易结束，不可退款）

        try:
            aliPayObj = AliPayObject()
            alipay = aliPayObj.conf()
            result = alipay.api_alipay_trade_query(out_trade_no=out_trade_no)
            result = result['result']

            if result['code'] == '100000':
                trade_status = result['trade_status']
                if trade_status == 'TRADE_CLOSED' or trade_status == 'WAIT_BUYER_PAY':
                    order.status = 2
                    order.updTime = int(time.time())
                    order.save()
                    return response.json(0)
                else:
                    order.status = 1
                    order.updTime = int(time.time())
                    order.save()
                    return response.json(802)
            else:
                return response.json(10, result['sub_msg'])

        except Exception as e:
            print(repr(e))
            return response.json(10, repr(e))

    def do_alipay_refund(self, request_dict, userID, response):
        out_trade_no = request_dict.get('out_trade_no', None)
        refund_amount = request_dict.get('refund_amount', None)
        reason = request_dict.get('reason', '正常退款')

        if out_trade_no is None:
            return response.json(444)

        order_qs = Order_Model.objects.filter(orderID=out_trade_no)

        if not order_qs.exists():
            return response.json(800)

        order = order_qs[0]
        if refund_amount > order.price:
            return response.json(801)

        try:
            # extra = {
            #     'refund_currency': order[0].currency
            # }
            aliPayObj = AliPayObject()
            alipay = aliPayObj.conf()
            result = alipay.api_alipay_trade_refund(refund_amount=refund_amount, out_trade_no=out_trade_no)
            result = result['result']
            print(result)
            if result['code'] == '10000':
                order.status = 3
                order.updTime = int(time.time())
                order.save()
                return response.json(0)
            else:
                return response.json(10, result['sub_msg'])

        except Exception as e:
            print(repr(e))
            return response.json(10, repr(e))

    def do_paypal_refund(self, request_dict, userID, response):
        out_trade_no = request_dict.get('out_trade_no', None)
        refund_amount = request_dict.get('refund_amount', None)

        order_qs = Order_Model.objects.filter(orderID=out_trade_no, userID__userID=userID)

        if not order_qs.exists():
            return response.json(800)

        order = order_qs[0]

        refund_amount = float(refund_amount)
        if order.price < refund_amount:
            return response.json(801)

        paypalrestsdk.configure(PAYPAL_CRD)
        payment = paypalrestsdk.Payment.find(order.trade_no)
        transactions = payment['transactions']
        transaction = transactions[0]
        related_resources = transaction['related_resources']
        if len(related_resources) > 0:
            related_resource = related_resources[0]
            sale = related_resource['sale']
            id = sale['id']

            if sale['state'] == 'completed':
                paypalSale = paypalrestsdk.Sale.find(id)
                refund = paypalSale.refund({
                    'amount': {
                        'total': refund_amount,
                        'currency': order.currency
                    }
                })

                if refund.success():
                    return response.json(0)
                else:
                    return response.json(10, refund.error)
            elif sale['state'] == 'refunded':
                return response.json(804)
        else:
            return response.json(804)




def deleteVodHls(request):
    response = ResponseObject()
    i = int(request.GET.get('i', 5))

    import time
    nowTime = int(time.time())
    for i in range(i):
        vh_qs = VodHlsModel.objects.filter(time__lte=str(nowTime - 3600 * 24 * 35))[0:10000]
        id_list = vh_qs.values_list("id", flat=True)
        print(id_list)
        VodHlsModel.objects.filter(id__in=list(id_list)).delete()
    return response.json(0)
