CloudStorage.py 117 KB

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