CloudStorage.py 105 KB

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