CloudStorage.py 102 KB

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