1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341 |
- #!/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
- 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, AiService, UidSetModel, UidPushModel, \
- VodHlsTagType, ICloudStoreMeal, IcloudUseDetails, IcloudService
- from Object.AWS.AmazonS3Util import AmazonS3Util
- from Object.AWS.S3Email import S3Email
- from Object.AliPayObject import AliPayObject
- from Object.AliSmsObject import AliSmsObject
- from Object.ETkObject import ETkObject
- 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 == 'changevodaistatus': # 修改云存AI状态
- return self.do_change_vod_ai_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)
- uid_set_qs = UidSetModel.objects.filter(uid=uid).values('is_ai')
- if not uid_set_qs.exists():
- return response.json(173)
- is_ai = uid_set_qs[0]['is_ai']
- 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')
- if CONFIG_INFO != CONFIG_CN and is_ai != 2: # 返回支持AI的套餐
- store_qs = store_qs.filter(is_ai=1)
- else: # 返回不支持AI的套餐
- store_qs = store_qs.filter(is_ai=0)
- 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", 'is_beta', 'is_ai',
- "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, '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 == 34: # 枪球设备开通云存不区分通道
- 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()
- 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, '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 == 34: # 枪球设备开通云存不区分通道
- 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/'
- 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_change_vod_ai_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)
- vod_status = request_dict.get('vod_status', None)
- channel = request_dict.get('channel', None)
- domain_name = request_dict.get('domain_name', None)
- token_val = request_dict.get('token_val', None)
- appBundleId = request_dict.get('appBundleId', None)
- app_type = request_dict.get('app_type', None)
- push_type = request_dict.get('push_type', None)
- ai_status = request_dict.get('ai_status', None)
- m_code = request_dict.get('m_code', None)
- lang = request_dict.get('lang', 'en')
- tz = request_dict.get('tz', '0')
- detect_group = request_dict.get('detect_group', None)
- interval = request_dict.get('interval', None)
- if not all([uid, vod_status, channel]):
- return response.json(444, 'uid,vod_status,channel')
- vod_status = int(vod_status)
- 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']
- uid_set_qs = UidSetModel.objects.filter(uid=uid)
- if not uid_set_qs.exists():
- return response.json(12)
- if device_type == 34: # 枪球设备开通云存不区分通道
- 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())
- end_time = uid_bucket_qs[0].endTime
- if now_time > end_time:
- return response.json(10031)
- try:
- with transaction.atomic():
- if vod_status == 0:
- uid_bucket_qs.update(status=vod_status)
- ai_status = '0'
- if uid_set_qs[0].is_ai == 2:
- return response.json(0)
- uid_bucket_qs.update(status=vod_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/'
- uid_tk_url = '{}cloudstorage/getsignsts?uidToken={}'.format(urls, uid_obj.token)
- store_hls_url = '{}cloudstorage/storeplaylist?uidToken={}'.format(urls, uid_obj.token)
- if uid_set_qs[0].is_ai != 2 and CONFIG_INFO != CONFIG_CN:
- if not all([appBundleId, app_type, token_val, uid, m_code, ai_status]):
- return response.json(444, 'appBundleId, app_type, token_val, uid,m_code, ai_status')
- # 如果传空上来,就默认为0
- tz = '0' if tz == '' else tz.replace('GMT', '')
- ai_status = int(ai_status)
- ai_service_qs = AiService.objects.filter(uid=uid, use_status=1)
- if not ai_service_qs.exists():
- return response.json(10053)
- uid_set_id = uid_set_qs[0].id
- interval = uid_set_qs[0].new_detect_interval if not interval else interval
- qs_data = {
- 'updTime': now_time,
- }
- if interval:
- qs_data['detect_interval'] = int(interval)
- qs_data['detect_group'] = detect_group if detect_group else ''
- uid_set_qs.update(**qs_data)
- qs_data['detect_status'] = ai_status # ai开关状态
- qs_data['endTime'] = end_time
- ai_service_qs.update(**qs_data)
- thing_name = CommonService.query_serial_with_uid(uid) # 存在序列号则为使用序列号作为物品名
- topic_name = 'ansjer/generic/{}'.format(thing_name)
- if ai_status == 0: # 关闭
- # mqtt通知设备关闭AI识别功能
- msg = {'commandType': 'AIDisable'}
- req_success = CommonService.req_publish_mqtt_msg(thing_name, topic_name, msg)
- if not req_success:
- return response.json(10044)
- if vod_status == 0:
- return response.json(0)
- return response.json(0, {'uidTkUrl': uid_tk_url, 'storeHlsUrl': store_hls_url})
- elif ai_status == 1: # 开启
- # 更新或创建uid_push数据
- uid_push_qs = UidPushModel.objects.filter(userID_id=user_id, m_code=m_code, uid_set__uid=uid)
- uid_push_data = {
- 'appBundleId': appBundleId,
- 'app_type': app_type,
- 'push_type': push_type,
- 'token_val': token_val,
- 'updTime': now_time,
- 'lang': lang,
- 'tz': tz
- }
- if uid_push_qs.exists():
- uid_push_qs.update(**uid_push_data)
- else:
- uid_push_data['uid_set_id'] = uid_set_id
- uid_push_data['userID_id'] = user_id
- uid_push_data['m_code'] = m_code
- uid_push_data['addTime'] = now_time
- UidPushModel.objects.create(**uid_push_data)
- etkObj = ETkObject(etk='')
- etk = etkObj.encrypt(uid)
- # mqtt通知设备开启AI识别功能
- push_url = DETECT_PUSH_DOMAINS
- # 欧洲域名固定返回欧洲域名
- if domain_name in ['api.zositeche.com', 'api.loocam3.com', 'common.neutral3.com']:
- push_url = 'https://push.zositeche.com/'
- aiIdentificationUrl = '{}AiService/identification'.format(push_url)
- msg = {
- 'commandType': 'AIEnable',
- 'payload': {
- 'etk': etk,
- 'endTime': end_time,
- 'aiIdentificationUrl': aiIdentificationUrl,
- }
- }
- req_success = CommonService.req_publish_mqtt_msg(thing_name, topic_name, msg)
- if not req_success:
- return response.json(10044)
- return response.json(0, {'uidTkUrl': uid_tk_url, 'storeHlsUrl': store_hls_url,
- 'aiIdentificationUrl': aiIdentificationUrl, 'endTime': end_time,
- 'etk': etk})
- return response.json(0, {'uidTkUrl': uid_tk_url, 'storeHlsUrl': store_hls_url})
- except Exception as e:
- return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
- @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",
- 'is_ai', 'icloud_store_meal_id')
- 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']
- # icloud_store_meal_id = store_qs[0]['icloud_store_meal_id']
- # icloud_meal_qs = ICloudStoreMeal.objects.filter(id=icloud_store_meal_id).values('size')
- # if not icloud_meal_qs.exists():
- # return response.json(173)
- # size = icloud_meal_qs[0]['size']
- 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
- unuse_meal_flag = False # 是否关联未使用套餐
- 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: # 已过期或者不相同的套餐加入未使用的关联套餐表
- unuse_meal_flag = True
- 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())
- # 开通AI服务
- if store_qs[0]['is_ai'] and CONFIG_INFO != CONFIG_CN and not unuse_meal_flag:
- ai_service_qs = AiService.objects.filter(uid=uid, channel=channel)
- if ai_service_qs.exists(): # 有正在使用的套餐,套餐结束时间保存为套餐有效期
- ai_service_qs.update(endTime=end_time, use_status=1, updTime=now_time)
- else:
- ai_service_dict = {
- 'uid': uid,
- 'channel': channel,
- 'detect_status': 1,
- 'addTime': now_time,
- 'updTime': now_time,
- 'use_status': 1,
- 'endTime': end_time
- }
- AiService.objects.create(**ai_service_dict)
- # 开通云盘服务
- # icloud_use_qs = IcloudUseDetails.objects.filter(user_id=userid).values('id')
- # if not icloud_use_qs.exists():
- # bucket_qs = VodBucketModel.objects.filter(bucket='icloud').values('id')
- # icloud_use_qs = IcloudUseDetails.objects.create(add_time=now_time, upd_time=now_time,
- # detect_status=1, user_id=userid,
- # bucket_id=bucket_qs[0]['id'])
- # use_details_id = icloud_use_qs.id
- # IcloudService.objects.create(add_time=now_time, upd_time=now_time, type=0,
- # size=1, use_details_id=use_details_id)
- # else:
- # use_details_id = icloud_use_qs[0]['id']
- # IcloudService.objects.create(order_id=order_id, add_time=now_time, upd_time=now_time, type=1,
- # size=size, end_time=end_time, use_details_id=use_details_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 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",
- 'is_ai', 'icloud_store_meal_id')
- 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']
- # icloud_store_meal_id = store_qs[0]['icloud_store_meal_id']
- # icloud_meal_qs = ICloudStoreMeal.objects.filter(id=icloud_store_meal_id).values('size')
- # if not icloud_meal_qs.exists():
- # return response.json(173)
- # size = icloud_meal_qs[0]['size']
- 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
- unuse_meal_flag = False # 是否关联未使用套餐
- 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: # 已过期或者不相同的套餐加入未使用的关联套餐表
- unuse_meal_flag = True
- 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())
- # 开通AI服务
- if store_qs[0]['is_ai'] and CONFIG_INFO != CONFIG_CN and not unuse_meal_flag:
- ai_service_qs = AiService.objects.filter(uid=uid, channel=channel)
- if ai_service_qs.exists(): # 有正在使用的套餐,套餐结束时间保存为套餐有效期
- ai_service_qs.update(endTime=end_time, use_status=1, updTime=now_time)
- else:
- ai_service_dict = {
- 'uid': uid,
- 'channel': channel,
- 'detect_status': 1,
- 'addTime': now_time,
- 'updTime': now_time,
- 'use_status': 1,
- 'endTime': end_time
- }
- AiService.objects.create(**ai_service_dict)
- # 开通云盘服务
- # icloud_use_qs = IcloudUseDetails.objects.filter(user_id=userid).values('id')
- # if not icloud_use_qs.exists():
- # bucket_qs = VodBucketModel.objects.filter(bucket='icloud').values('id')
- # icloud_use_qs = IcloudUseDetails.objects.create(add_time=now_time, upd_time=now_time,
- # detect_status=1, user_id=userid,
- # bucket_id=bucket_qs[0]['id'])
- # use_details_id = icloud_use_qs.id
- # IcloudService.objects.create(add_time=now_time, upd_time=now_time, type=0,
- # size=1, use_details_id=use_details_id)
- # else:
- # use_details_id = icloud_use_qs[0]['id']
- # IcloudService.objects.create(order_id=order_id, add_time=now_time, upd_time=now_time, type=1,
- # size=size, end_time=end_time, use_details_id=use_details_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 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",
- 'is_ai', 'icloud_store_meal_id')
- if not store_qs.exists():
- return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '套餐不存在'}))
- 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']
- # icloud_store_meal_id = store_qs[0]['icloud_store_meal_id']
- # icloud_meal_qs = ICloudStoreMeal.objects.filter(id=icloud_store_meal_id).values('size')
- # if not icloud_meal_qs.exists():
- # return response.json(173)
- # size = icloud_meal_qs[0]['size']
- 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
- unuse_meal_flag = False # 是否关联未使用套餐
- 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: # 已过期或者不相同的套餐加入未使用的关联套餐表
- unuse_meal_flag = True
- 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())
- # 开通AI服务
- if store_qs[0]['is_ai'] and CONFIG_INFO != CONFIG_CN and not unuse_meal_flag:
- ai_service_qs = AiService.objects.filter(uid=uid, channel=channel)
- if ai_service_qs.exists(): # 有正在使用的套餐,套餐结束时间保存为套餐有效期
- ai_service_qs.update(endTime=end_time, use_status=1, updTime=now_time)
- else:
- ai_service_dict = {
- 'uid': uid,
- 'channel': channel,
- 'detect_status': 1,
- 'addTime': now_time,
- 'updTime': now_time,
- 'use_status': 1,
- 'endTime': end_time
- }
- AiService.objects.create(**ai_service_dict)
- # 开通云盘服务
- # icloud_use_qs = IcloudUseDetails.objects.filter(user_id=userid).values('id')
- # if not icloud_use_qs.exists():
- # bucket_qs = VodBucketModel.objects.filter(bucket='icloud').values('id')
- # icloud_use_qs = IcloudUseDetails.objects.create(add_time=now_time, upd_time=now_time,
- # detect_status=1, user_id=userid,
- # bucket_id=bucket_qs[0]['id'])
- # use_details_id = icloud_use_qs.id
- # IcloudService.objects.create(add_time=now_time, upd_time=now_time, type=0,
- # size=1, use_details_id=use_details_id)
- # else:
- # use_details_id = icloud_use_qs[0]['id']
- # IcloudService.objects.create(order_id=order_id, add_time=now_time, upd_time=now_time, type=1,
- # size=size, end_time=end_time, use_details_id=use_details_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 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', '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']
- 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_qs = 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)
- if store_qs[0]['is_ai'] == 1:
- order_qs.order_type = 1
- 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_qs = 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)
- if store_qs[0]['is_ai'] == 1:
- order_qs.order_type = 1
- 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_qs = 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)
- if store_qs[0]['is_ai'] == 1:
- order_qs.order_type = 1
- 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_qs = 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)
- if store_qs[0]['is_ai'] == 1:
- order_qs.order_type = 1
- 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)
- 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())
- order_type = 0
- store_qs = Store_Meal.objects.filter(id=rank, lang__lang=lang, is_show=0).values("day", "bucket_id", 'is_ai',
- "bucket__storeDay", "expire",
- 'lang__content', 'price',
- 'currency', 'commodity_type',
- 'icloud_store_meal_id')
- 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']
- unuse_meal_flag = False # 是否关联未使用套餐
- # icloud_store_meal_id = store_qs[0]['icloud_store_meal_id']
- # icloud_meal_qs = ICloudStoreMeal.objects.filter(id=icloud_store_meal_id).values('size')
- # if not icloud_meal_qs.exists():
- # return response.json(173)
- # size = icloud_meal_qs[0]['size']
- 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: # 已过期或者不相同的套餐加入未使用的关联套餐表
- unuse_meal_flag = True
- 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
- # 开通AI体验
- if store_qs[0]['is_ai'] and CONFIG_INFO != CONFIG_CN and not unuse_meal_flag:
- order_type = 1
- ai_service_qs = AiService.objects.filter(uid=uid, channel=channel)
- if ai_service_qs.exists():
- ai_service_qs.update(endTime=end_time, use_status=1, updTime=now_time)
- else:
- AiService.objects.create(uid=uid, channel=channel, detect_status=1, endTime=end_time,
- addTime=now_time, updTime=now_time, use_status=1)
- # 开通云盘体验
- # icloud_use_qs = IcloudUseDetails.objects.filter(user_id=user_id).values('id')
- # if not icloud_use_qs.exists():
- # bucket_qs = VodBucketModel.objects.filter(bucket='icloud').values('id')
- # icloud_use_qs = IcloudUseDetails.objects.create(add_time=now_time, upd_time=now_time,
- # detect_status=1, user_id=user_id,
- # bucket_id=bucket_qs[0]['id'])
- # use_details_id = icloud_use_qs.id
- # IcloudService.objects.create(add_time=now_time, upd_time=now_time, type=0,
- # size=1, use_details_id=use_details_id)
- # else:
- # use_details_id = icloud_use_qs[0]['id']
- # IcloudService.objects.create(order_id=order_id, add_time=now_time, upd_time=now_time, type=1,
- # size=size, end_time=end_time, use_details_id=use_details_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,
- 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()
- AiService.objects.filter(uid=uid_bucket_qs[0].uid).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() # 删除播放列表,后期数据量多时应该考虑延后删除
- AiService.objects.filter(uid=uid, channel=unused_uid_bucket['channel']).update(endTime=end_time,
- updTime=now_time,
- use_status=1)
- 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, '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)
- 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'] != '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, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
|