12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- import base64
- import datetime
- import json
- import logging
- import sys
- import time
- import ssl
- from decimal import Decimal
- from itertools import groupby
- from operator import itemgetter
- from urllib.parse import quote, parse_qs, unquote
- import boto3
- import jwt
- import paypalrestsdk
- from django.db import transaction
- from django.db.models import Q, F
- from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
- from django.views.generic.base import View
- from Ansjer.config import SERVER_DOMAIN, PAYPAL_CRD, SERVER_DOMAIN_SSL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, \
- AWS_ARN, OAUTH_ACCESS_TOKEN_SECRET
- from Controller.CheckUserData import DataValid
- from Controller.CloudPhoto.CloudServiceController import CloudServiceController
- from Controller.PaymentCycle import Paypal
- from Model.models import Device_Info, Order_Model, Store_Meal, VodHlsModel, UID_Bucket, StsCrdModel, \
- ExperienceContextModel, Pay_Type, CDKcontextModel, Device_User, SysMsgModel, Unused_Uid_Meal, PromotionRuleModel, \
- VideoPlaybackTimeModel, CouponModel, VodBucketModel, VodHlsSummary, VodHlsTagType
- from Object.AWS.AmazonS3Util import AmazonS3Util
- from Object.AWS.S3Email import S3Email
- from Object.AliPayObject import AliPayObject
- from Object.AliSmsObject import AliSmsObject
- from Object.RedisObject import RedisObject
- from Object.ResponseObject import ResponseObject
- from Object.TokenObject import TokenObject
- from Object.UidTokenObject import UidTokenObject
- from Object.WechatPayObject import WechatPayObject
- from Object.m3u8generate import PlaylistGenerator
- from Service.CommonService import CommonService
- from Service.PayService import PaymentService
- from Service.VodHlsService import SplitVodHlsObject
- ssl._create_default_https_context = ssl._create_unverified_context
- LOGGER = logging.getLogger('info')
- # 设备信息添加
- 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):
- lang = request_dict.get('lang', 'en')
- response = ResponseObject(lang)
- 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_dict, response)
- 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(response)
- elif operation == 'doRefund': # 退款
- return self.do_refund(request_dict, response)
- else:
- token = request_dict.get('token', None)
- # 设备主键uid
- tko = TokenObject(token)
- if tko.code != 0:
- return response.json(tko.code)
- user_id = tko.userID
- if operation == 'createpayorder': # 创建支付订单
- ip = CommonService.get_ip_address(request)
- return self.do_create_pay_order(request_dict, user_id, ip, response)
- elif operation == 'changevodstatus': # 修改云存状态,传送两个url,即getsignsts接口和storeplaylist接口
- return self.do_change_vod_status(request_dict, user_id, response)
- elif operation == 'queryvodlist': # 获取视频播放列表
- return self.do_query_vod_list(request_dict, user_id, response)
- elif operation == 'commoditylist': # 查询套餐列表
- return self.do_commodity_list(request_dict, user_id, response)
- elif operation == 'queryorder': # 查询订单列表
- return self.do_query_order(request_dict, user_id, response)
- elif operation == 'experienceorder': # 生成体验订单
- return self.do_experience_order(request_dict, user_id, response)
- elif operation == 'experiencereset': # 重置设备云存体验
- return self.do_experience_reset(request_dict, response)
- elif operation == 'deletevodlist': # 删除播放列表
- return self.delete_vod_list(request_dict, user_id, response)
- elif operation == 'devicecommodity': # 设备关联套餐列表
- return self.device_commodity(request_dict, user_id, response)
- elif operation == 'switchdevicecommodity': # 提前使用设备关联套餐
- return self.switch_device_commodity(request_dict, user_id, response)
- elif operation == 'hasvod': # APP的回放界面,日历表显示当天有无录像
- return self.has_vod(request_dict, user_id, response)
- elif operation == 'videoPlaybackTime': # 记录app播放时间
- return self.video_playback_time(request_dict, user_id, response)
- else:
- return response.json(414)
- @staticmethod
- def do_query_order(request_dict, user_id, response): # 查询订单列表
- """
- 查询订单列表
- @param request_dict: 请求数据
- @request_dict status: uid
- @request_dict page: 通道
- @request_dict line: 支付类型
- @request_dict uid: 套餐id
- @param user_id: 用户id
- @param response: 响应
- @return: response
- """
- status = request_dict.get('status', None)
- page = request_dict.get('page', None)
- line = request_dict.get('line', None)
- uid = request_dict.get('uid', None)
- if not all([page, line]):
- return response.json(444)
- page = int(page)
- line = int(line)
- order_qs = Order_Model.objects.filter(userID_id=user_id)
- 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)
- count = order_qs.count()
- order_list = 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")
- data = []
- now_time = int(time.time())
- for order in order_list:
- if order['status'] == 0:
- if order['addTime'] + 3600 < now_time:
- order['status'] = 3
- device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=order['UID']).values('id', 'Type')
- order['did'] = device_info_qs[0]['id'] if device_info_qs.exists() else ''
- order['Type'] = device_info_qs[0]['Type'] if device_info_qs.exists() else ''
- data.append(order)
- return response.json(0, {'data': data, 'count': count})
- @staticmethod
- def do_commodity_list(request_dict, user_id, response): # 查询套餐列表
- """
- 查询套餐列表
- @param user_id: 用户id
- @param request_dict: 请求数据
- @request_dict mold: 存储区域类型
- @request_dict uid: uid
- @request_dict lang: 语言
- @param response: 响应
- @return: response
- """
- mold = request_dict.get('mold', None)
- uid = request_dict.get('uid', None)
- lang = request_dict.get('lang', 'en')
- if not all([uid]):
- return response.json(444)
- now_time = int(time.time())
- # DVR/NVR设备暂不返回云存套餐列表
- device_info_qs = Device_Info.objects.filter(Q(UID=uid), Q(Type__lte=4) | Q(Type=10001))
- if device_info_qs.exists():
- return response.json(0)
- store_qs = Store_Meal.objects.filter(Q(lang__lang=lang), Q(is_show=0), ~Q(pay_type='11')) # 过滤激活码、隐藏套餐
- experience_context_qs = ExperienceContextModel.objects.filter(uid=uid, experience_type=0)
- if mold:
- store_qs = store_qs.filter(bucket__mold=mold)
- # 没体验过的设备只返回体验套餐,体验过的不返回体验套餐
- if experience_context_qs.exists():
- store_qs = store_qs.filter(~Q(pay_type='10'))
- else:
- store_qs = store_qs.filter(pay_type='10')
- store_qs = store_qs.annotate(title=F('lang__title'), content=F('lang__content'),
- discount_content=F('lang__discount_content'))
- store_qs = store_qs.order_by('sort').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", "cycle_config_id")
- if not store_qs.exists():
- return response.json(0)
- store_list = list(store_qs)
- store_list.sort(key=itemgetter('bucket__area'))
- res = []
- coupon_qs = '' if not user_id else CloudServiceController.get_user_coupon_list(user_id)
- for area, items in groupby(store_list, key=itemgetter('bucket__area')):
- items_list = list(items)
- for item in items_list:
- pay_type_qs = Pay_Type.objects.filter(store_meal=item['id']).values("id", "payment")
- item['pay_type'] = list(pay_type_qs)
- item['is_pay_cycle'] = 1 if item['cycle_config_id'] else 0
- del item['cycle_config_id']
- item['isCoupon'] = False if not coupon_qs or not coupon_qs.exists() else \
- CloudStorageView.check_user_coupon_is_available(coupon_qs, item['id'])
- res_c = {'area': area, 'items': items_list}
- res.append(res_c)
- # 是否促销
- promotion_rule_qs = PromotionRuleModel.objects.filter(status=1, startTime__lte=now_time,
- endTime__gte=now_time).values('id', 'ruleConfig',
- 'ruleName',
- 'startTime', 'endTime',
- 'ruleDesc')
- if promotion_rule_qs.exists():
- promotion = {
- 'is_promotion': 1,
- 'promotionStartTime': promotion_rule_qs[0]['startTime'],
- 'promotionEndTime': promotion_rule_qs[0]['endTime'],
- 'promotionName': json.loads(promotion_rule_qs[0]['ruleName']).get(lang, ''),
- 'promotionDesc': json.loads(promotion_rule_qs[0]['ruleDesc']).get(lang, ''),
- 'nowTime': now_time
- }
- else:
- promotion = {
- 'is_promotion': 0
- }
- result = {
- 'meals': res,
- 'extra':
- {
- 'cloud_banner': SERVER_DOMAIN + 'web/images/cloud_cn_banner.png',
- 'cloud_en_baner': SERVER_DOMAIN_SSL + 'web/images/cloud_en_banner.png'
- },
- 'promotion': promotion,
- }
- return response.json(0, result)
- @staticmethod
- def check_user_coupon_is_available(coupon_qs, combo_id):
- """
- 查看用户优惠券是否可用
- @param coupon_qs: 优惠券列表
- @param combo_id: 套餐id
- @return:
- """
- if not coupon_qs.exists():
- return False
- result = False
- for item in coupon_qs:
- if result:
- break
- combo_list = CloudServiceController.get_combo_list(0, item['coupon_config__id'])
- if not combo_list:
- continue
- if combo_id in combo_list:
- result = True
- return result
- @staticmethod
- def do_sign_play_m3u8(request_dict, response): # 根据sts播放m3u8 视频流
- """
- 获取m3u8视频流
- @param request_dict: 请求数据
- @request_dict uid: uid_token
- @request_dict channel: 通道
- @request_dict time: 播放列表名字时间戳
- @param response: 响应
- @return: response
- """
- uid_token = request_dict.get('uid', None)
- channel = request_dict.get('channel', None)
- start_time = request_dict.get('time', None)
- if not all([uid_token, channel, start_time]):
- return response.json(444)
- uid = jwt.decode(uid_token, OAUTH_ACCESS_TOKEN_SECRET, algorithms='HS256').get('uid', '')
- now_time = int(time.time())
- split_vod_hls_obj = SplitVodHlsObject()
- vod_hls_qs = split_vod_hls_obj.get_vod_hls_data(uid=uid, channel=channel, start_time__gte=start_time,
- end_time__gte=now_time).values("sec", "fg", "bucket_id",
- 'start_time')[:10]
- if not vod_hls_qs.exists():
- return response.json(173)
- vod_hls_qs = sorted(vod_hls_qs, key=lambda item: item['start_time'])[:10]
- bucket_id = vod_hls_qs[0]['bucket_id']
- vod_bucket_qs = VodBucketModel.objects.filter(id=bucket_id).values('bucket', 'region', 'mold')
- if not vod_bucket_qs.exists():
- return response.json(173)
- bucket_region = vod_bucket_qs[0]['region']
- bucket_name = vod_bucket_qs[0]['bucket']
- mold = vod_bucket_qs[0]["mold"]
- s3_obj = AmazonS3Util(
- AWS_ACCESS_KEY_ID[mold],
- AWS_SECRET_ACCESS_KEY[mold],
- bucket_region
- )
- playlist_entries = []
- # ts_count = fg & 0xf
- # fg 64位整型,低四位代表ts文件总数,然后进行位运算,一次移四位,每四位转为十进制即为当前ts文件的秒数
- for item in vod_hls_qs:
- fg = int(item['fg'])
- temp_time = item['start_time']
- for i in range(15):
- shift = (i + 1) * 4
- duration = (fg >> shift) & 0xf
- if duration > 0:
- ts_file = '{uid}/vod{channel}/{time}/ts{i}.ts'.format(uid=uid, channel=channel, time=temp_time,
- i=i)
- response_url = s3_obj.generate_file_obj_url(bucket_name, ts_file)
- 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
- @staticmethod
- def do_get_sign_sts(request_dict, ip, response): # 获取sts令牌
- """
- 获取sts令牌
- @param request_dict: 请求数据
- @param ip: ip地址
- @request_dict uidToken: uid_token
- @param response: 响应
- @return: response
- """
- uid_token = request_dict.get('uidToken', None)
- uid_obj = UidTokenObject(uid_token)
- if uid_obj.flag is False:
- return response.json(444, 'uidToken')
- uid = uid_obj.UID
- channel = uid_obj.channel
- now_time = int(time.time())
- try:
- uid_bucket_qs = 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')
- if not uid_bucket_qs.exists():
- res = {'code': 405, 'msg': 'Not purchased or expired!'}
- return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
- # 亚马逊 s3 sts
- sts_crd_qs = StsCrdModel.objects.filter(uid=uid, channel=channel).values("addTime", "data")
- if sts_crd_qs.exists():
- end_time = int(sts_crd_qs[0]["addTime"]) + 5000
- if end_time > now_time:
- res = json.loads(sts_crd_qs[0]["data"])
- return JsonResponse(status=200, data=res)
- storage = '{uid}/vod{channel}/'.format(uid=uid, channel=channel)
- bucket_name = uid_bucket_qs[0]['bucket__bucket']
- endpoint = uid_bucket_qs[0]['bucket__endpoint']
- region_id = uid_bucket_qs[0]['bucket__region']
- try:
- aws_access_key_id = AWS_ACCESS_KEY_ID[uid_bucket_qs[0]["bucket__mold"]]
- aws_secret_access_key = AWS_SECRET_ACCESS_KEY[uid_bucket_qs[0]["bucket__mold"]]
- aws_arn = AWS_ARN[uid_bucket_qs[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': uid_bucket_qs[0]['endTime'],
- 'ip': ip,
- 'region': region_id,
- 'bucket_mold': uid_bucket_qs[0]['bucket__mold']
- }
- if sts_crd_qs.exists():
- sts_crd_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)
- except Exception as e:
- return response.json(500, repr(e))
- @staticmethod
- def do_query_vod_list(request_dict, user_id, response): # 获取视频播放列表
- """
- 获取视频播放列表
- @param request_dict: 请求数据
- @param user_id: 用户id
- @request_dict startTime: 开始时间
- @request_dict endTime: 结束时间
- @request_dict uid: uid
- @request_dict channel: 通道
- @param response: 响应
- @return: response
- """
- logger = logging.getLogger('info')
- into_time = int(time.time())
- start_time = request_dict.get('startTime', None)
- end_time = request_dict.get('endTime', None)
- uid = request_dict.get('uid', None)
- channel = request_dict.get('channel', None)
- event_types = request_dict.get('eventTypes', None)
- if not all([uid, channel, start_time, end_time]):
- return response.json(444)
- if uid == 'UWE2ZJ52SE4FX75U111A':
- logger.info({
- "intoTime": into_time,
- })
- device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False).values(
- 'vodPrimaryUserID',
- 'vodPrimaryMaster')
- if not device_info_qs.exists():
- return response.json(12)
- device_info_qs_time_over = int(time.time())
- if uid == 'UWE2ZJ52SE4FX75U111A':
- logger.info({
- "intoTime": into_time,
- "dvQsModelOverTime": device_info_qs_time_over,
- })
- if device_info_qs[0]['vodPrimaryUserID'] != user_id:
- return response.json(10034)
- now_time = int(time.time())
- uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel).values(
- 'bucket_id').order_by('addTime')
- if not uid_bucket_qs.exists():
- return response.json(10030)
- uid_bucket_qs_time_over = int(time.time())
- logger.info({
- "intoTime": into_time,
- "dvQsModelOverTime": device_info_qs_time_over,
- "UidBucketModelOverTime": uid_bucket_qs_time_over,
- })
- type_list = []
- if event_types:
- if ',' in event_types:
- type_list = event_types.split(',')
- type_list = [int(i.strip()) for i in type_list]
- else:
- type_list = [int(event_types)]
- split_vod_hls_obj = SplitVodHlsObject()
- vod_hls_qs = split_vod_hls_obj.get_vod_hls_data(uid=uid, channel=channel,
- end_time__gte=now_time,
- start_time__range=(start_time, end_time),
- type_list=type_list) \
- .values("id", "start_time", "sec", "fg", "bucket_id")
- vod_play_list = []
- if not vod_hls_qs.exists():
- return response.json(0, vod_play_list)
- # 不用关联外键查询,因为会查询非常慢
- vod_bucket_qs = VodBucketModel.objects.values()
- regroup_bucket_qs = {}
- for bucket_dict in vod_bucket_qs:
- regroup_bucket_qs[bucket_dict['id']] = bucket_dict
- vod_hls_qs_time_over = int(time.time())
- logger.info({
- "intoTime": into_time,
- "dvQsModelOverTime": device_info_qs_time_over,
- "UidBucketModelOverTime": uid_bucket_qs_time_over,
- "vodHlsModelOverTime": vod_hls_qs_time_over,
- })
- bucket_mold = regroup_bucket_qs[vod_hls_qs[0]['bucket_id']]['mold']
- bucket_region = regroup_bucket_qs[vod_hls_qs[0]['bucket_id']]['region']
- aws_access_key_id = AWS_ACCESS_KEY_ID[bucket_mold]
- aws_secret_access_key = AWS_SECRET_ACCESS_KEY[bucket_mold]
- s3_obj = AmazonS3Util(aws_access_key_id, aws_secret_access_key, bucket_region)
- uid_token = TokenObject().encryption(data={'uid': uid})
- aws_object_over_time = int(time.time())
- logger.info({
- "intoTime": into_time,
- "dvQsModelOverTime": device_info_qs_time_over,
- "UidBucketModelOverTime": uid_bucket_qs_time_over,
- "vodHlsModelOverTime": vod_hls_qs_time_over,
- "awsObjectOverTime": aws_object_over_time,
- })
- ids = [val['id'] for val in vod_hls_qs]
- tag_type_list = SplitVodHlsObject.query_tag_type_list(start_time, ids)
- for vod in vod_hls_qs:
- bucket_name = regroup_bucket_qs[vod['bucket_id']]['bucket']
- thumbs_png = '{uid}/vod{channel}/{time}/Thumb.jpeg'.format(uid=uid, channel=channel, time=vod['start_time'])
- response_url = s3_obj.generate_file_obj_url(bucket_name, thumbs_png)
- vod_url = '{server_domain}cloudstorage/signplaym3u8?' \
- 'uid={uid}&channel={channel}&time={time}&sign=tktktktk'. \
- format(server_domain=SERVER_DOMAIN_SSL, uid=uid_token, channel=channel, time=vod['start_time'])
- ts_num = int(vod['fg']) & 0xf
- dict_item = [item for item in tag_type_list if item['vod_hls_id'] == vod['id']]
- types = []
- if dict_item:
- tag_qs = VodHlsTagType.objects.filter(tag_id=dict_item[0]['id']).values('type')
- types = [val['type'] for val in tag_qs]
- vod_play_list.append({
- 'start_time': vod['start_time'],
- 'sign_url': vod_url,
- 'thumb': response_url,
- 'sec': vod['sec'],
- 'ts_num': ts_num,
- 'vod_id': vod['id'],
- 'types': types
- })
- vod_play_list = sorted(vod_play_list, key=lambda item: -item['start_time'])
- generate_presigned_over_time = int(time.time())
- if uid == 'UWE2ZJ52SE4FX75U111A':
- logger.info({
- "intoTime": into_time,
- "dvQsModelOverTime": device_info_qs_time_over,
- "UidBucketModelOverTime": uid_bucket_qs_time_over,
- "vodHlsModelOverTime": vod_hls_qs_time_over,
- "awsObjectOverTime": aws_object_over_time,
- "generatePresignedOverTime": generate_presigned_over_time,
- })
- return response.json(0, vod_play_list)
- @staticmethod
- def do_store_playlist(request_dict, response):
- """
- 存储设备上传云存信息数据
- @param request_dict: 请求数据
- @request_dict uidToken: uid_token
- @request_dict time: 播放列表名字时间戳
- @request_dict sec: 秒数
- @request_dict fg: ts个数,时间描述片段数
- @param response: 响应
- @return: response
- """
- uid_token = request_dict.get('uidToken', None)
- start_time = request_dict.get('time', None)
- sec = request_dict.get('sec', None)
- fg = request_dict.get('fg', None)
- if not all([uid_token, start_time, sec]):
- return response.json(0)
- uid_obj = UidTokenObject(uid_token)
- if uid_obj.flag is False:
- return response.json(444, 'uidToken')
- try:
- sec = int(sec)
- uid = uid_obj.UID
- channel = uid_obj.channel
- now_time = int(time.time())
- uid_bucket_qs = 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')
- if not uid_bucket_qs.exists():
- return response.json(10030)
- # 判断设备是否开启云存
- uid_bucket = uid_bucket_qs.first()
- store_day = uid_bucket['bucket__storeDay']
- bucket_id = uid_bucket['bucket__id']
- end_time = int(start_time) + store_day * 86400
- if uid_bucket['status'] != 1:
- return response.json(10, {'msg': '设备未开启云存'})
- # 保存云存信息数据
- # 创建分表数据
- split_vod_hls_obj = SplitVodHlsObject()
- vod_vo, week = split_vod_hls_obj.creat_vod_hls_data(uid=uid, channel=channel, start_time=start_time,
- end_time=end_time, bucket_id=bucket_id, fg=fg, sec=sec)
- split_vod_hls_obj.cloud_vod_hls_tag(vod_vo.id, week, uid, start_time)
- end_time_stamp = datetime.datetime.fromtimestamp(int(start_time))
- end_time_str = datetime.datetime(end_time_stamp.year, end_time_stamp.month, 1)
- end_time_stamp = CommonService.str_to_timestamp(end_time_str.strftime('%Y-%m-%d %H:%M:%S'))
- vod_hls_sum_qs = VodHlsSummary.objects.filter(uid=uid, time=end_time_stamp)
- if vod_hls_sum_qs.exists():
- vod_hls_sum = vod_hls_sum_qs.first()
- vod_hls_sum.upload_frequency += 1
- vod_hls_sum.upload_duration += sec
- vod_hls_sum.updated_time = now_time
- vod_hls_sum.save()
- else:
- VodHlsSummary.objects.create(uid=uid, time=end_time_stamp, created_time=now_time, updated_time=now_time,
- upload_duration=sec, upload_frequency=1)
- res = {'code': 0, 'msg': '存储成功'}
- return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json,charset=utf-8')
- except Exception as e:
- return response.json(500, repr(e))
- @staticmethod
- def do_change_vod_status(request_dict, user_id, response): # 修改云存状态
- """
- 修改云存状态
- @param request_dict: 请求数据
- @param user_id: 用户id
- @request_dict uid: uid
- @request_dict status: 套餐状态
- @request_dict channel: 通道
- @param response: 响应
- @return: response
- """
- uid = request_dict.get('uid', None)
- status = request_dict.get('status', None)
- channel = request_dict.get('channel', None)
- domain_name = request_dict.get('domain_name', None)
- if not all([uid, status, channel]):
- return response.json(444, 'uid,status,channel')
- device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
- 'vodPrimaryUserID')
- if not device_info_qs.exists() or device_info_qs[0]['vodPrimaryUserID'] != user_id:
- return response.json(12)
- uid_bucket_qs = UID_Bucket.objects.filter(channel=channel, uid=uid)
- if not uid_bucket_qs.exists():
- return response.json(10030)
- now_time = int(time.time())
- if now_time > uid_bucket_qs[0].endTime:
- return response.json(10031)
- uid_bucket_qs.update(status=status)
- if status == 0:
- return response.json(0)
- uid_obj = UidTokenObject()
- uid_obj.generate(data={'uid': uid, 'channel': channel})
- # 欧洲域名固定返回欧洲域名
- urls = SERVER_DOMAIN_SSL
- if domain_name in ['api.zositeche.com', 'api.loocam3.com', 'common.neutral3.com']:
- urls = 'https://api.zositeche.com/'
- uid_tk_url = '{}cloudstorage/getsignsts?uidToken={}'.format(urls, uid_obj.token)
- store_hls_url = '{}cloudstorage/storeplaylist?uidToken={}'.format(urls, uid_obj.token)
- return response.json(0, {'uidTkUrl': uid_tk_url, 'storeHlsUrl': store_hls_url})
- @staticmethod
- def do_pay_error():
- response = HttpResponse()
- response.content = PaymentService.get_pay_error_content()
- return response
- @staticmethod
- def do_pay_ok(request_dict): # 支付成功
- """
- 支付成功
- @param request_dict: 请求数据
- @request_dict paytype: 支付类型
- @request_dict lang: 语言
- @return: response
- """
- lang = request_dict.get('lang', 'en')
- pay_type = request_dict.get('paytype', None)
- response = HttpResponse()
- response.content = PaymentService.get_pay_ok_content(lang, pay_type)
- return response
- def do_pay_by_ali_callback(self, request_dict, response): # 阿里支付回调
- """
- 阿里支付回调
- @param request_dict: 请求数据
- @request_dict out_trade_no: 订单id
- @request_dict sign: 语言
- @request_dict trade_status: 语言
- @request_dict passback_params: 语言
- @param response: 响应
- @return: response
- """
- request_dict = request_dict.dict()
- pass_back_params = request_dict["passback_params"]
- signature = request_dict["sign"]
- request_dict.pop('sign')
- order_id = request_dict['out_trade_no']
- trade_status = request_dict["trade_status"]
- if not all([pass_back_params, signature, order_id, trade_status]):
- return response.json(444)
- parmap = dict([(k, v[0]) for k, v in parse_qs(unquote(pass_back_params)).items()])
- lang = parmap["lang"]
- order_qs = Order_Model.objects.filter(orderID=order_id, status=0)
- if not order_qs.exists():
- return response.json(173)
- # redis加锁,防止订单重复
- redis_obj = RedisObject()
- is_lock = redis_obj.CONN.setnx(order_id + 'do_notify', 1)
- redis_obj.CONN.expire(order_id + 'do_notify', 60)
- if not is_lock:
- return response.json(5)
- promotion_rule_id = ''
- try:
- # 验证阿里支付链接
- ali_pay_obj = AliPayObject()
- alipay = ali_pay_obj.conf()
- success = alipay.verify(request_dict, signature)
- if success and trade_status in ("TRADE_SUCCESS", "TRADE_FINISHED"):
- order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
- "userID__userID", "userID__username", "coupon_id")
- 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']
- store_qs = Store_Meal.objects.filter(id=rank).values("day", "bucket_id", "bucket__storeDay", "expire")
- bucket_id = store_qs[0]['bucket_id']
- if not store_qs.exists():
- return response.json(173)
- uiu_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id", "bucket__storeDay",
- "bucket__region", "endTime", "use_status")
- expire = store_qs[0]['expire']
- if order_list[0]['isSelectDiscounts'] == 1:
- expire = store_qs[0]['expire'] * 2
- # 是否有促销
- now_time = int(time.time())
- promotion = PromotionRuleModel.objects.filter(status=1, startTime__lte=now_time,
- endTime__gte=now_time).values('id', 'ruleConfig')
- if promotion.exists():
- promotion_rule_id = promotion[0]['id']
- expire = expire * 2
- with transaction.atomic():
- if uiu_bucket_qs.exists():
- uid_bucket = uiu_bucket_qs.first()
- if uid_bucket['use_status'] == 1 and uid_bucket['bucket_id'] == bucket_id: # 套餐使用中并且相同套餐叠加过期时间
- end_time = CommonService.calcMonthLater(expire, uid_bucket['endTime'])
- UID_Bucket.objects.filter(id=uid_bucket['id']).update(uid=uid, channel=channel,
- bucket_id=bucket_id, endTime=end_time,
- updateTime=now_time)
- else: # 已过期或者不相同的套餐加入未使用的关联套餐表
- unused_uid_qs = Unused_Uid_Meal.objects.filter(uid=uid, bucket_id=bucket_id)
- nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
- if promotion.exists():
- nums = nums + 1
- if unused_uid_qs.exists():
- unused_uid_qs.update(num=F('num') + nums)
- else:
- Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, num=nums,
- expire=store_qs[0]['expire'], bucket_id=bucket_id)
- UID_Bucket.objects.filter(id=uid_bucket['id']).update(has_unused=1)
- uid_bucket_id = uid_bucket['id']
- else:
- end_time = CommonService.calcMonthLater(expire)
- uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
- endTime=end_time, addTime=now_time, updateTime=now_time,
- use_status=1)
- uid_bucket_id = uid_bucket.id
- device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
- if device_info_qs.exists():
- dvq_set_update_dict = {
- 'vodPrimaryUserID': userid,
- 'vodPrimaryMaster': username
- }
- device_info_qs.update(**dvq_set_update_dict)
- # 核销coupon
- if order_list[0]['coupon_id']:
- CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2,
- update_time=now_time)
- order_qs.update(status=1, updTime=now_time, uid_bucket_id=uid_bucket_id,
- promotion_rule_id=promotion_rule_id)
- date_time = time.strftime("%Y-%m-%d", time.localtime())
- # 如果存在序列号,消息提示用序列号
- device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
- serial_number = device_info_qs[0]['serial_number']
- device_type = device_info_qs[0]['Type']
- if serial_number:
- device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
- else:
- device_name = uid
- sys_msg_text_list = [
- '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
- 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' 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 = "{}web/paid2/success.html".format(SERVER_DOMAIN_SSL)
- if lang != 'cn':
- red_url = red_url.replace('success.html', 'en_success.html')
- redis_obj.del_data(key=order_id + 'do_notify')
- return HttpResponseRedirect(red_url)
- return response.json(0, signature)
- except Exception as e:
- logger = logging.getLogger('info')
- logger.info('alipay----notify---------')
- logger.info(repr(e))
- logger.info(sys.exc_info())
- logger.info('alipay支付失败:----')
- logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
- logger.info(repr(e))
- if order_qs:
- order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
- redis_obj.del_data(key=order_id + 'do_notify')
- red_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
- if lang != 'cn':
- red_url = red_url.replace('fail.html', 'en_fail.html')
- return HttpResponseRedirect(red_url)
- def do_pay_by_paypal_callback(self, request_dict, response): # paypal支付回调
- """
- paypal支付回调
- @param request_dict: 请求数据
- @request_dict paymentId: 支付id
- @request_dict PayerID: 支付人id
- @request_dict orderID: 订单id
- @request_dict lang: 语言
- @param response: 响应
- @return: response
- """
- logger = logging.getLogger('info')
- logger.info('---------进入paypal异步回调')
- payment_id = request_dict.get('paymentId', None)
- payer_id = request_dict.get('PayerID', None)
- order_id = request_dict.get('orderID', None)
- lang = request_dict.get('lang', 'en')
- if not all([payer_id, payment_id]):
- return response.json(444)
- logger.info("paymentID={paymentId},payerID={PayerID}".format(paymentId=payment_id, PayerID=payer_id))
- # redis加锁,防止订单重复
- redis_obj = RedisObject()
- is_lock = redis_obj.CONN.setnx(order_id + 'do_notify', 1)
- redis_obj.CONN.expire(order_id + 'do_notify', 60)
- if not is_lock:
- return response.json(5)
- order_qs = Order_Model.objects.filter(orderID=order_id, status=0)
- if not order_qs.exists():
- return response.json(173)
- promotion_rule_id = ''
- try:
- if not order_id:
- red_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
- if lang != 'cn':
- red_url = red_url.replace('fail.html', 'en_fail.html')
- return HttpResponseRedirect(red_url)
- paypalrestsdk.configure(PAYPAL_CRD)
- payment = paypalrestsdk.Payment.find(payment_id)
- logger.info("payment------")
- logger.info(payment)
- payers = payment.execute({"payer_id": payer_id})
- logger.info(payers)
- if not payers:
- red_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
- if lang != 'cn':
- red_url = red_url.replace('fail.html', 'en_fail.html')
- redis_obj.del_data(key=order_id + 'do_notify')
- return HttpResponseRedirect(red_url)
- order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
- "userID__userID", "userID__username", "coupon_id")
- 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']
- store_qs = Store_Meal.objects.filter(id=rank).values("day", "bucket_id", "bucket__storeDay", "expire")
- bucket_id = store_qs[0]['bucket_id']
- if not store_qs.exists():
- return response.json(173)
- uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id", "bucket__storeDay",
- "bucket__region", "endTime", "use_status")
- expire = store_qs[0]['expire']
- if order_list[0]['isSelectDiscounts'] == 1:
- expire = store_qs[0]['expire'] * 2
- # 是否有促销
- now_time = int(time.time())
- promotion_rule_qs = PromotionRuleModel.objects.filter(status=1, startTime__lte=now_time,
- endTime__gte=now_time).values('id', 'ruleConfig')
- if promotion_rule_qs.exists():
- promotion_rule_id = promotion_rule_qs[0]['id']
- expire = expire * 2
- with transaction.atomic():
- if uid_bucket_qs.exists():
- uid_bucket = uid_bucket_qs.first()
- if uid_bucket['use_status'] == 1 and uid_bucket['bucket_id'] == bucket_id: # 套餐使用中并且相同套餐叠加过期时间
- end_time = CommonService.calcMonthLater(expire, uid_bucket['endTime'])
- UID_Bucket.objects.filter(id=uid_bucket['id']).update(uid=uid, channel=channel,
- endTime=end_time,
- bucket_id=bucket_id, updateTime=now_time)
- else: # 已过期或者不相同的套餐加入未使用的关联套餐表
- unused_uid_qs = Unused_Uid_Meal.objects.filter(uid=uid, bucket_id=bucket_id)
- nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
- if promotion_rule_qs.exists():
- nums = nums + 1
- if unused_uid_qs.exists():
- unused_uid_qs.update(num=F('num') + nums)
- else:
- Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, num=nums,
- expire=store_qs[0]['expire'], bucket_id=bucket_id)
- UID_Bucket.objects.filter(id=uid_bucket['id']).update(has_unused=1)
- uid_bucket_id = uid_bucket['id']
- else:
- end_time = CommonService.calcMonthLater(expire)
- uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
- endTime=end_time, addTime=now_time, updateTime=now_time,
- use_status=1)
- uid_bucket_id = uid_bucket.id
- device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
- if device_info_qs.exists():
- dvq_set_update_dict = {
- 'vodPrimaryUserID': userid,
- 'vodPrimaryMaster': username
- }
- device_info_qs.update(**dvq_set_update_dict)
- # 核销coupon
- if order_list[0]['coupon_id']:
- CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2, update_time=now_time)
- order_qs.update(status=1, updTime=now_time, uid_bucket_id=uid_bucket_id,
- promotion_rule_id=promotion_rule_id)
- date_time = time.strftime("%Y-%m-%d", time.localtime())
- # 如果存在序列号,消息提示用序列号
- device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
- serial_number = device_info_qs[0]['serial_number']
- device_type = device_info_qs[0]['Type']
- if serial_number:
- device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
- else:
- device_name = uid
- sys_msg_text_list = [
- '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
- 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' 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 = "{}web/paid2/success.html".format(SERVER_DOMAIN_SSL)
- if lang != 'cn':
- red_url = red_url.replace('success.html', 'en_success.html')
- redis_obj.del_data(key=order_id + 'do_notify')
- return HttpResponseRedirect(red_url)
- except Exception as e:
- logger.info('paypal支付失败:----')
- logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
- logger.info(repr(e))
- if order_qs:
- order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
- red_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
- if lang != 'cn':
- red_url = red_url.replace('fail.html', 'en_fail.html')
- redis_obj.del_data(key=order_id + 'do_notify')
- return HttpResponseRedirect(red_url)
- def do_pay_by_wechat_callback(self, request, response): # 微信支付回调
- """
- 查询套餐列表
- @param request: 请求体
- @request_dict result_code: 业务结果
- @request_dict out_trade_no: 商户订单号
- @request_dict lang: 语言
- @param response: 响应
- @return: response
- """
- logger = logging.getLogger('info')
- 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
- order_id = data['out_trade_no'] # 商户订单号
- if not all([attach, trade_status, order_id]):
- return response.json(444)
- logger.info(order_id)
- order_qs = Order_Model.objects.filter(orderID=order_id, status=0)
- if not order_qs.exists():
- return response.json(173)
- # redis加锁,防止订单重复
- redis_obj = RedisObject()
- is_lock = redis_obj.CONN.setnx(order_id + 'do_notify', 1)
- redis_obj.CONN.expire(order_id + 'do_notify', 60)
- if not is_lock:
- return response.json(5)
- promotion_rule_id = ''
- try:
- if trade_status == "SUCCESS":
- check_sign = pay.get_notifypay(data)
- if not check_sign:
- return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '签名失败'}))
- order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
- "userID__userID", "userID__username", "status", "coupon_id")
- logger.info(order_list[0]['UID'])
- 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']
- store_qs = Store_Meal.objects.filter(id=rank).values("day", "bucket_id", "bucket__storeDay", "expire")
- bucket_id = store_qs[0]['bucket_id']
- if not store_qs.exists():
- return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '套餐不存在'}))
- uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id", "bucket__storeDay",
- "bucket__region", "endTime", "use_status")
- expire = store_qs[0]['expire']
- if order_list[0]['isSelectDiscounts'] == 1:
- expire = store_qs[0]['expire'] * 2
- # 是否有促销
- now_time = int(time.time())
- promotion_rule_qs = PromotionRuleModel.objects.filter(status=1, startTime__lte=now_time,
- endTime__gte=now_time).values('id', 'ruleConfig')
- if promotion_rule_qs.exists():
- promotion_rule_id = promotion_rule_qs[0]['id']
- expire = expire * 2
- with transaction.atomic():
- if uid_bucket_qs.exists():
- uid_bucket = uid_bucket_qs.first()
- if uid_bucket['use_status'] == 1 and uid_bucket['bucket_id'] == bucket_id: # 套餐使用中并且相同套餐叠加过期时间
- end_time = CommonService.calcMonthLater(expire, uid_bucket['endTime'])
- UID_Bucket.objects.filter(id=uid_bucket['id']).update(uid=uid, channel=channel,
- bucket_id=bucket_id,
- endTime=end_time, updateTime=now_time)
- else: # 已过期或者不相同的套餐加入未使用的关联套餐表
- unused_uid_qs = Unused_Uid_Meal.objects.filter(uid=uid, bucket_id=bucket_id)
- nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
- if promotion_rule_qs.exists():
- nums = nums + 1
- if unused_uid_qs.exists():
- unused_uid_qs.update(num=F('num') + nums)
- else:
- Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, num=nums,
- expire=store_qs[0]['expire'], bucket_id=bucket_id)
- UID_Bucket.objects.filter(id=uid_bucket['id']).update(has_unused=1)
- uid_bucket_id = uid_bucket['id']
- else:
- end_time = CommonService.calcMonthLater(expire)
- uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
- endTime=end_time, addTime=now_time,
- updateTime=now_time, use_status=1)
- uid_bucket_id = uid_bucket.id
- device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
- if device_info_qs.exists():
- dvq_set_update_dict = {
- 'vodPrimaryUserID': userid,
- 'vodPrimaryMaster': username
- }
- device_info_qs.update(**dvq_set_update_dict)
- # 核销coupon
- if order_list[0]['coupon_id']:
- CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2,
- update_time=now_time)
- order_qs.update(status=1, updTime=now_time, uid_bucket_id=uid_bucket_id,
- promotion_rule_id=promotion_rule_id)
- date_time = time.strftime("%Y-%m-%d", time.localtime())
- # 如果存在序列号,消息提示用序列号
- device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
- serial_number = device_info_qs[0]['serial_number']
- device_type = device_info_qs[0]['Type']
- if serial_number:
- device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
- else:
- device_name = uid
- sys_msg_text_list = [
- '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
- 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
- "%b %dth,%Y", time.localtime())]
- self.do_vod_msg_notice(uid, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
- redis_obj.del_data(key=order_id + 'do_notify')
- return HttpResponse("<xml>\
- <return_code><![CDATA[SUCCESS]]></return_code>\
- <return_msg><![CDATA[OK]]></return_msg>\
- </xml>")
- else:
- order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
- return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '参数格式校验错误'}))
- except Exception as e:
- logger.info('wechat支付失败:----')
- logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
- logger.info(repr(e))
- if order_qs:
- order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
- redis_obj.del_data(key=order_id + 'do_notify')
- return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': repr(e)}))
- @staticmethod
- def do_create_pay_order(request_dict, user_id, ip, response): # 创建支付订单
- """
- 创建支付订单
- @param request_dict: 请求数据
- @param user_id: 用户id
- @param ip: ip地址
- @request_dict uid: uid
- @request_dict channel: 通道
- @request_dict pay_type: 支付类型
- @request_dict rank: 套餐id
- @request_dict is_select_discount: 用户是否选择了第二年优惠
- @request_dict coupon_id: 优惠券id
- @request_dict lang: 语言
- @param response: 响应
- @return: response
- """
- logger = logging.getLogger('info')
- uid = request_dict.get('uid', None)
- channel = request_dict.get('channel', None)
- pay_type = request_dict.get('pay_type', None)
- rank = request_dict.get('rank', None)
- is_select_discount = request_dict.get('is_select_discount', 0)
- coupon_id = request_dict.get('coupon_id', 0)
- lang = request_dict.get('lang', 'en')
- if not all([uid, channel, pay_type, rank]):
- return response.json(444)
- pay_type = int(pay_type)
- device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
- 'vodPrimaryUserID',
- 'vodPrimaryMaster')
- if not device_info_qs.exists():
- return response.json(12)
- device_info_qs = Device_Info.objects.filter(Q(UID=uid), ~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
- if device_info_qs.exists():
- if device_info_qs[0]['vodPrimaryUserID'] != user_id:
- return response.json(10033)
- now_time = int(time.time())
- store_qs = Store_Meal.objects.filter(id=rank, pay_type=pay_type, lang__lang=lang, is_show=0). \
- values('currency', 'price', 'lang__content', 'day', 'commodity_type', 'lang__title', 'expire',
- 'commodity_code', 'discount_price', 'bucket__mold', 'cycle_config_id')
- if not store_qs.exists():
- return response.json(173)
- store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=0).values('lang__title',
- 'lang__content')
- if store_meal_qs.exists():
- store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
- else:
- store_meal_name = '未知套餐'
- currency = store_qs[0]['currency']
- price = store_qs[0]['price']
- if is_select_discount == '1':
- price = float(store_qs[0]['price']) + float(store_qs[0]['discount_price'])
- content = store_qs[0]['lang__content']
- commodity_code = store_qs[0]['commodity_code']
- commodity_type = store_qs[0]['commodity_type']
- is_mold = 1 if store_qs[0]['bucket__mold'] == 0 else 0 # 判断国内外
- order_qs = Order_Model.objects.filter(UID=uid, rank__bucket__mold=is_mold)
- if order_qs.exists():
- if is_mold == 1:
- return response.json(10060)
- return response.json(10041)
- order_id = CommonService.createOrderID()
- # 优惠券
- if coupon_id:
- coupon_qs = CouponModel.objects.filter(id=coupon_id, use_status=0, distribute_time__lte=now_time,
- valid_time__gt=now_time).values("id", "coupon_config__type",
- "coupon_config__coupon_discount")
- if not coupon_qs.exists():
- return response.json(10049)
- price = Decimal(price)
- coupon_discount = Decimal(coupon_qs[0]['coupon_config__coupon_discount'])
- if coupon_qs[0]['coupon_config__type'] == 1: # 打折
- price = coupon_discount / 10 * price
- elif coupon_qs[0]['coupon_config__type'] == 2: # 抵扣
- price = price - coupon_discount
- price = float(price)
- if price < 0 or price == 0 or price < 0.01:
- price = 0.01
- price = round(price, 2)
- if pay_type == 1:
- # 订阅周期扣款
- if store_qs[0]['cycle_config_id']:
- # 查询是否有订阅过,活跃状态
- check_has_subscribe = Paypal.checkSubscriptions(user_id, uid, rank)
- if not check_has_subscribe:
- return response.json(10050)
- sub_info = Paypal.subscriptions(store_info=store_qs[0], lang=lang, orderID=order_id, price=price)
- if not sub_info:
- return response.json(10048)
- Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
- desc=content, payType=pay_type, payTime=now_time,
- price=price, currency=currency, addTime=now_time, updTime=now_time,
- pay_url=sub_info['url'], isSelectDiscounts=is_select_discount,
- commodity_code=commodity_code, commodity_type=commodity_type,
- rank_id=rank, plan_id=sub_info['plan_id'], coupon_id=coupon_id, ai_rank_id=1,
- store_meal_name=store_meal_name)
- return response.json(0, {"redirectUrl": sub_info['url'], "orderID": order_id})
- # 正常扣款
- call_clc_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
- if lang != 'cn':
- call_clc_url = call_clc_url.replace('fail.html', 'en_fail.html')
- call_sub_url = "{}cloudstorage/dopaypalcallback?orderID={}&lang={}".format(SERVER_DOMAIN_SSL, order_id,
- lang)
- 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 not payment.create():
- return response.json(10, payment.error)
- logger.info('paypal创建订单返回----------')
- logger.info(payment)
- payment_id = payment['id'] # 获取paymentID
- for link in payment.links:
- if link.rel == "approval_url":
- approval_url = str(link.href)
- Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
- desc=content, payType=pay_type, payTime=now_time,
- price=price, currency=currency, addTime=now_time, updTime=now_time,
- pay_url=approval_url, isSelectDiscounts=is_select_discount,
- commodity_code=commodity_code, commodity_type=commodity_type,
- rank_id=rank, paymentID=payment_id, coupon_id=coupon_id, ai_rank_id=1,
- store_meal_name=store_meal_name)
- return response.json(0, {"redirectUrl": approval_url, "orderID": order_id})
- return response.json(10, 'generate_order_false')
- elif pay_type == 2:
- try:
- ali_pay_obj = AliPayObject()
- alipay = ali_pay_obj.conf()
- subject = store_qs[0]['lang__title'] + store_qs[0]['lang__content']
- order_string = alipay.api_alipay_trade_wap_pay(
- out_trade_no=order_id,
- total_amount=price,
- subject=subject,
- return_url="{}web/paid2/success.html".format(SERVER_DOMAIN_SSL),
- notify_url="{}cloudstorage/doalicallback".format(SERVER_DOMAIN_SSL),
- quit_url="{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL),
- passback_params=quote("lang=" + lang)
- )
- except Exception as e:
- print(repr(e))
- return response.json(10, repr(e))
- else:
- if order_string:
- redirect_url = ali_pay_obj.alipay_prefix + order_string
- Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
- desc=content, payType=pay_type, payTime=now_time,
- price=price, currency=currency, addTime=now_time, updTime=now_time,
- pay_url=redirect_url, isSelectDiscounts=is_select_discount,
- commodity_code=commodity_code, commodity_type=commodity_type,
- rank_id=rank, coupon_id=coupon_id, ai_rank_id=1,
- store_meal_name=store_meal_name)
- return JsonResponse(status=200, data={'result_code': 0, 'reason': 'success',
- 'result': {"redirectUrl": redirect_url, "orderID": order_id},
- 'error_code': 0})
- else:
- return response.json(10, '生成订单错误.')
- elif pay_type == 3:
- pay = WechatPayObject()
- notify_url = "{}cloudstorage/dowechatnotify".format(SERVER_DOMAIN_SSL)
- content = CommonService.Package_Type(0, content) # 云存套餐
- # 获取参数
- parameter_dict = pay.get_parameter(order_id, 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=order_id)
- if not response:
- return response.json(10, '生成订单错误.')
- # 回调函数
- Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
- desc=content, payType=pay_type, payTime=now_time,
- price=price, currency=currency, addTime=now_time, updTime=now_time,
- pay_url=notify_url, isSelectDiscounts=is_select_discount,
- commodity_code=commodity_code, commodity_type=commodity_type, rank_id=rank,
- ai_rank_id=1, store_meal_name=store_meal_name)
- return JsonResponse(status=200, data={'result_code': 0, 'reason': 'success',
- 'result': response,
- 'orderId': order_id,
- 'error_code': 0})
- def do_experience_order(self, request_dict, user_id, response): # 生成体验订单
- """
- 生成体验订单
- @param request_dict: 请求数据
- @param user_id: 用户id
- @request_dict uid: uid
- @request_dict channel: 通道
- @request_dict commodity_code: 套餐规格码
- @request_dict pay_type: 支付类型
- @request_dict rank: 存储套餐id
- @request_dict cdk: 激活码
- @request_dict lang: 语言
- @param response: 响应
- @return: response
- """
- uid = request_dict.get('uid', None)
- channel = request_dict.get('channel', None)
- commodity_code = request_dict.get('commodity_code', '')
- 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 uid is None:
- return response.json(444, 'uid.')
- redis_obj = RedisObject()
- is_lock = redis_obj.CONN.setnx(uid + 'do_experience_order', 1)
- redis_obj.CONN.expire(uid + 'do_experience_order', 60)
- logger = logging.getLogger('info')
- if not is_lock:
- return response.json(5)
- if pay_type == 10: # 判断是否已体验过套餐
- experience_context_qs = ExperienceContextModel.objects.filter(uid=uid, experience_type=0)
- if experience_context_qs.exists():
- return response.json(5)
- if cdk is not 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 not all([channel, pay_type, rank]):
- redis_obj.del_data(key=uid + 'do_experience_order')
- return response.json(444, 'channel, pay_type, rank')
- device_info_qs = Device_Info.objects.filter(Q(UID=uid), ~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
- if device_info_qs.exists():
- if device_info_qs[0]['vodPrimaryUserID'] != user_id:
- if pay_type == 10:
- return response.json(10035)
- if pay_type == 11:
- return response.json(10036)
- device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1)
- if not device_info_qs.exists():
- return response.json(12)
- order_id = CommonService.createOrderID()
- now_time = int(time.time())
- store_qs = Store_Meal.objects.filter(id=rank, lang__lang=lang, is_show=0).values("day", "bucket_id",
- "bucket__storeDay", "expire",
- 'lang__content', 'price',
- 'currency', 'commodity_type')
- if not store_qs.exists():
- return response.json(173)
- bucket_id = store_qs[0]['bucket_id']
- uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id", "bucket__storeDay",
- "bucket__region", "endTime", "use_status")
- expire = store_qs[0]['expire']
- try:
- with transaction.atomic():
- if uid_bucket_qs.exists():
- uid_bucket = uid_bucket_qs.first()
- if uid_bucket['use_status'] == 1 and uid_bucket['bucket_id'] == bucket_id: # 套餐使用中并且相同套餐叠加过期时间
- end_time = CommonService.calcMonthLater(expire, uid_bucket['endTime'])
- UID_Bucket.objects.filter(id=uid_bucket['id']).update(uid=uid, channel=channel,
- bucket_id=bucket_id,
- endTime=end_time, updateTime=now_time)
- else: # 已过期或者不相同的套餐加入未使用的关联套餐表
- unused_uid_qs = Unused_Uid_Meal.objects.filter(uid=uid, bucket_id=bucket_id)
- nums = 1
- if unused_uid_qs.exists():
- unused_uid_qs.update(num=F('num') + nums)
- else:
- Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, num=nums,
- expire=store_qs[0]['expire'], bucket_id=bucket_id)
- UID_Bucket.objects.filter(id=uid_bucket['id']).update(has_unused=1)
- uid_bucket_id = uid_bucket['id']
- else:
- end_time = CommonService.calcMonthLater(expire)
- uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
- endTime=end_time, addTime=now_time, updateTime=now_time,
- use_status=1)
- uid_bucket_id = uid_bucket.id
- store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=0).values('lang__title',
- 'lang__content')
- if store_meal_qs.exists():
- store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
- else:
- store_meal_name = '未知套餐'
- Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
- desc=store_qs[0]['lang__content'], payType=pay_type, payTime=now_time,
- price=store_qs[0]['price'], currency=store_qs[0]['currency'],
- addTime=now_time,
- updTime=now_time,
- pay_url="体验版", store_meal_name=store_meal_name,
- commodity_code=commodity_code, commodity_type=store_qs[0]['commodity_type'],
- rank_id=rank, status=1, uid_bucket_id=uid_bucket_id, ai_rank_id=1)
- device_user_qs = Device_User.objects.filter(userID=user_id).values('username')
- device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
- if device_info_qs.exists():
- dvq_set_update_dict = {
- 'vodPrimaryUserID': user_id,
- 'vodPrimaryMaster': device_user_qs[0]['username']
- }
- device_info_qs.update(**dvq_set_update_dict)
- sms = 'SMS_219738485'
- date_time = time.strftime("%Y-%m-%d", time.localtime())
- # 如果存在序列号,消息提示用序列号
- device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
- serial_number = device_info_qs[0]['serial_number']
- device_type = device_info_qs[0]['Type']
- if serial_number:
- device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
- else:
- device_name = uid
- sys_msg_text_list = [
- '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
- 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
- "%b %dth,%Y", time.localtime())]
- return_url = "{}cloudstorage/payOK?lang={}".format(SERVER_DOMAIN_SSL, lang)
- if pay_type == 10:
- ExperienceContextModel.objects.create(
- experience_type=0,
- uid=uid,
- do_time=now_time
- )
- return_url = "{}cloudstorage/payOK?paytype=10&lang={}".format(SERVER_DOMAIN_SSL, lang)
- date_time = time.strftime("%Y-%m-%d", time.localtime())
- sys_msg_text_list = [
- '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功开通云存体验套餐',
- 'Dear customer,you already subscribed the free trial cloud storage service successfully for device ' + device_name + ' on ' + time.strftime(
- "%b %dth,%Y", time.localtime())]
- sms = 'SMS_222870823'
- if pay_type == 11:
- update_dict = {'is_activate': 1, 'order': order_id}
- CDKcontextModel.objects.filter(cdk=cdk).update(**update_dict)
- return_url = "{}cloudstorage/payOK?paytype=11&lang={}".format(SERVER_DOMAIN_SSL, lang)
- date_time = time.strftime("%Y-%m-%d", time.localtime())
- sys_msg_text_list = [
- '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功兑换云存套餐',
- 'Dear customer, you already redeemed for the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
- "%b %dth,%Y", time.localtime())]
- sms = 'SMS_219748439'
- self.do_vod_msg_notice(uid, channel, user_id, lang, sys_msg_text_list, sms)
- result = return_url
- redis_obj.del_data(key=uid + 'do_experience_order')
- return response.json(0, result)
- except Exception as e:
- logger.info('出错了~体验云存异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
- redis_obj.del_data(key=uid + 'do_experience_order')
- return response.json(474)
- @staticmethod
- def do_experience_reset(request_dict, response): # 重置设备云存体验
- """
- 重置设备云存体验
- @param request_dict: 请求数据
- @request_dict id: 关联套餐id
- @param response: 响应
- @return: response
- """
- bucket_id = request_dict.get("id", None)
- uid_bucket_qs = UID_Bucket.objects.filter(id=bucket_id)
- if uid_bucket_qs.exists():
- experience_context_qs = ExperienceContextModel.objects.filter(uid=uid_bucket_qs[0].uid)
- if experience_context_qs.exists():
- experience_context_qs.delete()
- Order_Model.objects.filter(uid_bucket_id=bucket_id).delete()
- uid_bucket_qs.delete()
- else:
- return response.json(10007)
- else:
- return response.json(0, '重置云存体验失败')
- return response.json(0, '重置云存体验成功')
- @staticmethod
- def delete_vod_list(request_dict, user_id, response): # 删除播放列表
- """
- 删除播放列表
- @param request_dict: 请求数据
- @param user_id: 用户id
- @request_dict uid: uid
- @request_dict vod_id_list: 云存视频id列表
- @param response: 响应
- @return: response
- """
- uid = request_dict.get('uid', None)
- vod_id_list = request_dict.get('vod_id_list', None)
- is_del_all = request_dict.get('is_del_all', 0)
- if not all([uid, vod_id_list]):
- return response.json(444)
- device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
- 'vodPrimaryUserID')
- if not device_info_qs.exists() or device_info_qs[0]['vodPrimaryUserID'] != user_id:
- return response.json(12)
- vod_id_list = json.loads(vod_id_list)
- try:
- if is_del_all == 1:
- VodHlsModel.objects.filter(uid=uid).delete()
- # 删除vod_hls分表数据
- split_vod_hls_obj = SplitVodHlsObject()
- split_vod_hls_obj.del_vod_hls_data(uid=uid)
- else:
- if type(vod_id_list).__name__ != 'list':
- return response.json(444)
- VodHlsModel.objects.filter(id__in=vod_id_list).delete()
- # 删除vod_hls分表数据
- split_vod_hls_obj = SplitVodHlsObject()
- split_vod_hls_obj.del_vod_hls_data(id__in=vod_id_list)
- except Exception as e:
- return response.json(424, repr(e))
- else:
- return response.json(0)
- @staticmethod
- def device_commodity(request_dict, user_id, response): # 设备关联套餐列表
- """
- 设备关联套餐列表
- @param request_dict: 请求数据
- @param user_id: 用户id
- @request_dict uid: uid
- @request_dict lang: 语言
- @param response: 响应
- @return: response
- """
- uid = request_dict.get('uid', None)
- lang = request_dict.get('lang', 'en')
- if not uid:
- return response.json(444)
- device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
- 'vodPrimaryUserID', 'serial_number', 'Type')
- if not device_info_qs.exists() or device_info_qs[0]['vodPrimaryUserID'] != user_id:
- return response.json(12)
- now_time = int(time.time())
- bucket_id_list = []
- store_list = []
- uid_bucket_qs = 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_qs:
- return response.json(10030)
- # 如果存在序列号返回完整序列号
- device_id = uid
- serial_number = device_info_qs[0]['serial_number']
- device_type = device_info_qs[0]['Type']
- if serial_number:
- device_id = CommonService.get_full_serial_number(uid, serial_number, device_type)
- uid_bucket_qs[0]['uid'] = device_id
- uid_bucket_qs[0]['storage'] = 0
- has_unused = uid_bucket_qs[0]['has_unused']
- del uid_bucket_qs[0]['has_unused']
- store_list.append(uid_bucket_qs[0])
- bucket_id_list.append(uid_bucket_qs[0]['bucket__id'])
- if has_unused == 1:
- unused_uid_qs = 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 unused_uid in unused_uid_qs:
- storage_time = unused_uid['num'] * unused_uid['expire']
- if lang != 'cn' and storage_time > 1: # 英文大于一个月使用复数
- month += 's'
- storage = str(storage_time) + month
- unused_dict = {
- "id": unused_uid['unused_id'],
- "uid": device_id,
- "bucket__content": unused_uid['bucket__content'],
- "use_status": 0,
- "endTime": 0,
- "bucket__id": unused_uid['bucket__id'],
- "storage": storage,
- }
- store_list.append(unused_dict)
- bucket_id_list.append(unused_uid['bucket__id'])
- store_qs = Store_Meal.objects.filter(bucket__id__in=bucket_id_list, lang__lang=lang).annotate(
- title=F('lang__title'), content=F('lang__content')).values('lang__content', 'lang__lang',
- 'bucket__id', 'lang__title')
- for index, value in enumerate(store_list):
- for store in store_qs:
- if value['bucket__id'] == store['bucket__id']:
- value['bucket__content'] = store['lang__title'] + '-' + store['lang__content']
- return response.json(0, list(store_list))
- @staticmethod
- def switch_device_commodity(request_dict, user_id, response): # 提前使用设备关联套餐
- """
- 提前使用设备关联套餐
- @param request_dict: 请求数据
- @param user_id: 用户id
- @request_dict uid: uid
- @request_dict switch_commodity_id: 未使用关联套餐id
- @param response: 响应
- @return: response
- """
- uid = request_dict.get('uid', None)
- unused_id = request_dict.get('switch_commodity_id', None)
- if not all([uid, unused_id]):
- return response.json(444)
- device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
- 'vodPrimaryUserID')
- if not device_info_qs.exists() or device_info_qs[0]['vodPrimaryUserID'] != user_id:
- return response.json(12)
- # 切换设备套餐关联
- using_uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, has_unused=1).values("id", "uid", "endTime",
- "bucket__content", "addTime")
- unused_uid_bucket_qs = Unused_Uid_Meal.objects.filter(id=unused_id).values("id", "uid", "channel", "addTime",
- "expire", "num", "bucket_id")
- if not unused_uid_bucket_qs.exists() or not using_uid_bucket_qs.exists():
- return response.json(10030)
- unused_uid_bucket = unused_uid_bucket_qs.first()
- now_time = 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
- end_time = CommonService.calcMonthLater(unused_uid_bucket['expire'] * unused_uid_bucket['num'])
- UID_Bucket.objects.filter(uid=uid).update(channel=unused_uid_bucket['channel'], endTime=end_time,
- bucket_id=unused_uid_bucket['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=uid).delete() # 删除sts记录
- # VodHlsModel.objects.filter(uid=uid).delete() # 删除播放列表,后期数据量多时应该考虑延后删除
- return response.json(0)
- except Exception:
- return response.json(474)
- @staticmethod
- def has_vod(request_dict, user_id, response):
- """
- 云存日期
- @param request_dict: 请求数据
- @param user_id: 用户id
- @request_dict uid: uid
- @request_dict channel: 通道
- @param response: 响应
- @return: response
- """
- uid = request_dict.get('uid', None)
- channel = request_dict.get('channel', 1)
- if not uid:
- return response.json(444)
- device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False).values(
- 'vodPrimaryUserID',
- 'vodPrimaryMaster')
- if not device_info_qs.exists():
- return response.json(12)
- if device_info_qs[0]['vodPrimaryUserID'] != user_id:
- return response.json(10034)
- now_time = int(time.time())
- uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel).values(
- 'bucket_id').order_by(
- 'addTime')
- if not uid_bucket_qs.exists():
- return response.json(10030)
- # vod_hls_qs = 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]
- split_vod_hls_obj = SplitVodHlsObject()
- vod_hls_qs = split_vod_hls_obj.get_vod_hls_date(uid=uid, end_time__gte=now_time, channel=channel)
- had_vod_list = []
- for vod in vod_hls_qs:
- had_vod_list.append({
- 'timestamp': CommonService.str_to_timestamp(vod['date'], '%Y-%m-%d'),
- 'vod_count': vod['count'],
- 'date_format': vod['date'],
- })
- had_vod_list = sorted(had_vod_list, key=lambda item: -item['timestamp'])[:31]
- return response.json(0, had_vod_list)
- @staticmethod
- def video_playback_time(request_dict, user_id, response):
- """
- 存储视频播放数据
- @param request_dict: 请求数据
- @param user_id: 用户id
- @request_dict parms: 参数列表
- @param response: 响应
- @return: response
- """
- params = request_dict.get('parms', None)
- if not params:
- return response.json(444)
- try:
- params = eval(params)
- bulk = []
- for parm in params:
- parm['userID'] = user_id
- # 解密uid
- for i in range(1, 4):
- parm['uid'] = base64.b64decode(parm['uid'])
- parm['uid'] = parm['uid'].decode('utf-8')
- parm['uid'] = parm['uid'][i:-i]
- video_playback_time = VideoPlaybackTimeModel(**parm)
- bulk.append(video_playback_time)
- VideoPlaybackTimeModel.objects.bulk_create(bulk)
- return response.json(0)
- except Exception as e:
- print(e)
- return response.json(500, repr(e))
- def do_vod_msg_notice(self, uid, channel, user_id, lang, sys_msg_text_list, sms): # 云存操作系统消息
- """
- 云存操作系统消息
- @param uid: uid
- @param channel: 通道
- @param user_id: 用户id
- @param lang: 语言
- @param sys_msg_text_list: 消息列表
- @param sms: sms码
- @return: response
- """
- try:
- logger = logging.getLogger('log')
- logger.info('进来了')
- if lang == 'cn':
- sys_msg_text = sys_msg_text_list[0]
- else:
- sys_msg_text = sys_msg_text_list[1]
- now_time = int(time.time())
- create_data = {'userID_id': user_id, 'msg': sys_msg_text, 'addTime': now_time,
- 'updTime': now_time, 'uid': uid, 'eventType': 0}
- SysMsgModel.objects.create(**create_data)
- user_qs = Device_User.objects.filter(userID=user_id)
- if user_qs.exists():
- user = user_qs.first()
- username = user.username
- data_valid = DataValid()
- if data_valid.email_validate(username):
- S3Email().faEmail(sys_msg_text, username)
- elif data_valid.mobile_validate(username):
- # 如果存在序列号,消息提示用序列号
- device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
- if device_info_qs.exists():
- serial_number = device_info_qs[0]['serial_number']
- device_type = device_info_qs[0]['Type']
- if serial_number:
- device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
- else:
- device_name = uid
- params = '{"devname":"%s","submittime":"%s"}' % (
- device_name, time.strftime("%Y-%m-%d", time.localtime()))
- self.send_message(username, params, sms)
- logger.info('出去了')
- except Exception as e:
- return repr(e)
- def do_vod_msg_end(self, response): # 云存到期续费提醒 提前3天
- """
- 云存到期续费提醒
- @param response: 响应
- @return: response
- """
- now_time = int(time.time())
- # 过期前第7天提示一次
- uid_bucket_qs = 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, uid_bucket_qs)
- # 过期前第3天提示一次
- uid_bucket_qs = 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, uid_bucket_qs)
- return response.json(0)
- def do_vod_msg(self, now_time, qs):
- """
- 云存到期续费提醒
- @param now_time: 现在时间
- @param qs: 查询集
- @return: response
- """
- msg_list = []
- ids = []
- for item in qs:
- ids.append(item['id'])
- order_qs = Order_Model.objects.filter(uid_bucket_id__in=ids).values('userID_id', 'uid_bucket_id')
- for item in qs:
- for order in order_qs:
- if item['id'] == order['uid_bucket_id']:
- # 如果存在序列号,消息提示用序列号
- uid = item['uid']
- device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
- serial_number = device_info_qs[0]['serial_number']
- device_type = device_info_qs[0]['Type']
- if serial_number and device_type == 101:
- device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
- else:
- device_name = uid
- if item['bucket__area'] == 'cn':
- sys_msg_text = "温馨提示:尊敬的客户,您%s设备的云存套餐将在%s到期" % (
- device_name, time.strftime("%Y-%m-%d", time.localtime(item['endTime'])))
- else:
- sys_msg_text = 'Dear customer,the cloud storage package for your device %s will expire on %s' % \
- (device_name, time.strftime('%m-%d-%y', time.localtime(item['endTime'])))
- msg_list.append(SysMsgModel(
- userID_id=order['userID_id'],
- addTime=now_time,
- updTime=now_time,
- uid=item['uid'],
- eventType=0,
- msg=sys_msg_text,
- status=0
- ))
- SysMsgModel.objects.bulk_create(msg_list)
- user_qs = Device_User.objects.filter(userID=order['userID_id'])
- if user_qs.exists():
- user = user_qs.first()
- 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":"%s","submittime":"%s"}' % (
- device_name, time.strftime("%Y-%m-%d", time.localtime(item['endTime'])))
- self.send_message(username, params, 'SMS_219748440')
- @staticmethod
- def send_message(phone, params, temp_msg):
- """
- 发送手机消息
- @param phone: 用户名
- @param params: 消息参数
- @param temp_msg: sms码
- """
- sign_ms = '周视'
- ali_sms = AliSmsObject()
- ali_sms.send_code_sms_cloud(phone=phone, params=params, sign_name=sign_ms, temp_msg=temp_msg)
- @staticmethod
- def do_refund(request_dict, response):
- """
- 退款
- @param request_dict: 请求数据
- @request_dict orderID: 订单id
- @request_dict refund_amount: 退款金额
- @param response: 响应
- @return: response
- """
- order_id = request_dict.get('orderID', None) # 商户订单号
- refund_amount = request_dict.get('refund_amount', None) # 退款金额
- if not all([order_id, refund_amount]):
- return response.json(444)
- try:
- order_qs = Order_Model.objects.filter(orderID=order_id) \
- .values('status', 'payType', 'price', 'refunded_amount',
- 'currency', 'paymentID', 'trade_no')
- if not order_qs.exists():
- return response.json(173)
- # 支付状态不为支付成功和退款失败和部分退款
- status = order_qs[0]['status']
- if status != 1 and status != 4 and status != 6:
- return response.json(805)
- refund_amount = float(refund_amount)
- now_time = int(time.time())
- pay_type = order_qs[0]['payType']
- price = order_qs[0]['price'] # 订单金额
- refunded_amount = order_qs[0]['refunded_amount'] # 已退款金额
- currency = order_qs[0]['currency'] # 货币
- # 判断是否符合付款条件
- if refunded_amount == float(price): # 已全额退款
- return response.json(805)
- if refund_amount + refunded_amount > float(price): # 退款金额超出订单价格
- return response.json(805)
- # 部分退款标识
- is_partial_refund = True if (float(price) > refund_amount + refunded_amount) else False
- out_request_no = str(time.strftime('%Y%m%d%H%M%S', time.localtime(now_time))) # 退款请求号
- # 根据支付类型处理退款
- if pay_type == 1: # PayPal
- payment_id = order_qs[0]['paymentID'] # PayPal PAYMENT_ID
- trade_no = order_qs[0]['trade_no']
- sale_id = ''
- paypalrestsdk.configure(PAYPAL_CRD)
- if payment_id:
- payment = paypalrestsdk.Payment.find(payment_id)
- related_resources = payment['transactions'][0]['related_resources']
- if not related_resources:
- return response.json(805)
- sale = related_resources[0]['sale']
- # 没退款过 'state' 不为 'completed' 或 已退款过但 'state' 不为 'partially_refunded'
- if (refunded_amount == 0 and sale['state'] != 'completed') or (
- refunded_amount != 0 and sale['state'] != 'partially_refunded'):
- return response.json(805)
- sale_id = sale['id']
- sale_id = sale_id if sale_id else trade_no
- paypal_sale = paypalrestsdk.Sale.find(sale_id)
- if not paypal_sale or paypal_sale['state'] != 'completed':
- return response.json(805)
- refund = paypal_sale.refund({
- 'amount': {
- 'total': refund_amount,
- 'currency': currency
- }
- })
- refund_success = True if refund.success() else False
- elif pay_type == 2: # 支付宝
- ali_pay_obj = AliPayObject()
- alipay = ali_pay_obj.conf()
- refund_response = alipay.api_alipay_trade_refund(refund_amount=refund_amount, out_trade_no=order_id,
- out_request_no=out_request_no)
- refund_success = True if (refund_response['code'] == '10000') else False
- elif pay_type == 3: # 微信
- wechat_pay_obj = WechatPayObject()
- refund_fee = int(refund_amount * 100) # 退款金额,单位为分,只能为整数
- success = wechat_pay_obj.refund(out_trade_no=order_id, out_refund_no=out_request_no,
- total_fee=refund_fee, refund_fee=refund_fee)
- refund_success = True if success else False
- else: # 不支持退款的支付类型
- return response.json(805)
- # 更新订单状态和已退款金额
- update_dict = {'updTime': now_time}
- if refund_success:
- update_dict['status'] = 6 if is_partial_refund else 5
- update_dict['refunded_amount'] = refunded_amount + refund_amount
- else:
- update_dict['status'] = 4
- order_qs.update(**update_dict)
- return response.json(0)
- except Exception as e:
- logger = logging.getLogger('info')
- logger.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
- return response.json(500, repr(e))
|