#!/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, DETECT_PUSH_DOMAINS, CONFIG_INFO, CONFIG_CN, BINOCULAR_DEVICE_TYPE, CONFIG_US, \ CONFIG_TEST, CONFIG_EUR 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, UidSetModel, AiService, \ StsFrequency, InAppPurchasePackage 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') is_ai = request_dict.get('is_ai', 0) app_type = request_dict.get('app_type', None) if not all([uid]): return response.json(444) # 苹果内购,app_type:1 is_ios = False if app_type is not None: if int(app_type) == 1: is_ios = True is_ai = int(is_ai) 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) try: # 查询设备像素 uid_set_qs = UidSetModel.objects.filter(uid=uid).values('ucode', 'is_ai') if not uid_set_qs.exists(): return response.json(173) ucode = uid_set_qs[0]['ucode'] dpi_flag = 0 if ucode: if ucode[-5] == 'A': dpi_flag = 10 else: dpi_flag = int(ucode[-5]) pixel_level = 1 if ucode and dpi_flag >= 8 else 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(): if not is_ai: # 返回云存套餐 store_qs = store_qs.filter(~Q(pay_type='10'), Q(is_ai=0)) # 筛选像素等级 else: # 返回云存+AI套餐 is_ai = uid_set_qs[0]['is_ai'] is_ai = 1 if is_ai != 2 and CONFIG_INFO != CONFIG_CN else 0 # 国内不支持AI服务 if not is_ai: return response.json(0) store_qs = store_qs.filter(~Q(pay_type='10'), Q(is_ai=1)) # 筛选像素等级 if CONFIG_INFO != CONFIG_CN: # 国内生产环境不筛选像素 加载所有上架套餐 store_qs = store_qs.filter(Q(pixel_level=pixel_level)) if is_ios: store_qs = store_qs.filter(pay_type=5) else: store_qs = store_qs.exclude(pay_type=5) if uid not in ["VXJ267WU5NZ1S89H111A", "18SM4J9DYWB2AEG1111A", "517J385BNUGP3CPP111A"] and CONFIG_INFO == CONFIG_TEST: store_qs = store_qs.exclude(id=88) elif uid not in ["VXJ267WU5NZ1S89H111A", "18SM4J9DYWB2AEG1111A", "517J385BNUGP3CPP111A"] and CONFIG_INFO == CONFIG_US: store_qs = store_qs.exclude(id=34) elif uid not in ["VXJ267WU5NZ1S89H111A", "18SM4J9DYWB2AEG1111A", "517J385BNUGP3CPP111A"] and CONFIG_INFO == CONFIG_EUR: store_qs = store_qs.exclude(id=34) else: is_ai = uid_set_qs[0]['is_ai'] is_ai = 1 if is_ai != 2 and CONFIG_INFO != CONFIG_CN else 0 # 国内不支持AI服务 store_qs = store_qs.filter(pay_type='10') # 体验套餐不区分像素等级 store_qs = store_qs.annotate(title=F('lang__title'), content=F('lang__content'), new_title=F('lang__new_title'), discount_content=F('lang__discount_content')) store_qs = store_qs.order_by('sort').values("id", "title", "content", "price", "day", "currency", "bucket__storeDay", "new_title", "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']) for each in item['pay_type']: if each['id'] == 10 and CONFIG_INFO != CONFIG_CN: if is_ai == 0: item['content'] = item['new_title'].get('1', '') elif is_ai == 1: item['content'] = item['new_title'].get('2', '') 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) except Exception as e: return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e))) @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=start_time, end_time__gte=now_time).values("sec", "fg", "bucket_id", 'start_time') if not vod_hls_qs.exists(): return response.json(173) 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"] fg = int(vod_hls_qs[0]['fg']) 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 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=start_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") # 统计sts请求次数,一小时超过20次进行报警 redis_obj = RedisObject() key = 'sts_count_{}'.format(uid) sts_count = redis_obj.get_data(key) if sts_count: sts_count = int(sts_count) if sts_count % 20 == 0: sts_frequency_qs = StsFrequency.objects.filter(uid=uid) if sts_frequency_qs.exists(): sts_frequency_qs[0].frequency += 1 sts_frequency_qs[0].updateTime = now_time sts_frequency_qs[0].save() else: StsFrequency.objects.create(uid=uid, frequency=1, addTime=now_time, updateTime=now_time) sts_count += 1 ttl = redis_obj.get_ttl(key) else: sts_count = 1 ttl = 3600 redis_obj.set_data(key, sts_count) redis_obj.set_expire(key, ttl) # 亚马逊 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, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, 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', 'Type', 'vodPrimaryMaster') if not device_info_qs.exists(): return response.json(12) device_type = device_info_qs[0]['Type'] 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()) if device_type in BINOCULAR_DEVICE_TYPE: # 枪球设备开通云存不区分通道 uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time) else: uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel) 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() if device_type in BINOCULAR_DEVICE_TYPE: vod_hls_qs = split_vod_hls_obj.get_vod_hls_data(uid=uid, end_time__gte=now_time, start_time__range=(start_time, end_time), type_list=type_list) \ .values("id", "start_time", "sec", "fg", "bucket_id", "channel") else: 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", "channel") 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=vod['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=vod['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, sec) # 云存关联AI标签 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, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, 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', 'Type') if not device_info_qs.exists() or device_info_qs[0]['vodPrimaryUserID'] != user_id: return response.json(12) device_type = device_info_qs[0]['Type'] if device_type in BINOCULAR_DEVICE_TYPE: # 枪球设备开通云存不区分通道 uid_bucket_qs = UID_Bucket.objects.filter(uid=uid) else: 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) if status == 0: uid_bucket_qs.update(status=status) return response.json(0) uid_bucket_qs.update(status=status, channel=channel) 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/' sign = CommonService.encode_data(uid[0:8], start=0, end=1) uid_tk_url = '{}cloudstorage/getsignsts?uidToken={}&sn={}'.format(urls, uid_obj.token, sign) 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', 'expire') if not store_qs.exists(): return response.json(173) bucket_id = store_qs[0]['bucket_id'] expire = store_qs[0]['expire'] uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id", "bucket__region", "endTime", "use_status") 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 end_time = CommonService.calcMonthLater(expire) with transaction.atomic(): if uid_bucket_qs.exists(): uid_bucket = uid_bucket_qs.first() uid_bucket_id = uid_bucket['id'] if uid_bucket['use_status'] == 1 and uid_bucket['endTime'] > now_time: # 套餐使用中并且相同套餐叠加过期时间 Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, is_ai=0, expire=expire, bucket_id=bucket_id, order_id=order_id) UID_Bucket.objects.filter(id=uid_bucket_id).update(has_unused=1) else: UID_Bucket.objects.filter(id=uid_bucket_id).update(channel=channel, bucket_id=bucket_id, endTime=end_time, updateTime=now_time, use_status=1, orderId=order_id) else: 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, orderId=order_id) 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, payTime=now_time, promotion_rule_id=promotion_rule_id, create_vod=1) 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.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", "expire", "is_ai") if not store_qs.exists(): return response.json(173) bucket_id = store_qs[0]['bucket_id'] is_ai = store_qs[0]['is_ai'] expire = store_qs[0]['expire'] uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id", "bucket__region", "endTime", "use_status") 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 end_time = CommonService.calcMonthLater(expire) use_flag = True with transaction.atomic(): if uid_bucket_qs.exists(): uid_bucket = uid_bucket_qs.first() uid_bucket_id = uid_bucket['id'] if uid_bucket['use_status'] == 1 and uid_bucket['endTime'] > now_time: # 套餐使用中并且相同套餐叠加过期时间 Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, order_id=order_id, expire=expire, is_ai=is_ai, bucket_id=bucket_id) update_status = UID_Bucket.objects.filter(id=uid_bucket_id).update(has_unused=1) use_flag = False else: update_status = UID_Bucket.objects.filter(id=uid_bucket_id).update(channel=channel, bucket_id=bucket_id, endTime=end_time, updateTime=now_time, use_status=1, orderId=order_id) else: 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, orderId=order_id) update_status = True 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) logger.info( 'uid:{},uid_bucket_id:{},update_status:{},order_id:{}'.format(uid, uid_bucket_id, update_status, order_id)) order_qs.update(status=1, updTime=now_time, uid_bucket_id=uid_bucket_id, payTime=now_time, promotion_rule_id=promotion_rule_id, create_vod=1) date_time = time.strftime("%Y-%m-%d", time.localtime()) # 开通AI服务 if is_ai and use_flag: ai_service = AiService.objects.filter(uid=uid, channel=channel) if ai_service.exists(): # 有正在使用的套餐,套餐结束时间保存为套餐有效期 ai_service.update(updTime=now_time, use_status=1, orders_id=order_id, endTime=end_time) else: AiService.objects.create(uid=uid, channel=channel, detect_status=1, addTime=now_time, updTime=now_time, endTime=end_time, use_status=1, orders_id=order_id) # 如果存在序列号,消息提示用序列号 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 have now successfully subscribed to the cloud storage plan 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", "expire") if not store_qs.exists(): return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '套餐不存在'})) bucket_id = store_qs[0]['bucket_id'] expire = store_qs[0]['expire'] uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id", "bucket__region", "endTime", "use_status") 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 end_time = CommonService.calcMonthLater(expire) with transaction.atomic(): if uid_bucket_qs.exists(): uid_bucket = uid_bucket_qs.first() uid_bucket_id = uid_bucket['id'] if uid_bucket['use_status'] == 1 and uid_bucket['endTime'] > now_time: # 套餐使用中并且相同套餐叠加过期时间 Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, is_ai=0, expire=expire, bucket_id=bucket_id, order_id=order_id) UID_Bucket.objects.filter(id=uid_bucket['id']).update(has_unused=1) else: UID_Bucket.objects.filter(id=uid_bucket_id).update(channel=channel, bucket_id=bucket_id, endTime=end_time, updateTime=now_time, use_status=1, orderId=order_id) else: 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, orderId=order_id) 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, payTime=now_time, promotion_rule_id=promotion_rule_id, create_vod=1) 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("\ \ \ ") 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) logger.info(f'uid:{uid}创建订单云存订单, 时间戳为{int(time.time())}, 支付类型为{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', 'is_ai') 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'] is_ai = store_qs[0]['is_ai'] order_type = 1 if is_ai else 0 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, order_type=order_type, 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, order_type=order_type, 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) product_name = store_qs[0]['lang__title'] + store_qs[0]['lang__content'] # 云存套餐 # 获取参数 parameter_dict = pay.get_parameter(order_id, product_name, 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}) elif pay_type == 5: # 内购订阅型订单 之前订阅过任意套餐返回不可再次订阅 if store_qs[0]['cycle_config_id']: return response.json(173) else: product_id = InAppPurchasePackage.objects.filter(rank_id=rank).values("product_id")[0]["product_id"] 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, isSelectDiscounts=is_select_discount, order_type=order_type, 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': {"orderID": order_id, "productId": product_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'] username = request_dict.get('username', None) if username: user_qs = Device_User.objects.filter(username=username).values('userID') if not user_qs.exists(): return response.json(444, 'username') user_id = user_qs[0]['userID'] 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) device_vo = device_info_qs.first() if device_vo.Type == 103 or device_vo.Type == 26: return response.json(10064) 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", "expire", "is_ai", '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__region", "endTime", "use_status") expire = store_qs[0]['expire'] uid_set_qs = UidSetModel.objects.filter(uid=uid).values('is_ai', 'ucode') if not uid_set_qs.exists(): return response.json(173) is_ai = 1 if uid_set_qs[0]['is_ai'] != 2 else 0 if is_ai != 1: is_ai = self.check_ucode_exists(uid_set_qs[0]['ucode']) if cdk: is_ai = store_qs[0]['is_ai'] order_type = 1 if is_ai and CONFIG_INFO != CONFIG_CN else 0 use_flag = True end_time = CommonService.calcMonthLater(expire) try: with transaction.atomic(): if uid_bucket_qs.exists(): uid_bucket = uid_bucket_qs.first() uid_bucket_id = uid_bucket['id'] if uid_bucket['use_status'] == 1 and uid_bucket['endTime'] > now_time: Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, is_ai=is_ai, order_id=order_id, expire=expire, bucket_id=bucket_id) UID_Bucket.objects.filter(id=uid_bucket_id).update(has_unused=1) use_flag = False else: UID_Bucket.objects.filter(id=uid_bucket_id).update(channel=channel, bucket_id=bucket_id, endTime=end_time, updateTime=now_time, use_status=1, orderId=order_id) else: 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, orderId=order_id) 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, order_type=order_type, updTime=now_time, create_vod=1, 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) # 开通AI服务,国内不支持AI if is_ai and use_flag and CONFIG_INFO != CONFIG_CN: ai_service = AiService.objects.filter(uid=uid, channel=channel) if ai_service.exists(): # 有正在使用的套餐,套餐结束时间保存为套餐有效期 ai_service.update(updTime=now_time, use_status=1, orders_id=order_id, endTime=end_time) else: AiService.objects.create(uid=uid, channel=channel, detect_status=1, addTime=now_time, updTime=now_time, endTime=end_time, use_status=1, orders_id=order_id) 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 have now successfully subscribed to the cloud storage plan 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 have now successfully subscribed to the free trial of cloud storage service 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 have now successfully redeemed for the cloud storage service 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", "orderId") 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", "bucket__id", "expire", "order_id") month = 'month' if lang != 'cn' else '个月' for unused_uid in unused_uid_qs: storage_time = 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, "orderId": unused_uid['order_id'], } store_list.append(unused_dict) bucket_id_list.append(unused_uid['bucket__id']) for index, value in enumerate(store_list): if value['orderId'] and CONFIG_INFO != CONFIG_CN: order_qs = Order_Model.objects.filter(orderID=value['orderId'], rank__lang__lang=lang).values('payType', 'rank__pay_type__id', 'order_type', 'rank__is_ai', 'rank__pixel_level', 'rank__commodity_code', 'rank__lang__new_title') if order_qs.exists(): order = order_qs[0] if order['payType'] not in [10, 11]: if order['rank__pixel_level'] == 0 and order['rank__is_ai'] == 0: if order['rank__commodity_code']: value['bucket__content'] = order['rank__lang__new_title'].get('5', '') else: value['bucket__content'] = order['rank__lang__new_title'].get('1', '') elif order['rank__pixel_level'] == 1 and order['rank__is_ai'] == 0: if order['rank__commodity_code']: value['bucket__content'] = order['rank__lang__new_title'].get('6', '') else: value['bucket__content'] = order['rank__lang__new_title'].get('2', '') elif order['rank__pixel_level'] == 0 and order['rank__is_ai'] == 1: if order['rank__commodity_code']: value['bucket__content'] = order['rank__lang__new_title'].get('7', '') else: value['bucket__content'] = order['rank__lang__new_title'].get('3', '') elif order['rank__pixel_level'] == 1 and order['rank__is_ai'] == 1: if order['rank__commodity_code']: value['bucket__content'] = order['rank__lang__new_title'].get('8', '') else: value['bucket__content'] = order['rank__lang__new_title'].get('4', '') elif order['payType'] == 10: # 免费套餐 if order['order_type'] == 0: value['bucket__content'] = order['rank__lang__new_title'].get('1', '') elif order['order_type'] == 1: value['bucket__content'] = order['rank__lang__new_title'].get('2', '') else: # cdk套餐 if order['rank__pay_type__id'] != 11: if order['rank__pixel_level'] == 0 and order['rank__is_ai'] == 0: value['bucket__content'] = order['rank__lang__new_title'].get('1', '') elif order['rank__pixel_level'] == 1 and order['rank__is_ai'] == 0: value['bucket__content'] = order['rank__lang__new_title'].get('2', '') elif order['rank__pixel_level'] == 0 and order['rank__is_ai'] == 1: value['bucket__content'] = order['rank__lang__new_title'].get('3', '') elif order['rank__pixel_level'] == 1 and order['rank__is_ai'] == 1: value['bucket__content'] = order['rank__lang__new_title'].get('4', '') else: if order['order_type'] == 0: value['bucket__content'] = order['rank__lang__new_title'].get('1', '') elif order['order_type'] == 1: value['bucket__content'] = order['rank__lang__new_title'].get('2', '') value['bucket__content'] += '(cdk)' else: 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 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", "is_ai", "bucket_id", "order_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']) UID_Bucket.objects.filter(uid=uid).update(channel=unused_uid_bucket['channel'], endTime=end_time, bucket_id=unused_uid_bucket['bucket_id'], orderId=unused_uid_bucket['order_id'], updateTime=now_time, use_status=1, has_unused=has_unused) # 开通AI服务 if unused_uid_bucket['is_ai']: ai_service = AiService.objects.filter(uid=uid, channel=unused_uid_bucket['channel']) if ai_service.exists(): # 有正在使用的套餐,套餐结束时间保存为套餐有效期 ai_service.update(updTime=now_time, use_status=1, orders_id=unused_uid_bucket['order_id'], endTime=end_time) else: AiService.objects.create(uid=uid, channel=unused_uid_bucket['channel'], detect_status=1, addTime=now_time, updTime=now_time, endTime=end_time, use_status=1, orders_id=unused_uid_bucket['order_id']) 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', 'Type') 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()) device_type = device_info_qs[0]['Type'] if device_type in BINOCULAR_DEVICE_TYPE: # 枪球设备开通云存不区分通道 uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time).values( 'bucket_id').order_by( 'addTime') else: 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() if device_type in BINOCULAR_DEVICE_TYPE: # 枪球设备开通云存不区分通道 vod_hls_qs = split_vod_hls_obj.get_vod_hls_date(uid=uid, end_time__gte=now_time) else: 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, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, 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) # 不接收邮件用户 if user_id == '167015836969813800138000': return 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) msg_list.clear() 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'] not in ['completed', 'partially_refunded']: 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) # 退款金额,单位为分,只能为整数 total_fee = int(float(price) * 100) # 订单金额,单位为分,只能为整数 success = wechat_pay_obj.refund(out_trade_no=order_id, out_refund_no=out_request_no, total_fee=total_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, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e))) def check_ucode_exists(self, ucode): if not ucode: return 0 ucode_set = {'823C01552AA', '823C01550AA', '823C01550XA', '522001352AA', '823C01550TA', '823C01550VA', '823C01850XA', 'C18201850KA', '823C01850TA', 'C22501850VA', 'V82301850AA', 'V82301850XA', '730201350AA', '730201450AA', '730201450MA', '730201450NA', '72V201252AA', '72V201253AA', '72V201353AA', '72V201354AA', '72V201355AA', '72V201254AA', '72V201256AA', '72V201257AA'} return 1 if ucode in ucode_set else 0