#!/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: cloudstorage.py
@Contact: chanjunkai@163.com
"""
import json
import os
import time
import urllib
from urllib.parse import quote, parse_qs, unquote

import apns2
import boto3
import jpush
import oss2
import paypalrestsdk
import threading
import calendar
import datetime
import logging
from aliyunsdkcore import client
from aliyunsdksts.request.v20150401 import AssumeRoleRequest
from boto3.session import Session
from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
from django.db import transaction
from django.views.generic.base import View
import jwt
from pyfcm import FCMNotification

from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, OSS_ROLE_ARN, SERVER_DOMAIN, PAYPAL_CRD, \
    SERVER_DOMAIN_SSL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ARN, APNS_MODE, APNS_CONFIG, BASE_DIR, \
    JPUSH_CONFIG, FCM_CONFIG, OAUTH_ACCESS_TOKEN_SECRET
from Controller.CheckUserData import DataValid
from Model.models import Device_Info, Order_Model, Store_Meal, VodHlsModel, OssCrdModel, UID_Bucket, StsCrdModel, \
    ExperienceContextModel, Pay_Type, CDKcontextModel, Device_User, SysMassModel, SysMsgModel, UidPushModel, \
    Unused_Uid_Meal, UIDMainUser, UserModel
from Object.AWS.S3Email import S3Email
from Object.AliPayObject import AliPayObject
from Object.AliSmsObject import AliSmsObject
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Object.UidTokenObject import UidTokenObject
from Service.CommonService import CommonService
from Object.m3u8generate import PlaylistGenerator
from Object.WechatPayObject import WechatPayObject
from django.db.models import Q, F

from Service.ModelService import ModelService

# SERVER_DOMAIN = 'http://test.dvema.com/'

'''
生成订单
http://test.dvema.com/cloudstorage/createpayorder?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJleHAiOjE1ODk1MjM0OTIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCIsImxhbmciOiJlbiIsInVzZXIiOiIxMzExOTY1NzcxMyJ9.e2NdhJtbXrDngZTSmOX_52Y-oxyfUEXjZD_qNxg6VrU&uid=VVDHCVBYDKFMJRWA111A&channel=1&pay_type=0&commodity_code=aws_us_vod_7_val_30
开启开关
http://test.dvema.com/cloudstorage/changevodstatus?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJleHAiOjE1ODk1MjM0OTIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCIsImxhbmciOiJlbiIsInVzZXIiOiIxMzExOTY1NzcxMyJ9.e2NdhJtbXrDngZTSmOX_52Y-oxyfUEXjZD_qNxg6VrU&uid=VVDHCVBYDKFMJRWA111A&channel=1&status=1
# 获取播放列表
http://localhost:8077/cloudstorage/queryvodlist?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJleHAiOjE1ODk1MjM0OTIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCIsImxhbmciOiJlbiIsInVzZXIiOiIxMzExOTY1NzcxMyJ9.e2NdhJtbXrDngZTSmOX_52Y-oxyfUEXjZD_qNxg6VrU&uid=VVDHCVBYDKFMJRWA111A&startTime=1&endTime=1954687458&channel=1
# 存储视频列表信息
http://test.dvema.com/cloudstorage/storeplaylist?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJWVkRIQ1ZCWURLRk1KUldBMTExQSIsImNoYW5uZWwiOiIxIn0.eGwi5QKyrXi4WSKRbrUG7iFTChv_Utec2hSnqZkDKt8&time=1586940120&sec=20&fg=10
# 获取订单列表
http://localhost:8077/cloudstorage/queryorder?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJsYW5nIjoiZW4iLCJ1c2VyIjoiMTMxMTk2NTc3MTMiLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJleHAiOjE1ODk1OTIyNzh9.u211DHiMKg-pqhXv4b2yR__eNyOcSwBZCyPUGjsxFLU&page=1&line=10&uid=VVDHCVBYDKFMJRWA111A
# commoditylist
http://test.dvema.com/cloudstorage/commoditylist?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJleHAiOjE1ODk1MjM0OTIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCIsImxhbmciOiJlbiIsInVzZXIiOiIxMzExOTY1NzcxMyJ9.e2NdhJtbXrDngZTSmOX_52Y-oxyfUEXjZD_qNxg6VrU
'''


# 设备信息添加
class CloudStorageView(View):

    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()
        if operation is None:
            return response.json(444, 'error path')
        elif operation == 'dopaypalcallback':  # paypal支付回调
            return self.do_pay_by_paypal_callback(request_dict, response)
        elif operation == 'doalicallback':  # 阿里支付回调
            return self.do_pay_by_ali_callback(request)
        elif operation == 'dowechatnotify':  # 微信支付回调
            return self.do_pay_by_wechat_callback(request, response)
        elif operation == 'getsignsts':  # 设备调用，获取sts令牌
            ip = CommonService.get_ip_address(request)
            return self.do_get_sign_sts(request_dict, ip, response)
        elif operation == 'storeplaylist':  # 设备调用，设备把视频上传到s3，同时把视频数据信息传给服务器，服务器存储播放内容
            return self.do_store_playlist(request_dict, response)
        elif operation == 'signplaym3u8':  # 根据sts播放m3u8 视频流
            return self.do_sign_play_m3u8(request_dict, response)
        elif operation == 'payOK':  # 支付成功
            return self.do_pay_ok(request_dict)
        elif operation == 'vodMsgEnd':  # 云存到期续费提醒   提前1天
            return self.do_vod_msg_end(request_dict)
        elif operation == 'vodMsgNotice':  # 云存操作系统消息
            return self.do_vod_msg_Notice(request_dict)

        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 == 'createpayorder':  # 创建支付订单
                ip = CommonService.get_ip_address(request)
                return self.do_create_pay_order(request_dict, userID, ip, response)
            elif operation == 'changevodstatus':  # 修改云存状态，传送两个url，即getsignsts接口和storeplaylist接口
                return self.do_change_vod_status(request_dict, userID, response)
            elif operation == 'queryvodlist':  # 获取视频播放列表
                return self.do_query_vod_list(request_dict, userID, response)
            elif operation == 'commoditylist':  # 查询套餐列表
                return self.do_commodity_list(request_dict, userID, response)
            elif operation == 'queryorder':  # 查询订单列表
                return self.do_query_order(request_dict, userID, response)
            elif operation == 'experienceorder':  # 生成体验订单
                return self.do_experience_order(request_dict, userID, response)
            elif operation == 'experiencereset':  # 重置设备云存体验
                return self.do_experience_reset(request_dict, userID, response)
            elif operation == 'deletevodlist':  # 删除播放列表
                return self.deleteVodList(request_dict, userID, response)
            elif operation == 'devicecommodity':  # 设备关联套餐列表
                return self.device_commodity(request_dict, userID, response)
            elif operation == 'switchdevicecommodity':  # 提前使用设备关联套餐
                return self.switch_device_commodity(request_dict, userID, response)
            else:
                return response.json(414)

    def do_query_order(self, request_dict, userID, response):  # 查询订单列表
        status = request_dict.get('status', None)
        page = int(request_dict.get('page', None))
        line = int(request_dict.get('line', None))
        uid = request_dict.get('uid', None)
        order_qs = Order_Model.objects.filter(userID_id=userID)
        if status:
            order_qs = order_qs.filter(status=status)
        # 筛选指定设备id的订单
        if uid:
            order_qs = order_qs.filter(UID=uid)
        if not order_qs.exists():
            return response.json(173)
            # return response.json(10, '订单不存在')
        count = order_qs.count()
        order_ql = order_qs[(page - 1) * line:page * line]. \
            values("orderID", "UID", "channel", "desc", "price", "currency",
                   "addTime", "updTime", "endTime", "pay_url", "payType",
                   "status", "commodity_type", "commodity_code")
        order_list = list(order_ql)
        data = []
        nowTime = int(time.time())
        # 这里需要进行优化
        uid_list = []
        for od in order_list:
            uid_list.append(od['UID'])
        didqs = Device_Info.objects.filter(userID_id=userID, UID__in=uid_list). \
            values('id', 'UID', 'Type')
        for d in order_list:
            if d['status'] == 0:
                if d['addTime'] + 3600 < nowTime:
                    d['status'] = 3
            for did in didqs:
                if d['UID'] == did['UID']:
                    d['did'] = did['id']
                    d['Type'] = did['Type']
                    data.append(d)
        return response.json(0, {'data': data, 'count': count})

    def do_commodity_list(self, request_dict, userID, response):  # 查询套餐列表
        mold = request_dict.get('mold', None)
        uid = request_dict.get('uid', None)
        lang = request_dict.get('lang', 'en')
        qs = Store_Meal.objects
        eq = ExperienceContextModel.objects.filter(uid=uid, experience_type=0).values('id')

        if mold:
            qs = qs.filter(bucket__mold=mold,lang__lang=lang)
        else:
            qs = qs.filter(lang__lang=lang)

        if eq:
            qs = qs.filter(~Q(pay_type='10'))
        else:
            qs = qs.filter(pay_type='10')

        qs = qs.filter(~Q(pay_type='11'))  # 过滤不显示激活码套餐
        #qs = qs.filter(id='11111111')
        #qs = qs.filter(bucket__region_id=regionObj.region_id)  # 过滤大洲
        qs = qs.annotate(title=F('lang__title'),content=F('lang__content'),discount_content=F('lang__discount_content'))
        qs = qs.values("id", "title", "content", "price", "day", "currency", "bucket__storeDay",
                       "bucket__bucket", "bucket__area", "commodity_code",
                       "commodity_type", "is_discounts", "virtual_price", "expire",
                       "discount_price", "discount_content", "symbol")

        if qs.exists():
            ql = list(qs)
            from operator import itemgetter
            from itertools import groupby
            ql.sort(key=itemgetter('bucket__area'))
            res = []
            for area, items in groupby(ql, key=itemgetter('bucket__area')):
                items_list = list(items)
                for key, val in enumerate(items_list):
                    pay_types = Pay_Type.objects.filter(store_meal=items_list[key]['id']).values("id", "payment")
                    items_list[key]['pay_type'] = list(pay_types)

                res_c = {'area': area, 'items': items_list}
                res.append(res_c)
            result = {
                'meals': res,
                'extra':
                    {
                        'cloud_banner': 'https://www.dvema.com/web/images/cloud_cn_banner.png',
                        'cloud_en_baner': 'https://www.dvema.com/web/images/cloud_en_banner.png'
                    }
            }
            return response.json(0, result)
        else:
            return response.json(0)

    def do_sign_play_m3u8(self, request_dict, response):  # 根据sts播放m3u8 视频流
        uid = request_dict.get('uid', None)
        uid = jwt.decode(uid, OAUTH_ACCESS_TOKEN_SECRET, algorithms='HS256').get('uid', '')
        channel = request_dict.get('channel', None)
        storeTime = request_dict.get('time', None)
        now_time = int(time.time())
        vh_qs = VodHlsModel.objects.filter(uid=uid, channel=channel, time=storeTime, endTime__gte=now_time). \
            values("sec", "fg", "bucket__bucket", "bucket__endpoint", "bucket__region", "bucket__mold")
        if not vh_qs.exists():
            return response.json(173)
        sec = vh_qs[0]['sec']
        fg = vh_qs[0]['fg']
        bucket__region = vh_qs[0]['bucket__region']
        bucket_name = vh_qs[0]['bucket__bucket']
        print(bucket__region)
        print(bucket_name)


        session = Session(
            aws_access_key_id=AWS_ACCESS_KEY_ID[vh_qs[0]["bucket__mold"]],
            aws_secret_access_key = AWS_SECRET_ACCESS_KEY[vh_qs[0]["bucket__mold"]],
            region_name=bucket__region
        )
        '''
            http://test.dvema.com/cloudstorage/signplaym3u8?uid=VVDHCVBYDKFMJRWA111A&channel=1&time=1586940120&sign=tktktktk
        '''
        conn = session.client('s3')
        playlist_entries = []
        fg = int(fg)
        # ts_count = fg & 0xf
        #fg 64位整型，低四位代表ts文件总数，然后进行位运算，一次移四位，每四位转为十进制即为当前ts文件的秒数
        for i in range(15):
            shift = (i + 1) * 4
            duration = (fg >> shift) & 0xf
            if duration > 0:
                tsFile = '{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': tsFile
                    },
                    ExpiresIn=3600
                )
                # m3u8 = '{uid}/vod{channel}/{time}/{time}.m3u8'. \
                #     format(uid=uid, channel=channel, time=vod['time'])
                playlist_entries.append({
                    'name': response_url,
                    'duration': duration,
                })

        playlist = PlaylistGenerator(playlist_entries).generate()
        response = HttpResponse(playlist)
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="play.m3u8"'
        return response

        # response = HttpResponse(playlist, content_type="application/vnd.apple.mpegurl")
        # response = HttpResponse(playlist, content_type="application/octet-stream")
        # return response

    def do_get_sign_sts(self, request_dict, ip, response):  # 获取sts令牌
        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, endTime__gte=now_time, channel=channel). \
                   values("bucket__mold", "bucket__bucket", "bucket__endpoint",
                          "bucket__region", "endTime").order_by('addTime')[:1]
        if ubqs.exists():
            # 亚马逊 s3 sts
            sts_qs = StsCrdModel.objects.filter(uid=uid, channel=channel). \
                values("addTime", "data")
            if sts_qs.exists():
                endTime = int(sts_qs[0]["addTime"]) + 5000
                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']

            try:
                aws_access_key_id = AWS_ACCESS_KEY_ID[ubqs[0]["bucket__mold"]]
                aws_secret_access_key = AWS_SECRET_ACCESS_KEY[ubqs[0]["bucket__mold"]]
                aws_arn = AWS_ARN[ubqs[0]["bucket__mold"]]
            except:
                res = {'code': 404, 'msg': 'mold not exists!'}
                return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")

            ###############
            boto3_sts = boto3.client(
                'sts',
                aws_access_key_id=aws_access_key_id,
                aws_secret_access_key=aws_secret_access_key,
                region_name=region_id
            )
            Policy = {
                "Version": "2012-10-17",
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Action": "s3:*",
                        "Resource": ["{aws_arn}:::{bucket_name}/{uid_channel}*".
                                         format(aws_arn=aws_arn, bucket_name=bucket_name, uid_channel=storage)]
                    }
                ]
            }
            response = boto3_sts.get_federation_token(
                Name='{role_name}'.format(role_name=uid + '_' + str(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': 900,
                'endpoint': endpoint,
                'bucket_name': bucket_name,
                'arn': response['FederatedUser']['Arn'],
                'code': 0,
                'storage': storage,
                'endTime': ubqs[0]['endTime'],
                'ip': ip,
                'region': region_id,
                'bucket_mold':ubqs[0]['bucket__mold']
            }
            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")
        res = {'code': 405, 'msg': 'Not purchased or expired!'}
        return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")

    def do_query_vod_list(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)

        dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False).values('vodPrimaryUserID',
                                                                                            'vodPrimaryMaster')
        if not dv_qs.exists():
            return response.json(12)
        if dv_qs[0]['vodPrimaryUserID'] != userID:
            return response.json(10034)
        now_time = int(time.time())
        bv_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time ,channel=channel).values('bucket_id').order_by('addTime')
        if not bv_qs.exists():
            return response.json(10030)
        vh_qs = VodHlsModel.objects.filter \
            (uid=uid, channel=channel, endTime__gte=now_time,time__range=(startTime, endTime), bucket_id=bv_qs[0]['bucket_id']). \
            values("id", "time", "sec", "bucket__bucket", "fg", "bucket__endpoint", "bucket__region", "bucket__mold")
        vod_play_list = []
        if not vh_qs.exists():
            return response.json(0, vod_play_list)
        aws_access_key_id = AWS_ACCESS_KEY_ID[vh_qs[0]["bucket__mold"]]
        aws_secret_access_key = AWS_SECRET_ACCESS_KEY[vh_qs[0]["bucket__mold"]]
        session = Session(
            aws_access_key_id=aws_access_key_id,
            aws_secret_access_key=aws_secret_access_key,
            region_name=vh_qs[0]["bucket__region"]
        )
        conn = session.client('s3')

        for vod in vh_qs:
            bucket__mold = vod["bucket__mold"]
            bucket_name = vod["bucket__bucket"]
            endpoint = vod["bucket__endpoint"]
            bucket__region = vod["bucket__region"]
            thumbspng = '{uid}/vod{channel}/{time}/Thumb.jpeg'. \
                format(uid=uid, channel=channel, time=vod['time'])
            response_url = conn.generate_presigned_url(
                'get_object',
                Params={
                    'Bucket': bucket_name,
                    'Key': thumbspng
                },
                ExpiresIn=3600
            )
            vod_url = '{server_domain}/cloudstorage/signplaym3u8?' \
                      'uid={uid}&channel={channel}&time={time}&sign=tktktktk'. \
                format(server_domain=SERVER_DOMAIN_SSL, uid=TokenObject().encryption(data={'uid': uid}), channel=channel, time=vod['time'])
            ts_num = int(vod['fg']) & 0xf
            vod_play_list.append({
                'start_time': vod['time'],
                'sign_url': vod_url,
                'thumb': response_url,
                'sec': vod['sec'],
                'ts_num': ts_num,
                'vod_id': vod['id']
            }),
        return response.json(0, vod_play_list)

    def do_store_playlist(self, request_dict, response):  # 设备调用，上传视频到s3，同时把视频数据信息传给服务器，服务器存储播放内容
        uidToken = request_dict.get('uidToken', None)
        storeTime = request_dict.get('time', None)
        sec = request_dict.get('sec', None)
        fg = request_dict.get('fg', 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(0)
        pass
        UID = utko.UID
        channel = utko.channel
        print('UID:')
        print(UID)
        print('channel:')
        print(channel)
        now_time = int(time.time())
        ubqs = UID_Bucket.objects.filter(uid=UID, endTime__gte=now_time, channel=channel). \
                   values("bucket__mold", "bucket__bucket", "bucket__endpoint",
                          "bucket__region", "status", "bucket__storeDay", "bucket__id").order_by('addTime')[:1]
        if ubqs.exists():
            ub_qs_data = ubqs[0]
            store_day = ub_qs_data['bucket__storeDay']
            bucket_id = ub_qs_data['bucket__id']
            end_time = int(storeTime) + store_day * 86400
            if ub_qs_data['status'] == 1:
                sts_qs = StsCrdModel.objects.filter(uid=UID, channel=channel, type=1). \
                    values("addTime", "data")
                if sts_qs.exists():
                    VodHlsModel.objects.create(
                        uid=UID,
                        channel=channel,
                        time=storeTime,
                        endTime=end_time,
                        bucket_id=bucket_id,
                        fg=fg,
                        sec=sec,
                    )
                    res = {'code': 0, 'msg': '存储成功'}
                    return HttpResponse(json.dumps(res, ensure_ascii=False),
                                        content_type="application/json,charset=utf-8")
                else:
                    res = {'code': 404, 'msg': '设备未购买'}
                    return HttpResponse(json.dumps(res, ensure_ascii=False),
                                        content_type="application/json,charset=utf-8")
            else:
                res = {'code': 404, 'msg': '设备未开启'}
                return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
        else:
            res = {'code': 404, 'msg': '设备未购买'}
            return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")

    def do_change_vod_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')
        dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1) \
            .values('vodPrimaryUserID')
        if not dv_qs.exists() or dv_qs[0]['vodPrimaryUserID'] != userID:
            return response.json(12)
        ubqs = UID_Bucket.objects.filter(channel=channel, uid=uid)
        if not ubqs.exists():
            return response.json(10030)
        now_time = int(time.time())
        if now_time > ubqs[0].endTime:
            return response.json(10031)
        ubqs.update(status=status)
        if status == 0:
            return response.json(0)
        utko = UidTokenObject()
        utko.generate(data={'uid': uid, 'channel': channel})
        uidTkUrl = "{SERVER_DOMAIN_SSL}cloudstorage/getsignsts?uidToken={uidToken}". \
            format(uidToken=utko.token, SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
        storeHlsUrl = "{SERVER_DOMAIN_SSL}cloudstorage/storeplaylist?uidToken={uidToken}". \
            format(uidToken=utko.token, SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
        return response.json(0, {'uidTkUrl': uidTkUrl, 'storeHlsUrl': storeHlsUrl})

    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.location.href="https://www.baidu.com?page=closePage";
    }
	</script>
</body> 
</html>
                '''
        return response

    def do_pay_ok(self, request_dict):  # 支付成功
        response = HttpResponse()
        paytype = request_dict.get('paytype', None)
        lang = request_dict.get('lang', 'en')

        showtitle = "支付成功"
        if paytype == "10" :
            showtitle = "成功体验云存"

        if paytype == "11":
            showtitle = "兑换成功"

        wancheng = '完成'
        if lang != 'cn':
            showtitle = "Payment successful"
            if paytype == "10":
                showtitle = "Successful experience of cloud storage"

            if paytype == "11":
                showtitle = "Successful exchange"

            wancheng = 'complete'
        response.content = '''
        
<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>''' + showtitle + '''</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: 15px;
                    color:#0000008A;
					
            }
            .content_img{
					margin-bottom:15px;
                    width: 60px; 
                    height: 60px;
            }
            .bottom{
                     margin-bottom: 10px; 
                     margin-top: 250px; 
                     color : white;
            }
            .bottom_div{
                    border: 1px solid #68c9c5; 
                    line-height: 38px; 
                    text-align: center; 
                    width: 100px; 
                    height: 38px;
                    border-radius: 30px;
					background-color:#68c9c5; 
            }
            
            .bottom_div:hover{
                    background-color: #dde4e2;
            }
    </style>
</head>
<body style="" rlt="1" inmaintabuse="true">
        
    <div class="content">
            <p>
					<img src="https://test.dvema.com/web/images/success.png" class="content_img">
                    <br>
                    ''' + showtitle + '''
            </p>
    </div>
    <center class="bottom">
            <div class="bottom_div" onclick="payOKButton()"> 
             '''+wancheng+'''
            </div>
    </center>
    <script src="//hm.baidu.com/hm.js?eaa57ca47dacb4ad4f5a257001a3457c"></script><script>             // 点击付款成功按钮
    function payOKButton() {
        // 复杂数据
        console.log('success')
        window.location.href="https://www.baidu.com?page=closePage"  
    }
        </script>
 

        <div id="qds" style="display:none;"></div></body></html>
        '''
        return response

    def do_pay_by_ali_callback(self, request):  # 阿里支付回调
        response = ResponseObject()
        data = request.POST.dict()
        # logger = logging.getLogger('log')
        try:
            passback_params = data["passback_params"]
            parmap = dict([(k, v[0]) for k, v in parse_qs(unquote(passback_params)).items()])
            lang = parmap["lang"]
            signature = data["sign"]
            data.pop('sign')
            orderID = data['out_trade_no']

            order_qs = Order_Model.objects.filter(orderID=orderID, status=0)

            aliPayObj = AliPayObject()
            alipay = aliPayObj.conf()
            success = alipay.verify(data, signature)

            if success and data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
                print("trade succeed")

                nowTime = int(time.time())
                order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
                                             "userID__userID", "userID__username")
                userid = order_list[0]['userID__userID']
                username = order_list[0]['userID__username']
                UID = order_list[0]['UID']
                channel = order_list[0]['channel']
                rank = order_list[0]['rank']

                smqs = Store_Meal.objects.filter(id=rank). \
                    values("day", "bucket_id", "bucket__storeDay", "expire")
                bucketId = smqs[0]['bucket_id']
                if not smqs.exists():
                    return response.json(173)
                ubqs = UID_Bucket.objects.filter(uid=UID).values("id", "bucket_id", "bucket__storeDay", "bucket__region",
                                                                 "endTime", "use_status")
                expire = smqs[0]['expire']
                if order_list[0]['isSelectDiscounts'] == 1:
                    expire = smqs[0]['expire'] * 2
                with transaction.atomic():
                    if ubqs.exists():
                        ubq = ubqs[0]
                        if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId:  #套餐使用中并且相同套餐叠加过期时间
                            endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
                            UID_Bucket.objects.filter(id=ubq['id']).update \
                                (uid=UID, channel=channel, bucket_id=bucketId,
                                 endTime=endTime, updateTime=nowTime)
                        else:     #已过期或者不相同的套餐加入未使用的关联套餐表
                            has_unused = Unused_Uid_Meal.objects.filter(uid=UID, bucket_id=bucketId).values("id")
                            nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
                            if has_unused.exists():
                                Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
                            else:
                                Unused_Uid_Meal.objects.create(uid=UID,channel=channel,addTime=nowTime,num=nums,
                                                               expire=smqs[0]['expire'],bucket_id=bucketId)
                            UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
                        uid_bucket_id = ubq['id']
                    else:
                        endTime = CommonService.calcMonthLater(expire)
                        ub_cqs = UID_Bucket.objects.create \
                            (uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
                             updateTime=nowTime,use_status=1)
                        uid_bucket_id = ub_cqs.id

                    dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
                    if dvq.exists():
                        dvq_set_update_dict = {
                            'vodPrimaryUserID': userid,
                            'vodPrimaryMaster': username
                        }
                        dvq.update(**dvq_set_update_dict)

                    # uid_main_exist = UIDMainUser.objects.filter(UID=UID)
                    # if not uid_main_exist.exists():
                    #     uid_main_dict = {
                    #         'UID': UID,
                    #         'user_id': userid
                    #     }
                    #     UIDMainUser.objects.create(**uid_main_dict)

                    order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id)
                    datetime = time.strftime("%Y-%m-%d", time.localtime())
                    sys_msg_text_list = ['尊重的客户，您的'+UID+'设备在'+datetime+'已成功购买云存套餐，特此通知。', 'Dear customer, your '+UID+' device has successfully purchased the cloud storage package at '+datetime+', hereby notified.']
                    self.do_vod_msg_Notice(UID, channel, userid, lang, sys_msg_text_list)
                    red_url = "{SERVER_DOMAIN_SSL}web/paid2/success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
                    if lang != 'cn':
                        red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
                    return HttpResponseRedirect(red_url)
            return response.json(0, signature)
        except Exception as e:
            if order_qs:
                order_qs.update(status=10)
            red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
            if lang != 'cn':
                red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
            return HttpResponseRedirect(red_url)

    def do_pay_by_paypal_callback(self, request_dict, response):  # paypal支付回调
        paymentId = request_dict.get('paymentId', None)
        PayerID = request_dict.get('PayerID', None)
        orderID = request_dict.get('orderID', None)
        lang = request_dict.get('lang', 'en')
        try:
            order_qs = Order_Model.objects.filter(orderID=orderID, status=0)

            if not orderID:
                red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
                if lang != 'cn':
                    red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
                return HttpResponseRedirect(red_url)
            # else:
            #     order_qs.update(status=9)
            paypalrestsdk.configure(PAYPAL_CRD)
            # ID of the payment. This ID is provided when creating payment.
            payment = paypalrestsdk.Payment.find(paymentId)
            payres = payment.execute({"payer_id": PayerID})
            print(payres)
            if not payres:
                red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
                if lang != 'cn':
                    red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
                return HttpResponseRedirect(red_url)
            print("Payment execute successfully")

            nowTime = int(time.time())
            order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
                                         "userID__userID",
                                         "userID__username")
            userid = order_list[0]['userID__userID']
            username = order_list[0]['userID__username']
            UID = order_list[0]['UID']
            channel = order_list[0]['channel']
            rank = order_list[0]['rank']
            smqs = Store_Meal.objects.filter(id=rank). \
                values("day", "bucket_id", "bucket__storeDay", "expire")
            bucketId = smqs[0]['bucket_id']
            if not smqs.exists():
                return response.json(173)
            # ##
            ubqs = UID_Bucket.objects.filter(uid=UID).values("id", "bucket_id", "bucket__storeDay", "bucket__region",
                                                             "endTime", "use_status")
            expire = smqs[0]['expire']

            if order_list[0]['isSelectDiscounts'] == 1:
                expire = smqs[0]['expire'] * 2
            with transaction.atomic():
                if ubqs.exists():
                    ubq = ubqs[0]
                    if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId:  #套餐使用中并且相同套餐叠加过期时间
                        endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
                        UID_Bucket.objects.filter(id=ubq['id']).update \
                            (uid=UID, channel=channel, bucket_id=bucketId,
                             endTime=endTime, updateTime=nowTime)
                    else:     #已过期或者不相同的套餐加入未使用的关联套餐表
                        has_unused = Unused_Uid_Meal.objects.filter(uid=UID, bucket_id=bucketId).values("id")
                        nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
                        if has_unused.exists():
                            Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
                        else:
                            Unused_Uid_Meal.objects.create(uid=UID,channel=channel,addTime=nowTime,num=nums,
                                                           expire=smqs[0]['expire'],bucket_id=bucketId)
                        UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
                    uid_bucket_id = ubq['id']
                else:
                    endTime = CommonService.calcMonthLater(expire)
                    ub_cqs = UID_Bucket.objects.create \
                        (uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
                         updateTime=nowTime,use_status=1)
                    uid_bucket_id = ub_cqs.id

                dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
                if dvq.exists():
                    dvq_set_update_dict = {
                        'vodPrimaryUserID': userid,
                        'vodPrimaryMaster': username
                    }
                    dvq.update(**dvq_set_update_dict)

                # uid_main_exist = UIDMainUser.objects.filter(UID=UID)
                # if not uid_main_exist.exists():
                #     uid_main_dict = {
                #         'UID': UID,
                #         'user_id': userid
                #     }
                #     UIDMainUser.objects.create(**uid_main_dict)

                order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id)
                datetime = time.strftime("%Y-%m-%d", time.localtime())
                sys_msg_text_list = ['尊重的客户，您的' + UID + '设备在' + datetime + '已成功购买云存套餐，特此通知。',
                                     'Dear customer, your ' + UID + ' device has successfully purchased the cloud storage package at ' + datetime + ', hereby notified.']

                self.do_vod_msg_Notice(UID, channel, userid, lang, sys_msg_text_list)

                # return response.json(0)
                red_url = "{SERVER_DOMAIN_SSL}web/paid2/success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
                if lang != 'cn':
                    red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)

                return HttpResponseRedirect(red_url)
        except Exception as e:
            print(repr(e))
            if order_qs:
                order_qs.update(status=10)
            red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
            if lang != 'cn':
                red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
            return HttpResponseRedirect(red_url)

    def do_pay_by_wechat_callback(self, request, response):  # 微信支付回调

        logger = logging.getLogger('log')
        try:
            pay = WechatPayObject()
            data = pay.weixinpay_call_back(request.body)
            attach = data["attach"]
            parmap = dict([(k, v[0]) for k, v in parse_qs(unquote(attach)).items()])
            lang = parmap["lang"]
            trade_status = data['result_code']  # 业务结果  SUCCESS/FAIL
            out_trade_no = data['out_trade_no']  # 商户订单号
            order_qs = Order_Model.objects.filter(orderID=out_trade_no, status=0)
            if trade_status == "SUCCESS":
                logger.info('微信回调返回值 进来了。')
                check_sign = pay.get_notifypay(data)
                if not check_sign:
                    return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '签名失败'}))
                logger.info('签名成功')
                orderID = out_trade_no
                print("进来了,微信支付成功回调")

                nowTime = int(time.time())
                order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
                                             "userID__userID", "userID__username")
                userid = order_list[0]['userID__userID']
                username = order_list[0]['userID__username']
                UID = order_list[0]['UID']
                channel = order_list[0]['channel']
                rank = order_list[0]['rank']
                smqs = Store_Meal.objects.filter(id=rank). \
                    values("day", "bucket_id", "bucket__storeDay", "expire")
                bucketId = smqs[0]['bucket_id']
                if not smqs.exists():
                    return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '套餐不存在'}))
                # ##
                ubqs = UID_Bucket.objects.filter(uid=UID).values("id", "bucket_id", "bucket__storeDay",
                                                                 "bucket__region", "endTime", "use_status")
                expire = smqs[0]['expire']
                if order_list[0]['isSelectDiscounts'] == 1:
                    expire = smqs[0]['expire'] * 2
                with transaction.atomic():
                    if ubqs.exists():
                        ubq = ubqs[0]
                        if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId:  #套餐使用中并且相同套餐叠加过期时间
                            endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
                            UID_Bucket.objects.filter(id=ubq['id']).update \
                                (uid=UID, channel=channel, bucket_id=bucketId,
                                 endTime=endTime, updateTime=nowTime)
                        else:     #已过期或者不相同的套餐加入未使用的关联套餐表
                            has_unused = Unused_Uid_Meal.objects.filter(uid=UID, bucket_id=bucketId).values("id")
                            nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
                            if has_unused.exists():
                                Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
                            else:
                                Unused_Uid_Meal.objects.create(uid=UID,channel=channel,addTime=nowTime,num=nums,
                                                               expire=smqs[0]['expire'],bucket_id=bucketId)
                            UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
                        uid_bucket_id = ubq['id']
                    else:
                        endTime = CommonService.calcMonthLater(expire)
                        ub_cqs = UID_Bucket.objects.create \
                            (uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
                             updateTime=nowTime,use_status=1)
                        uid_bucket_id = ub_cqs.id

                    dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
                    if dvq.exists():
                        dvq_set_update_dict = {
                            'vodPrimaryUserID': userid,
                            'vodPrimaryMaster': username
                        }
                        dvq.update(**dvq_set_update_dict)

                    # uid_main_exist = UIDMainUser.objects.filter(UID=UID)
                    # if not uid_main_exist.exists():
                    #     uid_main_dict = {
                    #         'UID': UID,
                    #         'user_id': userid
                    #     }
                    #     UIDMainUser.objects.create(**uid_main_dict)

                    order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id)
                    datetime = time.strftime("%Y-%m-%d", time.localtime())
                    sys_msg_text_list = ['尊重的客户，您的' + UID + '设备在' + datetime + '已成功购买云存套餐，特此通知。',
                                         'Dear customer, your ' + UID + ' device has successfully purchased the cloud storage package at ' + datetime + ', hereby notified.']
                    self.do_vod_msg_Notice(UID, channel, userid, lang, sys_msg_text_list)
                    return HttpResponse(pay.xml_to_dict({'return_code': 'SUCCESS', 'return_msg': 'OK'}))
            else:
                order_qs.update(status=10)
            return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '参数格式校验错误'}))
        except Exception as e:
            if order_qs:
                order_qs.update(status=10)
            return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': repr(e)}))

    def do_create_pay_order(self, request_dict, userID, ip, response):  # 创建支付订单
        uid = request_dict.get('uid', None)
        channel = request_dict.get('channel', None)
        pay_type = int(request_dict.get('pay_type', None))
        rank = request_dict.get('rank', None)
        is_select_discount = request_dict.get('is_select_discount', 0)
        lang = request_dict.get('lang', 'en')
        if not uid or not channel or not pay_type or not rank:
            return response.json(444)
        dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1).values(
            'vodPrimaryUserID',
            'vodPrimaryMaster')
        if not dv_qs.exists():
            return response.json(12)

        dvq = Device_Info.objects.filter(UID=uid)
        dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
        if dvq.exists():
            if dvq[0]['vodPrimaryUserID'] != userID:
                return response.json(10033)

        nowTime = int(time.time())

        # uq = UID_Bucket.objects.filter(uid=uid,endTime__gt=str(nowTime)).values('endTime')
        # if uq.exists():
        #     return response.json(10033)

        # if dv_qs[0]['vodPrimaryUserID'] != '' and dv_qs[0]['vodPrimaryUserID'] != userID:
        #     return response.json(10033)
        smqs = Store_Meal.objects.filter(id=rank, pay_type=pay_type, lang__lang=lang). \
            values('currency', 'price', 'lang__content', 'day',
                   'commodity_type', 'lang__title',
                   'expire', 'commodity_code', 'discount_price', 'bucket__mold')
        if not smqs.exists():
            return response.json(173)
        currency = smqs[0]['currency']
        price = smqs[0]['price']
        if is_select_discount == '1':
            price = float(smqs[0]['price']) + float(smqs[0]['discount_price'])
        content = smqs[0]['lang__content']
        day = smqs[0]['day']
        commodity_code = smqs[0]['commodity_code']
        commodity_type = smqs[0]['commodity_type']
        # ubqs = UID_Bucket.objects.filter(uid=uid, channel=channel, endTime__gte=nowTime). \
        #     values("bucket__storeDay", "bucket__region", "endTime")
        # if ubqs.exists():
        #     ubqs_count = ubqs.count()
        #     ubq = ubqs[ubqs_count - 1, ubqs_count]
        #     new_starTime = ubq['endTime'] + 1
        is_mold = 0  #判断国内外
        if smqs[0]['bucket__mold']==0:
            is_mold = 1

        order_qs = Order_Model.objects.filter(UID=uid , rank__bucket__mold=is_mold)
        if order_qs.exists():
            return response.json(10041)

        orderID = CommonService.createOrderID()
        if pay_type == 1:

            cal_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
            if lang != 'cn':
                cal_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
            call_sub_url = "{SERVER_DOMAIN_SSL}cloudstorage/dopaypalcallback?orderID={orderID}&lang={lang}". \
                format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, orderID=orderID, lang=lang)
            # call_sub_url = "http://binbin.uicp.vip/cloudstorage/dopaypalcallback?orderID={orderID}".format(
            # SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, orderID=orderID)
            call_clc_url = cal_url
            paypalrestsdk.configure(PAYPAL_CRD)
            payment = paypalrestsdk.Payment({
                "intent": "sale",
                "payer": {"payment_method": "paypal"},
                "redirect_urls": {"return_url": call_sub_url, "cancel_url": call_clc_url},
                "transactions": [{
                    "item_list": {"items": [
                        {"name": "Cloud video", "sku": "1", "price": price, "currency": "USD", "quantity": 1}]},
                    "amount": {"total": price, "currency": currency},
                    "description": content}]})
            if payment.create():
                print("Payment created successfully")
            else:
                print(payment.error)
                return response.json(10, payment.error)
            print(payment)
            for link in payment.links:
                if link.rel == "approval_url":
                    approval_url = str(link.href)
                    print("Redirect for approval: %s" % (approval_url))
                    Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
                                               desc=content, payType=pay_type, payTime=nowTime,
                                               price=price, currency=currency, addTime=nowTime, updTime=nowTime,
                                               pay_url=approval_url, isSelectDiscounts=is_select_discount,
                                               commodity_code=commodity_code, commodity_type=commodity_type,
                                               rank_id=rank)
                    return response.json(0, {"redirectUrl": approval_url, "orderID": orderID})
            return response.json(10, 'generate_order_false')
        elif pay_type == 2:
            try:
                aliPayObj = AliPayObject()
                alipay = aliPayObj.conf()
                subject = smqs[0]['lang__title'] + smqs[0]['lang__content']
                # biz_content = {
                #     "subject": subject,
                #     "out_trade_no": orderID,
                #     "total_amount": price,
                #     "product_code": "QUICK_WAP_PAY",
                #     "quit_url": "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
                #     # "qr_pay_mode":4
                # }
                order_string = alipay.api_alipay_trade_wap_pay(
                    out_trade_no=orderID,
                    total_amount=price,
                    subject=subject,
                    return_url="{SERVER_DOMAIN_SSL}web/paid2/success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL),
                    notify_url="{SERVER_DOMAIN_SSL}cloudstorage/doalicallback".format(
                        SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL),
                    quit_url="{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL),
                    passback_params=quote("lang="+lang)
                    # return_url="http://192.168.136.40/cloudstorage/payOK",
                    # notify_url="http://192.168.136.40/cloudstorage/aliPayCallback"
                )


            except Exception as e:
                print(repr(e))
                return response.json(10, repr(e))
            else:
                if order_string:
                    redirectUrl = aliPayObj.alipay_prefix + order_string
                    print('---------tttt')
                    print(redirectUrl)
                    Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
                                               desc=content, payType=pay_type, payTime=nowTime,
                                               price=price, currency=currency, addTime=nowTime, updTime=nowTime,
                                               pay_url=redirectUrl, isSelectDiscounts=is_select_discount,
                                               commodity_code=commodity_code, commodity_type=commodity_type,
                                               rank_id=rank)

                    return JsonResponse(status=200, data={'result_code': 0, 'reason': 'success',
                                                          'result': {"redirectUrl": redirectUrl, "orderID": orderID},
                                                          'error_code': 0})
                else:
                    return response.json(10, '生成订单错误.')

        elif pay_type == 3:
            pay = WechatPayObject()
            notify_url = "{SERVER_DOMAIN_SSL}cloudstorage/dowechatnotify".format(
                SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
            # 获取参数
            response = ResponseObject()

            parameter_dict = pay.get_parameter(orderID, content, float(price) * 100, ip, notify_url, quote("lang="+lang))
            print('parameter_dict', parameter_dict)
            # parameter_dict 参数中获取MWEB_URL 调转页面在路径后面添加redirect_url
            # 统一调用接口
            response = pay.re_finall(orderid=orderID)
            if not response:
                return response.json(10, '生成订单错误.')
            # 回调函数
            Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
                                       desc=content, payType=pay_type, payTime=nowTime,
                                       price=price, currency=currency, addTime=nowTime, updTime=nowTime,
                                       pay_url=notify_url, isSelectDiscounts=is_select_discount,
                                       commodity_code=commodity_code, commodity_type=commodity_type, rank_id=rank)
            return JsonResponse(status=200, data={'result_code': 0, 'reason': 'success',
                                                  'result': response,
                                                  'orderId': orderID,
                                                  'error_code': 0})
            # 调起支付接口

    # 生成体验订单
    def do_experience_order(self, request_dict, userID, response):
        uid = request_dict.get('uid', None)
        channel = request_dict.get('channel', None)
        commodity_code = request_dict.get('commodity_code', None)
        pay_type = int(request_dict.get('pay_type', None))
        rank = request_dict.get('rank', None)
        cdk = request_dict.get('cdk', None)
        lang = request_dict.get('lang', 'en')
        if cdk != None and pay_type == 11:
            cdk_qs = CDKcontextModel.objects.filter(cdk=cdk).values('is_activate', 'rank__id', 'rank__commodity_code')
            if not cdk_qs.exists():
                return response.json(10040)
            if cdk_qs[0]['is_activate'] == 1:
                return response.json(10039)
            rank = cdk_qs[0]['rank__id']
            commodity_code = cdk_qs[0]['rank__commodity_code']

        if uid == None or channel == None or commodity_code == None or pay_type == None or rank == None:
            return response.json(13, '参数有误.')

        dvq = Device_Info.objects.filter(UID=uid)
        dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
        if dvq.exists():
            if dvq[0]['vodPrimaryUserID'] != userID:
                if pay_type == 10:
                    return response.json(10035)
                if pay_type == 11:
                    return response.json(10036)

        dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1)
        if not dv_qs.exists():
            return response.json(12)

        orderID = CommonService.createOrderID()
        nowTime = int(time.time())
        smqs = Store_Meal.objects.filter(id=rank,lang__lang=lang). \
            values("day", "bucket_id", "bucket__storeDay", "expire", 'lang__content', 'price', 'currency', 'commodity_type')
        if not smqs.exists():
            return response.json(173)
        bucketId = smqs[0]['bucket_id']
        # ##
        ubqs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id", "bucket__storeDay", "bucket__region",
                                                         "endTime", "use_status")
        expire = smqs[0]['expire']
        try:
            with transaction.atomic():
                if ubqs.exists():
                    ubq = ubqs[0]
                    if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId:  #套餐使用中并且相同套餐叠加过期时间
                        endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
                        UID_Bucket.objects.filter(id=ubq['id']).update \
                            (uid=uid, channel=channel, bucket_id=bucketId,
                             endTime=endTime, updateTime=nowTime)
                    else:     #已过期或者不相同的套餐加入未使用的关联套餐表
                        has_unused = Unused_Uid_Meal.objects.filter(uid=uid, bucket_id=bucketId).values("id")
                        nums = 1
                        if has_unused.exists():
                            Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
                        else:
                            Unused_Uid_Meal.objects.create(uid=uid,channel=channel,addTime=nowTime,num=nums,
                                                           expire=smqs[0]['expire'],bucket_id=bucketId)
                        UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
                    uid_bucket_id = ubq['id']
                else:
                    endTime = CommonService.calcMonthLater(expire)
                    ub_cqs = UID_Bucket.objects.create \
                        (uid=uid, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
                         updateTime=nowTime,use_status=1)
                    uid_bucket_id = ub_cqs.id
                Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
                                           desc=smqs[0]['lang__content'], payType=pay_type, payTime=nowTime,
                                           price=smqs[0]['price'], currency=smqs[0]['currency'], addTime=nowTime,
                                           updTime=nowTime,
                                           pay_url="体验版",
                                           commodity_code=commodity_code, commodity_type=smqs[0]['commodity_type'],
                                           rank_id=rank, status=1, uid_bucket_id=uid_bucket_id)

                duq = Device_User.objects.filter(userID=userID).values('username')
                dvq = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')



                if dvq.exists():
                    dvq_set_update_dict = {
                        'vodPrimaryUserID': userID,
                        'vodPrimaryMaster': duq[0]['username']
                    }
                    dvq.update(**dvq_set_update_dict)

                # uid_main_exist = UIDMainUser.objects.filter(UID=uid)
                # if not uid_main_exist.exists():
                #     uid_main_dict = {
                #         'UID': uid,
                #         'user_id': userID
                #     }
                #     UIDMainUser.objects.create(**uid_main_dict)

                datetime = time.strftime("%Y-%m-%d", time.localtime())
                sys_msg_text_list = ['尊重的客户，您的' + uid + '设备在' + datetime + '已成功购买云存套餐，特此通知。',
                                     'Dear customer, your ' + uid + ' device has successfully purchased the cloud storage package at ' + datetime + ', hereby notified.']
                # return response.json(0)
                returnurl = "{SERVER_DOMAIN_SSL}cloudstorage/payOK?lang={lang}".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL,lang=lang)
                if pay_type == 10:
                    ExperienceContextModel.objects.create(
                        experience_type=0,
                        uid=uid,
                        do_time=nowTime
                    )
                    returnurl = "{SERVER_DOMAIN_SSL}cloudstorage/payOK?paytype=10&lang={lang}".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL,lang=lang)
                    datetime = time.strftime("%Y-%m-%d", time.localtime())
                    sys_msg_text_list = ['尊重的客户，您的' + uid + '设备在' + datetime + '已成功体验云存，特此通知。',
                                         'Dear customers, your '+uid+' device has successfully experienced cloud storage at '+datetime+', hereby notified.']

                if pay_type == 11:
                    update_dict = {}
                    update_dict['is_activate'] = 1
                    update_dict['order'] = orderID
                    CDKcontextModel.objects.filter(cdk=cdk).update(**update_dict)
                    returnurl = "{SERVER_DOMAIN_SSL}cloudstorage/payOK?paytype=11&lang={lang}".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL,lang=lang)

                    datetime = time.strftime("%Y-%m-%d", time.localtime())
                    sys_msg_text_list = ['尊重的客户，您的' + uid + '设备在' + datetime + '已成功兑换云存，特此通知。',
                                         'Dear customer, your '+uid+' device has been redeemed for cloud deposit at '+datetime+', hereby notified.']


                self.do_vod_msg_Notice(uid, channel, userID, lang, sys_msg_text_list)
                result = returnurl
                return response.json(0, result)
        except Exception:
            return response.json(474)
        # red_url =
        # return JsonResponse(status=200, data={'red_url': red_url})

        # return HttpResponseRedirect(red_url)

    # 重置设备云存体验
    def do_experience_reset(self, request_dict, userID, response):
        bid = request_dict.get("id", None)
        ubq = UID_Bucket.objects.filter(id=bid)
        if ubq:
            eq = ExperienceContextModel.objects.filter(uid=ubq[0].uid)
            if eq:
                eq.delete()
                Order_Model.objects.filter(uid_bucket_id=bid).delete()
                ubq.delete()
            else:
                return response.json(10007)

        else:
            return response.json(0, '重置云存体验失败')

        return response.json(0, '重置云存体验成功')

    def deleteVodList(self, request_dict, userID, response):  # 删除播放列表
        uid = request_dict.get('uid', None)
        dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1) \
            .values('vodPrimaryUserID')
        if not dv_qs.exists() or dv_qs[0]['vodPrimaryUserID'] != userID:
            return response.json(12)
        vod_id_list = json.loads(request_dict.get('vod_id_list', None))
        is_del_all = request_dict.get('is_del_all', 0)
        try:
            if is_del_all == 1:
                VodHlsModel.objects.filter(uid=uid).delete()
            else:
                if type(vod_id_list).__name__ != 'list':
                    return response.json(444)
                VodHlsModel.objects.filter(id__in=vod_id_list).delete()
        except Exception as e:
            return response.json(424, repr(e))
        else:
            return response.json(0)

    # 设备关联套餐列表
    def device_commodity(self, request_dict, userID, response):
        uid = request_dict.get('uid', None)
        lang = request_dict.get('lang', 'en')
        dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1) \
            .values('vodPrimaryUserID')
        if not dv_qs.exists() or dv_qs[0]['vodPrimaryUserID'] != userID:
            return response.json(12)
        now_time = int(time.time())
        bucket_id_list = []
        store_list = []
        uid_bucket = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time).values("id", "uid","bucket__content",
                                                                    "use_status","endTime","has_unused","bucket__id")
        if not uid_bucket:
            return response.json(10030)
        uid_bucket[0]['storage'] = 0
        has_unused = uid_bucket[0]['has_unused']
        del uid_bucket[0]['has_unused']
        store_list.append(uid_bucket[0])
        bucket_id_list.append(uid_bucket[0]['bucket__id'])
        if has_unused == 1:
            unuseds = Unused_Uid_Meal.objects.filter(uid=uid).annotate(unused_id=F('id')) \
                .values("unused_id","uid","bucket__content","num","bucket__id","expire")
            for ub in unuseds:
                storage_time = ub['num'] *  ub['expire']
                storage = "{storage_time}个月".format(storage_time=storage_time)
                unused_dict = {
                    "id":ub['unused_id'],
                    "uid":ub['uid'],
                    "bucket__content":ub['bucket__content'],
                    "use_status":0,
                    "endTime":0,
                    "bucket__id":ub['bucket__id'],
                    "storage":storage,
                }
                store_list.append(unused_dict)
                bucket_id_list.append(ub['bucket__id'])
        smqs = Store_Meal.objects.filter(bucket__id__in=bucket_id_list, lang__lang=lang).values('lang__lang','bucket__id','lang__title')
        for index, value in enumerate(store_list):
            for sm in smqs:
                if value['bucket__id'] == sm['bucket__id']:
                    value['bucket__content'] = sm['lang__title']

        return response.json(0, list(store_list))

    # 提前使用设备关联套餐
    def switch_device_commodity(self, request_dict, userID, response):
        uid = request_dict.get('uid', None)
        dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1) \
            .values('vodPrimaryUserID')
        if not dv_qs.exists() or dv_qs[0]['vodPrimaryUserID'] != userID:
            return response.json(12)
        unused_id = request_dict.get('switch_commodity_id', None)
        if unused_id:
            # 切换设备套餐关联
            using_uid_bucket = UID_Bucket.objects.filter(uid=uid,has_unused=1).values("id", "uid", "endTime",
                                                                 "bucket__content","addTime")
            unuseds = Unused_Uid_Meal.objects.filter(id=unused_id).values("id","uid","channel","addTime","expire",
                                                                         "num","bucket_id")
            if not unuseds.exists() or not using_uid_bucket.exists():
                return response.json(10030)
            unused = unuseds[0]
            nowTime = int(time.time())
            try:
                with transaction.atomic():
                    count_unused = Unused_Uid_Meal.objects.filter(uid=uid).count()
                    has_unused = 1 if count_unused>1 else 0
                    endTime = CommonService.calcMonthLater(unused['expire'] * unused['num'])
                    UID_Bucket.objects.filter(uid=uid).update(channel=unused['channel'],endTime=endTime,bucket_id=unused['bucket_id']
                                                              ,updateTime=nowTime,use_status=1, has_unused=has_unused)
                    Unused_Uid_Meal.objects.filter(id=unused_id).delete()
                    StsCrdModel.objects.filter(uid=uid).delete()  # 删除sts记录
                    VodHlsModel.objects.filter(uid=uid).delete()  # 删除播放列表,后期数据量多时应该考虑延后删除
            except Exception:
                return response.json(474)
            return response.json(0)
        return response.json(444)

    # 云存操作系统消息
    def do_vod_msg_Notice(self, uid, channel, userID, lang, sys_msg_text_list):
        try:
            logger = logging.getLogger('log')
            logger.info('进来了')
            # user = Device_User.objects.get(userID = userID)
            # lang = user.language;
            if lang == 'cn':
                sys_msg_text = sys_msg_text_list[0]
            else:
                sys_msg_text = sys_msg_text_list[1]
            nowTime = int(time.time())
            create_data = {'userID_id': userID, 'msg': sys_msg_text, 'addTime': nowTime,
                           'updTime': nowTime, 'uid': uid, 'eventType': 0}
            SysMsgModel.objects.create(**create_data)

            user_qs = Device_User.objects.filter(userID=userID)
            if user_qs.exists():
                user = user_qs[0]
                username = user.username
                data_valid = DataValid()
                if data_valid.email_validate(username):
                    S3Email.faEmail(sys_msg_text,username)
                elif data_valid.mobile_validate(username):
                    params = u'{"devname":"' + uid + '","submittime":"' + time.strftime("%Y-%m-%d",time.localtime()) + '"}'
                    self.sendMessage(username, params, 'SMS_217405528')

                self.pushApp(nowTime, uid, channel, sys_msg_text)


            logger.info('出去了')
        except Exception as e:
            return repr(e)
    # 云存到期续费提醒   提前3天
    def do_vod_msg_end(self, request_dict):
        response = ResponseObject()
        now_time = int(time.time())
        # 前7天提示一次
        list = UID_Bucket.objects.filter(Q(endTime__lte=(now_time - 3600 * 168)) & Q(endTime__gt=now_time - 3600 * 72)).values('id','uid','bucket__area','channel','endTime')
        self.do_vod_msg(now_time,list)

        # 前3天提示一次
        list = UID_Bucket.objects.filter(Q(endTime__lte=(now_time - 3600 * 72)) & Q(endTime__gt=now_time)).values('id','uid','bucket__area','channel','endTime')
        self.do_vod_msg(now_time,list)
        return response.json(0)

    def do_vod_msg(self, now_time, list):
        uq_list = []
        ids = []
        for ub in list:
            ids.append(ub['id'])

        oqlist = Order_Model.objects.filter(uid_bucket_id__in=ids).values('userID_id', 'uid_bucket_id')

        for ub in list:
            for oo in oqlist:
                if ub['id'] == oo['uid_bucket_id']:
                    if ub['bucket__area'] == 'cn':
                        sys_msg_text = "尊重的客户，您" + ub['uid'] + "设备的云存套餐将在" + time.strftime("%Y-%m-%d",
                                                                                           ub['endTime']) + "到期，特此通知。"
                    else:
                        sys_msg_text = "Dear customer, the cloud storage package of your " + ub[
                            'uid'] + " device will expire in " + time.strftime("%Y-%m-%d",
                                                                               ub['endTime']) + ", hereby notified."
                    uq_list.append(SysMsgModel(
                        userID_id=oo['userID_id'],
                        addTime=now_time,
                        updTime=now_time,
                        uid=ub['uid'],
                        eventType=0,
                        msg=sys_msg_text,
                        status=0
                    ))
                    user_qs = Device_User.objects.filter(userID=oo['userID_id'])
                    if user_qs.exists():
                        user = user_qs[0]
                        username = user.username
                        data_valid = DataValid()

                        if data_valid.email_validate(username):
                            S3Email.faEmail(sys_msg_text, username)
                        elif data_valid.mobile_validate(username):
                            params = u'{"devname":"' + ub['uid'] + '","submittime":"' + time.strftime("%Y-%m-%d",
                                                                                                      ub[
                                                                                                          'endTime']) + '"}'
                            self.sendMessage(username, params, 'SMS_217425550')

                        self.pushApp(now_time, ub['uid'], ub['channel'], sys_msg_text)

        SysMsgModel.objects.bulk_create(uq_list)


    def pushApp(self, nowTime, uid, channel, sys_msg_text):
        n_time = nowTime

        kwag_args = {
            'uid': uid,
            'channel': channel,
            'event_type': 0,
            'n_time': n_time
        }

        # 从数据库查询出来
        uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
            values('token_val', 'app_type', 'appBundleId', 'm_code',
                   'push_type', 'userID_id', 'userID__NickName',
                   'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
                   'uid_set__channel')
        print(uid_push_qs)
        # 新建一个list接收数据
        redis_list = []
        # 把数据库数据追加进redis_list
        for qs in uid_push_qs:
            redis_list.append(qs)

        nickname = redis_list[0]['uid_set__nickname']

        for up in redis_list:
            push_type = up['push_type']
            appBundleId = up['appBundleId']
            token_val = up['token_val']
            lang = up['lang']
            tz = up['tz']
            if tz is None or tz == '':
                tz = 0

            package_title_config = FCM_CONFIG[appBundleId]
            if appBundleId in package_title_config.keys():
                msg_title = package_title_config[appBundleId] + '(' + nickname + ')'
            else:
                msg_title = nickname

            # 发送内容
            msg_text = sys_msg_text
            kwag_args['appBundleId'] = appBundleId
            kwag_args['token_val'] = token_val
            kwag_args['msg_title'] = msg_title
            kwag_args['msg_text'] = msg_text
            push_server_status = 0
            # 推送
            if push_type == 0:  # ios apns

                try:
                    cli = apns2.APNSClient(mode=APNS_MODE,
                                           client_cert=os.path.join(BASE_DIR,
                                                                    APNS_CONFIG[appBundleId]['pem_path']))

                    push_data = {"alert": "Motion ", "event_time": n_time, "event_type": 0, "msg": "",
                                 "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1",
                                 "channel": channel}
                    alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
                    payload = apns2.Payload(alert=alert, custom=push_data)

                    # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
                    n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
                    res = cli.push(n=n, device_token=token_val, topic=appBundleId)
                    print(res.status_code)
                    if res.status_code == 200:
                        return res.status_code
                    else:
                        print('apns push fail')
                        print(res.reason)
                        return res.status_code
                except (ValueError, ArithmeticError):
                    return 'The program has a numeric format exception, one of the arithmetic exceptions'
                except Exception as e:
                    print(repr(e))
                    return repr(e)

            elif push_type == 1:  # android gcm
                try:
                    serverKey = FCM_CONFIG[appBundleId]
                except Exception as e:
                    return 'serverKey abnormal'
                push_service = FCMNotification(api_key=serverKey)
                data = {"alert": "Motion ", "event_time": n_time, "event_type": 0, "msg": "",
                        "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
                result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
                                                           message_body=msg_text, data_message=data,
                                                           extra_kwargs={
                                                               'default_vibrate_timings': True,
                                                               'default_sound': True,
                                                               'default_light_settings': True
                                                           })
                print('fcm push ing')
                print(result)
                return result
            elif push_type == 2:  # android jpush
                print('do_jpush')
                app_key = JPUSH_CONFIG[appBundleId]['Key']
                master_secret = JPUSH_CONFIG[appBundleId]['Secret']
                # 此处换成各自的app_key和master_secre
                _jpush = jpush.JPush(app_key, master_secret)
                push = _jpush.create_push()
                # if you set the logging level to "DEBUG",it will show the debug logging.
                # _jpush.set_logging("DEBUG")
                # push.audience = jpush.all_
                push.audience = jpush.registration_id(token_val)
                push_data = {"alert": "Motion ", "event_time": n_time, "event_type": 0, "msg": "",
                             "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
                android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
                                        big_text=msg_text, title=msg_title,
                                        extras=push_data)
                push.notification = jpush.notification(android=android)
                push.platform = jpush.all_
                res = push.send()
                print(res)
                return res.status_code

    def sendMessage(self, phone , params, temp_msg):
            # 购买成功
            sign_ms = 'Ansjer'
            # 发送手机验证码
            aliSms = AliSmsObject()
            res = aliSms.send_code_sms_cloud(phone=phone, params = params, sign_name=sign_ms,
                                       temp_msg=temp_msg)



# 删除过期云存播放列表
def deleteVodHls(request):
    # UID = 'DSXG7481JVA2JM94111A'
    # channel = 1
    # ubqs = UID_Bucket.objects.filter(uid=UID, channel=channel). \
    #     values("bucket_id", "endTime", "bucket__storeDay")
    # nowTime = int(time.time())
    # if ubqs.exists():
    #     ubqs_count = ubqs.count()
    #     ubq = ubqs[ubqs_count - 1, ubqs_count]
    #     new_starTime = ubq['endTime'] + 1
    #     print(new_starTime)
    #     exit()
    #
    #     # ub_cqs = UID_Bucket.objects.create(uid=UID, channel=channel, bucket_id=bucketId,
    #     #                                    endTime=new_starTime + addTime)
    #     # uid_bucket_id = ub_cqs.id
    # exit()

    response = ResponseObject()
    i = int(request.GET.get('i', 5))
    nowTime = int(time.time())
    for i in range(i):
        vh_qs = VodHlsModel.objects.filter(endTime__lte=str(nowTime))[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)


# 更新过期云存关联套餐
def updateExpiredUidBucket(request):
    response = ResponseObject()
    now_time = int(time.time())
    expired_uid_bucket = UID_Bucket.objects.filter(endTime__lte=now_time)
    id_list = expired_uid_bucket.values_list("id", flat=True)
    UID_Bucket.objects.filter(id__in=list(id_list)).update(use_status=2)  # 更新过期云存关联套餐状态
    return response.json(0)

# 如果云存关联套餐过期，更新未使用的关联套餐
def updateUnusedUidBucket(request):
    response = ResponseObject()
    now_time = int(time.time())
    expired_uid_buckets = UID_Bucket.objects.filter(endTime__lte=now_time,has_unused=1).values("id","uid")[0:1000]
    for expired_uid_bucket in expired_uid_buckets:
        unuseds = Unused_Uid_Meal.objects.filter(uid=expired_uid_bucket['uid']).values("id","uid","channel","addTime","expire",
                                                                  "num","bucket_id").order_by('addTime')[0:1]
        if not unuseds.exists():
            continue
        unused = unuseds[0]
        try:
            with transaction.atomic():
                count_unused = Unused_Uid_Meal.objects.filter(uid=expired_uid_bucket['uid']).count()
                has_unused = 1 if count_unused>1 else 0
                endTime = CommonService.calcMonthLater(unused['expire'] * unused['num'])
                UID_Bucket.objects.filter(uid=expired_uid_bucket['uid']).update(channel=unused['channel'],endTime=endTime,bucket_id=unused['bucket_id']
                                                          ,updateTime=now_time,use_status=1,
                                                          has_unused=has_unused)
                Unused_Uid_Meal.objects.filter(id=unused['id']).delete()
                StsCrdModel.objects.filter(uid=expired_uid_bucket['uid']).delete()  # 删除sts记录
                VodHlsModel.objects.filter(uid=expired_uid_bucket['uid']).delete()  # 删除播放列表,后期数据量多时应该考虑延后删除
        except Exception:
            continue
    # UID_Bucket.objects.filter(id__in=list(id_list)).update(use_status=2)  # 更新过期云存关联套餐状态
    return response.json(0)