| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808 | #!/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 Controller.CheckUserData import DataValidfrom 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, UserModelfrom Object.AWS.S3Email import S3Emailfrom Object.AliPayObject import AliPayObjectfrom Object.AliSmsObject import AliSmsObjectfrom 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, F, Countfrom 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# 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 == '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)        elif operation == 'doRefund':  # 退款            return self.do_refund(request_dict, response)        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)            elif operation == 'hasvod':  #APP的回放界面,日历表显示当天有无录像                return self.has_vod(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')        uidToken = TokenObject().encryption(data={'uid': uid})        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=uidToken, 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:                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")    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.zositechc.cn/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.zositechc.cn/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.zositechc.cn/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.zositechc.cn/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,you already subscribed the cloud storage package successfully for device ' + UID + ' on '+ time.strftime("%b %dth,%Y", time.localtime())]                    self.do_vod_msg_Notice(UID, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')                    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)            print(payment)            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,you already subscribed the cloud storage package successfully for device ' + UID + ' on ' + time.strftime(                                         "%b %dth,%Y", time.localtime())]                self.do_vod_msg_Notice(UID, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')                # 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,you already subscribed the cloud storage package successfully for device ' + UID + ' on ' + time.strftime(                                             "%b %dth,%Y", time.localtime())]                    self.do_vod_msg_Notice(UID, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')                    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)            paymentID = payment['id']   # 获取paymentID            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, paymentID=paymentID)                    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)                sms = 'SMS_219738485'                datetime = time.strftime("%Y-%m-%d", time.localtime())                sys_msg_text_list = ['温馨提示:尊敬的客户,您的' + uid + '设备在' + datetime + '已成功购买云存套餐',                                     'Dear customer,you already subscribed the cloud storage package successfully for device ' + uid + ' on ' + time.strftime(                                         "%b %dth,%Y", time.localtime())]                # 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 customer,you already subscribed the free trial cloud storage service successfully for device ' + uid + ' on '+ time.strftime("%b %dth,%Y", time.localtime())]                    sms = 'SMS_222870823'                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, you already redeemed for the cloud storage package successfully for device ' +uid +' on '+time.strftime("%b %dth,%Y", time.localtime())]                    sms = 'SMS_219748439'                self.do_vod_msg_Notice(uid, channel, userID, lang, sys_msg_text_list, sms)                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")            month = 'month' if lang != 'cn' else '个月'            for ub in unuseds:                storage_time = ub['num'] * ub['expire']                if lang != 'cn' and storage_time > 1:   # 英文大于一个月使用复数                    month += 's'                storage = "{storage_time}{month}".format(storage_time=storage_time, month=month)                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 has_vod(self, request_dict, userID, response):        uid = request_dict.get('uid', None)        channel = request_dict.get('channel', 1)        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)        had_vod_query = VodHlsModel.objects.extra(select={'date': "FROM_UNIXTIME(time,'%%Y-%%m-%%d')"}).values(            'date').filter(uid=uid,endTime__gte=now_time,channel=channel).annotate(count=Count('time')).order_by('-date')[:31]        had_vod_list = []        for vod in had_vod_query:            had_vod_list.append({                'timestamp': CommonService.str_to_timestamp(vod['date'], '%Y-%m-%d'),                'vod_count': vod['count'],                'date_format': vod['date'],            })        return response.json(0, had_vod_list)    # 云存操作系统消息    def do_vod_msg_Notice(self, uid, channel, userID, lang, sys_msg_text_list, sms):        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)                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__gt=now_time + 3600 * 144) & Q(endTime__lte=(now_time + 3600 * 168))).values('id','uid','bucket__area','channel','endTime')        self.do_vod_msg(now_time,list)        # 过期前第3天提示一次        list = UID_Bucket.objects.filter(Q(endTime__gt=now_time + 3600 * 48) & Q(endTime__lte=(now_time + 3600 * 72))).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", time.localtime(ub['endTime'])) + "到期"                    else:                        sys_msg_text = 'Dear customer,the cloud storage package for your device '+ub['uid']+' will expire on '+time.strftime('%m-%d-%y',time.localtme(ub['endTime']))                    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                    ))                    SysMsgModel.objects.bulk_create(uq_list)                    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",                                                                                                      time.localtime(ub['endTime'])) + '"}'                            self.sendMessage(username, params, 'SMS_219748440')                        self.pushApp(now_time, ub['uid'], ub['channel'], sys_msg_text)    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 = '周视'            # 发送手机验证码            aliSms = AliSmsObject()            res = aliSms.send_code_sms_cloud(phone=phone, params = params, sign_name=sign_ms,                                       temp_msg=temp_msg)    def do_refund(self, request_dict, response):        orderID = request_dict.get('orderID', None)    # 商户订单号        if not orderID:            return response.json(444)        try:            order_qs = Order_Model.objects.filter(orderID=orderID).\                values('status', 'payType', 'price', 'currency', 'paymentID')            if not order_qs.exists():                return response.json(173)            # 支付状态不为支付成功和退款失败            status = order_qs[0]['status']            if status != 1 and status != 4:                return response.json(805)            now_time = int(time.time())            payType = order_qs[0]['payType']            refund_amount = order_qs[0]['price']    # 退款金额            currency = order_qs[0]['currency']      # 货币            paymentID = order_qs[0]['paymentID']    # 退款id            out_request_no = str(time.strftime('%Y%m%d%H%M%S', time.localtime(now_time)))    # 退款请求号            # 根据支付类型处理退款            if payType == 1:    # PayPal                paypalrestsdk.configure(PAYPAL_CRD)                payment = paypalrestsdk.Payment.find(paymentID)                print(payment)                related_resources = payment['transactions'][0]['related_resources']                if not related_resources:                    return response.json(805)                sale = related_resources[0]['sale']                if sale['state'] != 'completed':                    return response.json(805)                sale_id = sale['id']                paypalSale = paypalrestsdk.Sale.find(sale_id)                refund = paypalSale.refund({                    'amount': {                        'total': refund_amount,                        'currency': currency                    }                })                status = 5 if refund.success() else 4            elif payType == 2:  # 支付宝                aliPayObj = AliPayObject()                alipay = aliPayObj.conf()                refund_response = alipay.api_alipay_trade_refund(refund_amount=refund_amount, out_trade_no=orderID,                                                                 out_request_no=out_request_no)                # 退款成功,修改订单支付状态为'退款成功',否则改为'退款失败'                status = 5 if refund_response['code'] == '10000' else 4            elif payType == 3:  # 微信                wechatPayObj = WechatPayObject()                refund_amount = int(float(refund_amount) * 100)  # 退款金额,单位为分,只能为整数                refund_success = wechatPayObj.refund(out_trade_no=orderID, out_refund_no=out_request_no,                                                     total_fee=refund_amount, refund_fee=refund_amount)                status = 5 if refund_success else 4            else:   # 不支持退款的支付类型                return response.json(805)            order_qs.update(status=status, updTime=now_time)    # 更新订单状态            return response.json(0)        except Exception as e:            print(e)            return response.json(500, repr(e))# 删除过期云存播放列表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)
 |