CloudStorage.py 119 KB

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