CloudStorage.py 136 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import base64
  4. import datetime
  5. import json
  6. import logging
  7. import sys
  8. import threading
  9. import time
  10. import ssl
  11. from decimal import Decimal
  12. from itertools import groupby
  13. from operator import itemgetter
  14. from packaging import version
  15. from urllib.parse import quote, parse_qs, unquote
  16. from aliyunsdkcore import client
  17. from aliyunsdkcore.request import CommonRequest
  18. import boto3
  19. import jwt
  20. import paypalrestsdk
  21. from django.db import transaction
  22. from django.db.models import Q, F
  23. from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
  24. from django.views.generic.base import View
  25. from Controller.UserDevice.DeviceVersionInfoController import DeviceVersionInfoView
  26. from Object.AliOssUtil import AliOssUtil
  27. from AdminController.CloudServiceManage.AgentOrderController import AgentOrderView
  28. from Ansjer.config import SERVER_DOMAIN, PAYPAL_CRD, SERVER_DOMAIN_SSL, \
  29. AWS_ARN, OAUTH_ACCESS_TOKEN_SECRET, DETECT_PUSH_DOMAINS, CONFIG_INFO, CONFIG_CN, BINOCULAR_DEVICE_TYPE, CONFIG_US, \
  30. CONFIG_TEST, CONFIG_EUR, OSS_ROLE_ARN
  31. from Controller.CheckUserData import DataValid
  32. from Controller.CloudPhoto.CloudServiceController import CloudServiceController
  33. from Controller.PaymentCycle import Paypal
  34. from Controller.UserDevice.DeviceVersionInfoController import DeviceVersionInfoView
  35. from Model.models import Device_Info, Order_Model, Store_Meal, VodHlsModel, UID_Bucket, StsCrdModel, \
  36. ExperienceContextModel, Pay_Type, CDKcontextModel, Device_User, SysMsgModel, Unused_Uid_Meal, PromotionRuleModel, \
  37. VideoPlaybackTimeModel, CouponModel, VodBucketModel, VodHlsSummary, VodHlsTagType, UidSetModel, AiService, \
  38. StsFrequency, InAppPurchasePackage, CouponCombo, CouponConfigModel, DeviceApplePackage
  39. from Object.AWS.AmazonS3Util import AmazonS3Util
  40. from Object.AWS.S3Email import S3Email
  41. from Object.AliPayObject import AliPayObject
  42. from Object.AliSmsObject import AliSmsObject
  43. from Object.AppleInAppPurchaseSubscriptionObject import InAppPurchase
  44. from Object.Enums.RedisKeyConstant import RedisKeyConstant
  45. from Object.RedisObject import RedisObject
  46. from Object.ResponseObject import ResponseObject
  47. from Object.TokenObject import TokenObject
  48. from Object.UidTokenObject import UidTokenObject
  49. from Object.WechatPayObject import WechatPayObject
  50. from Object.m3u8generate import PlaylistGenerator
  51. from Service.CommonService import CommonService
  52. from Service.PayService import PaymentService
  53. from Service.VodHlsOssService import SplitVodHlsOssObject
  54. from Service.VodHlsService import SplitVodHlsObject
  55. from django.conf import settings
  56. ALICLOUD_AK = settings.ALICLOUD_AK
  57. ALICLOUD_SK = settings.ALICLOUD_SK
  58. ssl._create_default_https_context = ssl._create_unverified_context
  59. LOGGER = logging.getLogger('info')
  60. from django.conf import settings
  61. AWS_ACCESS_KEY_ID = settings.AWS_ACCESS_KEY_ID
  62. AWS_SECRET_ACCESS_KEY = settings.AWS_SECRET_ACCESS_KEY
  63. # 设备信息添加
  64. class CloudStorageView(View):
  65. def get(self, request, *args, **kwargs):
  66. request.encoding = 'utf-8'
  67. operation = kwargs.get('operation')
  68. return self.validation(request.GET, request, operation)
  69. def post(self, request, *args, **kwargs):
  70. request.encoding = 'utf-8'
  71. operation = kwargs.get('operation')
  72. return self.validation(request.POST, request, operation)
  73. def validation(self, request_dict, request, operation):
  74. lang = request_dict.get('lang', 'en')
  75. response = ResponseObject(lang)
  76. if operation is None:
  77. return response.json(444, 'error path')
  78. elif operation == 'dopaypalcallback': # paypal支付回调
  79. return self.do_pay_by_paypal_callback(request_dict, response)
  80. elif operation == 'doalicallback': # 阿里支付回调
  81. return self.do_pay_by_ali_callback(request_dict, response)
  82. elif operation == 'dowechatnotify': # 微信支付回调
  83. return self.do_pay_by_wechat_callback(request, response)
  84. elif operation == 'getsignsts': # 设备调用,获取sts令牌
  85. ip = CommonService.get_ip_address(request)
  86. return self.do_get_sign_sts(request_dict, ip, response)
  87. elif operation == 'getsignstsoss': # 设备调用,获取sts令牌
  88. ip = CommonService.get_ip_address(request)
  89. return self.do_get_sign_sts_oss(request_dict, ip, response)
  90. elif operation == 'storeplaylist': # 设备调用,设备把视频上传到s3,同时把视频数据信息传给服务器,服务器存储播放内容
  91. return self.do_store_playlist(request_dict, response)
  92. elif operation == 'signplaym3u8': # 根据sts播放m3u8 视频流
  93. return self.do_sign_play_m3u8(request_dict, response)
  94. elif operation == 'payOK': # 支付成功
  95. return self.do_pay_ok(request_dict)
  96. elif operation == 'vodMsgEnd': # 云存到期续费提醒 提前1天
  97. return self.do_vod_msg_end(response)
  98. elif operation == 'doRefund': # 退款
  99. return self.do_refund(request_dict, response)
  100. else:
  101. token = request_dict.get('token', None)
  102. # 设备主键uid
  103. tko = TokenObject(token)
  104. if tko.code != 0:
  105. return response.json(tko.code)
  106. user_id = tko.userID
  107. if operation == 'createpayorder': # 创建支付订单
  108. ip = CommonService.get_ip_address(request)
  109. return self.do_create_pay_order(request_dict, user_id, ip, response)
  110. elif operation == 'changevodstatus': # 修改云存状态,传送两个url,即getsignsts接口和storeplaylist接口
  111. return self.do_change_vod_status(request_dict, user_id, response)
  112. elif operation == 'queryvodlist': # 获取视频播放列表
  113. return self.do_query_vod_list(request_dict, user_id, response)
  114. elif operation == 'commoditylist': # 查询套餐列表
  115. return self.do_commodity_list(request_dict, user_id, response)
  116. elif operation == 'queryorder': # 查询订单列表
  117. return self.do_query_order(request_dict, user_id, response)
  118. elif operation == 'experienceorder': # 生成体验订单
  119. return self.do_experience_order(request_dict, user_id, response)
  120. elif operation == 'experiencereset': # 重置设备云存体验
  121. return self.do_experience_reset(request_dict, response)
  122. elif operation == 'deletevodlist': # 删除播放列表
  123. return self.delete_vod_list(request_dict, user_id, response)
  124. elif operation == 'devicecommodity': # 设备关联套餐列表
  125. return self.device_commodity(request_dict, user_id, response)
  126. elif operation == 'switchdevicecommodity': # 提前使用设备关联套餐
  127. return self.switch_device_commodity(request_dict, user_id, response)
  128. elif operation == 'hasvod': # APP的回放界面,日历表显示当天有无录像
  129. return self.has_vod(request_dict, user_id, response)
  130. elif operation == 'videoPlaybackTime': # 记录app播放时间
  131. return self.video_playback_time(request_dict, user_id, response)
  132. else:
  133. return response.json(414)
  134. @staticmethod
  135. def do_query_order(request_dict, user_id, response): # 查询订单列表
  136. """
  137. 查询订单列表
  138. @param request_dict: 请求数据
  139. @request_dict status: uid
  140. @request_dict page: 通道
  141. @request_dict line: 支付类型
  142. @request_dict uid: 套餐id
  143. @param user_id: 用户id
  144. @param response: 响应
  145. @return: response
  146. """
  147. status = request_dict.get('status', None)
  148. page = request_dict.get('page', None)
  149. line = request_dict.get('line', None)
  150. uid = request_dict.get('uid', None)
  151. if not all([page, line]):
  152. return response.json(444)
  153. page = int(page)
  154. line = int(line)
  155. order_qs = Order_Model.objects.filter(userID_id=user_id)
  156. if status:
  157. order_qs = order_qs.filter(status=status)
  158. # 筛选指定设备id的订单
  159. if uid:
  160. order_qs = order_qs.filter(UID=uid)
  161. if not order_qs.exists():
  162. return response.json(173)
  163. count = order_qs.count()
  164. order_list = order_qs.values(
  165. "orderID", "UID", "channel", "desc", "price", "currency", "addTime", "updTime", "pay_url",
  166. "payType", "status", "commodity_type", "commodity_code")[(page - 1) * line:page * line]
  167. data = []
  168. now_time = int(time.time())
  169. for order in order_list:
  170. if order['status'] == 0:
  171. if order['addTime'] + 3600 < now_time:
  172. order['status'] = 3
  173. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=order['UID']).values('id', 'Type')
  174. order['did'] = device_info_qs[0]['id'] if device_info_qs.exists() else ''
  175. order['Type'] = device_info_qs[0]['Type'] if device_info_qs.exists() else ''
  176. data.append(order)
  177. return response.json(0, {'data': data, 'count': count})
  178. def do_commodity_list(self, request_dict, user_id, response): # 查询套餐列表
  179. """
  180. 查询云存套餐列表
  181. @param user_id: 用户id
  182. @param request_dict: 请求数据
  183. @request_dict mold: 存储区域类型
  184. @request_dict uid: uid
  185. @request_dict lang: 语言
  186. @param response: 响应
  187. @return: response
  188. """
  189. mold = request_dict.get('mold', None)
  190. uid = request_dict.get('uid', None)
  191. lang = request_dict.get('lang', 'en')
  192. is_ai = request_dict.get('is_ai', 0)
  193. app_type = request_dict.get('app_type', None)
  194. ios_version = request_dict.get('ios_version', "")
  195. app_bundle_id = request_dict.get('app_bundle_id', None)
  196. if not all([uid]):
  197. return response.json(444)
  198. # 苹果内购,app_type:1 或 app_type:2
  199. is_ios = False
  200. if app_type is not None:
  201. if int(app_type) == 1 or int(app_type) == 2:
  202. is_ios = True
  203. is_ai = int(is_ai)
  204. now_time = int(time.time())
  205. # DVR/NVR设备暂不返回云存套餐列表
  206. device_info_qs = Device_Info.objects.filter(Q(UID=uid), Q(Type__lte=4) | Q(Type=10001))
  207. if device_info_qs.exists():
  208. return response.json(0)
  209. try:
  210. # 查询设备像素
  211. uid_set_qs = UidSetModel.objects.filter(uid=uid).values('ucode', 'is_ai', 'mobile_4g', 'version')
  212. if not uid_set_qs.exists():
  213. return response.json(173)
  214. ucode = uid_set_qs[0]['ucode']
  215. dpi_flag = 0
  216. if ucode:
  217. if ucode[-5] == 'A':
  218. dpi_flag = 10
  219. else:
  220. dpi_flag = int(ucode[-5])
  221. pixel_level = 1 if ucode and dpi_flag >= 8 else 0
  222. # 查询是否为4G设备
  223. is_4g = 0
  224. vod_location = 0
  225. ver = uid_set_qs[0]['version']
  226. if ver:
  227. ver = ver.replace('V', '')
  228. d_ver = DeviceVersionInfoView.cache_device_version_info(ucode, ver)
  229. if d_ver:
  230. has_4g_cloud = d_ver['has_4g_cloud']
  231. if has_4g_cloud == 0:
  232. LOGGER.info('4G不支持云存设备:{}'.format(uid))
  233. return response.json(0)
  234. is_4g = 1 if d_ver['has_4g_cloud'] == 1 else 0
  235. vod_location = d_ver['vod_location']
  236. # 国外服不切换云存位置
  237. if CONFIG_INFO == CONFIG_US or CONFIG_INFO == CONFIG_EUR:
  238. vod_location = 0
  239. # 过滤激活码、隐藏套餐
  240. store_qs = Store_Meal.objects.filter(
  241. Q(lang__lang=lang), Q(is_show=0), ~Q(pay_type='11'), Q(bucket__vod_location=vod_location))
  242. experience_context_qs = ExperienceContextModel.objects.filter(uid=uid, experience_type=0)
  243. ios_meal = None
  244. if mold:
  245. store_qs = store_qs.filter(bucket__mold=mold)
  246. if uid in ['5Z1LZLK7D5Y6WKDE111A', '7ZB7V8B5LA48K1MC111A', '4XES12WGN9D9KLEJ111A']:
  247. ios_meal = store_qs # 提审测试UID
  248. # 没体验过的设备只返回体验套餐,体验过的不返回体验套餐
  249. if experience_context_qs.exists() or is_4g == 1:
  250. if not is_ai: # 返回云存套餐
  251. store_qs = store_qs.filter(~Q(pay_type='10'), Q(is_ai=0)) # 筛选像素等级
  252. else: # 返回云存+AI套餐
  253. is_ai = uid_set_qs[0]['is_ai']
  254. is_ai = 1 if is_ai != 2 and CONFIG_INFO != CONFIG_CN else 0 # 国内不支持AI服务
  255. if not is_ai:
  256. return response.json(0)
  257. store_qs = store_qs.filter(~Q(pay_type='10'), Q(is_ai=1)) # 筛选像素等级
  258. if CONFIG_INFO != CONFIG_CN: # 国内生产环境不筛选像素 加载所有上架套餐
  259. store_qs = store_qs.filter(Q(pixel_level=pixel_level))
  260. elif CONFIG_INFO == CONFIG_CN and is_4g == 1:
  261. store_qs = store_qs.filter(Q(pixel_level=pixel_level))
  262. # 根据是否支持4g过滤设备
  263. store_qs = store_qs.filter(is_4g=is_4g)
  264. # 判断是否支持内购周期付款
  265. if is_ios and version.parse(ios_version) >= version.parse("15.0"):
  266. store_qs = store_qs.filter(pay_type=5, app_type=app_type)
  267. elif is_ios and version.parse(ios_version) < version.parse("15.0"):
  268. store_qs = store_qs.filter(pay_type=5, commodity_type=0, app_type=app_type)
  269. else:
  270. store_qs = store_qs.exclude(pay_type=5)
  271. if uid not in ["VXJ267WU5NZ1S89H111A", "18SM4J9DYWB2AEG1111A",
  272. "517J385BNUGP3CPP111A", "5Z1LZLK7D5Y6WKDE111A"] and CONFIG_INFO == CONFIG_TEST:
  273. store_qs = store_qs.exclude(id__in=[88, 102])
  274. elif uid not in ["VXJ267WU5NZ1S89H111A", "18SM4J9DYWB2AEG1111A",
  275. "517J385BNUGP3CPP111A", "5Z1LZLK7D5Y6WKDE111A"] and CONFIG_INFO == CONFIG_US:
  276. store_qs = store_qs.exclude(id__in=[34, 43])
  277. elif uid not in ["VXJ267WU5NZ1S89H111A", "18SM4J9DYWB2AEG1111A",
  278. "517J385BNUGP3CPP111A", "5Z1LZLK7D5Y6WKDE111A"] and CONFIG_INFO == CONFIG_EUR:
  279. store_qs = store_qs.exclude(id__in=[34, 43])
  280. else:
  281. is_ai = uid_set_qs[0]['is_ai']
  282. is_ai = 1 if is_ai != 2 and CONFIG_INFO != CONFIG_CN else 0 # 国内不支持AI服务
  283. store_qs = store_qs.filter(pay_type='10') # 体验套餐不区分像素等级
  284. if ios_meal: # 所有IOS提审要用
  285. store_qs = ios_meal.filter(app_type=app_type)
  286. store_qs = store_qs.annotate(title=F('lang__title'), content=F('lang__content'),
  287. new_title=F('lang__new_title'), discount_content=F('lang__discount_content'))
  288. store_qs = store_qs.order_by('sort').values("id", "title", "content", "price", "day", "currency",
  289. "bucket__storeDay", "new_title",
  290. "bucket__bucket", "bucket__area", "commodity_code",
  291. "commodity_type", "is_discounts", "virtual_price", "expire",
  292. "discount_price", "discount_content", "symbol",
  293. "cycle_config_id")
  294. if not store_qs.exists():
  295. return response.json(0)
  296. store_list = list(store_qs)
  297. store_list.sort(key=itemgetter('bucket__area'))
  298. res = []
  299. coupon_conf_ids = CloudServiceController.get_user_coupon_list(user_id)
  300. for area, items in groupby(store_list, key=itemgetter('bucket__area')):
  301. items_list = list(items)
  302. for i in range(len(items_list) - 1, -1, -1):
  303. item = items_list[i]
  304. # 判断是否支持微信支付
  305. pay_type_qs = Pay_Type.objects.filter(store_meal=item['id']).values("id", "payment")
  306. if app_bundle_id in ["com.cloudlife.commissionf_a", "com.cloudlife.commissionf"]:
  307. pay_type_qs = pay_type_qs.exclude(id=3)
  308. item['pay_type'] = list(pay_type_qs)
  309. # 没有支付类型则跳过这个套餐
  310. if not item['pay_type']:
  311. continue
  312. item['is_pay_cycle'] = 1 if item['cycle_config_id'] else 0
  313. del item['cycle_config_id']
  314. # 检查优惠券是否可用,并赋值给 item['isCoupon']
  315. if coupon_conf_ids:
  316. item['isCoupon'] = CloudStorageView.check_user_coupon_is_available(coupon_conf_ids, item['id'])
  317. else:
  318. item['isCoupon'] = False
  319. for each in item['pay_type']:
  320. if each['id'] == 10 and CONFIG_INFO != CONFIG_CN:
  321. if is_ai == 0:
  322. item['content'] = item['new_title'].get('1', '')
  323. elif is_ai == 1:
  324. item['content'] = item['new_title'].get('2', '')
  325. if is_ios:
  326. if item['isCoupon']:
  327. item['isCoupon'] = False
  328. else:
  329. # 在列表删除这个套餐
  330. if self.check_combo_is_coupon(item['id']) and ios_meal is None:
  331. items_list.remove(item)
  332. res_c = {'area': area, 'items': items_list}
  333. res.append(res_c)
  334. # 是否促销
  335. promotion_rule_qs = PromotionRuleModel.objects.filter(status=1, startTime__lte=now_time,
  336. endTime__gte=now_time).values('id', 'ruleConfig',
  337. 'ruleName',
  338. 'startTime', 'endTime',
  339. 'ruleDesc')
  340. if promotion_rule_qs.exists():
  341. promotion = {
  342. 'is_promotion': 1,
  343. 'promotionStartTime': promotion_rule_qs[0]['startTime'],
  344. 'promotionEndTime': promotion_rule_qs[0]['endTime'],
  345. 'promotionName': json.loads(promotion_rule_qs[0]['ruleName']).get(lang, ''),
  346. 'promotionDesc': json.loads(promotion_rule_qs[0]['ruleDesc']).get(lang, ''),
  347. 'nowTime': now_time
  348. }
  349. else:
  350. promotion = {
  351. 'is_promotion': 0
  352. }
  353. result = {
  354. 'meals': res,
  355. 'extra':
  356. {
  357. 'cloud_banner': SERVER_DOMAIN + 'web/images/cloud_cn_banner.png',
  358. 'cloud_en_baner': SERVER_DOMAIN_SSL + 'web/images/cloud_en_banner.png'
  359. },
  360. 'promotion': promotion,
  361. }
  362. # 保存访问次数到redis中
  363. redis_obj = RedisObject()
  364. today = datetime.datetime.now().strftime("%Y-%m-%d")
  365. redis_key = RedisKeyConstant.TODAY_CLOUD_QUERY_NUMBER.value
  366. redis_obj.hash_field_increment(redis_key, today, 1)
  367. return response.json(0, result)
  368. except Exception as e:
  369. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  370. @staticmethod
  371. def check_user_coupon_is_available(coupon_conf_ids, combo_id):
  372. """
  373. 查看用户优惠券是否可用
  374. @param coupon_conf_ids: 优惠券配置ids列表
  375. @param combo_id: 套餐id
  376. @return:
  377. """
  378. result = False
  379. for conf_id in coupon_conf_ids:
  380. if result:
  381. break
  382. combo_list = CloudServiceController.get_combo_list(0, conf_id)
  383. if not combo_list:
  384. continue
  385. if combo_id in combo_list:
  386. result = True
  387. return result
  388. @staticmethod
  389. def check_combo_is_coupon(combo_id):
  390. """
  391. 确认套餐是否有优惠信息
  392. """
  393. try:
  394. key_coupon = RedisKeyConstant.PACKAGE_IS_COUPON_TRUE.value
  395. key_not_coupon = RedisKeyConstant.PACKAGE_IS_COUPON_FALSE.value
  396. redis_obj = RedisObject()
  397. # 获取缓存数据列表,有优惠和无优惠
  398. coupon_data = redis_obj.lrange(key_coupon, 0, -1)
  399. not_coupon = redis_obj.lrange(key_not_coupon, 0, -1)
  400. if combo_id in coupon_data:
  401. return True
  402. elif combo_id in not_coupon:
  403. return False
  404. else:
  405. # 如果没有缓存数据,执行数据库查询
  406. coupon_combo_ids = CouponCombo.objects.filter(combo_id=combo_id).values_list("coupon_id", flat=True)
  407. coupon_config_qs = CouponConfigModel.objects.filter(id__in=coupon_combo_ids)
  408. # 如果有优惠券配置,将套餐id添加到缓存中,并返回True
  409. if coupon_config_qs.exists():
  410. redis_obj.rpush(key_coupon, combo_id)
  411. return True
  412. redis_obj.rpush(key_not_coupon, combo_id)
  413. return False
  414. except Exception as e:
  415. # 如果没有缓存数据,执行数据库查询
  416. coupon_combo_ids = CouponCombo.objects.filter(combo_id=combo_id).values_list("coupon_id", flat=True)
  417. coupon_config_qs = CouponConfigModel.objects.filter(id__in=coupon_combo_ids)
  418. if coupon_config_qs.exists():
  419. return True
  420. LOGGER.info('error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  421. return False
  422. @staticmethod
  423. def do_sign_play_m3u8(request_dict, response):
  424. """
  425. 获取m3u8视频流
  426. @param request_dict: 请求数据
  427. @request_dict uid: uid_token
  428. @request_dict channel: 通道
  429. @request_dict time: 播放列表名字时间戳
  430. @param response: 响应
  431. @return: response
  432. """
  433. uid_token = request_dict.get('uid', None)
  434. channel = request_dict.get('channel', None)
  435. start_time = request_dict.get('time', None)
  436. if not all([uid_token, channel, start_time]):
  437. return response.json(444)
  438. uid = jwt.decode(uid_token, OAUTH_ACCESS_TOKEN_SECRET, algorithms='HS256').get('uid', '')
  439. now_time = int(time.time())
  440. split_vod_hls_obj = SplitVodHlsObject()
  441. vod_hls_qs = split_vod_hls_obj.get_vod_hls_data(
  442. uid=uid, channel=channel, start_time=start_time, end_time__gte=now_time).\
  443. values("sec", "fg", "bucket_id", 'start_time')
  444. if not vod_hls_qs.exists():
  445. # 查询OSS
  446. split_vod_hls_obj = SplitVodHlsOssObject()
  447. vod_hls_qs = split_vod_hls_obj.get_vod_hls_data(
  448. uid=uid, channel=channel, start_time=start_time, end_time__gte=now_time). \
  449. values("sec", "fg", "bucket_id", 'start_time')
  450. if not vod_hls_qs.exists():
  451. return response.json(173)
  452. bucket_id = vod_hls_qs[0]['bucket_id']
  453. vod_bucket_qs = VodBucketModel.objects.filter(id=bucket_id).values('bucket', 'region', 'mold', 'vod_location')
  454. if not vod_bucket_qs.exists():
  455. return response.json(173)
  456. fg = int(vod_hls_qs[0]['fg'])
  457. bucket_region = vod_bucket_qs[0]['region']
  458. bucket_name = vod_bucket_qs[0]['bucket']
  459. vod_location = vod_bucket_qs[0]['vod_location']
  460. playlist_entries = []
  461. # AWS S3
  462. if vod_location == 0:
  463. mold = vod_bucket_qs[0]["mold"]
  464. s3_obj = AmazonS3Util(
  465. AWS_ACCESS_KEY_ID[mold],
  466. AWS_SECRET_ACCESS_KEY[mold],
  467. bucket_region
  468. )
  469. # ts_count = fg & 0xf
  470. # fg 64位整型,低四位代表ts文件总数,然后进行位运算,一次移四位,每四位转为十进制即为当前ts文件的秒数
  471. for i in range(15):
  472. shift = (i + 1) * 4
  473. duration = (fg >> shift) & 0xf
  474. if duration > 0:
  475. ts_file = '{uid}/vod{channel}/{time}/ts{i}.ts'.format(uid=uid, channel=channel, time=start_time, i=i)
  476. response_url = s3_obj.generate_file_obj_url(bucket_name, ts_file)
  477. playlist_entries.append({
  478. 'name': response_url,
  479. 'duration': duration,
  480. })
  481. # 阿里云OSS
  482. else:
  483. # 初始化阿里云OSS工具类
  484. oss_obj = AliOssUtil(
  485. ALICLOUD_AK,
  486. ALICLOUD_SK,
  487. f'https://oss-{bucket_region}.aliyuncs.com' # 构建OSS endpoint
  488. )
  489. for i in range(15):
  490. shift = (i + 1) * 4
  491. duration = (fg >> shift) & 0xf
  492. if duration > 0:
  493. ts_file = '{uid}/vod{channel}/{time}/ts{i}.ts'.format(uid=uid, channel=channel, time=start_time, i=i)
  494. response_url = oss_obj.generate_file_obj_url(bucket_name, ts_file)
  495. playlist_entries.append({
  496. 'name': response_url,
  497. 'duration': duration,
  498. })
  499. playlist = PlaylistGenerator(playlist_entries).generate()
  500. response = HttpResponse(playlist)
  501. response['Content-Type'] = 'application/octet-stream'
  502. response['Content-Disposition'] = 'attachment;filename="play.m3u8"'
  503. return response
  504. @staticmethod
  505. def do_get_sign_sts(request_dict, ip, response):
  506. """
  507. 获取sts令牌
  508. @param request_dict: 请求数据
  509. @param ip: ip地址
  510. @request_dict uidToken: uid_token
  511. @param response: 响应
  512. @return: response
  513. """
  514. uid_token = request_dict.get('uidToken', None)
  515. uid_obj = UidTokenObject(uid_token)
  516. if uid_obj.flag is False:
  517. return response.json(444, 'uidToken')
  518. uid = uid_obj.UID
  519. channel = uid_obj.channel
  520. now_time = int(time.time())
  521. try:
  522. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel).values(
  523. "bucket__mold",
  524. "bucket__bucket",
  525. "bucket__endpoint",
  526. "bucket__region",
  527. "bucket__vod_location",
  528. "endTime").order_by(
  529. 'addTime')
  530. if not uid_bucket_qs.exists():
  531. res = {'code': 405, 'msg': 'Not purchased or expired!'}
  532. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  533. # 统计sts请求次数,一小时超过20次进行报警
  534. redis_obj = RedisObject()
  535. key = 'sts_count_{}'.format(uid)
  536. sts_count = redis_obj.get_data(key)
  537. if sts_count:
  538. sts_count = int(sts_count)
  539. if sts_count % 20 == 0:
  540. sts_frequency_qs = StsFrequency.objects.filter(uid=uid)
  541. if sts_frequency_qs.exists():
  542. sts_frequency_qs[0].frequency += 1
  543. sts_frequency_qs[0].updateTime = now_time
  544. sts_frequency_qs[0].save()
  545. else:
  546. StsFrequency.objects.create(uid=uid, frequency=1, addTime=now_time, updateTime=now_time)
  547. sts_count += 1
  548. ttl = redis_obj.get_ttl(key)
  549. else:
  550. sts_count = 1
  551. ttl = 3600
  552. redis_obj.set_data(key, sts_count)
  553. redis_obj.set_expire(key, ttl)
  554. # 从sts缓存表读取数据
  555. sts_crd_qs = StsCrdModel.objects.filter(uid=uid, channel=channel).values("addTime", "data")
  556. if sts_crd_qs.exists():
  557. end_time = int(sts_crd_qs[0]["addTime"]) + 3000
  558. if end_time > now_time:
  559. res = json.loads(sts_crd_qs[0]["data"])
  560. return JsonResponse(status=200, data=res)
  561. storage = '{uid}/vod{channel}/'.format(uid=uid, channel=channel)
  562. bucket_name = uid_bucket_qs[0]['bucket__bucket']
  563. endpoint = uid_bucket_qs[0]['bucket__endpoint']
  564. region_id = uid_bucket_qs[0]['bucket__region']
  565. end_time = uid_bucket_qs[0]['endTime']
  566. bucket_mold = uid_bucket_qs[0]['bucket__mold']
  567. vod_location = uid_bucket_qs[0]['bucket__vod_location']
  568. # AWS S3
  569. if vod_location == 0:
  570. try:
  571. aws_access_key_id = AWS_ACCESS_KEY_ID[uid_bucket_qs[0]["bucket__mold"]]
  572. aws_secret_access_key = AWS_SECRET_ACCESS_KEY[uid_bucket_qs[0]["bucket__mold"]]
  573. aws_arn = AWS_ARN[uid_bucket_qs[0]["bucket__mold"]]
  574. except:
  575. res = {'code': 404, 'msg': 'mold not exists!'}
  576. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  577. boto3_sts = boto3.client(
  578. 'sts',
  579. aws_access_key_id=aws_access_key_id,
  580. aws_secret_access_key=aws_secret_access_key,
  581. region_name=region_id
  582. )
  583. policy = {
  584. "Version": "2012-10-17",
  585. "Statement": [
  586. {
  587. "Effect": "Allow",
  588. "Action": "s3:*",
  589. "Resource": ["{aws_arn}:::{bucket_name}/{uid_channel}*".
  590. format(aws_arn=aws_arn, bucket_name=bucket_name, uid_channel=storage)]
  591. }
  592. ]
  593. }
  594. response = boto3_sts.get_federation_token(
  595. Name='{role_name}'.format(role_name=uid + '_' + str(channel)),
  596. Policy=json.dumps(policy),
  597. DurationSeconds=7200
  598. )
  599. res = {
  600. 'AccessKeyId': response['Credentials']['AccessKeyId'],
  601. 'AccessKeySecret': response['Credentials']['SecretAccessKey'],
  602. 'SessionToken': response['Credentials']['SessionToken'],
  603. 'Expiration': response['Credentials']['Expiration'],
  604. 'expire': 900,
  605. 'endpoint': endpoint,
  606. 'bucket_name': bucket_name,
  607. 'arn': response['FederatedUser']['Arn'],
  608. 'code': 0,
  609. 'storage': storage,
  610. 'endTime': end_time,
  611. 'ip': ip,
  612. 'region': region_id,
  613. 'bucket_mold': bucket_mold
  614. }
  615. # 阿里云OSS
  616. else:
  617. # 创建 AcsClient 实例
  618. clt = client.AcsClient(ALICLOUD_AK, ALICLOUD_SK, region_id)
  619. # 创建 CommonRequest 请求
  620. request = CommonRequest(product="Sts", version='2015-04-01', action_name='AssumeRole')
  621. request.set_method('POST')
  622. request.set_protocol_type('https')
  623. request.add_query_param('RoleArn', OSS_ROLE_ARN)
  624. request.add_query_param('RoleSessionName', '{role_name}'.format(role_name=uid + '_' + str(channel)))
  625. request.add_query_param('DurationSeconds', '3600') # 修改为1小时(3600秒),符合阿里云STS的限制
  626. request.set_accept_format('JSON')
  627. # 设置权限策略
  628. resource_access = "acs:oss:*:*:{}/*".format(bucket_name)
  629. policy = {
  630. "Version": "1",
  631. "Statement": [
  632. {
  633. "Effect": "Allow",
  634. "Action": ["oss:*"], # 可以根据需要限制操作权限
  635. "Resource": [resource_access]
  636. }
  637. ]
  638. }
  639. request.add_query_param('Policy', json.dumps(policy))
  640. # 发送请求,获取响应
  641. body = clt.do_action_with_exception(request)
  642. token = json.loads(body.decode('utf-8'))
  643. # 构建返回结果
  644. res = {
  645. 'AccessKeyId': token['Credentials']['AccessKeyId'],
  646. 'AccessKeySecret': token['Credentials']['AccessKeySecret'],
  647. 'SessionToken': token['Credentials']['SecurityToken'],
  648. 'Expiration': token['Credentials']['Expiration'],
  649. 'expire': 3600,
  650. 'endpoint': endpoint,
  651. 'bucket_name': bucket_name,
  652. 'arn': token['AssumedRoleUser']['Arn'],
  653. 'code': 0,
  654. 'storage': storage,
  655. 'endTime': end_time,
  656. 'ip': ip,
  657. 'region': region_id,
  658. 'bucket_mold': bucket_mold
  659. }
  660. # sts缓存表更新或创建数据
  661. if sts_crd_qs.exists():
  662. sts_crd_qs.update(data=json.dumps(res, default=str), addTime=now_time)
  663. else:
  664. StsCrdModel.objects.create(
  665. uid=uid, channel=channel, data=json.dumps(res, default=str), addTime=now_time, type=1)
  666. return JsonResponse(status=200, data=res)
  667. except Exception as e:
  668. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  669. @staticmethod
  670. def do_get_sign_sts_oss(request_dict, ip, response):
  671. """
  672. 获取 阿里云 oss sts令牌
  673. @param request_dict: 请求数据
  674. @param ip: ip地址
  675. @request_dict uidToken: uid_token
  676. @param response: 响应
  677. @return: response
  678. """
  679. uid = request_dict.get('uid', None)
  680. channel = request_dict.get('channel', None)
  681. if not all([uid, channel]):
  682. return response.json(444)
  683. try:
  684. # 阿里云 oss sts
  685. storage = '{uid}/vod{channel}/'.format(uid=uid, channel=channel)
  686. bucket_name = 'asj-test-1' # 存储桶名称
  687. endpoint = 'oss-cn-shenzhen.aliyuncs.com' # OSS endpoint
  688. region_id = 'cn-shenzhen' # 地域ID
  689. # 创建 AcsClient 实例
  690. clt = client.AcsClient(ALICLOUD_AK, ALICLOUD_SK, region_id)
  691. # 创建 CommonRequest 请求
  692. request = CommonRequest(product="Sts", version='2015-04-01', action_name='AssumeRole')
  693. request.set_method('POST')
  694. request.set_protocol_type('https')
  695. request.add_query_param('RoleArn', OSS_ROLE_ARN)
  696. request.add_query_param('RoleSessionName', '{role_name}'.format(role_name=uid + '_' + str(channel)))
  697. request.add_query_param('DurationSeconds', '3600') # 修改为1小时(3600秒),符合阿里云STS的限制
  698. request.set_accept_format('JSON')
  699. # 设置权限策略
  700. resource_access = "acs:oss:*:*:{}/*".format(bucket_name)
  701. policy = {
  702. "Version": "1",
  703. "Statement": [
  704. {
  705. "Effect": "Allow",
  706. "Action": ["oss:*"], # 可以根据需要限制操作权限
  707. "Resource": [resource_access]
  708. }
  709. ]
  710. }
  711. request.add_query_param('Policy', json.dumps(policy))
  712. # 发送请求,获取响应
  713. try:
  714. body = clt.do_action_with_exception(request)
  715. token = json.loads(body.decode('utf-8'))
  716. # 构建返回结果
  717. res = {
  718. 'AccessKeyId': token['Credentials']['AccessKeyId'],
  719. 'AccessKeySecret': token['Credentials']['AccessKeySecret'],
  720. 'SessionToken': token['Credentials']['SecurityToken'],
  721. 'Expiration': token['Credentials']['Expiration'],
  722. 'expire': 3600,
  723. 'endpoint': endpoint,
  724. 'bucket_name': bucket_name,
  725. 'arn': token['AssumedRoleUser']['Arn'],
  726. 'code': 0,
  727. 'storage': storage,
  728. 'endTime': 9999999999,
  729. 'ip': ip,
  730. 'region': region_id,
  731. 'bucket_mold': 0
  732. }
  733. except Exception as e:
  734. # 捕获所有异常并返回自定义错误信息
  735. return response.json(
  736. 500,
  737. 'Internal error!',
  738. 'STS服务异常: {}'.format(str(e)),
  739. 500
  740. )
  741. return JsonResponse(status=200, data=res)
  742. except Exception as e:
  743. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  744. @classmethod
  745. def do_query_vod_list(cls, request_dict, user_id, response):
  746. """
  747. 获取视频播放列表
  748. @param request_dict: 请求数据
  749. @param user_id: 用户id
  750. @request_dict startTime: 开始时间
  751. @request_dict endTime: 结束时间
  752. @request_dict uid: uid
  753. @request_dict channel: 通道
  754. @param response: 响应
  755. @return: response
  756. """
  757. start_time = request_dict.get('startTime', None)
  758. end_time = request_dict.get('endTime', None)
  759. uid = request_dict.get('uid', None)
  760. channel = request_dict.get('channel', None)
  761. event_types = request_dict.get('eventTypes', None)
  762. if not all([uid, channel, start_time, end_time]):
  763. return response.json(444)
  764. try:
  765. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False).values(
  766. 'vodPrimaryUserID', 'Type', 'vodPrimaryMaster')
  767. if not device_info_qs.exists():
  768. return response.json(12)
  769. if device_info_qs[0]['vodPrimaryUserID'] != user_id:
  770. return response.json(10034)
  771. now_time = int(time.time())
  772. device_type = device_info_qs[0]['Type']
  773. if device_type in BINOCULAR_DEVICE_TYPE: # 枪球设备开通云存不区分通道
  774. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time)
  775. else:
  776. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel)
  777. if not uid_bucket_qs.exists():
  778. return response.json(10030)
  779. # 处理标签类型列表
  780. type_list = []
  781. if event_types:
  782. if ',' in event_types:
  783. type_list = event_types.split(',')
  784. type_list = [int(i.strip()) for i in type_list]
  785. else:
  786. type_list = [int(event_types)]
  787. uid_token = TokenObject().encryption(data={'uid': uid})
  788. # 查询aws+oss分表数据
  789. split_vod_hls_obj = SplitVodHlsObject()
  790. split_vod_hls_oss_obj = SplitVodHlsOssObject()
  791. if device_type in BINOCULAR_DEVICE_TYPE:
  792. vod_hls_qs = split_vod_hls_obj.get_vod_hls_data(
  793. uid=uid, end_time__gte=now_time, start_time__range=(start_time, end_time), type_list=type_list) \
  794. .values("id", "start_time", "sec", "fg", "bucket_id", "channel", "tab_val")
  795. vod_hls_oss_qs = split_vod_hls_oss_obj.get_vod_hls_data(
  796. uid=uid, end_time__gte=now_time, start_time__range=(start_time, end_time), type_list=type_list) \
  797. .values("id", "start_time", "sec", "fg", "bucket_id", "channel", "tab_val")
  798. else:
  799. vod_hls_qs = split_vod_hls_obj.get_vod_hls_data(
  800. uid=uid, channel=channel, end_time__gte=now_time, start_time__range=(start_time, end_time),
  801. type_list=type_list) \
  802. .values("id", "start_time", "sec", "fg", "bucket_id", "channel", "tab_val")
  803. vod_hls_oss_qs = split_vod_hls_oss_obj.get_vod_hls_data(
  804. uid=uid, channel=channel, end_time__gte=now_time, start_time__range=(start_time, end_time),
  805. type_list=type_list) \
  806. .values("id", "start_time", "sec", "fg", "bucket_id", "channel", "tab_val")
  807. vod_play_list = []
  808. if not vod_hls_qs.exists() and not vod_hls_oss_qs.exists():
  809. return response.json(0, vod_play_list)
  810. vod_bucket_qs = VodBucketModel.objects.values()
  811. regroup_bucket_qs = {}
  812. for bucket_dict in vod_bucket_qs:
  813. regroup_bucket_qs[bucket_dict['id']] = bucket_dict
  814. # 装载AWS云存播放列表数据
  815. if vod_hls_qs.exists():
  816. aws_vod_play_list = cls.get_vod_play_list(regroup_bucket_qs, vod_hls_qs, uid, uid_token)
  817. vod_play_list[len(vod_play_list):] = aws_vod_play_list
  818. # 装载OSS云存播放列表数据
  819. if vod_hls_oss_qs.exists():
  820. oss_vod_play_list = cls.get_vod_play_list(
  821. regroup_bucket_qs, vod_hls_oss_qs, uid, uid_token, is_aws=False)
  822. vod_play_list[len(vod_play_list):] = oss_vod_play_list
  823. # 根据时间倒序排序
  824. vod_play_list = sorted(vod_play_list, key=lambda item: -item['start_time'])
  825. return response.json(0, vod_play_list)
  826. except Exception as e:
  827. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  828. @staticmethod
  829. def get_vod_play_list(regroup_bucket_qs, vod_hls_qs, uid, uid_token, is_aws=True):
  830. vod_play_list = []
  831. bucket_region = regroup_bucket_qs[vod_hls_qs[0]['bucket_id']]['region']
  832. if is_aws:
  833. bucket_mold = regroup_bucket_qs[vod_hls_qs[0]['bucket_id']]['mold']
  834. aws_access_key_id = AWS_ACCESS_KEY_ID[bucket_mold]
  835. aws_secret_access_key = AWS_SECRET_ACCESS_KEY[bucket_mold]
  836. util_obj = AmazonS3Util(aws_access_key_id, aws_secret_access_key, bucket_region)
  837. else:
  838. if not bucket_region:
  839. return vod_play_list
  840. util_obj = AliOssUtil(
  841. ALICLOUD_AK,
  842. ALICLOUD_SK,
  843. f'https://oss-{bucket_region}.aliyuncs.com'
  844. )
  845. for vod in vod_hls_qs:
  846. channel = vod['channel']
  847. start_time = vod['start_time']
  848. bucket_name = regroup_bucket_qs[vod['bucket_id']]['bucket']
  849. thumbs_png = '{}/vod{}/{}/Thumb.jpeg'.format(uid, channel, start_time)
  850. response_url = util_obj.generate_file_obj_url(bucket_name, thumbs_png)
  851. vod_url = '{}cloudstorage/signplaym3u8?uid={}&channel={}&time={}&sign=tktktktk'. \
  852. format(SERVER_DOMAIN_SSL, uid_token, channel, start_time)
  853. ts_num = int(vod['fg']) & 0xf
  854. types = []
  855. vod_play_list.append({
  856. 'start_time': vod['start_time'],
  857. 'sign_url': vod_url,
  858. 'thumb': response_url,
  859. 'sec': vod['sec'],
  860. 'ts_num': ts_num,
  861. 'vod_id': vod['tab_val'] + str(vod['id']),
  862. 'types': types
  863. })
  864. return vod_play_list
  865. @staticmethod
  866. def do_store_playlist(request_dict, response):
  867. """
  868. 存储设备上传云存信息数据
  869. @param request_dict: 请求数据
  870. @request_dict uidToken: uid_token
  871. @request_dict time: 播放列表名字时间戳
  872. @request_dict sec: 秒数
  873. @request_dict fg: ts个数,时间描述片段数
  874. @param response: 响应
  875. @return: response
  876. """
  877. uid_token = request_dict.get('uidToken', None)
  878. start_time = request_dict.get('time', None)
  879. sec = request_dict.get('sec', None)
  880. fg = request_dict.get('fg', None)
  881. if not all([uid_token, start_time, sec]):
  882. return response.json(0)
  883. uid_obj = UidTokenObject(uid_token)
  884. if uid_obj.flag is False:
  885. return response.json(444, 'uidToken')
  886. try:
  887. sec = int(sec)
  888. uid = uid_obj.UID
  889. channel = uid_obj.channel
  890. now_time = int(time.time())
  891. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel).values(
  892. "bucket__mold",
  893. "bucket__bucket",
  894. "bucket__endpoint",
  895. "bucket__region",
  896. "status",
  897. "bucket__storeDay",
  898. "bucket__vod_location",
  899. "bucket__id").order_by(
  900. 'addTime')
  901. if not uid_bucket_qs.exists():
  902. return response.json(10030)
  903. # 判断设备是否开启云存
  904. uid_bucket = uid_bucket_qs.first()
  905. store_day = uid_bucket['bucket__storeDay']
  906. bucket_id = uid_bucket['bucket__id']
  907. end_time = int(start_time) + store_day * 86400
  908. if uid_bucket['status'] != 1:
  909. return response.json(10, {'msg': '设备未开启云存'})
  910. # 根据存储桶类型保存云存数据
  911. vod_location = uid_bucket['bucket__vod_location']
  912. if vod_location == 0:
  913. split_vod_hls_obj = SplitVodHlsObject()
  914. vod_vo, num = split_vod_hls_obj.creat_vod_hls_data(
  915. uid=uid, channel=channel, start_time=start_time, end_time=end_time, bucket_id=bucket_id, fg=fg,
  916. sec=sec)
  917. # 云存关联AI标签
  918. split_vod_hls_obj.cloud_vod_hls_tag(vod_vo.id, num, uid, start_time, sec)
  919. else:
  920. split_vod_hls_oss_obj = SplitVodHlsOssObject()
  921. split_vod_hls_oss_obj.creat_vod_hls_data(
  922. uid=uid, channel=channel, start_time=start_time, end_time=end_time, bucket_id=bucket_id, fg=fg,
  923. sec=sec)
  924. # 保存云存回放汇总数据
  925. end_time_stamp = datetime.datetime.fromtimestamp(int(start_time))
  926. end_time_str = datetime.datetime(end_time_stamp.year, end_time_stamp.month, 1)
  927. end_time_stamp = CommonService.str_to_timestamp(end_time_str.strftime('%Y-%m-%d %H:%M:%S'))
  928. vod_hls_sum_qs = VodHlsSummary.objects.filter(uid=uid, time=end_time_stamp)
  929. if vod_hls_sum_qs.exists():
  930. vod_hls_sum = vod_hls_sum_qs.first()
  931. vod_hls_sum.upload_frequency += 1
  932. vod_hls_sum.upload_duration += sec
  933. vod_hls_sum.updated_time = now_time
  934. vod_hls_sum.save()
  935. else:
  936. VodHlsSummary.objects.create(uid=uid, time=end_time_stamp, created_time=now_time, updated_time=now_time,
  937. upload_duration=sec, upload_frequency=1)
  938. res = {'code': 0, 'msg': '存储成功'}
  939. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json,charset=utf-8')
  940. except Exception as e:
  941. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  942. @staticmethod
  943. def do_change_vod_status(request_dict, user_id, response): # 修改云存状态
  944. """
  945. 修改云存状态
  946. @param request_dict: 请求数据
  947. @param user_id: 用户id
  948. @request_dict uid: uid
  949. @request_dict status: 套餐状态
  950. @request_dict channel: 通道
  951. @param response: 响应
  952. @return: response
  953. """
  954. uid = request_dict.get('uid', None)
  955. status = request_dict.get('status', None)
  956. channel = request_dict.get('channel', None)
  957. domain_name = request_dict.get('domain_name', None)
  958. if not all([uid, status, channel]):
  959. return response.json(444, 'uid,status,channel')
  960. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
  961. 'vodPrimaryUserID', 'Type')
  962. if not device_info_qs.exists() or device_info_qs[0]['vodPrimaryUserID'] != user_id:
  963. return response.json(12)
  964. device_type = device_info_qs[0]['Type']
  965. if device_type in BINOCULAR_DEVICE_TYPE: # 枪球设备开通云存不区分通道
  966. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid)
  967. else:
  968. uid_bucket_qs = UID_Bucket.objects.filter(channel=channel, uid=uid)
  969. if not uid_bucket_qs.exists():
  970. return response.json(10030)
  971. now_time = int(time.time())
  972. if now_time > uid_bucket_qs[0].endTime:
  973. return response.json(10031)
  974. if status == 0:
  975. uid_bucket_qs.update(status=status)
  976. return response.json(0)
  977. uid_bucket_qs.update(status=status, channel=channel)
  978. uid_obj = UidTokenObject()
  979. uid_obj.generate(data={'uid': uid, 'channel': channel})
  980. urls = SERVER_DOMAIN_SSL
  981. # 欧洲域名固定返回欧洲域名
  982. if domain_name in ['api.zositeche.com', 'api.loocam3.com', 'common.neutral3.com']:
  983. urls = 'https://api.zositeche.com/'
  984. sign = CommonService.encode_data(uid[0:8], start=0, end=1)
  985. uid_tk_url = '{}cloudstorage/getsignsts?uidToken={}&sn={}'.format(urls, uid_obj.token, sign)
  986. store_hls_url = '{}cloudstorage/storeplaylist?uidToken={}'.format(urls, uid_obj.token)
  987. return response.json(0, {'uidTkUrl': uid_tk_url, 'storeHlsUrl': store_hls_url})
  988. @staticmethod
  989. def do_pay_error():
  990. response = HttpResponse()
  991. response.content = PaymentService.get_pay_error_content()
  992. return response
  993. @staticmethod
  994. def do_pay_ok(request_dict): # 支付成功
  995. """
  996. 支付成功
  997. @param request_dict: 请求数据
  998. @request_dict paytype: 支付类型
  999. @request_dict lang: 语言
  1000. @return: response
  1001. """
  1002. lang = request_dict.get('lang', 'en')
  1003. pay_type = request_dict.get('paytype', None)
  1004. response = HttpResponse()
  1005. response.content = PaymentService.get_pay_ok_content(lang, pay_type)
  1006. return response
  1007. def do_pay_by_ali_callback(self, request_dict, response): # 阿里支付回调
  1008. """
  1009. 阿里支付回调
  1010. @param request_dict: 请求数据
  1011. @request_dict out_trade_no: 订单id
  1012. @request_dict sign: 语言
  1013. @request_dict trade_status: 语言
  1014. @request_dict passback_params: 语言
  1015. @param response: 响应
  1016. @return: response
  1017. """
  1018. request_dict = request_dict.dict()
  1019. pass_back_params = request_dict["passback_params"]
  1020. signature = request_dict["sign"]
  1021. request_dict.pop('sign')
  1022. order_id = request_dict['out_trade_no']
  1023. trade_status = request_dict["trade_status"]
  1024. if not all([pass_back_params, signature, order_id, trade_status]):
  1025. return response.json(444)
  1026. parmap = dict([(k, v[0]) for k, v in parse_qs(unquote(pass_back_params)).items()])
  1027. lang = parmap["lang"]
  1028. order_qs = Order_Model.objects.filter(orderID=order_id, status=0)
  1029. if not order_qs.exists():
  1030. return response.json(173)
  1031. # redis加锁,防止订单重复
  1032. redis_obj = RedisObject()
  1033. is_lock = redis_obj.CONN.setnx(order_id + 'do_notify', 1)
  1034. redis_obj.CONN.expire(order_id + 'do_notify', 60)
  1035. if not is_lock:
  1036. return response.json(5)
  1037. promotion_rule_id = ''
  1038. try:
  1039. # 验证阿里支付链接
  1040. ali_pay_obj = AliPayObject()
  1041. alipay = ali_pay_obj.conf()
  1042. success = alipay.verify(request_dict, signature)
  1043. if success and trade_status in ("TRADE_SUCCESS", "TRADE_FINISHED"):
  1044. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  1045. "userID__userID", "userID__username", "coupon_id")
  1046. userid = order_list[0]['userID__userID']
  1047. username = order_list[0]['userID__username']
  1048. uid = order_list[0]['UID']
  1049. channel = order_list[0]['channel']
  1050. rank = order_list[0]['rank']
  1051. store_qs = Store_Meal.objects.filter(id=rank).values('day', 'bucket_id', 'expire')
  1052. if not store_qs.exists():
  1053. return response.json(173)
  1054. bucket_id = store_qs[0]['bucket_id']
  1055. expire = store_qs[0]['expire']
  1056. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id",
  1057. "bucket__region", "endTime", "use_status")
  1058. if order_list[0]['isSelectDiscounts'] == 1:
  1059. expire = store_qs[0]['expire'] * 2
  1060. # 是否有促销
  1061. now_time = int(time.time())
  1062. promotion = PromotionRuleModel.objects.filter(status=1, startTime__lte=now_time,
  1063. endTime__gte=now_time).values('id', 'ruleConfig')
  1064. if promotion.exists():
  1065. promotion_rule_id = promotion[0]['id']
  1066. expire = expire * 2
  1067. end_time = CommonService.calcMonthLater(expire)
  1068. with transaction.atomic():
  1069. if uid_bucket_qs.exists():
  1070. uid_bucket = uid_bucket_qs.first()
  1071. uid_bucket_id = uid_bucket['id']
  1072. if uid_bucket['use_status'] == 1 and uid_bucket['endTime'] > now_time: # 套餐使用中并且相同套餐叠加过期时间
  1073. Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, is_ai=0,
  1074. expire=expire, bucket_id=bucket_id, order_id=order_id)
  1075. UID_Bucket.objects.filter(id=uid_bucket_id).update(has_unused=1)
  1076. else:
  1077. UID_Bucket.objects.filter(id=uid_bucket_id).update(channel=channel, bucket_id=bucket_id,
  1078. endTime=end_time, updateTime=now_time,
  1079. use_status=1, orderId=order_id)
  1080. else:
  1081. uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
  1082. endTime=end_time, addTime=now_time, updateTime=now_time,
  1083. use_status=1, orderId=order_id)
  1084. uid_bucket_id = uid_bucket.id
  1085. device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
  1086. if device_info_qs.exists():
  1087. dvq_set_update_dict = {
  1088. 'vodPrimaryUserID': userid,
  1089. 'vodPrimaryMaster': username
  1090. }
  1091. device_info_qs.update(**dvq_set_update_dict)
  1092. # 核销coupon
  1093. if order_list[0]['coupon_id']:
  1094. CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2,
  1095. update_time=now_time)
  1096. order_qs.update(status=1, updTime=now_time, uid_bucket_id=uid_bucket_id, payTime=now_time,
  1097. promotion_rule_id=promotion_rule_id, create_vod=1)
  1098. date_time = time.strftime("%Y-%m-%d", time.localtime())
  1099. # 如果存在序列号,消息提示用序列号
  1100. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  1101. serial_number = device_info_qs[0]['serial_number']
  1102. device_type = device_info_qs[0]['Type']
  1103. if serial_number:
  1104. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1105. else:
  1106. device_name = uid
  1107. sys_msg_text_list = [
  1108. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
  1109. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  1110. "%b %dth,%Y", time.localtime())]
  1111. self.do_vod_msg_notice(uid, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
  1112. red_url = "{}web/paid2/success.html".format(SERVER_DOMAIN_SSL)
  1113. if lang != 'cn':
  1114. red_url = red_url.replace('success.html', 'en_success.html')
  1115. redis_obj.del_data(key=order_id + 'do_notify')
  1116. return HttpResponseRedirect(red_url)
  1117. return response.json(0, signature)
  1118. except Exception as e:
  1119. LOGGER.info('alipay----notify---------')
  1120. LOGGER.info(repr(e))
  1121. LOGGER.info(sys.exc_info())
  1122. LOGGER.info('alipay支付失败:----')
  1123. LOGGER.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
  1124. LOGGER.info(repr(e))
  1125. if order_qs:
  1126. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  1127. redis_obj.del_data(key=order_id + 'do_notify')
  1128. red_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
  1129. if lang != 'cn':
  1130. red_url = red_url.replace('fail.html', 'en_fail.html')
  1131. return HttpResponseRedirect(red_url)
  1132. def do_pay_by_paypal_callback(self, request_dict, response): # paypal支付回调
  1133. """
  1134. paypal支付回调
  1135. @param request_dict: 请求数据
  1136. @request_dict paymentId: 支付id
  1137. @request_dict PayerID: 支付人id
  1138. @request_dict orderID: 订单id
  1139. @request_dict lang: 语言
  1140. @param response: 响应
  1141. @return: response
  1142. """
  1143. logger = logging.getLogger('info')
  1144. logger.info('---------进入paypal异步回调')
  1145. payment_id = request_dict.get('paymentId', None)
  1146. payer_id = request_dict.get('PayerID', None)
  1147. order_id = request_dict.get('orderID', None)
  1148. lang = request_dict.get('lang', 'en')
  1149. if not all([payer_id, payment_id]):
  1150. return response.json(444)
  1151. logger.info("paymentID={paymentId},payerID={PayerID}".format(paymentId=payment_id, PayerID=payer_id))
  1152. # redis加锁,防止订单重复
  1153. redis_obj = RedisObject()
  1154. is_lock = redis_obj.CONN.setnx(order_id + 'do_notify', 1)
  1155. redis_obj.CONN.expire(order_id + 'do_notify', 60)
  1156. if not is_lock:
  1157. return response.json(5)
  1158. order_qs = Order_Model.objects.filter(orderID=order_id, status=0)
  1159. if not order_qs.exists():
  1160. return response.json(173)
  1161. promotion_rule_id = ''
  1162. try:
  1163. if not order_id:
  1164. red_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
  1165. if lang != 'cn':
  1166. red_url = red_url.replace('fail.html', 'en_fail.html')
  1167. return HttpResponseRedirect(red_url)
  1168. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  1169. "userID__userID", "userID__username", "coupon_id", "app_type")
  1170. app_type = order_list[0]['app_type']
  1171. if app_type == 1:
  1172. paypalrestsdk.configure(PAYPAL_CRD['Zosi'])
  1173. elif app_type == 2:
  1174. paypalrestsdk.configure(PAYPAL_CRD['Vsees'])
  1175. payment = paypalrestsdk.Payment.find(payment_id)
  1176. logger.info("payment------")
  1177. logger.info(payment)
  1178. payers = payment.execute({"payer_id": payer_id})
  1179. logger.info(payers)
  1180. if not payers:
  1181. red_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
  1182. if lang != 'cn':
  1183. red_url = red_url.replace('fail.html', 'en_fail.html')
  1184. redis_obj.del_data(key=order_id + 'do_notify')
  1185. return HttpResponseRedirect(red_url)
  1186. userid = order_list[0]['userID__userID']
  1187. username = order_list[0]['userID__username']
  1188. uid = order_list[0]['UID']
  1189. channel = order_list[0]['channel']
  1190. rank = order_list[0]['rank']
  1191. store_qs = Store_Meal.objects.filter(id=rank).values("day", "bucket_id", "expire", "is_ai")
  1192. if not store_qs.exists():
  1193. return response.json(173)
  1194. bucket_id = store_qs[0]['bucket_id']
  1195. is_ai = store_qs[0]['is_ai']
  1196. expire = store_qs[0]['expire']
  1197. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id",
  1198. "bucket__region", "endTime", "use_status")
  1199. if order_list[0]['isSelectDiscounts'] == 1:
  1200. expire = store_qs[0]['expire'] * 2
  1201. # 是否有促销
  1202. now_time = int(time.time())
  1203. promotion_rule_qs = PromotionRuleModel.objects.filter(status=1, startTime__lte=now_time,
  1204. endTime__gte=now_time).values('id', 'ruleConfig')
  1205. if promotion_rule_qs.exists():
  1206. promotion_rule_id = promotion_rule_qs[0]['id']
  1207. expire = expire * 2
  1208. end_time = CommonService.calcMonthLater(expire)
  1209. use_flag = True
  1210. with transaction.atomic():
  1211. if uid_bucket_qs.exists():
  1212. uid_bucket = uid_bucket_qs.first()
  1213. uid_bucket_id = uid_bucket['id']
  1214. if uid_bucket['use_status'] == 1 and uid_bucket['endTime'] > now_time: # 套餐使用中并且相同套餐叠加过期时间
  1215. Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, order_id=order_id,
  1216. expire=expire, is_ai=is_ai, bucket_id=bucket_id)
  1217. update_status = UID_Bucket.objects.filter(id=uid_bucket_id).update(has_unused=1)
  1218. use_flag = False
  1219. else:
  1220. update_status = UID_Bucket.objects.filter(id=uid_bucket_id).update(channel=channel,
  1221. bucket_id=bucket_id,
  1222. endTime=end_time,
  1223. updateTime=now_time,
  1224. use_status=1,
  1225. orderId=order_id)
  1226. else:
  1227. uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
  1228. endTime=end_time, addTime=now_time, updateTime=now_time,
  1229. use_status=1, orderId=order_id)
  1230. update_status = True
  1231. uid_bucket_id = uid_bucket.id
  1232. device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
  1233. if device_info_qs.exists():
  1234. dvq_set_update_dict = {
  1235. 'vodPrimaryUserID': userid,
  1236. 'vodPrimaryMaster': username
  1237. }
  1238. device_info_qs.update(**dvq_set_update_dict)
  1239. # 核销coupon
  1240. if order_list[0]['coupon_id']:
  1241. CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2, update_time=now_time)
  1242. logger.info(
  1243. 'uid:{},uid_bucket_id:{},update_status:{},order_id:{}'.format(uid, uid_bucket_id, update_status,
  1244. order_id))
  1245. order_qs.update(status=1, updTime=now_time, uid_bucket_id=uid_bucket_id, payTime=now_time,
  1246. promotion_rule_id=promotion_rule_id, create_vod=1)
  1247. date_time = time.strftime("%Y-%m-%d", time.localtime())
  1248. # 开通AI服务
  1249. if is_ai and use_flag:
  1250. ai_service = AiService.objects.filter(uid=uid, channel=channel)
  1251. if ai_service.exists(): # 有正在使用的套餐,套餐结束时间保存为套餐有效期
  1252. ai_service.update(updTime=now_time, use_status=1, orders_id=order_id, endTime=end_time)
  1253. else:
  1254. AiService.objects.create(uid=uid, channel=channel, detect_status=1, addTime=now_time,
  1255. updTime=now_time, endTime=end_time, use_status=1, orders_id=order_id)
  1256. try:
  1257. check_thread = threading.Thread(
  1258. target=AgentOrderView.check_agent_service_package, args=(order_id, uid, rank)
  1259. )
  1260. check_thread.start()
  1261. except Exception as e:
  1262. logger.error('{}PayPal单次购买异步检查代理订单异常e:{}'.format(order_id, repr(e)))
  1263. logger.info('PayPal单次购买支付成功orderId:{}'.format(order_id))
  1264. # 如果存在序列号,消息提示用序列号
  1265. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  1266. serial_number = device_info_qs[0]['serial_number']
  1267. device_type = device_info_qs[0]['Type']
  1268. if serial_number:
  1269. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1270. else:
  1271. device_name = uid
  1272. sys_msg_text_list = [
  1273. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
  1274. 'Dear customer, you have now successfully subscribed to the cloud storage plan for device ' + device_name + ' on ' + time.strftime(
  1275. "%b %dth,%Y", time.localtime())]
  1276. self.do_vod_msg_notice(uid, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
  1277. red_url = "{}web/paid2/success.html".format(SERVER_DOMAIN_SSL)
  1278. if lang != 'cn':
  1279. red_url = red_url.replace('success.html', 'en_success.html')
  1280. redis_obj.del_data(key=order_id + 'do_notify')
  1281. return HttpResponseRedirect(red_url)
  1282. except Exception as e:
  1283. logger.info('paypal支付失败:----')
  1284. logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
  1285. logger.info(repr(e))
  1286. if order_qs:
  1287. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  1288. red_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
  1289. if lang != 'cn':
  1290. red_url = red_url.replace('fail.html', 'en_fail.html')
  1291. redis_obj.del_data(key=order_id + 'do_notify')
  1292. return HttpResponseRedirect(red_url)
  1293. def do_pay_by_wechat_callback(self, request, response): # 微信支付回调
  1294. """
  1295. 微信支付回调
  1296. @param request: 请求体
  1297. @request_dict result_code: 业务结果
  1298. @request_dict out_trade_no: 商户订单号
  1299. @request_dict lang: 语言
  1300. @param response: 响应
  1301. @return: response
  1302. """
  1303. logger = logging.getLogger('info')
  1304. pay = WechatPayObject()
  1305. data = pay.weixinpay_call_back(request.body)
  1306. attach = data["attach"]
  1307. parmap = dict([(k, v[0]) for k, v in parse_qs(unquote(attach)).items()])
  1308. lang = parmap["lang"]
  1309. trade_status = data['result_code'] # 业务结果 SUCCESS/FAIL
  1310. order_id = data['out_trade_no'] # 商户订单号
  1311. if not all([attach, trade_status, order_id]):
  1312. return response.json(444)
  1313. logger.info(order_id)
  1314. order_qs = Order_Model.objects.filter(orderID=order_id, status=0)
  1315. if not order_qs.exists():
  1316. return response.json(173)
  1317. # redis加锁,防止订单重复
  1318. redis_obj = RedisObject()
  1319. is_lock = redis_obj.CONN.setnx(order_id + 'do_notify', 1)
  1320. redis_obj.CONN.expire(order_id + 'do_notify', 60)
  1321. if not is_lock:
  1322. return response.json(5)
  1323. promotion_rule_id = ''
  1324. try:
  1325. if trade_status == "SUCCESS":
  1326. check_sign = pay.get_notifypay(data)
  1327. if not check_sign:
  1328. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '签名失败'}))
  1329. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  1330. "userID__userID", "userID__username", "status", "coupon_id")
  1331. logger.info(order_list[0]['UID'])
  1332. userid = order_list[0]['userID__userID']
  1333. username = order_list[0]['userID__username']
  1334. uid = order_list[0]['UID']
  1335. channel = order_list[0]['channel']
  1336. rank = order_list[0]['rank']
  1337. store_qs = Store_Meal.objects.filter(id=rank).values("day", "bucket_id", "expire")
  1338. if not store_qs.exists():
  1339. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '套餐不存在'}))
  1340. bucket_id = store_qs[0]['bucket_id']
  1341. expire = store_qs[0]['expire']
  1342. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id",
  1343. "bucket__region", "endTime", "use_status")
  1344. if order_list[0]['isSelectDiscounts'] == 1:
  1345. expire = store_qs[0]['expire'] * 2
  1346. # 是否有促销
  1347. now_time = int(time.time())
  1348. promotion_rule_qs = PromotionRuleModel.objects.filter(status=1, startTime__lte=now_time,
  1349. endTime__gte=now_time).values('id', 'ruleConfig')
  1350. if promotion_rule_qs.exists():
  1351. promotion_rule_id = promotion_rule_qs[0]['id']
  1352. expire = expire * 2
  1353. end_time = CommonService.calcMonthLater(expire)
  1354. with transaction.atomic():
  1355. if uid_bucket_qs.exists():
  1356. uid_bucket = uid_bucket_qs.first()
  1357. uid_bucket_id = uid_bucket['id']
  1358. if uid_bucket['use_status'] == 1 and uid_bucket['endTime'] > now_time: # 套餐使用中并且相同套餐叠加过期时间
  1359. Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, is_ai=0,
  1360. expire=expire, bucket_id=bucket_id, order_id=order_id)
  1361. UID_Bucket.objects.filter(id=uid_bucket['id']).update(has_unused=1)
  1362. else:
  1363. UID_Bucket.objects.filter(id=uid_bucket_id).update(channel=channel, bucket_id=bucket_id,
  1364. endTime=end_time, updateTime=now_time,
  1365. use_status=1, orderId=order_id)
  1366. else:
  1367. uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
  1368. endTime=end_time, addTime=now_time,
  1369. updateTime=now_time, use_status=1, orderId=order_id)
  1370. uid_bucket_id = uid_bucket.id
  1371. device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
  1372. if device_info_qs.exists():
  1373. dvq_set_update_dict = {
  1374. 'vodPrimaryUserID': userid,
  1375. 'vodPrimaryMaster': username
  1376. }
  1377. device_info_qs.update(**dvq_set_update_dict)
  1378. # 核销coupon
  1379. if order_list[0]['coupon_id']:
  1380. CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2,
  1381. update_time=now_time)
  1382. order_qs.update(status=1, updTime=now_time, uid_bucket_id=uid_bucket_id, payTime=now_time,
  1383. promotion_rule_id=promotion_rule_id, create_vod=1)
  1384. date_time = time.strftime("%Y-%m-%d", time.localtime())
  1385. # 如果存在序列号,消息提示用序列号
  1386. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  1387. serial_number = device_info_qs[0]['serial_number']
  1388. device_type = device_info_qs[0]['Type']
  1389. if serial_number:
  1390. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1391. else:
  1392. device_name = uid
  1393. sys_msg_text_list = [
  1394. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
  1395. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  1396. "%b %dth,%Y", time.localtime())]
  1397. self.do_vod_msg_notice(uid, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
  1398. redis_obj.del_data(key=order_id + 'do_notify')
  1399. return HttpResponse("<xml>\
  1400. <return_code><![CDATA[SUCCESS]]></return_code>\
  1401. <return_msg><![CDATA[OK]]></return_msg>\
  1402. </xml>")
  1403. else:
  1404. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  1405. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '参数格式校验错误'}))
  1406. except Exception as e:
  1407. logger.info('wechat支付失败:----')
  1408. logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
  1409. logger.info(repr(e))
  1410. if order_qs:
  1411. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  1412. redis_obj.del_data(key=order_id + 'do_notify')
  1413. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': repr(e)}))
  1414. @staticmethod
  1415. def do_create_pay_order(request_dict, user_id, ip, response): # 创建支付订单
  1416. """
  1417. 创建支付订单
  1418. @param request_dict: 请求数据
  1419. @param user_id: 用户id
  1420. @param ip: ip地址
  1421. @request_dict uid: uid
  1422. @request_dict channel: 通道
  1423. @request_dict pay_type: 支付类型
  1424. @request_dict rank: 套餐id
  1425. @request_dict is_select_discount: 用户是否选择了第二年优惠
  1426. @request_dict coupon_id: 优惠券id
  1427. @request_dict lang: 语言
  1428. @param response: 响应
  1429. @return: response
  1430. """
  1431. logger = logging.getLogger('info')
  1432. uid = request_dict.get('uid', None)
  1433. channel = request_dict.get('channel', None)
  1434. pay_type = request_dict.get('pay_type', None)
  1435. rank = request_dict.get('rank', None)
  1436. is_select_discount = request_dict.get('is_select_discount', 0)
  1437. coupon_id = request_dict.get('coupon_id', 0)
  1438. lang = request_dict.get('lang', 'en')
  1439. app_type = request_dict.get('app_type', 1)
  1440. if not all([uid, channel, pay_type, rank]):
  1441. return response.json(444)
  1442. pay_type = int(pay_type)
  1443. app_type = int(app_type)
  1444. logger.info(f'uid:{uid}创建订单云存订单, 时间戳为{int(time.time())}, 支付类型为{pay_type}')
  1445. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
  1446. 'vodPrimaryUserID',
  1447. 'vodPrimaryMaster')
  1448. if not device_info_qs.exists():
  1449. return response.json(12)
  1450. device_info_qs = Device_Info.objects.filter(Q(UID=uid), ~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  1451. if device_info_qs.exists():
  1452. if device_info_qs[0]['vodPrimaryUserID'] != user_id:
  1453. return response.json(10033)
  1454. now_time = int(time.time())
  1455. store_qs = Store_Meal.objects.filter(id=rank, pay_type=pay_type, lang__lang=lang, is_show=0). \
  1456. values('id', 'currency', 'price', 'lang__content', 'day', 'commodity_type', 'lang__title', 'expire',
  1457. 'commodity_code', 'discount_price', 'bucket__mold', 'cycle_config_id', 'is_ai')
  1458. if not store_qs.exists():
  1459. return response.json(173)
  1460. store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=0).values('lang__title',
  1461. 'lang__content')
  1462. if store_meal_qs.exists():
  1463. store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
  1464. else:
  1465. store_meal_name = '未知套餐'
  1466. currency = store_qs[0]['currency']
  1467. price = store_qs[0]['price']
  1468. is_ai = store_qs[0]['is_ai']
  1469. order_type = 1 if is_ai else 0
  1470. if is_select_discount == '1':
  1471. price = float(store_qs[0]['price']) + float(store_qs[0]['discount_price'])
  1472. content = store_qs[0]['lang__content']
  1473. commodity_code = store_qs[0]['commodity_code']
  1474. commodity_type = store_qs[0]['commodity_type']
  1475. is_mold = 1 if store_qs[0]['bucket__mold'] == 0 else 0 # 判断国内外
  1476. order_qs = Order_Model.objects.filter(UID=uid, rank__bucket__mold=is_mold)
  1477. if order_qs.exists():
  1478. if is_mold == 1:
  1479. return response.json(10060)
  1480. return response.json(10041)
  1481. order_id = CommonService.createOrderID()
  1482. # 优惠券
  1483. if coupon_id:
  1484. coupon_qs = CouponModel.objects.filter(id=coupon_id, use_status=0, distribute_time__lte=now_time,
  1485. valid_time__gt=now_time).values("id", "coupon_config__type",
  1486. "coupon_config__coupon_discount")
  1487. if not coupon_qs.exists():
  1488. return response.json(10049)
  1489. price = Decimal(price)
  1490. coupon_discount = Decimal(coupon_qs[0]['coupon_config__coupon_discount'])
  1491. if coupon_qs[0]['coupon_config__type'] == 1: # 打折
  1492. price = coupon_discount / 10 * price
  1493. elif coupon_qs[0]['coupon_config__type'] == 2: # 抵扣
  1494. price = price - coupon_discount
  1495. price = float(price)
  1496. if price < 0 or price == 0 or price < 0.01:
  1497. price = 0.01
  1498. price = round(price, 2)
  1499. if pay_type == 1:
  1500. # 订阅周期扣款
  1501. if store_qs[0]['cycle_config_id']:
  1502. # 查询是否有订阅过,活跃状态
  1503. check_has_subscribe = Paypal.checkSubscriptions(user_id, uid, rank, app_type)
  1504. if not check_has_subscribe:
  1505. return response.json(10050)
  1506. sub_info = Paypal.subscriptions(store_info=store_qs[0], lang=lang, orderID=order_id, price=price,
  1507. app_type=app_type)
  1508. if not sub_info:
  1509. return response.json(10048)
  1510. Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
  1511. desc=content, payType=pay_type, payTime=now_time,
  1512. price=price, currency=currency, addTime=now_time,
  1513. updTime=now_time, order_type=order_type,
  1514. pay_url=sub_info['url'], isSelectDiscounts=is_select_discount,
  1515. commodity_code=commodity_code, commodity_type=commodity_type,
  1516. rank_id=rank, plan_id=sub_info['plan_id'], coupon_id=coupon_id,
  1517. ai_rank_id=1, app_type=app_type,
  1518. store_meal_name=store_meal_name)
  1519. return response.json(0, {"redirectUrl": sub_info['url'], "orderID": order_id})
  1520. # 正常扣款
  1521. call_clc_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
  1522. if lang != 'cn':
  1523. call_clc_url = call_clc_url.replace('fail.html', 'en_fail.html')
  1524. call_sub_url = "{}cloudstorage/dopaypalcallback?orderID={}&lang={}".format(SERVER_DOMAIN_SSL, order_id,
  1525. lang)
  1526. if app_type == 1:
  1527. paypalrestsdk.configure(PAYPAL_CRD['Zosi'])
  1528. elif app_type == 2:
  1529. paypalrestsdk.configure(PAYPAL_CRD['Vsees'])
  1530. else:
  1531. return response.json(444)
  1532. payment = paypalrestsdk.Payment({
  1533. "intent": "sale",
  1534. "payer": {"payment_method": "paypal"},
  1535. "redirect_urls": {"return_url": call_sub_url, "cancel_url": call_clc_url},
  1536. "transactions": [{
  1537. "item_list": {"items": [
  1538. {"name": "Cloud video", "sku": "1", "price": price, "currency": "USD", "quantity": 1}]},
  1539. "amount": {"total": price, "currency": currency},
  1540. "description": content}]})
  1541. if not payment.create():
  1542. return response.json(10, payment.error)
  1543. logger.info('paypal创建订单返回----------')
  1544. logger.info(payment)
  1545. payment_id = payment['id'] # 获取paymentID
  1546. for link in payment.links:
  1547. if link.rel == "approval_url":
  1548. approval_url = str(link.href)
  1549. Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
  1550. desc=content, payType=pay_type, payTime=now_time,
  1551. price=price, currency=currency, addTime=now_time,
  1552. updTime=now_time, order_type=order_type,
  1553. pay_url=approval_url, isSelectDiscounts=is_select_discount,
  1554. commodity_code=commodity_code, commodity_type=commodity_type,
  1555. rank_id=rank, paymentID=payment_id, coupon_id=coupon_id,
  1556. ai_rank_id=1, app_type=app_type,
  1557. store_meal_name=store_meal_name)
  1558. return response.json(0, {"redirectUrl": approval_url, "orderID": order_id})
  1559. return response.json(10, 'generate_order_false')
  1560. elif pay_type == 2:
  1561. try:
  1562. ali_pay_obj = AliPayObject()
  1563. alipay = ali_pay_obj.conf()
  1564. subject = store_qs[0]['lang__title'] + store_qs[0]['lang__content']
  1565. order_string = alipay.api_alipay_trade_wap_pay(
  1566. out_trade_no=order_id,
  1567. total_amount=price,
  1568. subject=subject,
  1569. return_url="{}web/paid2/success.html".format(SERVER_DOMAIN_SSL),
  1570. notify_url="{}cloudstorage/doalicallback".format(SERVER_DOMAIN_SSL),
  1571. quit_url="{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL),
  1572. passback_params=quote("lang=" + lang)
  1573. )
  1574. except Exception as e:
  1575. print(repr(e))
  1576. return response.json(10, repr(e))
  1577. else:
  1578. if order_string:
  1579. redirect_url = ali_pay_obj.alipay_prefix + order_string
  1580. Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
  1581. desc=content, payType=pay_type, payTime=now_time,
  1582. price=price, currency=currency, addTime=now_time,
  1583. updTime=now_time,
  1584. pay_url=redirect_url, isSelectDiscounts=is_select_discount,
  1585. commodity_code=commodity_code, commodity_type=commodity_type,
  1586. rank_id=rank, coupon_id=coupon_id, ai_rank_id=1,
  1587. store_meal_name=store_meal_name)
  1588. return JsonResponse(status=200, data={'result_code': 0, 'reason': 'success',
  1589. 'result': {"redirectUrl": redirect_url, "orderID": order_id},
  1590. 'error_code': 0})
  1591. else:
  1592. return response.json(10, '生成订单错误.')
  1593. elif pay_type == 3:
  1594. pay = WechatPayObject()
  1595. notify_url = "{}cloudstorage/dowechatnotify".format(SERVER_DOMAIN_SSL)
  1596. product_name = store_qs[0]['lang__title'] + store_qs[0]['lang__content'] # 云存套餐
  1597. # 获取参数
  1598. parameter_dict = pay.get_parameter(order_id, product_name, float(price) * 100, ip, notify_url,
  1599. quote("lang=" + lang))
  1600. print('parameter_dict', parameter_dict)
  1601. # parameter_dict 参数中获取MWEB_URL 调转页面在路径后面添加redirect_url
  1602. # 统一调用接口
  1603. response = pay.re_finall(orderid=order_id)
  1604. if not response:
  1605. return response.json(10, '生成订单错误.')
  1606. # 回调函数
  1607. Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
  1608. desc=content, payType=pay_type, payTime=now_time,
  1609. price=price, currency=currency, addTime=now_time, updTime=now_time,
  1610. pay_url=notify_url, isSelectDiscounts=is_select_discount,
  1611. commodity_code=commodity_code, commodity_type=commodity_type,
  1612. rank_id=rank,
  1613. ai_rank_id=1, store_meal_name=store_meal_name)
  1614. return JsonResponse(status=200, data={'result_code': 0, 'reason': 'success',
  1615. 'result': response,
  1616. 'orderId': order_id,
  1617. 'error_code': 0})
  1618. elif pay_type == 5:
  1619. # 内购订阅型订单 之前订阅过任意套餐返回不可再次订阅
  1620. if store_qs[0]['cycle_config_id']:
  1621. # 检查Paypal订阅
  1622. check_subscribe_Paypal = Paypal.checkSubscriptions(user_id, uid, rank, app_type)
  1623. # 查设备是否有绑定套餐
  1624. device_apple_package_qs = DeviceApplePackage.objects.filter(userID=user_id, uid=uid).values(
  1625. "package_id__product_id", "package_id__subscription_group_id")
  1626. if device_apple_package_qs.exists():
  1627. product_id = device_apple_package_qs[0]["package_id__product_id"]
  1628. subscription_group_id = device_apple_package_qs[0]["package_id__subscription_group_id"]
  1629. # 检查内购订阅
  1630. bundle_id = "com.ansjer.zccloud"
  1631. if app_type == 2:
  1632. bundle_id = "com.cloudlife.commissionf"
  1633. in_app_subscription = InAppPurchase(bundle_id=bundle_id)
  1634. check_subscribe_InApp = in_app_subscription.check_subscriptions(uid, subscription_group_id)
  1635. if not check_subscribe_Paypal or check_subscribe_InApp:
  1636. logger.info(
  1637. f'设备订阅过套餐Paypal:{not check_subscribe_Paypal}, AppleInApp:{check_subscribe_InApp}')
  1638. return response.json(10050)
  1639. else:
  1640. # 查询所有符合条件的订阅套餐的 id 列表
  1641. package_list = (InAppPurchasePackage.objects.filter(is_ai=is_ai, package_type=1)
  1642. .values_list("id", flat=True))
  1643. # 查询用户和设备已绑定的套餐 id 列表
  1644. bound_packages = DeviceApplePackage.objects.filter(userID=user_id).values_list("package_id",
  1645. flat=True)
  1646. # 找到未绑定的套餐 id
  1647. unbound_packages = set(package_list) - set(bound_packages)
  1648. if not unbound_packages:
  1649. return response.json(10050)
  1650. # 选择一个未绑定的套餐 id
  1651. package_id = unbound_packages.pop()
  1652. # 绑定一个套餐
  1653. DeviceApplePackage.objects.create(
  1654. userID=user_id,
  1655. uid=uid,
  1656. package_id_id=package_id,
  1657. created_time=int(time.time()),
  1658. update_time=int(time.time())
  1659. )
  1660. product_id = InAppPurchasePackage.objects.filter(id=package_id).values("product_id")[0][
  1661. "product_id"]
  1662. else:
  1663. in_app_purchase_qs = InAppPurchasePackage.objects.filter(rank_id=rank).values("product_id", "is_coupon")
  1664. product_id = in_app_purchase_qs[0]["product_id"]
  1665. is_coupon = in_app_purchase_qs[0]["is_coupon"]
  1666. # 判断是否为优惠订单锁优惠券
  1667. if is_coupon:
  1668. coupon_combo_qs = CouponCombo.objects.filter(combo_id=store_qs[0]['id']).values("coupon_id")
  1669. coupon_ids = CouponModel.objects.filter(userID=user_id, use_status=0,
  1670. coupon_config__id=coupon_combo_qs[0]["coupon_id"],
  1671. valid_time__gte=now_time).values_list("id", flat=True)
  1672. redis_obj = RedisObject()
  1673. for c_id in coupon_ids:
  1674. key_coupon = f"{RedisKeyConstant.COUPON_ID_LOCK.value}{c_id}"
  1675. coupon_lock = redis_obj.get_data(key_coupon)
  1676. if not coupon_lock:
  1677. redis_obj.set_data(key_coupon, 1, 60)
  1678. coupon_id = c_id
  1679. break
  1680. else:
  1681. return response.json(5)
  1682. Order_Model.objects.create(
  1683. orderID=order_id, UID=uid, channel=channel, userID_id=user_id, desc=content, payType=pay_type,
  1684. payTime=now_time, price=price, currency=currency, addTime=now_time, updTime=now_time,
  1685. isSelectDiscounts=is_select_discount, order_type=order_type, commodity_code=commodity_code,
  1686. commodity_type=commodity_type, rank_id=rank, ai_rank_id=1, store_meal_name=store_meal_name,
  1687. app_type=app_type, coupon_id=coupon_id
  1688. )
  1689. return JsonResponse(status=200, data={'result_code': 0, 'reason': 'success',
  1690. 'result': {"orderID": order_id, "productId": product_id},
  1691. 'error_code': 0})
  1692. def do_experience_order(self, request_dict, user_id, response): # 生成体验订单
  1693. """
  1694. 生成体验订单
  1695. @param request_dict: 请求数据
  1696. @param user_id: 用户id
  1697. @request_dict uid: uid
  1698. @request_dict channel: 通道
  1699. @request_dict commodity_code: 套餐规格码
  1700. @request_dict pay_type: 支付类型
  1701. @request_dict rank: 存储套餐id
  1702. @request_dict cdk: 激活码
  1703. @request_dict lang: 语言
  1704. @param response: 响应
  1705. @return: response
  1706. """
  1707. uid = request_dict.get('uid', None)
  1708. channel = request_dict.get('channel', None)
  1709. commodity_code = request_dict.get('commodity_code', '')
  1710. pay_type = int(request_dict.get('pay_type', None))
  1711. rank = request_dict.get('rank', None)
  1712. cdk = request_dict.get('cdk', None)
  1713. lang = request_dict.get('lang', 'en')
  1714. if uid is None:
  1715. return response.json(444, 'uid.')
  1716. redis_obj = RedisObject()
  1717. is_lock = redis_obj.CONN.setnx(uid + 'do_experience_order', 1)
  1718. logger = logging.getLogger('info')
  1719. if not is_lock:
  1720. return response.json(5)
  1721. redis_obj.CONN.expire(uid + 'do_experience_order', 60)
  1722. # 检查pay_type是否为10或11
  1723. if pay_type not in [10, 11]:
  1724. return response.json(444, 'pay_type')
  1725. # 体验套餐检查store_meal的pay_type是否为10
  1726. if rank is not None:
  1727. store_meal_pay_types = [pt['id'] for pt in Pay_Type.objects.filter(store_meal=rank).values('id')]
  1728. if pay_type not in store_meal_pay_types:
  1729. redis_obj.del_data(key=uid + 'do_experience_order')
  1730. return response.json(444, 'rank')
  1731. if pay_type == 10: # 判断是否已体验过套餐
  1732. experience_context_qs = ExperienceContextModel.objects.filter(uid=uid, experience_type=0)
  1733. if experience_context_qs.exists():
  1734. return response.json(10062)
  1735. if cdk is not None and pay_type == 11:
  1736. cdk_qs = CDKcontextModel.objects.filter(cdk=cdk).values('is_activate', 'rank__id', 'rank__commodity_code')
  1737. if not cdk_qs.exists():
  1738. return response.json(10040)
  1739. if cdk_qs[0]['is_activate'] == 1:
  1740. return response.json(10039)
  1741. rank = cdk_qs[0]['rank__id']
  1742. commodity_code = cdk_qs[0]['rank__commodity_code']
  1743. username = request_dict.get('username', None)
  1744. if username:
  1745. user_qs = Device_User.objects.filter(username=username).values('userID')
  1746. if not user_qs.exists():
  1747. return response.json(444, 'username')
  1748. user_id = user_qs[0]['userID']
  1749. if not all([channel, pay_type, rank]):
  1750. redis_obj.del_data(key=uid + 'do_experience_order')
  1751. return response.json(444, 'channel, pay_type, rank')
  1752. device_info_qs = Device_Info.objects.filter(Q(UID=uid), ~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  1753. if device_info_qs.exists():
  1754. if device_info_qs[0]['vodPrimaryUserID'] != user_id:
  1755. if pay_type == 10:
  1756. return response.json(10035)
  1757. if pay_type == 11:
  1758. return response.json(10036)
  1759. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1)
  1760. if not device_info_qs.exists():
  1761. return response.json(12)
  1762. device_vo = device_info_qs.first()
  1763. if device_vo.Type == 103 or device_vo.Type == 26:
  1764. return response.json(10064)
  1765. order_id = CommonService.createOrderID()
  1766. now_time = int(time.time())
  1767. store_qs = Store_Meal.objects.filter(id=rank, lang__lang=lang, is_show=0).values("day", "bucket_id",
  1768. "expire", "is_ai",
  1769. 'lang__content', 'price',
  1770. 'currency', 'commodity_type')
  1771. if not store_qs.exists():
  1772. return response.json(173)
  1773. bucket_id = store_qs[0]['bucket_id']
  1774. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id", "bucket__region",
  1775. "endTime", "use_status")
  1776. expire = store_qs[0]['expire']
  1777. uid_set_qs = UidSetModel.objects.filter(uid=uid).values('is_ai', 'ucode')
  1778. if not uid_set_qs.exists():
  1779. return response.json(173)
  1780. is_ai = 1 if uid_set_qs[0]['is_ai'] != 2 else 0
  1781. if is_ai != 1:
  1782. is_ai = self.check_ucode_exists(uid_set_qs[0]['ucode'])
  1783. if cdk:
  1784. is_ai = store_qs[0]['is_ai']
  1785. order_type = 1 if is_ai and CONFIG_INFO != CONFIG_CN else 0
  1786. use_flag = True
  1787. end_time = CommonService.calcMonthLater(expire)
  1788. try:
  1789. with transaction.atomic():
  1790. if uid_bucket_qs.exists():
  1791. uid_bucket = uid_bucket_qs.first()
  1792. uid_bucket_id = uid_bucket['id']
  1793. if uid_bucket['use_status'] == 1 and uid_bucket['endTime'] > now_time:
  1794. Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, is_ai=is_ai,
  1795. order_id=order_id, expire=expire, bucket_id=bucket_id)
  1796. UID_Bucket.objects.filter(id=uid_bucket_id).update(has_unused=1)
  1797. use_flag = False
  1798. else:
  1799. UID_Bucket.objects.filter(id=uid_bucket_id).update(channel=channel, bucket_id=bucket_id,
  1800. endTime=end_time, updateTime=now_time,
  1801. use_status=1, orderId=order_id)
  1802. else:
  1803. uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
  1804. endTime=end_time, addTime=now_time, updateTime=now_time,
  1805. use_status=1, orderId=order_id)
  1806. uid_bucket_id = uid_bucket.id
  1807. store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=0).values('lang__title',
  1808. 'lang__content')
  1809. if store_meal_qs.exists():
  1810. store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
  1811. else:
  1812. store_meal_name = '未知套餐'
  1813. Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
  1814. desc=store_qs[0]['lang__content'], payType=pay_type, payTime=now_time,
  1815. price=store_qs[0]['price'], currency=store_qs[0]['currency'],
  1816. addTime=now_time, order_type=order_type,
  1817. updTime=now_time, create_vod=1,
  1818. pay_url="体验版", store_meal_name=store_meal_name,
  1819. commodity_code=commodity_code, commodity_type=store_qs[0]['commodity_type'],
  1820. rank_id=rank, status=1, uid_bucket_id=uid_bucket_id, ai_rank_id=1)
  1821. # 开通AI服务,国内不支持AI
  1822. if is_ai and use_flag and CONFIG_INFO != CONFIG_CN:
  1823. ai_service = AiService.objects.filter(uid=uid, channel=channel)
  1824. if ai_service.exists(): # 有正在使用的套餐,套餐结束时间保存为套餐有效期
  1825. ai_service.update(updTime=now_time, use_status=1, orders_id=order_id, endTime=end_time)
  1826. else:
  1827. AiService.objects.create(uid=uid, channel=channel, detect_status=1, addTime=now_time,
  1828. updTime=now_time, endTime=end_time, use_status=1, orders_id=order_id)
  1829. device_user_qs = Device_User.objects.filter(userID=user_id).values('username')
  1830. device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
  1831. if device_info_qs.exists():
  1832. dvq_set_update_dict = {
  1833. 'vodPrimaryUserID': user_id,
  1834. 'vodPrimaryMaster': device_user_qs[0]['username']
  1835. }
  1836. device_info_qs.update(**dvq_set_update_dict)
  1837. sms = 'SMS_219738485'
  1838. date_time = time.strftime("%Y-%m-%d", time.localtime())
  1839. # 如果存在序列号,消息提示用序列号
  1840. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  1841. serial_number = device_info_qs[0]['serial_number']
  1842. device_type = device_info_qs[0]['Type']
  1843. if serial_number:
  1844. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1845. else:
  1846. device_name = uid
  1847. sys_msg_text_list = [
  1848. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
  1849. 'Dear customer, you have now successfully subscribed to the cloud storage plan for device ' + device_name + ' on ' + time.strftime(
  1850. "%b %dth,%Y", time.localtime())]
  1851. return_url = "{}cloudstorage/payOK?lang={}".format(SERVER_DOMAIN_SSL, lang)
  1852. if pay_type == 10:
  1853. ExperienceContextModel.objects.create(
  1854. experience_type=0,
  1855. uid=uid,
  1856. do_time=now_time
  1857. )
  1858. return_url = "{}cloudstorage/payOK?paytype=10&lang={}".format(SERVER_DOMAIN_SSL, lang)
  1859. date_time = time.strftime("%Y-%m-%d", time.localtime())
  1860. sys_msg_text_list = [
  1861. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功开通云存体验套餐',
  1862. 'Dear customer, you have now successfully subscribed to the free trial of cloud storage service for device ' + device_name + ' on ' + time.strftime(
  1863. "%b %dth,%Y", time.localtime())]
  1864. sms = 'SMS_222870823'
  1865. if pay_type == 11:
  1866. update_dict = {'is_activate': 1, 'order': order_id}
  1867. CDKcontextModel.objects.filter(cdk=cdk).update(**update_dict)
  1868. return_url = "{}cloudstorage/payOK?paytype=11&lang={}".format(SERVER_DOMAIN_SSL, lang)
  1869. date_time = time.strftime("%Y-%m-%d", time.localtime())
  1870. sys_msg_text_list = [
  1871. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功兑换云存套餐',
  1872. 'Dear customer, you have now successfully redeemed for the cloud storage service for device ' + device_name + ' on ' + time.strftime(
  1873. "%b %dth,%Y", time.localtime())]
  1874. sms = 'SMS_219748439'
  1875. self.do_vod_msg_notice(uid, channel, user_id, lang, sys_msg_text_list, sms)
  1876. result = return_url
  1877. redis_obj.del_data(key=uid + 'do_experience_order')
  1878. return response.json(0, result)
  1879. except Exception as e:
  1880. logger.info('出错了~体验云存异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1881. redis_obj.del_data(key=uid + 'do_experience_order')
  1882. return response.json(474)
  1883. @staticmethod
  1884. def do_experience_reset(request_dict, response): # 重置设备云存体验
  1885. """
  1886. 重置设备云存体验
  1887. @param request_dict: 请求数据
  1888. @request_dict id: 关联套餐id
  1889. @param response: 响应
  1890. @return: response
  1891. """
  1892. bucket_id = request_dict.get("id", None)
  1893. uid_bucket_qs = UID_Bucket.objects.filter(id=bucket_id)
  1894. if uid_bucket_qs.exists():
  1895. experience_context_qs = ExperienceContextModel.objects.filter(uid=uid_bucket_qs[0].uid)
  1896. if experience_context_qs.exists():
  1897. experience_context_qs.delete()
  1898. Order_Model.objects.filter(uid_bucket_id=bucket_id).delete()
  1899. uid_bucket_qs.delete()
  1900. else:
  1901. return response.json(10007)
  1902. else:
  1903. return response.json(0, '重置云存体验失败')
  1904. return response.json(0, '重置云存体验成功')
  1905. @staticmethod
  1906. def delete_vod_list(request_dict, user_id, response): # 删除播放列表
  1907. """
  1908. 删除播放列表
  1909. @param request_dict: 请求数据
  1910. @param user_id: 用户id
  1911. @request_dict uid: uid
  1912. @request_dict vod_id_list: 云存视频id列表
  1913. @param response: 响应
  1914. @return: response
  1915. """
  1916. uid = request_dict.get('uid', None)
  1917. vod_id_list = request_dict.get('vod_id_list', None)
  1918. is_del_all = request_dict.get('is_del_all', 0)
  1919. if not all([uid, vod_id_list]):
  1920. return response.json(444)
  1921. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
  1922. 'vodPrimaryUserID')
  1923. if not device_info_qs.exists() or device_info_qs[0]['vodPrimaryUserID'] != user_id:
  1924. return response.json(12)
  1925. vod_id_list = json.loads(vod_id_list)
  1926. try:
  1927. if is_del_all == 1:
  1928. # 删除vod_hls分表数据
  1929. split_vod_hls_obj = SplitVodHlsObject()
  1930. split_vod_hls_obj.del_vod_hls_data(uid=uid)
  1931. # 删除vod_hls_oss分表数据
  1932. split_vod_hls_oss_obj = SplitVodHlsOssObject()
  1933. split_vod_hls_oss_obj.del_vod_hls_data(uid=uid)
  1934. else:
  1935. if not isinstance(vod_id_list, list):
  1936. return response.json(444)
  1937. # 删除vod_hls分表数据
  1938. split_vod_hls_obj = SplitVodHlsObject()
  1939. split_vod_hls_obj.del_vod_hls_data(id__in=vod_id_list, uid=uid)
  1940. # 删除vod_hls分表数据
  1941. split_vod_hls_oss_obj = SplitVodHlsOssObject()
  1942. split_vod_hls_oss_obj.del_vod_hls_data(id__in=vod_id_list, uid=uid)
  1943. except Exception as e:
  1944. return response.json(424, repr(e))
  1945. else:
  1946. return response.json(0)
  1947. @staticmethod
  1948. def device_commodity(request_dict, user_id, response): # 设备关联套餐列表
  1949. """
  1950. 设备关联套餐列表
  1951. @param request_dict: 请求数据
  1952. @param user_id: 用户id
  1953. @request_dict uid: uid
  1954. @request_dict lang: 语言
  1955. @param response: 响应
  1956. @return: response
  1957. """
  1958. uid = request_dict.get('uid', None)
  1959. lang = request_dict.get('lang', 'en')
  1960. if not uid:
  1961. return response.json(444)
  1962. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
  1963. 'vodPrimaryUserID', 'serial_number', 'Type')
  1964. if not device_info_qs.exists() or device_info_qs[0]['vodPrimaryUserID'] != user_id:
  1965. return response.json(12)
  1966. now_time = int(time.time())
  1967. bucket_id_list = []
  1968. store_list = []
  1969. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time).values("id", "uid", "bucket__content",
  1970. "use_status", "endTime",
  1971. "has_unused", "bucket__id",
  1972. "orderId")
  1973. if not uid_bucket_qs:
  1974. return response.json(10030)
  1975. try:
  1976. # 如果存在序列号返回完整序列号
  1977. device_id = uid
  1978. serial_number = device_info_qs[0]['serial_number']
  1979. device_type = device_info_qs[0]['Type']
  1980. if serial_number:
  1981. device_id = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1982. uid_bucket_qs[0]['uid'] = device_id
  1983. uid_bucket_qs[0]['storage'] = 0
  1984. has_unused = uid_bucket_qs[0]['has_unused']
  1985. del uid_bucket_qs[0]['has_unused']
  1986. store_list.append(uid_bucket_qs[0])
  1987. bucket_id_list.append(uid_bucket_qs[0]['bucket__id'])
  1988. if has_unused == 1:
  1989. unused_uid_qs = Unused_Uid_Meal.objects.filter(uid=uid).annotate(unused_id=F('id')).values("unused_id",
  1990. "uid",
  1991. "bucket__content",
  1992. "bucket__id",
  1993. "expire",
  1994. "order_id")
  1995. month = 'month' if lang != 'cn' else '个月'
  1996. for unused_uid in unused_uid_qs:
  1997. storage_time = unused_uid['expire']
  1998. if lang != 'cn' and storage_time > 1: # 英文大于一个月使用复数
  1999. month += 's'
  2000. storage = str(storage_time) + month
  2001. unused_dict = {
  2002. "id": unused_uid['unused_id'],
  2003. "uid": device_id,
  2004. "bucket__content": unused_uid['bucket__content'],
  2005. "use_status": 0,
  2006. "endTime": 0,
  2007. "bucket__id": unused_uid['bucket__id'],
  2008. "storage": storage,
  2009. "orderId": unused_uid['order_id'],
  2010. }
  2011. store_list.append(unused_dict)
  2012. bucket_id_list.append(unused_uid['bucket__id'])
  2013. for index, value in enumerate(store_list):
  2014. if value['orderId'] and CONFIG_INFO != CONFIG_CN:
  2015. order_qs = Order_Model.objects.filter(orderID=value['orderId'], rank__lang__lang=lang).values('payType',
  2016. 'rank__pay_type__id',
  2017. 'order_type',
  2018. 'rank__is_ai',
  2019. 'rank__pixel_level',
  2020. 'rank__commodity_code',
  2021. 'rank__lang__new_title')
  2022. if order_qs.exists():
  2023. order = order_qs[0]
  2024. new_title_raw = order.get('rank__lang__new_title', '{}')
  2025. try:
  2026. new_title_dict = json.loads(new_title_raw) if isinstance(new_title_raw,
  2027. str) else new_title_raw
  2028. except json.JSONDecodeError:
  2029. new_title_dict = {}
  2030. if order['payType'] not in [10, 11]:
  2031. if order['rank__pixel_level'] == 0 and order['rank__is_ai'] == 0:
  2032. if order['rank__commodity_code']:
  2033. value['bucket__content'] = new_title_dict.get('5', '')
  2034. else:
  2035. value['bucket__content'] = new_title_dict.get('1', '')
  2036. elif order['rank__pixel_level'] == 1 and order['rank__is_ai'] == 0:
  2037. if order['rank__commodity_code']:
  2038. value['bucket__content'] = new_title_dict.get('6', '')
  2039. else:
  2040. value['bucket__content'] = new_title_dict.get('2', '')
  2041. elif order['rank__pixel_level'] == 0 and order['rank__is_ai'] == 1:
  2042. if order['rank__commodity_code']:
  2043. value['bucket__content'] = new_title_dict.get('7', '')
  2044. else:
  2045. value['bucket__content'] = new_title_dict.get('3', '')
  2046. elif order['rank__pixel_level'] == 1 and order['rank__is_ai'] == 1:
  2047. if order['rank__commodity_code']:
  2048. value['bucket__content'] = new_title_dict.get('8', '')
  2049. else:
  2050. value['bucket__content'] = new_title_dict.get('4', '')
  2051. elif order['payType'] == 10: # 免费套餐
  2052. if order['order_type'] == 0:
  2053. value['bucket__content'] = new_title_dict.get('1', '')
  2054. elif order['order_type'] == 1:
  2055. value['bucket__content'] = new_title_dict.get('2', '')
  2056. else: # cdk套餐
  2057. if order['rank__pay_type__id'] != 11:
  2058. if order['rank__pixel_level'] == 0 and order['rank__is_ai'] == 0:
  2059. value['bucket__content'] = new_title_dict.get('1', '')
  2060. elif order['rank__pixel_level'] == 1 and order['rank__is_ai'] == 0:
  2061. value['bucket__content'] = new_title_dict.get('2', '')
  2062. elif order['rank__pixel_level'] == 0 and order['rank__is_ai'] == 1:
  2063. value['bucket__content'] = new_title_dict.get('3', '')
  2064. elif order['rank__pixel_level'] == 1 and order['rank__is_ai'] == 1:
  2065. value['bucket__content'] = new_title_dict.get('4', '')
  2066. else:
  2067. if order['order_type'] == 0:
  2068. value['bucket__content'] = new_title_dict.get('1', '')
  2069. elif order['order_type'] == 1:
  2070. value['bucket__content'] = new_title_dict.get('2', '')
  2071. value['bucket__content'] += '(cdk)'
  2072. else:
  2073. store_qs = Store_Meal.objects.filter(bucket__id__in=bucket_id_list, lang__lang=lang).annotate(
  2074. title=F('lang__title'), content=F('lang__content')).values('lang__content', 'lang__lang',
  2075. 'bucket__id', 'lang__title')
  2076. for store in store_qs:
  2077. if value['bucket__id'] == store['bucket__id']:
  2078. value['bucket__content'] = store['lang__title'] + '-' + store['lang__content']
  2079. return response.json(0, list(store_list))
  2080. except Exception as e:
  2081. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  2082. @staticmethod
  2083. def switch_device_commodity(request_dict, user_id, response): # 提前使用设备关联套餐
  2084. """
  2085. 提前使用设备关联套餐
  2086. @param request_dict: 请求数据
  2087. @param user_id: 用户id
  2088. @request_dict uid: uid
  2089. @request_dict switch_commodity_id: 未使用关联套餐id
  2090. @param response: 响应
  2091. @return: response
  2092. """
  2093. uid = request_dict.get('uid', None)
  2094. unused_id = request_dict.get('switch_commodity_id', None)
  2095. if not all([uid, unused_id]):
  2096. return response.json(444)
  2097. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
  2098. 'vodPrimaryUserID')
  2099. if not device_info_qs.exists() or device_info_qs[0]['vodPrimaryUserID'] != user_id:
  2100. return response.json(12)
  2101. # 切换设备套餐关联
  2102. using_uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, has_unused=1).values("id", "uid", "endTime",
  2103. "bucket__content", "addTime")
  2104. unused_uid_bucket_qs = Unused_Uid_Meal.objects.filter(id=unused_id).values("id", "uid", "channel", "addTime",
  2105. "expire", "is_ai", "bucket_id",
  2106. "order_id")
  2107. if not unused_uid_bucket_qs.exists() or not using_uid_bucket_qs.exists():
  2108. return response.json(10030)
  2109. unused_uid_bucket = unused_uid_bucket_qs.first()
  2110. now_time = int(time.time())
  2111. try:
  2112. with transaction.atomic():
  2113. count_unused = Unused_Uid_Meal.objects.filter(uid=uid).count()
  2114. has_unused = 1 if count_unused > 1 else 0
  2115. end_time = CommonService.calcMonthLater(unused_uid_bucket['expire'])
  2116. UID_Bucket.objects.filter(uid=uid).update(channel=unused_uid_bucket['channel'], endTime=end_time,
  2117. bucket_id=unused_uid_bucket['bucket_id'],
  2118. orderId=unused_uid_bucket['order_id'],
  2119. updateTime=now_time, use_status=1,
  2120. has_unused=has_unused)
  2121. # 开通AI服务
  2122. if unused_uid_bucket['is_ai']:
  2123. ai_service = AiService.objects.filter(uid=uid, channel=unused_uid_bucket['channel'])
  2124. if ai_service.exists(): # 有正在使用的套餐,套餐结束时间保存为套餐有效期
  2125. ai_service.update(updTime=now_time, use_status=1, orders_id=unused_uid_bucket['order_id'],
  2126. endTime=end_time)
  2127. else:
  2128. AiService.objects.create(uid=uid, channel=unused_uid_bucket['channel'], detect_status=1,
  2129. addTime=now_time, updTime=now_time, endTime=end_time, use_status=1,
  2130. orders_id=unused_uid_bucket['order_id'])
  2131. Unused_Uid_Meal.objects.filter(id=unused_id).delete()
  2132. StsCrdModel.objects.filter(uid=uid).delete() # 删除sts记录
  2133. # VodHlsModel.objects.filter(uid=uid).delete() # 删除播放列表,后期数据量多时应该考虑延后删除
  2134. return response.json(0)
  2135. except Exception:
  2136. return response.json(474)
  2137. @classmethod
  2138. def has_vod(cls, request_dict, user_id, response):
  2139. """
  2140. 云存日期
  2141. @param request_dict: 请求数据
  2142. @param user_id: 用户id
  2143. @request_dict uid: uid
  2144. @request_dict channel: 通道
  2145. @param response: 响应
  2146. @return: response
  2147. """
  2148. uid = request_dict.get('uid', None)
  2149. channel = request_dict.get('channel', 1)
  2150. if not uid:
  2151. return response.json(444)
  2152. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False).values(
  2153. 'vodPrimaryUserID',
  2154. 'vodPrimaryMaster',
  2155. 'Type')
  2156. if not device_info_qs.exists():
  2157. return response.json(12)
  2158. if device_info_qs[0]['vodPrimaryUserID'] != user_id:
  2159. return response.json(10034)
  2160. now_time = int(time.time())
  2161. device_type = device_info_qs[0]['Type']
  2162. if device_type in BINOCULAR_DEVICE_TYPE: # 枪球设备开通云存不区分通道
  2163. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time).values(
  2164. 'bucket_id', 'bucket__vod_location').order_by(
  2165. 'addTime')
  2166. else:
  2167. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel).values(
  2168. 'bucket_id', 'bucket__vod_location').order_by(
  2169. 'addTime')
  2170. if not uid_bucket_qs.exists():
  2171. return response.json(10030)
  2172. split_vod_hls_obj = SplitVodHlsObject()
  2173. had_vod_list = cls.get_vod_date_list(split_vod_hls_obj, device_type, uid, channel, now_time)
  2174. vod_location = uid_bucket_qs[0]['bucket__vod_location']
  2175. # 拼接OSS分表数据
  2176. if vod_location == 1:
  2177. split_vod_hls_oss_obj = SplitVodHlsOssObject()
  2178. oss_vod_list = cls.get_vod_date_list(split_vod_hls_oss_obj, device_type, uid, channel, now_time)
  2179. had_vod_list[len(had_vod_list):] = oss_vod_list
  2180. had_vod_list = sorted(had_vod_list, key=lambda item: -item['timestamp'])[:31]
  2181. return response.json(0, had_vod_list)
  2182. @staticmethod
  2183. def get_vod_date_list(split_vod_hls_obj, device_type, uid, channel, now_time):
  2184. if device_type in BINOCULAR_DEVICE_TYPE: # 枪球设备开通云存不区分通道
  2185. vod_hls_qs = split_vod_hls_obj.get_vod_hls_date(uid=uid, end_time__gte=now_time)
  2186. else:
  2187. vod_hls_qs = split_vod_hls_obj.get_vod_hls_date(uid=uid, end_time__gte=now_time, channel=channel)
  2188. had_vod_list = []
  2189. for vod in vod_hls_qs:
  2190. had_vod_list.append({
  2191. 'timestamp': CommonService.str_to_timestamp(vod['date'], '%Y-%m-%d'),
  2192. 'vod_count': vod['count'],
  2193. 'date_format': vod['date'],
  2194. })
  2195. return had_vod_list
  2196. @staticmethod
  2197. def video_playback_time(request_dict, user_id, response):
  2198. """
  2199. 存储视频播放数据
  2200. @param request_dict: 请求数据
  2201. @param user_id: 用户id
  2202. @request_dict parms: 参数列表
  2203. @param response: 响应
  2204. @return: response
  2205. """
  2206. params = request_dict.get('parms', None)
  2207. if not params:
  2208. return response.json(444)
  2209. try:
  2210. params = eval(params)
  2211. bulk = []
  2212. for parm in params:
  2213. parm['userID'] = user_id
  2214. # 解密uid
  2215. for i in range(1, 4):
  2216. parm['uid'] = base64.b64decode(parm['uid'])
  2217. parm['uid'] = parm['uid'].decode('utf-8')
  2218. parm['uid'] = parm['uid'][i:-i]
  2219. video_playback_time = VideoPlaybackTimeModel(**parm)
  2220. bulk.append(video_playback_time)
  2221. VideoPlaybackTimeModel.objects.bulk_create(bulk)
  2222. return response.json(0)
  2223. except Exception as e:
  2224. print(e)
  2225. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  2226. def do_vod_msg_notice(self, uid, channel, user_id, lang, sys_msg_text_list, sms): # 云存操作系统消息
  2227. """
  2228. 云存操作系统消息
  2229. @param uid: uid
  2230. @param channel: 通道
  2231. @param user_id: 用户id
  2232. @param lang: 语言
  2233. @param sys_msg_text_list: 消息列表
  2234. @param sms: sms码
  2235. @return: response
  2236. """
  2237. try:
  2238. logger = logging.getLogger('log')
  2239. logger.info('进来了')
  2240. if lang == 'cn':
  2241. sys_msg_text = sys_msg_text_list[0]
  2242. else:
  2243. sys_msg_text = sys_msg_text_list[1]
  2244. now_time = int(time.time())
  2245. create_data = {'userID_id': user_id, 'msg': sys_msg_text, 'addTime': now_time,
  2246. 'updTime': now_time, 'uid': uid, 'eventType': 0}
  2247. SysMsgModel.objects.create(**create_data)
  2248. # 不接收邮件用户
  2249. if user_id == '167015836969813800138000':
  2250. return
  2251. user_qs = Device_User.objects.filter(userID=user_id)
  2252. if user_qs.exists():
  2253. user = user_qs.first()
  2254. username = user.username
  2255. data_valid = DataValid()
  2256. if data_valid.email_validate(username):
  2257. S3Email().faEmail(sys_msg_text, username)
  2258. elif data_valid.mobile_validate(username):
  2259. # 如果存在序列号,消息提示用序列号
  2260. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  2261. if device_info_qs.exists():
  2262. serial_number = device_info_qs[0]['serial_number']
  2263. device_type = device_info_qs[0]['Type']
  2264. if serial_number:
  2265. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  2266. else:
  2267. device_name = uid
  2268. params = '{"devname":"%s","submittime":"%s"}' % (
  2269. device_name, time.strftime("%Y-%m-%d", time.localtime()))
  2270. self.send_message(username, params, sms)
  2271. logger.info('出去了')
  2272. except Exception as e:
  2273. return repr(e)
  2274. def do_vod_msg_end(self, response): # 云存到期续费提醒 提前3天
  2275. """
  2276. 云存到期续费提醒
  2277. @param response: 响应
  2278. @return: response
  2279. """
  2280. now_time = int(time.time())
  2281. # 过期前第7天提示一次
  2282. uid_bucket_qs = UID_Bucket.objects.filter(
  2283. Q(endTime__gt=now_time + 3600 * 144) & Q(endTime__lte=(now_time + 3600 * 168))).values('id', 'uid',
  2284. 'bucket__area',
  2285. 'channel', 'endTime')
  2286. self.do_vod_msg(now_time, uid_bucket_qs)
  2287. # 过期前第3天提示一次
  2288. uid_bucket_qs = UID_Bucket.objects.filter(
  2289. Q(endTime__gt=now_time + 3600 * 48) & Q(endTime__lte=(now_time + 3600 * 72))).values('id', 'uid',
  2290. 'bucket__area',
  2291. 'channel', 'endTime')
  2292. self.do_vod_msg(now_time, uid_bucket_qs)
  2293. return response.json(0)
  2294. def do_vod_msg(self, now_time, qs):
  2295. """
  2296. 云存到期续费提醒
  2297. @param now_time: 现在时间
  2298. @param qs: 查询集
  2299. @return: response
  2300. """
  2301. msg_list = []
  2302. ids = []
  2303. for item in qs:
  2304. ids.append(item['id'])
  2305. order_qs = Order_Model.objects.filter(uid_bucket_id__in=ids).values('userID_id', 'uid_bucket_id')
  2306. for item in qs:
  2307. for order in order_qs:
  2308. if item['id'] == order['uid_bucket_id']:
  2309. # 如果存在序列号,消息提示用序列号
  2310. uid = item['uid']
  2311. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  2312. serial_number = device_info_qs[0]['serial_number']
  2313. device_type = device_info_qs[0]['Type']
  2314. if serial_number and device_type == 101:
  2315. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  2316. else:
  2317. device_name = uid
  2318. if item['bucket__area'] == 'cn':
  2319. sys_msg_text = "温馨提示:尊敬的客户,您%s设备的云存套餐将在%s到期" % (
  2320. device_name, time.strftime("%Y-%m-%d", time.localtime(item['endTime'])))
  2321. else:
  2322. sys_msg_text = 'Dear customer,the cloud storage package for your device %s will expire on %s' % \
  2323. (device_name, time.strftime('%m-%d-%y', time.localtime(item['endTime'])))
  2324. msg_list.append(SysMsgModel(
  2325. userID_id=order['userID_id'],
  2326. addTime=now_time,
  2327. updTime=now_time,
  2328. uid=item['uid'],
  2329. eventType=0,
  2330. msg=sys_msg_text,
  2331. status=0
  2332. ))
  2333. SysMsgModel.objects.bulk_create(msg_list)
  2334. msg_list.clear()
  2335. user_qs = Device_User.objects.filter(userID=order['userID_id'])
  2336. if user_qs.exists():
  2337. user = user_qs.first()
  2338. username = user.username
  2339. data_valid = DataValid()
  2340. if data_valid.email_validate(username):
  2341. S3Email().faEmail(sys_msg_text, username)
  2342. elif data_valid.mobile_validate(username):
  2343. params = u'{"devname":"%s","submittime":"%s"}' % (
  2344. device_name, time.strftime("%Y-%m-%d", time.localtime(item['endTime'])))
  2345. self.send_message(username, params, 'SMS_219748440')
  2346. @staticmethod
  2347. def send_message(phone, params, temp_msg):
  2348. """
  2349. 发送手机消息
  2350. @param phone: 用户名
  2351. @param params: 消息参数
  2352. @param temp_msg: sms码
  2353. """
  2354. sign_name = CommonService.confirm_msg_sign_name_with_phone(phone)
  2355. ali_sms = AliSmsObject()
  2356. ali_sms.send_code_sms_cloud(phone=phone, params=params, sign_name=sign_name, temp_msg=temp_msg)
  2357. @staticmethod
  2358. def do_refund(request_dict, response):
  2359. """
  2360. 退款
  2361. @param request_dict: 请求数据
  2362. @request_dict orderID: 订单id
  2363. @request_dict refund_amount: 退款金额
  2364. @param response: 响应
  2365. @return: response
  2366. """
  2367. order_id = request_dict.get('orderID', None) # 商户订单号
  2368. refund_amount = request_dict.get('refund_amount', None) # 退款金额
  2369. if not all([order_id, refund_amount]):
  2370. return response.json(444)
  2371. try:
  2372. order_qs = Order_Model.objects.filter(orderID=order_id) \
  2373. .values('status', 'payType', 'price', 'refunded_amount',
  2374. 'currency', 'paymentID', 'trade_no', "app_type")
  2375. if not order_qs.exists():
  2376. return response.json(173)
  2377. # 支付状态不为支付成功和退款失败和部分退款
  2378. status = order_qs[0]['status']
  2379. if status != 1 and status != 4 and status != 6:
  2380. return response.json(805)
  2381. refund_amount = float(refund_amount)
  2382. now_time = int(time.time())
  2383. pay_type = order_qs[0]['payType']
  2384. price = order_qs[0]['price'] # 订单金额
  2385. refunded_amount = order_qs[0]['refunded_amount'] # 已退款金额
  2386. currency = order_qs[0]['currency'] # 货币
  2387. # 判断是否符合付款条件
  2388. if refunded_amount == float(price): # 已全额退款
  2389. return response.json(805)
  2390. if refund_amount + refunded_amount > float(price): # 退款金额超出订单价格
  2391. return response.json(805)
  2392. # 部分退款标识
  2393. is_partial_refund = True if (float(price) > refund_amount + refunded_amount) else False
  2394. out_request_no = str(time.strftime('%Y%m%d%H%M%S', time.localtime(now_time))) # 退款请求号
  2395. # 根据支付类型处理退款
  2396. if pay_type == 1: # PayPal
  2397. payment_id = order_qs[0]['paymentID'] # PayPal PAYMENT_ID
  2398. trade_no = order_qs[0]['trade_no']
  2399. app_type = order_qs[0]['app_type']
  2400. sale_id = ''
  2401. if app_type == 1:
  2402. paypalrestsdk.configure(PAYPAL_CRD['Zosi'])
  2403. elif app_type == 2:
  2404. paypalrestsdk.configure(PAYPAL_CRD['Vsees'])
  2405. if payment_id:
  2406. payment = paypalrestsdk.Payment.find(payment_id)
  2407. related_resources = payment['transactions'][0]['related_resources']
  2408. if not related_resources:
  2409. return response.json(805)
  2410. sale = related_resources[0]['sale']
  2411. # 没退款过 'state' 不为 'completed' 或 已退款过但 'state' 不为 'partially_refunded'
  2412. if (refunded_amount == 0 and sale['state'] != 'completed') or (
  2413. refunded_amount != 0 and sale['state'] != 'partially_refunded'):
  2414. return response.json(805)
  2415. sale_id = sale['id']
  2416. sale_id = sale_id if sale_id else trade_no
  2417. paypal_sale = paypalrestsdk.Sale.find(sale_id)
  2418. if not paypal_sale or paypal_sale['state'] not in ['completed', 'partially_refunded']:
  2419. return response.json(805)
  2420. refund = paypal_sale.refund({
  2421. 'amount': {
  2422. 'total': refund_amount,
  2423. 'currency': currency
  2424. }
  2425. })
  2426. refund_success = True if refund.success() else False
  2427. elif pay_type == 2: # 支付宝
  2428. ali_pay_obj = AliPayObject()
  2429. alipay = ali_pay_obj.conf()
  2430. refund_response = alipay.api_alipay_trade_refund(refund_amount=refund_amount, out_trade_no=order_id,
  2431. out_request_no=out_request_no)
  2432. refund_success = True if (refund_response['code'] == '10000') else False
  2433. elif pay_type == 3: # 微信
  2434. wechat_pay_obj = WechatPayObject()
  2435. refund_fee = int(refund_amount * 100) # 退款金额,单位为分,只能为整数
  2436. total_fee = int(float(price) * 100) # 订单金额,单位为分,只能为整数
  2437. success = wechat_pay_obj.refund(out_trade_no=order_id, out_refund_no=out_request_no,
  2438. total_fee=total_fee, refund_fee=refund_fee)
  2439. refund_success = True if success else False
  2440. else: # 不支持退款的支付类型
  2441. return response.json(805)
  2442. # 更新订单状态和已退款金额
  2443. update_dict = {'updTime': now_time}
  2444. if refund_success:
  2445. update_dict['status'] = 6 if is_partial_refund else 5
  2446. update_dict['refunded_amount'] = refunded_amount + refund_amount
  2447. else:
  2448. update_dict['status'] = 4
  2449. order_qs.update(**update_dict)
  2450. return response.json(0)
  2451. except Exception as e:
  2452. logger = logging.getLogger('info')
  2453. logger.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  2454. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  2455. def check_ucode_exists(self, ucode):
  2456. if not ucode:
  2457. return 0
  2458. ucode_set = {'823C01552AA', '823C01550AA', '823C01550XA', '522001352AA', '823C01550TA', '823C01550VA',
  2459. '823C01850XA', 'C18201850KA', '823C01850TA', 'C22501850VA', 'V82301850AA',
  2460. 'V82301850XA', '730201350AA', '730201450AA', '730201450MA', '730201450NA',
  2461. '72V201252AA', '72V201253AA', '72V201353AA', '72V201354AA', '72V201355AA',
  2462. '72V201254AA', '72V201256AA', '72V201257AA'}
  2463. return 1 if ucode in ucode_set else 0