| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767 | #!/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 jsonimport osimport timeimport urllibfrom urllib.parse import quote, parse_qs, unquoteimport apns2import boto3import jpushimport oss2import paypalrestsdkimport threadingimport calendarimport datetimeimport loggingfrom aliyunsdkcore import clientfrom aliyunsdksts.request.v20150401 import AssumeRoleRequestfrom boto3.session import Sessionfrom django.http import JsonResponse, HttpResponseRedirect, HttpResponsefrom django.db import transactionfrom django.views.generic.base import Viewimport jwtfrom pyfcm import FCMNotificationfrom 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_SECRETfrom 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, RegionCountryModelfrom Object.AliPayObject import AliPayObjectfrom Object.ResponseObject import ResponseObjectfrom Object.TokenObject import TokenObjectfrom Object.UidTokenObject import UidTokenObjectfrom Service.CommonService import CommonServicefrom Object.m3u8generate import PlaylistGeneratorfrom Object.WechatPayObject import WechatPayObjectfrom django.db.models import Q, Ffrom Service.ModelService import ModelServiceSERVER_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# commoditylisthttp://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 == 'testpaly.m3u8':            return self.do_test_play_m3u8(request_dict, response)        elif operation == 'dopaypalcallback':            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':            ip = CommonService.get_ip_address(request)            return self.do_get_sign_sts(request_dict, ip, response)        elif operation == 'testgetsignsts':            ip = CommonService.get_ip_address(request)            return self.do_test_get_sign_sts(request_dict, ip, response)            # return self.do_get_sign_sts_test(request_dict, ip, response)        elif operation == 'storeplaylist':            return self.do_store_playlist(request_dict, response)        elif operation == 'signplaym3u8':            return self.do_sign_play_m3u8(request_dict, response)        elif operation == 'payOK':            return self.do_pay_ok(request_dict)        elif operation == 'vodMsgEnd':            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':                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_test_play_m3u8(self, request_dict, response):        playlist_entries = [            {                'name': 'https://azvod1.s3-ap-northeast-1.amazonaws.com/test/output000.ts',                'duration': 10,            },            {                'name': 'https://azvod1.s3-ap-northeast-1.amazonaws.com/test/output000.ts',                'duration': 10,            },            {                'name': 'https://azvod1.s3-ap-northeast-1.amazonaws.com/test/output000.ts',                'duration': 10,            },        ]        playlist = PlaylistGenerator(playlist_entries).generate()        # return HttpResponse(playlist)        # response = HttpResponse(playlist, content_type="application/octet-stream")        response = HttpResponse(playlist, content_type="application/vnd.apple.mpegurl")        return response    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')        #userObj = Device_User.objects.get(userID=userID)        #regionObj = RegionCountryModel.objects.get(number=userObj.region_country)        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(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):        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 = []        # for i in range(fg):        #     thumbspng = '{uid}/vod{channel}/{time}/ts{i}.ts'. \        #         format(uid=uid, channel=channel, time=storeTime, i=i)        #     response_url = conn.generate_presigned_url(        #         'get_object',        #         Params={        #             'Bucket': bucket_name,        #             'Key': thumbspng        #         },        #         ExpiresIn=3600        #     )        #     # m3u8 = '{uid}/vod{channel}/{time}/{time}.m3u8'. \        #     #     format(uid=uid, channel=channel, time=vod['time'])        #     playlist_entries.append({        #         'name': response_url,        #         'duration': sec,        #     })        fg = int(fg)        ts_count = fg & 0xf        for i in range(ts_count):            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):        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").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"]) + 500                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=900            )            ##############            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_test_get_sign_sts(self, request_dict, ip, response):        uidToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJYS1daU0M1RkNKWVQxOUI3MTExQSIsImNoYW5uZWwiOjF9.YvBCETPrKknw7B-RU3Mij-WJLKf46KGrDQvZMMN7dQk'        reset = request_dict.get('reset', 0)        utko = UidTokenObject(uidToken)        if utko.flag is False:            return response.json(444, 'uidToken')        uid = utko.UID        channel = utko.channel        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").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"]) + 300                # if reset == '0':                #     print(endTime)                #     print(now_time)                #     res = json.loads(sts_qs[0]["data"])                #     return JsonResponse(status=200, data=res)                if reset == '0' and endTime > now_time:                    print(endTime)                    print(now_time)                    res = json.loads(sts_qs[0]["data"])                    return JsonResponse(status=200, data=res)                # 套餐id            storage = '{uid}/test/'.format(uid=uid)            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=900            )            ##############            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, channel=channel, endTime__gte=now_time).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, uid=TokenObject().encryption(data={'uid': uid}), channel=channel, time=vod['time'])            ts_num = int(vod['fg']) & 0xf            vod_play_list.append({                'name': 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):        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, channel=channel, endTime__gte=now_time). \                   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}cloudstorage/getsignsts?uidToken={uidToken}". \            format(uidToken=utko.token, SERVER_DOMAIN=SERVER_DOMAIN)        storeHlsUrl = "{SERVER_DOMAIN}cloudstorage/storeplaylist?uidToken={uidToken}". \            format(uidToken=utko.token, SERVER_DOMAIN=SERVER_DOMAIN)        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)                    order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id)                    sys_msg_text_list = ['成功购买云存', 'Successful purchase of cloud storage']                    self.do_vod_msg_Notice(UID, channel, userid, lang, sys_msg_text_list)                    red_url = "{SERVER_DOMAIN}web/paid2/success.html".format(SERVER_DOMAIN=SERVER_DOMAIN)                    if lang != 'cn':                        red_url = "{SERVER_DOMAIN}web/paid2/en_success.html".format(SERVER_DOMAIN=SERVER_DOMAIN)                    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}web/paid2/fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)            if lang != 'cn':                red_url = "{SERVER_DOMAIN}web/paid2/en_fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)            return HttpResponseRedirect(red_url)    def do_pay_by_paypal_callback(self, request_dict, response):        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}web/paid2/fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)                if lang != 'cn':                    red_url = "{SERVER_DOMAIN}web/paid2/en_fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)                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}web/paid2/fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)                if lang != 'cn':                    red_url = "{SERVER_DOMAIN}web/paid2/en_fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)                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)                order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id)                sys_msg_text_list = ['成功购买云存','Successful purchase of cloud storage']                self.do_vod_msg_Notice(UID, channel, userid, lang, sys_msg_text_list)                # return response.json(0)                red_url = "{SERVER_DOMAIN}web/paid2/success.html".format(SERVER_DOMAIN=SERVER_DOMAIN)                if lang != 'cn':                    red_url = "{SERVER_DOMAIN}web/paid2/en_success.html".format(SERVER_DOMAIN=SERVER_DOMAIN)                return HttpResponseRedirect(red_url)        except Exception as e:            print(repr(e))            if order_qs:                order_qs.update(status=10)            red_url = "{SERVER_DOMAIN}web/paid2/fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)            if lang != 'cn':                red_url = "{SERVER_DOMAIN}web/paid2/en_fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)            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)                    order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id)                    sys_msg_text_list = ['成功购买云存', 'Successful purchase of cloud storage']                    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}web/paid2/fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)            if lang != 'cn':                cal_url = "{SERVER_DOMAIN}web/paid2/en_fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)            call_sub_url = "{SERVER_DOMAIN}cloudstorage/dopaypalcallback?orderID={orderID}&lang={lang}". \                format(SERVER_DOMAIN=SERVER_DOMAIN, orderID=orderID, lang=lang)            # call_sub_url = "http://binbin.uicp.vip/cloudstorage/dopaypalcallback?orderID={orderID}".format(            # SERVER_DOMAIN=SERVER_DOMAIN, 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}web/paid2/fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)                #     # "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}web/paid2/success.html".format(SERVER_DOMAIN=SERVER_DOMAIN),                    notify_url="{SERVER_DOMAIN_SSL}cloudstorage/doalicallback".format(                        SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL),                    quit_url="{SERVER_DOMAIN}web/paid2/fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN),                    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)                sys_msg_text_list = ['成功购买云存', 'Successful purchase of cloud storage']                # return response.json(0)                returnurl = "{SERVER_DOMAIN}cloudstorage/payOK?lang={lang}".format(SERVER_DOMAIN=SERVER_DOMAIN,lang=lang)                if pay_type == 10:                    ExperienceContextModel.objects.create(                        experience_type=0,                        uid=uid,                        do_time=nowTime                    )                    returnurl = "{SERVER_DOMAIN}cloudstorage/payOK?paytype=10&lang={lang}".format(SERVER_DOMAIN=SERVER_DOMAIN,lang=lang)                    sys_msg_text_list = ['成功体验云存', 'Successful experience of cloud storage']                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}cloudstorage/payOK?paytype=11&lang={lang}".format(SERVER_DOMAIN=SERVER_DOMAIN,lang=lang)                    sys_msg_text_list = ['成功兑换云存', 'Successful exchange of cloud storage']                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)            self.pushApp(nowTime, uid, channel, sys_msg_text)            logger.info('出去了')        except Exception as e:            return repr(e)    # 云存到期续费提醒   提前1天    def do_vod_msg_end(self, request_dict):        response = ResponseObject()        now_time = int(time.time())        list = UID_Bucket.objects.filter(Q(endTime__lte=(now_time - 3600 * 24)) & Q(endTime__gt=now_time)).values('id',                                                                                                                  'uid',                                                                                                                  'bucket__area','channel')        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 = "云存即将过期,请您注意!"                    else:                        sys_msg_text = "Cloud storage is about to expire, please pay attention!"                    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                    ))                    self.pushApp(now_time, ub['uid'], ub['channel'], sys_msg_text)        SysMsgModel.objects.bulk_create(uq_list)        return response.json(0)    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 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","userID_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,userID_id=unused['userID_id'],                                                          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)
 |