CloudStorage.py 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @AUTHOR: ASJRD018
  6. @NAME: AnsjerFormal
  7. @software: PyCharm
  8. @DATE: 2018/12/5 9:30
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: cloudstorage.py
  12. @Contact: chanjunkai@163.com
  13. """
  14. import json
  15. import os
  16. import time
  17. import urllib
  18. from urllib.parse import quote, parse_qs, unquote
  19. import apns2
  20. import boto3
  21. import jpush
  22. import oss2
  23. import paypalrestsdk
  24. import threading
  25. import calendar
  26. import datetime
  27. import logging
  28. from aliyunsdkcore import client
  29. from aliyunsdksts.request.v20150401 import AssumeRoleRequest
  30. from boto3.session import Session
  31. from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
  32. from django.db import transaction
  33. from django.views.generic.base import View
  34. import jwt
  35. from pyfcm import FCMNotification
  36. from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, OSS_ROLE_ARN, SERVER_DOMAIN, PAYPAL_CRD, \
  37. SERVER_DOMAIN_SSL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ARN, APNS_MODE, APNS_CONFIG, BASE_DIR, \
  38. JPUSH_CONFIG, FCM_CONFIG, OAUTH_ACCESS_TOKEN_SECRET
  39. from Model.models import Device_Info, Order_Model, Store_Meal, VodHlsModel, OssCrdModel, UID_Bucket, StsCrdModel, \
  40. ExperienceContextModel, Pay_Type, CDKcontextModel, Device_User, SysMassModel, SysMsgModel, UidPushModel, Unused_Uid_Meal
  41. from Object.AliPayObject import AliPayObject
  42. from Object.ResponseObject import ResponseObject
  43. from Object.TokenObject import TokenObject
  44. from Object.UidTokenObject import UidTokenObject
  45. from Service.CommonService import CommonService
  46. from Object.m3u8generate import PlaylistGenerator
  47. from Object.WechatPayObject import WechatPayObject
  48. from django.db.models import Q, F
  49. from Service.ModelService import ModelService
  50. SERVER_DOMAIN = 'http://test.dvema.com/'
  51. '''
  52. 生成订单
  53. http://test.dvema.com/cloudstorage/createpayorder?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJleHAiOjE1ODk1MjM0OTIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCIsImxhbmciOiJlbiIsInVzZXIiOiIxMzExOTY1NzcxMyJ9.e2NdhJtbXrDngZTSmOX_52Y-oxyfUEXjZD_qNxg6VrU&uid=VVDHCVBYDKFMJRWA111A&channel=1&pay_type=0&commodity_code=aws_us_vod_7_val_30
  54. 开启开关
  55. http://test.dvema.com/cloudstorage/changevodstatus?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJleHAiOjE1ODk1MjM0OTIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCIsImxhbmciOiJlbiIsInVzZXIiOiIxMzExOTY1NzcxMyJ9.e2NdhJtbXrDngZTSmOX_52Y-oxyfUEXjZD_qNxg6VrU&uid=VVDHCVBYDKFMJRWA111A&channel=1&status=1
  56. # 获取播放列表
  57. http://localhost:8077/cloudstorage/queryvodlist?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJleHAiOjE1ODk1MjM0OTIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCIsImxhbmciOiJlbiIsInVzZXIiOiIxMzExOTY1NzcxMyJ9.e2NdhJtbXrDngZTSmOX_52Y-oxyfUEXjZD_qNxg6VrU&uid=VVDHCVBYDKFMJRWA111A&startTime=1&endTime=1954687458&channel=1
  58. # 存储视频列表信息
  59. http://test.dvema.com/cloudstorage/storeplaylist?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJWVkRIQ1ZCWURLRk1KUldBMTExQSIsImNoYW5uZWwiOiIxIn0.eGwi5QKyrXi4WSKRbrUG7iFTChv_Utec2hSnqZkDKt8&time=1586940120&sec=20&fg=10
  60. # 获取订单列表
  61. http://localhost:8077/cloudstorage/queryorder?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJsYW5nIjoiZW4iLCJ1c2VyIjoiMTMxMTk2NTc3MTMiLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJleHAiOjE1ODk1OTIyNzh9.u211DHiMKg-pqhXv4b2yR__eNyOcSwBZCyPUGjsxFLU&page=1&line=10&uid=VVDHCVBYDKFMJRWA111A
  62. # commoditylist
  63. http://test.dvema.com/cloudstorage/commoditylist?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJleHAiOjE1ODk1MjM0OTIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCIsImxhbmciOiJlbiIsInVzZXIiOiIxMzExOTY1NzcxMyJ9.e2NdhJtbXrDngZTSmOX_52Y-oxyfUEXjZD_qNxg6VrU
  64. '''
  65. # 设备信息添加
  66. class CloudStorageView(View):
  67. def get(self, request, *args, **kwargs):
  68. request.encoding = 'utf-8'
  69. operation = kwargs.get('operation')
  70. return self.validation(request.GET, request, operation)
  71. def post(self, request, *args, **kwargs):
  72. request.encoding = 'utf-8'
  73. operation = kwargs.get('operation')
  74. return self.validation(request.POST, request, operation)
  75. def validation(self, request_dict, request, operation):
  76. response = ResponseObject()
  77. if operation is None:
  78. return response.json(444, 'error path')
  79. elif operation == 'testpaly.m3u8':
  80. return self.do_test_play_m3u8(request_dict, response)
  81. elif operation == 'dopaypalcallback':
  82. return self.do_pay_by_paypal_callback(request_dict, response)
  83. elif operation == 'doalicallback':
  84. return self.do_pay_by_ali_callback(request)
  85. elif operation == 'dowechatnotify':
  86. return self.do_pay_by_wechat_callback(request, response)
  87. elif operation == 'getsignsts':
  88. ip = CommonService.get_ip_address(request)
  89. return self.do_get_sign_sts(request_dict, ip, response)
  90. elif operation == 'testgetsignsts':
  91. ip = CommonService.get_ip_address(request)
  92. return self.do_test_get_sign_sts(request_dict, ip, response)
  93. # return self.do_get_sign_sts_test(request_dict, ip, response)
  94. elif operation == 'storeplaylist':
  95. return self.do_store_playlist(request_dict, response)
  96. elif operation == 'signplaym3u8':
  97. return self.do_sign_play_m3u8(request_dict, response)
  98. elif operation == 'payOK':
  99. return self.do_pay_ok(request_dict)
  100. elif operation == 'vodMsgEnd':
  101. return self.do_vod_msg_end(request_dict)
  102. elif operation == 'vodMsgNotice':
  103. return self.do_vod_msg_Notice(request_dict)
  104. else:
  105. token = request_dict.get('token', None)
  106. # 设备主键uid
  107. tko = TokenObject(token)
  108. response.lang = tko.lang
  109. if tko.code != 0:
  110. return response.json(tko.code)
  111. userID = tko.userID
  112. if operation == 'createpayorder':
  113. ip = CommonService.get_ip_address(request)
  114. return self.do_create_pay_order(request_dict, userID, ip, response)
  115. elif operation == 'changevodstatus':
  116. return self.do_change_vod_status(request_dict, userID, response)
  117. elif operation == 'queryvodlist':
  118. return self.do_query_vod_list(request_dict, userID, response)
  119. elif operation == 'commoditylist':
  120. return self.do_commodity_list(request_dict, userID, response)
  121. elif operation == 'queryorder':
  122. return self.do_query_order(request_dict, userID, response)
  123. elif operation == 'experienceorder':
  124. return self.do_experience_order(request_dict, userID, response)
  125. elif operation == 'experiencereset':
  126. return self.do_experience_reset(request_dict, userID, response)
  127. elif operation == 'deletevodlist':
  128. return self.deleteVodList(request_dict, userID, response)
  129. elif operation == 'devicecommodity':
  130. return self.device_commodity(request_dict, userID, response)
  131. elif operation == 'switchdevicecommodity':
  132. return self.switch_device_commodity(request_dict, userID, response)
  133. else:
  134. return response.json(414)
  135. def do_test_play_m3u8(self, request_dict, response):
  136. playlist_entries = [
  137. {
  138. 'name': 'https://azvod1.s3-ap-northeast-1.amazonaws.com/test/output000.ts',
  139. 'duration': 10,
  140. },
  141. {
  142. 'name': 'https://azvod1.s3-ap-northeast-1.amazonaws.com/test/output000.ts',
  143. 'duration': 10,
  144. },
  145. {
  146. 'name': 'https://azvod1.s3-ap-northeast-1.amazonaws.com/test/output000.ts',
  147. 'duration': 10,
  148. },
  149. ]
  150. playlist = PlaylistGenerator(playlist_entries).generate()
  151. # return HttpResponse(playlist)
  152. # response = HttpResponse(playlist, content_type="application/octet-stream")
  153. response = HttpResponse(playlist, content_type="application/vnd.apple.mpegurl")
  154. return response
  155. def do_query_order(self, request_dict, userID, response):
  156. status = request_dict.get('status', None)
  157. page = int(request_dict.get('page', None))
  158. line = int(request_dict.get('line', None))
  159. uid = request_dict.get('uid', None)
  160. order_qs = Order_Model.objects.filter(userID_id=userID)
  161. if status:
  162. order_qs = order_qs.filter(status=status)
  163. # 筛选指定设备id的订单
  164. if uid:
  165. order_qs = order_qs.filter(UID=uid)
  166. if not order_qs.exists():
  167. return response.json(173)
  168. # return response.json(10, '订单不存在')
  169. count = order_qs.count()
  170. order_ql = order_qs[(page - 1) * line:page * line]. \
  171. values("orderID", "UID", "channel", "desc", "price", "currency",
  172. "addTime", "updTime", "endTime", "pay_url", "payType",
  173. "status", "commodity_type", "commodity_code")
  174. order_list = list(order_ql)
  175. data = []
  176. nowTime = int(time.time())
  177. # 这里需要进行优化
  178. uid_list = []
  179. for od in order_list:
  180. uid_list.append(od['UID'])
  181. didqs = Device_Info.objects.filter(userID_id=userID, UID__in=uid_list). \
  182. values('id', 'UID', 'Type')
  183. for d in order_list:
  184. if d['status'] == 0:
  185. if d['addTime'] + 3600 < nowTime:
  186. d['status'] = 3
  187. for did in didqs:
  188. if d['UID'] == did['UID']:
  189. d['did'] = did['id']
  190. d['Type'] = did['Type']
  191. data.append(d)
  192. return response.json(0, {'data': data, 'count': count})
  193. def do_commodity_list(self, request_dict, userID, response):
  194. mold = request_dict.get('mold', None)
  195. uid = request_dict.get('uid', None)
  196. lang = request_dict.get('lang', None)
  197. qs = Store_Meal.objects
  198. eq = ExperienceContextModel.objects.filter(uid=uid, experience_type=0).values('id')
  199. # userqs = Device_User.objects.filter(userID=userID).values('is_experience')
  200. if mold:
  201. qs = qs.filter(bucket__mold=mold,lang__lang=lang)
  202. else:
  203. qs = qs.filter(lang__lang=lang)
  204. if eq:
  205. qs = qs.filter(~Q(pay_type='10'))
  206. else:
  207. qs = qs.filter(pay_type='10')
  208. qs = qs.filter(~Q(pay_type='11')) # 过滤不显示激活码套餐
  209. qs = qs.annotate(title=F('lang__title'),content=F('lang__content'),discount_content=F('lang__discount_content'))
  210. qs = qs.values("id", "title", "content", "price", "day", "currency", "bucket__storeDay",
  211. "bucket__bucket", "bucket__area", "commodity_code",
  212. "commodity_type", "is_discounts", "virtual_price", "expire",
  213. "discount_price", "discount_content", "symbol")
  214. if qs.exists():
  215. ql = list(qs)
  216. from operator import itemgetter
  217. from itertools import groupby
  218. ql.sort(key=itemgetter('bucket__area'))
  219. res = []
  220. for area, items in groupby(ql, key=itemgetter('bucket__area')):
  221. items_list = list(items)
  222. for key, val in enumerate(items_list):
  223. pay_types = Pay_Type.objects.filter(store_meal=items_list[key]['id']).values("id", "payment")
  224. items_list[key]['pay_type'] = list(pay_types)
  225. res_c = {'area': area, 'items': items_list}
  226. res.append(res_c)
  227. result = {
  228. 'meals': res,
  229. 'extra':
  230. {
  231. 'cloud_banner': 'https://www.dvema.com/web/images/cloud_cn_banner.png',
  232. 'cloud_en_baner': 'https://www.dvema.com/web/images/cloud_en_banner.png'
  233. }
  234. }
  235. return response.json(0, result)
  236. else:
  237. return response.json(0)
  238. def do_sign_play_m3u8(self, request_dict, response):
  239. uid = request_dict.get('uid', None)
  240. uid = jwt.decode(uid, OAUTH_ACCESS_TOKEN_SECRET, algorithms='HS256').get('uid', '')
  241. channel = request_dict.get('channel', None)
  242. storeTime = request_dict.get('time', None)
  243. now_time = int(time.time())
  244. vh_qs = VodHlsModel.objects.filter(uid=uid, channel=channel, time=storeTime, endTime__gte=now_time). \
  245. values("sec", "fg", "bucket__bucket", "bucket__endpoint", "bucket__region", "bucket__mold")
  246. if not vh_qs.exists():
  247. return response.json(173)
  248. sec = vh_qs[0]['sec']
  249. fg = vh_qs[0]['fg']
  250. bucket__region = vh_qs[0]['bucket__region']
  251. bucket_name = vh_qs[0]['bucket__bucket']
  252. print(bucket__region)
  253. print(bucket_name)
  254. session = Session(
  255. aws_access_key_id=AWS_ACCESS_KEY_ID[vh_qs[0]["bucket__mold"]],
  256. aws_secret_access_key = AWS_SECRET_ACCESS_KEY[vh_qs[0]["bucket__mold"]],
  257. region_name=bucket__region
  258. )
  259. '''
  260. http://test.dvema.com/cloudstorage/signplaym3u8?uid=VVDHCVBYDKFMJRWA111A&channel=1&time=1586940120&sign=tktktktk
  261. '''
  262. conn = session.client('s3')
  263. playlist_entries = []
  264. # for i in range(fg):
  265. # thumbspng = '{uid}/vod{channel}/{time}/ts{i}.ts'. \
  266. # format(uid=uid, channel=channel, time=storeTime, i=i)
  267. # response_url = conn.generate_presigned_url(
  268. # 'get_object',
  269. # Params={
  270. # 'Bucket': bucket_name,
  271. # 'Key': thumbspng
  272. # },
  273. # ExpiresIn=3600
  274. # )
  275. # # m3u8 = '{uid}/vod{channel}/{time}/{time}.m3u8'. \
  276. # # format(uid=uid, channel=channel, time=vod['time'])
  277. # playlist_entries.append({
  278. # 'name': response_url,
  279. # 'duration': sec,
  280. # })
  281. fg = int(fg)
  282. ts_count = fg & 0xf
  283. for i in range(ts_count):
  284. shift = (i + 1) * 4
  285. duration = (fg >> shift) & 0xf
  286. if duration > 0:
  287. tsFile = '{uid}/vod{channel}/{time}/ts{i}.ts'. \
  288. format(uid=uid, channel=channel, time=storeTime, i=i)
  289. response_url = conn.generate_presigned_url(
  290. 'get_object',
  291. Params={
  292. 'Bucket': bucket_name,
  293. 'Key': tsFile
  294. },
  295. ExpiresIn=3600
  296. )
  297. # m3u8 = '{uid}/vod{channel}/{time}/{time}.m3u8'. \
  298. # format(uid=uid, channel=channel, time=vod['time'])
  299. playlist_entries.append({
  300. 'name': response_url,
  301. 'duration': duration,
  302. })
  303. playlist = PlaylistGenerator(playlist_entries).generate()
  304. response = HttpResponse(playlist)
  305. response['Content-Type'] = 'application/octet-stream'
  306. response['Content-Disposition'] = 'attachment;filename="play.m3u8"'
  307. return response
  308. # response = HttpResponse(playlist, content_type="application/vnd.apple.mpegurl")
  309. # response = HttpResponse(playlist, content_type="application/octet-stream")
  310. # return response
  311. def do_get_sign_sts(self, request_dict, ip, response):
  312. uidToken = request_dict.get('uidToken', None)
  313. utko = UidTokenObject(uidToken)
  314. if utko.flag is False:
  315. return response.json(444, 'uidToken')
  316. uid = utko.UID
  317. channel = utko.channel
  318. print(channel)
  319. print(uid)
  320. now_time = int(time.time())
  321. ubqs = UID_Bucket.objects.filter(uid=uid, channel=channel, endTime__gte=now_time). \
  322. values("bucket__mold", "bucket__bucket", "bucket__endpoint",
  323. "bucket__region", "endTime").order_by('addTime')[:1]
  324. if ubqs.exists():
  325. # 亚马逊 s3 sts
  326. sts_qs = StsCrdModel.objects.filter(uid=uid, channel=channel). \
  327. values("addTime", "data")
  328. if sts_qs.exists():
  329. endTime = int(sts_qs[0]["addTime"]) + 800
  330. if endTime > now_time:
  331. print(endTime)
  332. print(now_time)
  333. res = json.loads(sts_qs[0]["data"])
  334. return JsonResponse(status=200, data=res)
  335. # 套餐id
  336. storage = '{uid}/vod{channel}/'.format(uid=uid, channel=channel)
  337. bucket_name = ubqs[0]['bucket__bucket']
  338. endpoint = ubqs[0]['bucket__endpoint']
  339. region_id = ubqs[0]['bucket__region']
  340. try:
  341. aws_access_key_id = AWS_ACCESS_KEY_ID[ubqs[0]["bucket__mold"]]
  342. aws_secret_access_key = AWS_SECRET_ACCESS_KEY[ubqs[0]["bucket__mold"]]
  343. aws_arn = AWS_ARN[ubqs[0]["bucket__mold"]]
  344. except:
  345. res = {'code': 404, 'msg': 'mold not exists!'}
  346. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  347. ###############
  348. boto3_sts = boto3.client(
  349. 'sts',
  350. aws_access_key_id=aws_access_key_id,
  351. aws_secret_access_key=aws_secret_access_key,
  352. region_name=region_id
  353. )
  354. Policy = {
  355. "Version": "2012-10-17",
  356. "Statement": [
  357. {
  358. "Effect": "Allow",
  359. "Action": "s3:*",
  360. "Resource": ["{aws_arn}:::{bucket_name}/{uid_channel}*".
  361. format(aws_arn=aws_arn, bucket_name=bucket_name, uid_channel=storage)]
  362. }
  363. ]
  364. }
  365. response = boto3_sts.get_federation_token(
  366. Name='{role_name}'.format(role_name=uid + '_' + str(channel)),
  367. Policy=json.dumps(Policy),
  368. DurationSeconds=900
  369. )
  370. ##############
  371. res = {
  372. 'AccessKeyId': response['Credentials']['AccessKeyId'],
  373. 'AccessKeySecret': response['Credentials']['SecretAccessKey'],
  374. 'SessionToken': response['Credentials']['SessionToken'],
  375. 'Expiration': response['Credentials']['Expiration'],
  376. 'expire': 900,
  377. 'endpoint': endpoint,
  378. 'bucket_name': bucket_name,
  379. 'arn': response['FederatedUser']['Arn'],
  380. 'code': 0,
  381. 'storage': storage,
  382. 'endTime': ubqs[0]['endTime'],
  383. 'ip': ip,
  384. 'region': region_id,
  385. 'bucket_mold':ubqs[0]['bucket__mold']
  386. }
  387. if sts_qs.exists():
  388. sts_qs.update(data=json.dumps(res, default=str), addTime=now_time)
  389. else:
  390. StsCrdModel.objects.create(uid=uid, channel=channel, data=json.dumps(res, default=str),
  391. addTime=now_time, type=1)
  392. return JsonResponse(status=200, data=res)
  393. # else:
  394. # res = {'code': 404, 'msg': 'data not exists!'}
  395. # return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  396. res = {'code': 405, 'msg': 'Not purchased or expired!'}
  397. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  398. def do_test_get_sign_sts(self, request_dict, ip, response):
  399. uidToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJYS1daU0M1RkNKWVQxOUI3MTExQSIsImNoYW5uZWwiOjF9.YvBCETPrKknw7B-RU3Mij-WJLKf46KGrDQvZMMN7dQk'
  400. reset = request_dict.get('reset', 0)
  401. utko = UidTokenObject(uidToken)
  402. if utko.flag is False:
  403. return response.json(444, 'uidToken')
  404. uid = utko.UID
  405. channel = utko.channel
  406. now_time = int(time.time())
  407. ubqs = UID_Bucket.objects.filter(uid=uid, channel=channel, endTime__gte=now_time). \
  408. values("bucket__mold", "bucket__bucket", "bucket__endpoint",
  409. "bucket__region", "endTime").order_by('addTime')[:1]
  410. if ubqs.exists():
  411. # 亚马逊 s3 sts
  412. sts_qs = StsCrdModel.objects.filter(uid=uid, channel=channel). \
  413. values("addTime", "data")
  414. if sts_qs.exists():
  415. endTime = int(sts_qs[0]["addTime"]) + 800
  416. if reset == '0' and endTime > now_time:
  417. print(endTime)
  418. print(now_time)
  419. res = json.loads(sts_qs[0]["data"])
  420. return JsonResponse(status=200, data=res)
  421. # 套餐id
  422. storage = '{uid}/test/'.format(uid=uid)
  423. bucket_name = ubqs[0]['bucket__bucket']
  424. endpoint = ubqs[0]['bucket__endpoint']
  425. region_id = ubqs[0]['bucket__region']
  426. try:
  427. aws_access_key_id = AWS_ACCESS_KEY_ID[ubqs[0]["bucket__mold"]]
  428. aws_secret_access_key = AWS_SECRET_ACCESS_KEY[ubqs[0]["bucket__mold"]]
  429. aws_arn = AWS_ARN[ubqs[0]["bucket__mold"]]
  430. except:
  431. res = {'code': 404, 'msg': 'mold not exists!'}
  432. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  433. ###############
  434. boto3_sts = boto3.client(
  435. 'sts',
  436. aws_access_key_id=aws_access_key_id,
  437. aws_secret_access_key=aws_secret_access_key,
  438. region_name=region_id
  439. )
  440. Policy = {
  441. "Version": "2012-10-17",
  442. "Statement": [
  443. {
  444. "Effect": "Allow",
  445. "Action": "s3:*",
  446. "Resource": ["{aws_arn}:::{bucket_name}/{uid_channel}*".
  447. format(aws_arn=aws_arn, bucket_name=bucket_name, uid_channel=storage)]
  448. }
  449. ]
  450. }
  451. response = boto3_sts.get_federation_token(
  452. Name='{role_name}'.format(role_name=uid + '_' + str(channel)),
  453. Policy=json.dumps(Policy),
  454. DurationSeconds=900
  455. )
  456. ##############
  457. res = {
  458. 'AccessKeyId': response['Credentials']['AccessKeyId'],
  459. 'AccessKeySecret': response['Credentials']['SecretAccessKey'],
  460. 'SessionToken': response['Credentials']['SessionToken'],
  461. 'Expiration': response['Credentials']['Expiration'],
  462. 'expire': 900,
  463. 'endpoint': endpoint,
  464. 'bucket_name': bucket_name,
  465. 'arn': response['FederatedUser']['Arn'],
  466. 'code': 0,
  467. 'storage': storage,
  468. 'endTime': ubqs[0]['endTime'],
  469. 'ip': ip,
  470. 'region': region_id,
  471. 'bucket_mold':ubqs[0]['bucket__mold']
  472. }
  473. if sts_qs.exists():
  474. sts_qs.update(data=json.dumps(res, default=str), addTime=now_time)
  475. else:
  476. StsCrdModel.objects.create(uid=uid, channel=channel, data=json.dumps(res, default=str),
  477. addTime=now_time, type=1)
  478. return JsonResponse(status=200, data=res)
  479. # else:
  480. # res = {'code': 404, 'msg': 'data not exists!'}
  481. # return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  482. res = {'code': 405, 'msg': 'Not purchased or expired!'}
  483. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  484. def do_query_vod_list(self, request_dict, userID, response):
  485. startTime = int(request_dict.get('startTime', None))
  486. endTime = int(request_dict.get('endTime', None))
  487. uid = request_dict.get('uid', None)
  488. channel = request_dict.get('channel', None)
  489. dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False).values('vodPrimaryUserID',
  490. 'vodPrimaryMaster')
  491. if not dv_qs.exists():
  492. return response.json(12)
  493. if dv_qs[0]['vodPrimaryUserID'] != userID:
  494. return response.json(10034)
  495. now_time = int(time.time())
  496. bv_qs = UID_Bucket.objects.filter(uid=uid, channel=channel, endTime__gte=now_time).values('bucket_id').order_by('addTime')
  497. if not bv_qs.exists():
  498. return response.json(10030)
  499. vh_qs = VodHlsModel.objects.filter \
  500. (uid=uid, channel=channel, endTime__gte=now_time,time__range=(startTime, endTime), bucket_id=bv_qs[0]['bucket_id']). \
  501. values("id", "time", "sec", "bucket__bucket", "fg", "bucket__endpoint", "bucket__region", "bucket__mold")
  502. vod_play_list = []
  503. if not vh_qs.exists():
  504. return response.json(0, vod_play_list)
  505. aws_access_key_id = AWS_ACCESS_KEY_ID[vh_qs[0]["bucket__mold"]]
  506. aws_secret_access_key = AWS_SECRET_ACCESS_KEY[vh_qs[0]["bucket__mold"]]
  507. session = Session(
  508. aws_access_key_id=aws_access_key_id,
  509. aws_secret_access_key=aws_secret_access_key,
  510. region_name=vh_qs[0]["bucket__region"]
  511. )
  512. conn = session.client('s3')
  513. for vod in vh_qs:
  514. bucket__mold = vod["bucket__mold"]
  515. bucket_name = vod["bucket__bucket"]
  516. endpoint = vod["bucket__endpoint"]
  517. bucket__region = vod["bucket__region"]
  518. thumbspng = '{uid}/vod{channel}/{time}/Thumb.jpeg'. \
  519. format(uid=uid, channel=channel, time=vod['time'])
  520. response_url = conn.generate_presigned_url(
  521. 'get_object',
  522. Params={
  523. 'Bucket': bucket_name,
  524. 'Key': thumbspng
  525. },
  526. ExpiresIn=3600
  527. )
  528. vod_url = '{server_domain}/cloudstorage/signplaym3u8?' \
  529. 'uid={uid}&channel={channel}&time={time}&sign=tktktktk'. \
  530. format(server_domain=SERVER_DOMAIN, uid=TokenObject().encryption(data={'uid': uid}), channel=channel, time=vod['time'])
  531. ts_num = int(vod['fg']) & 0xf
  532. vod_play_list.append({
  533. 'name': vod['time'],
  534. 'sign_url': vod_url,
  535. 'thumb': response_url,
  536. 'sec': vod['sec'],
  537. 'ts_num': ts_num,
  538. 'vod_id': vod['id']
  539. }),
  540. return response.json(0, vod_play_list)
  541. def do_store_playlist(self, request_dict, response):
  542. uidToken = request_dict.get('uidToken', None)
  543. storeTime = request_dict.get('time', None)
  544. sec = request_dict.get('sec', None)
  545. fg = request_dict.get('fg', None)
  546. utko = UidTokenObject(uidToken)
  547. if utko.flag is False:
  548. return response.json(444, 'uidToken')
  549. if not uidToken or not storeTime or not sec:
  550. return response.json(0)
  551. pass
  552. UID = utko.UID
  553. channel = utko.channel
  554. print('UID:')
  555. print(UID)
  556. print('channel:')
  557. print(channel)
  558. now_time = int(time.time())
  559. ubqs = UID_Bucket.objects.filter(uid=UID, channel=channel, endTime__gte=now_time). \
  560. values("bucket__mold", "bucket__bucket", "bucket__endpoint",
  561. "bucket__region", "status", "bucket__storeDay", "bucket__id").order_by('addTime')[:1]
  562. if ubqs.exists():
  563. ub_qs_data = ubqs[0]
  564. store_day = ub_qs_data['bucket__storeDay']
  565. bucket_id = ub_qs_data['bucket__id']
  566. end_time = int(storeTime) + store_day * 86400
  567. if ub_qs_data['status'] == 1:
  568. sts_qs = StsCrdModel.objects.filter(uid=UID, channel=channel, type=1). \
  569. values("addTime", "data")
  570. if sts_qs.exists():
  571. VodHlsModel.objects.create(
  572. uid=UID,
  573. channel=channel,
  574. time=storeTime,
  575. endTime=end_time,
  576. bucket_id=bucket_id,
  577. fg=fg,
  578. sec=sec,
  579. )
  580. res = {'code': 0, 'msg': '存储成功'}
  581. return HttpResponse(json.dumps(res, ensure_ascii=False),
  582. content_type="application/json,charset=utf-8")
  583. else:
  584. res = {'code': 404, 'msg': '设备未购买'}
  585. return HttpResponse(json.dumps(res, ensure_ascii=False),
  586. content_type="application/json,charset=utf-8")
  587. else:
  588. res = {'code': 404, 'msg': '设备未开启'}
  589. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  590. else:
  591. res = {'code': 404, 'msg': '设备未购买'}
  592. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  593. def do_change_vod_status(self, request_dict, userID, response):
  594. uid = request_dict.get('uid', None)
  595. status = request_dict.get('status', None)
  596. channel = request_dict.get('channel', None)
  597. if not uid or not status or not channel:
  598. return response.json(444, 'uid,status,channel')
  599. dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1) \
  600. .values('vodPrimaryUserID')
  601. if not dv_qs.exists() or dv_qs[0]['vodPrimaryUserID'] != userID:
  602. return response.json(12)
  603. ubqs = UID_Bucket.objects.filter(channel=channel, uid=uid)
  604. if not ubqs.exists():
  605. return response.json(10030)
  606. now_time = int(time.time())
  607. if now_time > ubqs[0].endTime:
  608. return response.json(10031)
  609. ubqs.update(status=status)
  610. if status == 0:
  611. return response.json(0)
  612. utko = UidTokenObject()
  613. utko.generate(data={'uid': uid, 'channel': channel})
  614. uidTkUrl = "{SERVER_DOMAIN}cloudstorage/getsignsts?uidToken={uidToken}". \
  615. format(uidToken=utko.token, SERVER_DOMAIN=SERVER_DOMAIN)
  616. storeHlsUrl = "{SERVER_DOMAIN}cloudstorage/storeplaylist?uidToken={uidToken}". \
  617. format(uidToken=utko.token, SERVER_DOMAIN=SERVER_DOMAIN)
  618. return response.json(0, {'uidTkUrl': uidTkUrl, 'storeHlsUrl': storeHlsUrl})
  619. def do_pay_error(self):
  620. response = HttpResponse()
  621. response.content = '''
  622. <!DOCTYPE html>
  623. <html>
  624. <head>
  625. <!--浏览器不缓存-->
  626. <meta http-equiv="Pragma" content="no-cache">
  627. <meta http-equiv="Cache-Control" content="no-cache">
  628. <meta http-equiv="Expires" content="0">
  629. <!--utf-8-->
  630. <meta http-equiv="content-type" content="text/html;charset=utf-8">
  631. <!-- viewport的<meta>标签,这个标签可以修改在大部分的移动设备上面的显示,为了确保适当的绘制和触屏缩放。-->
  632. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  633. <link rel="shortcut icon" href="https://test.dvema.com/web/images/favicon.ico" type="image/x-icon" charset="utf-8"/>
  634. <title>Trading particulars</title>
  635. <style>
  636. .title_head{
  637. height: 50px;
  638. border-radius: 5px;
  639. background-color: #c3c6c7;
  640. text-align: center;
  641. line-height: 50px;
  642. }
  643. .content{
  644. text-align: center;
  645. margin-top: 50px;
  646. font-size: 20px;
  647. color : #ec7648
  648. }
  649. .content_img{
  650. width: 60px;
  651. height: 60px;
  652. }
  653. .bottom{
  654. margin-bottom: 10px;
  655. margin-top: 250px;
  656. color : #ec7648
  657. }
  658. .bottom_div{
  659. border: 1px solid #ec7648;
  660. line-height: 38px;
  661. text-align: center;
  662. width: 100px;
  663. height: 38px;
  664. border-radius: 5px;
  665. }
  666. .bottom_div:hover{
  667. background-color: #dde4e2;
  668. }
  669. </style>
  670. </head>
  671. <body>
  672. <div class="title_head">Trading particulars</div>
  673. <div class="content">
  674. <p >
  675. <img src="https://test.dvema.com/web/images/failed.jpg" class="content_img">
  676. <br />
  677. Payment failure
  678. </p>
  679. </div>
  680. <center class="bottom">
  681. <div class="bottom_div" onclick="payOKButton()">
  682. Finish
  683. </div>
  684. </center>
  685. <script> // 点击付款成功按钮
  686. function payOKButton() {
  687. // 复杂数据
  688. console.log('success')
  689. window.location.href="https://www.baidu.com?page=closePage";
  690. }
  691. </script>
  692. </body>
  693. </html>
  694. '''
  695. return response
  696. def do_pay_ok(self, request_dict):
  697. response = HttpResponse()
  698. paytype = request_dict.get('paytype', None)
  699. lang = request_dict.get('lang', None)
  700. showtitle = "支付成功"
  701. if paytype == "10" :
  702. showtitle = "成功体验云存"
  703. if paytype == "11":
  704. showtitle = "兑换成功"
  705. wancheng = '完成'
  706. if lang != 'cn':
  707. showtitle = "Payment successful"
  708. if paytype == "10":
  709. showtitle = "Successful experience of cloud storage"
  710. if paytype == "11":
  711. showtitle = "Successful exchange"
  712. wancheng = 'complete'
  713. response.content = '''
  714. <html>
  715. <head>
  716. <!--浏览器不缓存-->
  717. <meta http-equiv="Pragma" content="no-cache">
  718. <meta http-equiv="Cache-Control" content="no-cache">
  719. <meta http-equiv="Expires" content="0">
  720. <!--utf-8-->
  721. <meta http-equiv="content-type" content="text/html;charset=utf-8">
  722. <!-- viewport的<meta>标签,这个标签可以修改在大部分的移动设备上面的显示,为了确保适当的绘制和触屏缩放。-->
  723. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  724. <link rel="shortcut icon" href="https://test.dvema.com/web/images/favicon.ico" type="image/x-icon" charset="utf-8">
  725. <title>''' + showtitle + '''</title>
  726. <style>
  727. .title_head{
  728. height: 50px;
  729. border-radius: 5px;
  730. background-color: #c3c6c7;
  731. text-align: center;
  732. line-height: 50px;
  733. }
  734. .content{
  735. text-align: center;
  736. margin-top: 50px;
  737. font-size: 15px;
  738. color:#0000008A;
  739. }
  740. .content_img{
  741. margin-bottom:15px;
  742. width: 60px;
  743. height: 60px;
  744. }
  745. .bottom{
  746. margin-bottom: 10px;
  747. margin-top: 250px;
  748. color : white;
  749. }
  750. .bottom_div{
  751. border: 1px solid #68c9c5;
  752. line-height: 38px;
  753. text-align: center;
  754. width: 100px;
  755. height: 38px;
  756. border-radius: 30px;
  757. background-color:#68c9c5;
  758. }
  759. .bottom_div:hover{
  760. background-color: #dde4e2;
  761. }
  762. </style>
  763. </head>
  764. <body style="" rlt="1" inmaintabuse="true">
  765. <div class="content">
  766. <p>
  767. <img src="https://test.dvema.com/web/images/success.png" class="content_img">
  768. <br>
  769. ''' + showtitle + '''
  770. </p>
  771. </div>
  772. <center class="bottom">
  773. <div class="bottom_div" onclick="payOKButton()">
  774. '''+wancheng+'''
  775. </div>
  776. </center>
  777. <script src="//hm.baidu.com/hm.js?eaa57ca47dacb4ad4f5a257001a3457c"></script><script> // 点击付款成功按钮
  778. function payOKButton() {
  779. // 复杂数据
  780. console.log('success')
  781. window.location.href="https://www.baidu.com?page=closePage"
  782. }
  783. </script>
  784. <div id="qds" style="display:none;"></div></body></html>
  785. '''
  786. return response
  787. def do_pay_by_ali_callback(self, request):
  788. response = ResponseObject()
  789. data = request.POST.dict()
  790. # logger = logging.getLogger('log')
  791. try:
  792. passback_params = data["passback_params"]
  793. parmap = dict([(k, v[0]) for k, v in parse_qs(unquote(passback_params)).items()])
  794. lang = parmap["lang"]
  795. signature = data["sign"]
  796. data.pop('sign')
  797. orderID = data['out_trade_no']
  798. order_qs = Order_Model.objects.filter(orderID=orderID, status=0)
  799. aliPayObj = AliPayObject()
  800. alipay = aliPayObj.conf()
  801. success = alipay.verify(data, signature)
  802. if success and data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
  803. print("trade succeed")
  804. nowTime = int(time.time())
  805. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  806. "userID__userID", "userID__username")
  807. userid = order_list[0]['userID__userID']
  808. username = order_list[0]['userID__username']
  809. UID = order_list[0]['UID']
  810. channel = order_list[0]['channel']
  811. rank = order_list[0]['rank']
  812. smqs = Store_Meal.objects.filter(id=rank). \
  813. values("day", "bucket_id", "bucket__storeDay", "expire")
  814. bucketId = smqs[0]['bucket_id']
  815. if not smqs.exists():
  816. return response.json(173)
  817. ubqs = UID_Bucket.objects.filter(uid=UID).values("id", "bucket_id", "bucket__storeDay", "bucket__region",
  818. "endTime", "use_status")
  819. expire = smqs[0]['expire']
  820. if order_list[0]['isSelectDiscounts'] == 1:
  821. expire = smqs[0]['expire'] * 2
  822. with transaction.atomic():
  823. if ubqs.exists():
  824. ubq = ubqs[0]
  825. if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId: #套餐使用中并且相同套餐叠加过期时间
  826. endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
  827. UID_Bucket.objects.filter(id=ubq['id']).update \
  828. (uid=UID, channel=channel, bucket_id=bucketId,
  829. endTime=endTime, updateTime=nowTime)
  830. else: #已过期或者不相同的套餐加入未使用的关联套餐表
  831. has_unused = Unused_Uid_Meal.objects.filter(uid=UID, bucket_id=bucketId).values("id")
  832. nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
  833. if has_unused.exists():
  834. Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
  835. else:
  836. Unused_Uid_Meal.objects.create(uid=UID,channel=channel,addTime=nowTime,num=nums,
  837. expire=smqs[0]['expire'],bucket_id=bucketId)
  838. UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
  839. uid_bucket_id = ubq['id']
  840. else:
  841. endTime = CommonService.calcMonthLater(expire)
  842. ub_cqs = UID_Bucket.objects.create \
  843. (uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
  844. updateTime=nowTime,use_status=1)
  845. uid_bucket_id = ub_cqs.id
  846. dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
  847. if dvq.exists():
  848. dvq_set_update_dict = {
  849. 'vodPrimaryUserID': userid,
  850. 'vodPrimaryMaster': username
  851. }
  852. dvq.update(**dvq_set_update_dict)
  853. order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id)
  854. sys_msg_text_list = ['成功购买云存', 'Successful purchase of cloud storage']
  855. self.do_vod_msg_Notice(UID, channel, userid, lang, sys_msg_text_list)
  856. red_url = "{SERVER_DOMAIN}web/paid2/success.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
  857. if lang != 'cn':
  858. red_url = "{SERVER_DOMAIN}web/paid2/en_success.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
  859. return HttpResponseRedirect(red_url)
  860. return response.json(0, signature)
  861. except Exception as e:
  862. if order_qs:
  863. order_qs.update(status=10)
  864. red_url = "{SERVER_DOMAIN}web/paid2/fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
  865. if lang != 'cn':
  866. red_url = "{SERVER_DOMAIN}web/paid2/en_fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
  867. return HttpResponseRedirect(red_url)
  868. def do_pay_by_paypal_callback(self, request_dict, response):
  869. paymentId = request_dict.get('paymentId', None)
  870. PayerID = request_dict.get('PayerID', None)
  871. orderID = request_dict.get('orderID', None)
  872. lang = request_dict.get('lang', None)
  873. try:
  874. order_qs = Order_Model.objects.filter(orderID=orderID, status=0)
  875. if not orderID:
  876. red_url = "{SERVER_DOMAIN}web/paid2/fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
  877. if lang != 'cn':
  878. red_url = "{SERVER_DOMAIN}web/paid2/en_fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
  879. return HttpResponseRedirect(red_url)
  880. # else:
  881. # order_qs.update(status=9)
  882. paypalrestsdk.configure(PAYPAL_CRD)
  883. # ID of the payment. This ID is provided when creating payment.
  884. payment = paypalrestsdk.Payment.find(paymentId)
  885. payres = payment.execute({"payer_id": PayerID})
  886. print(payres)
  887. if not payres:
  888. red_url = "{SERVER_DOMAIN}web/paid2/fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
  889. if lang != 'cn':
  890. red_url = "{SERVER_DOMAIN}web/paid2/en_fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
  891. return HttpResponseRedirect(red_url)
  892. print("Payment execute successfully")
  893. nowTime = int(time.time())
  894. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  895. "userID__userID",
  896. "userID__username")
  897. userid = order_list[0]['userID__userID']
  898. username = order_list[0]['userID__username']
  899. UID = order_list[0]['UID']
  900. channel = order_list[0]['channel']
  901. rank = order_list[0]['rank']
  902. smqs = Store_Meal.objects.filter(id=rank). \
  903. values("day", "bucket_id", "bucket__storeDay", "expire")
  904. bucketId = smqs[0]['bucket_id']
  905. if not smqs.exists():
  906. return response.json(173)
  907. # ##
  908. ubqs = UID_Bucket.objects.filter(uid=UID).values("id", "bucket_id", "bucket__storeDay", "bucket__region",
  909. "endTime", "use_status")
  910. expire = smqs[0]['expire']
  911. if order_list[0]['isSelectDiscounts'] == 1:
  912. expire = smqs[0]['expire'] * 2
  913. with transaction.atomic():
  914. if ubqs.exists():
  915. ubq = ubqs[0]
  916. if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId: #套餐使用中并且相同套餐叠加过期时间
  917. endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
  918. UID_Bucket.objects.filter(id=ubq['id']).update \
  919. (uid=UID, channel=channel, bucket_id=bucketId,
  920. endTime=endTime, updateTime=nowTime)
  921. else: #已过期或者不相同的套餐加入未使用的关联套餐表
  922. has_unused = Unused_Uid_Meal.objects.filter(uid=UID, bucket_id=bucketId).values("id")
  923. nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
  924. if has_unused.exists():
  925. Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
  926. else:
  927. Unused_Uid_Meal.objects.create(uid=UID,channel=channel,addTime=nowTime,num=nums,
  928. expire=smqs[0]['expire'],bucket_id=bucketId)
  929. UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
  930. uid_bucket_id = ubq['id']
  931. else:
  932. endTime = CommonService.calcMonthLater(expire)
  933. ub_cqs = UID_Bucket.objects.create \
  934. (uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
  935. updateTime=nowTime,use_status=1)
  936. uid_bucket_id = ub_cqs.id
  937. dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
  938. if dvq.exists():
  939. dvq_set_update_dict = {
  940. 'vodPrimaryUserID': userid,
  941. 'vodPrimaryMaster': username
  942. }
  943. dvq.update(**dvq_set_update_dict)
  944. order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id)
  945. sys_msg_text_list = ['成功购买云存','Successful purchase of cloud storage']
  946. self.do_vod_msg_Notice(UID, channel, userid, lang, sys_msg_text_list)
  947. # return response.json(0)
  948. red_url = "{SERVER_DOMAIN}web/paid2/success.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
  949. if lang != 'cn':
  950. red_url = "{SERVER_DOMAIN}web/paid2/en_success.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
  951. return HttpResponseRedirect(red_url)
  952. except Exception as e:
  953. print(repr(e))
  954. if order_qs:
  955. order_qs.update(status=10)
  956. red_url = "{SERVER_DOMAIN}web/paid2/fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
  957. if lang != 'cn':
  958. red_url = "{SERVER_DOMAIN}web/paid2/en_fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
  959. return HttpResponseRedirect(red_url)
  960. def do_pay_by_wechat_callback(self, request, response):
  961. logger = logging.getLogger('log')
  962. try:
  963. pay = WechatPayObject()
  964. data = pay.weixinpay_call_back(request.body)
  965. attach = data["attach"]
  966. parmap = dict([(k, v[0]) for k, v in parse_qs(unquote(attach)).items()])
  967. lang = parmap["lang"]
  968. trade_status = data['result_code'] # 业务结果 SUCCESS/FAIL
  969. out_trade_no = data['out_trade_no'] # 商户订单号
  970. order_qs = Order_Model.objects.filter(orderID=out_trade_no, status=0)
  971. if trade_status == "SUCCESS":
  972. logger.info('微信回调返回值 进来了。')
  973. check_sign = pay.get_notifypay(data)
  974. if not check_sign:
  975. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '签名失败'}))
  976. logger.info('签名成功')
  977. orderID = out_trade_no
  978. print("进来了,微信支付成功回调")
  979. nowTime = int(time.time())
  980. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  981. "userID__userID", "userID__username")
  982. userid = order_list[0]['userID__userID']
  983. username = order_list[0]['userID__username']
  984. UID = order_list[0]['UID']
  985. channel = order_list[0]['channel']
  986. rank = order_list[0]['rank']
  987. smqs = Store_Meal.objects.filter(id=rank). \
  988. values("day", "bucket_id", "bucket__storeDay", "expire")
  989. bucketId = smqs[0]['bucket_id']
  990. if not smqs.exists():
  991. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '套餐不存在'}))
  992. # ##
  993. ubqs = UID_Bucket.objects.filter(uid=UID).values("id", "bucket_id", "bucket__storeDay",
  994. "bucket__region", "endTime", "use_status")
  995. expire = smqs[0]['expire']
  996. if order_list[0]['isSelectDiscounts'] == 1:
  997. expire = smqs[0]['expire'] * 2
  998. with transaction.atomic():
  999. if ubqs.exists():
  1000. ubq = ubqs[0]
  1001. if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId: #套餐使用中并且相同套餐叠加过期时间
  1002. endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
  1003. UID_Bucket.objects.filter(id=ubq['id']).update \
  1004. (uid=UID, channel=channel, bucket_id=bucketId,
  1005. endTime=endTime, updateTime=nowTime)
  1006. else: #已过期或者不相同的套餐加入未使用的关联套餐表
  1007. has_unused = Unused_Uid_Meal.objects.filter(uid=UID, bucket_id=bucketId).values("id")
  1008. nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
  1009. if has_unused.exists():
  1010. Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
  1011. else:
  1012. Unused_Uid_Meal.objects.create(uid=UID,channel=channel,addTime=nowTime,num=nums,
  1013. expire=smqs[0]['expire'],bucket_id=bucketId)
  1014. UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
  1015. uid_bucket_id = ubq['id']
  1016. else:
  1017. endTime = CommonService.calcMonthLater(expire)
  1018. ub_cqs = UID_Bucket.objects.create \
  1019. (uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
  1020. updateTime=nowTime,use_status=1)
  1021. uid_bucket_id = ub_cqs.id
  1022. dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
  1023. if dvq.exists():
  1024. dvq_set_update_dict = {
  1025. 'vodPrimaryUserID': userid,
  1026. 'vodPrimaryMaster': username
  1027. }
  1028. dvq.update(**dvq_set_update_dict)
  1029. order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id)
  1030. sys_msg_text_list = ['成功购买云存', 'Successful purchase of cloud storage']
  1031. self.do_vod_msg_Notice(UID, channel, userid, lang, sys_msg_text_list)
  1032. return HttpResponse(pay.xml_to_dict({'return_code': 'SUCCESS', 'return_msg': 'OK'}))
  1033. else:
  1034. order_qs.update(status=10)
  1035. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '参数格式校验错误'}))
  1036. except Exception as e:
  1037. if order_qs:
  1038. order_qs.update(status=10)
  1039. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': repr(e)}))
  1040. def do_create_pay_order(self, request_dict, userID, ip, response):
  1041. uid = request_dict.get('uid', None)
  1042. channel = request_dict.get('channel', None)
  1043. pay_type = int(request_dict.get('pay_type', None))
  1044. rank = request_dict.get('rank', None)
  1045. is_select_discount = request_dict.get('is_select_discount', 0)
  1046. lang = request_dict.get('lang', 0)
  1047. if not uid or not channel or not pay_type or not rank:
  1048. return response.json(444)
  1049. dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1).values(
  1050. 'vodPrimaryUserID',
  1051. 'vodPrimaryMaster')
  1052. if not dv_qs.exists():
  1053. return response.json(12)
  1054. dvq = Device_Info.objects.filter(UID=uid)
  1055. dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  1056. if dvq.exists():
  1057. if dvq[0]['vodPrimaryUserID'] != userID:
  1058. return response.json(10033)
  1059. nowTime = int(time.time())
  1060. # uq = UID_Bucket.objects.filter(uid=uid,endTime__gt=str(nowTime)).values('endTime')
  1061. # if uq.exists():
  1062. # return response.json(10033)
  1063. # if dv_qs[0]['vodPrimaryUserID'] != '' and dv_qs[0]['vodPrimaryUserID'] != userID:
  1064. # return response.json(10033)
  1065. smqs = Store_Meal.objects.filter(id=rank, pay_type=pay_type, lang__lang=lang). \
  1066. values('currency', 'price', 'lang__content', 'day',
  1067. 'commodity_type', 'lang__title',
  1068. 'expire', 'commodity_code', 'discount_price')
  1069. if not smqs.exists():
  1070. return response.json(173)
  1071. currency = smqs[0]['currency']
  1072. price = smqs[0]['price']
  1073. if is_select_discount == '1':
  1074. price = float(smqs[0]['price']) + float(smqs[0]['discount_price'])
  1075. content = smqs[0]['lang__content']
  1076. day = smqs[0]['day']
  1077. commodity_code = smqs[0]['commodity_code']
  1078. commodity_type = smqs[0]['commodity_type']
  1079. # ubqs = UID_Bucket.objects.filter(uid=uid, channel=channel, endTime__gte=nowTime). \
  1080. # values("bucket__storeDay", "bucket__region", "endTime")
  1081. # if ubqs.exists():
  1082. # ubqs_count = ubqs.count()
  1083. # ubq = ubqs[ubqs_count - 1, ubqs_count]
  1084. # new_starTime = ubq['endTime'] + 1
  1085. orderID = CommonService.createOrderID()
  1086. if pay_type == 1:
  1087. cal_url = "{SERVER_DOMAIN}web/paid2/fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
  1088. if lang != 'cn':
  1089. cal_url = "{SERVER_DOMAIN}web/paid2/en_fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
  1090. call_sub_url = "{SERVER_DOMAIN}cloudstorage/dopaypalcallback?orderID={orderID}&lang={lang}". \
  1091. format(SERVER_DOMAIN=SERVER_DOMAIN, orderID=orderID, lang=lang)
  1092. # call_sub_url = "http://binbin.uicp.vip/cloudstorage/dopaypalcallback?orderID={orderID}".format(
  1093. # SERVER_DOMAIN=SERVER_DOMAIN, orderID=orderID)
  1094. call_clc_url = cal_url
  1095. paypalrestsdk.configure(PAYPAL_CRD)
  1096. payment = paypalrestsdk.Payment({
  1097. "intent": "sale",
  1098. "payer": {"payment_method": "paypal"},
  1099. "redirect_urls": {"return_url": call_sub_url, "cancel_url": call_clc_url},
  1100. "transactions": [{
  1101. "item_list": {"items": [
  1102. {"name": "Cloud video", "sku": "1", "price": price, "currency": "USD", "quantity": 1}]},
  1103. "amount": {"total": price, "currency": currency},
  1104. "description": content}]})
  1105. if payment.create():
  1106. print("Payment created successfully")
  1107. else:
  1108. print(payment.error)
  1109. return response.json(10, payment.error)
  1110. print(payment)
  1111. for link in payment.links:
  1112. if link.rel == "approval_url":
  1113. approval_url = str(link.href)
  1114. print("Redirect for approval: %s" % (approval_url))
  1115. Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
  1116. desc=content, payType=pay_type, payTime=nowTime,
  1117. price=price, currency=currency, addTime=nowTime, updTime=nowTime,
  1118. pay_url=approval_url, isSelectDiscounts=is_select_discount,
  1119. commodity_code=commodity_code, commodity_type=commodity_type,
  1120. rank_id=rank)
  1121. return response.json(0, {"redirectUrl": approval_url, "orderID": orderID})
  1122. return response.json(10, 'generate_order_false')
  1123. elif pay_type == 2:
  1124. try:
  1125. aliPayObj = AliPayObject()
  1126. alipay = aliPayObj.conf()
  1127. subject = smqs[0]['lang__title'] + smqs[0]['lang__content']
  1128. # biz_content = {
  1129. # "subject": subject,
  1130. # "out_trade_no": orderID,
  1131. # "total_amount": price,
  1132. # "product_code": "QUICK_WAP_PAY",
  1133. # "quit_url": "{SERVER_DOMAIN}web/paid2/fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
  1134. # # "qr_pay_mode":4
  1135. # }
  1136. order_string = alipay.api_alipay_trade_wap_pay(
  1137. out_trade_no=orderID,
  1138. total_amount=price,
  1139. subject=subject,
  1140. return_url="{SERVER_DOMAIN}web/paid2/success.html".format(SERVER_DOMAIN=SERVER_DOMAIN),
  1141. notify_url="{SERVER_DOMAIN_SSL}cloudstorage/doalicallback".format(
  1142. SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL),
  1143. quit_url="{SERVER_DOMAIN}web/paid2/fail.html".format(SERVER_DOMAIN=SERVER_DOMAIN),
  1144. passback_params=quote("lang="+lang)
  1145. # return_url="http://192.168.136.40/cloudstorage/payOK",
  1146. # notify_url="http://192.168.136.40/cloudstorage/aliPayCallback"
  1147. )
  1148. except Exception as e:
  1149. print(repr(e))
  1150. return response.json(10, repr(e))
  1151. else:
  1152. if order_string:
  1153. redirectUrl = aliPayObj.alipay_prefix + order_string
  1154. print('---------tttt')
  1155. print(redirectUrl)
  1156. Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
  1157. desc=content, payType=pay_type, payTime=nowTime,
  1158. price=price, currency=currency, addTime=nowTime, updTime=nowTime,
  1159. pay_url=redirectUrl, isSelectDiscounts=is_select_discount,
  1160. commodity_code=commodity_code, commodity_type=commodity_type,
  1161. rank_id=rank)
  1162. return JsonResponse(status=200, data={'result_code': 0, 'reason': 'success',
  1163. 'result': {"redirectUrl": redirectUrl, "orderID": orderID},
  1164. 'error_code': 0})
  1165. else:
  1166. return response.json(10, '生成订单错误.')
  1167. elif pay_type == 3:
  1168. pay = WechatPayObject()
  1169. notify_url = "{SERVER_DOMAIN_SSL}cloudstorage/dowechatnotify".format(
  1170. SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  1171. # 获取参数
  1172. response = ResponseObject()
  1173. parameter_dict = pay.get_parameter(orderID, content, float(price) * 100, ip, notify_url, quote("lang="+lang))
  1174. print('parameter_dict', parameter_dict)
  1175. # parameter_dict 参数中获取MWEB_URL 调转页面在路径后面添加redirect_url
  1176. # 统一调用接口
  1177. response = pay.re_finall(orderid=orderID)
  1178. if not response:
  1179. return response.json(10, '生成订单错误.')
  1180. # 回调函数
  1181. Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
  1182. desc=content, payType=pay_type, payTime=nowTime,
  1183. price=price, currency=currency, addTime=nowTime, updTime=nowTime,
  1184. pay_url=notify_url, isSelectDiscounts=is_select_discount,
  1185. commodity_code=commodity_code, commodity_type=commodity_type, rank_id=rank)
  1186. return JsonResponse(status=200, data={'result_code': 0, 'reason': 'success',
  1187. 'result': response,
  1188. 'orderId': orderID,
  1189. 'error_code': 0})
  1190. # 调起支付接口
  1191. # 生成体验订单
  1192. def do_experience_order(self, request_dict, userID, response):
  1193. uid = request_dict.get('uid', None)
  1194. channel = request_dict.get('channel', None)
  1195. commodity_code = request_dict.get('commodity_code', None)
  1196. pay_type = int(request_dict.get('pay_type', None))
  1197. rank = request_dict.get('rank', None)
  1198. cdk = request_dict.get('cdk', None)
  1199. lang = request_dict.get('lang', None)
  1200. if cdk != None and pay_type == 11:
  1201. cdk_qs = CDKcontextModel.objects.filter(cdk=cdk).values('is_activate', 'rank__id', 'rank__commodity_code')
  1202. if not cdk_qs.exists():
  1203. return response.json(10040)
  1204. if cdk_qs[0]['is_activate'] == 1:
  1205. return response.json(10039)
  1206. rank = cdk_qs[0]['rank__id']
  1207. commodity_code = cdk_qs[0]['rank__commodity_code']
  1208. if uid == None or channel == None or commodity_code == None or pay_type == None or rank == None:
  1209. return response.json(13, '参数有误.')
  1210. dvq = Device_Info.objects.filter(UID=uid)
  1211. dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  1212. if dvq.exists():
  1213. if dvq[0]['vodPrimaryUserID'] != userID:
  1214. if pay_type == 10:
  1215. return response.json(10035)
  1216. if pay_type == 11:
  1217. return response.json(10036)
  1218. dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1)
  1219. if not dv_qs.exists():
  1220. return response.json(12)
  1221. orderID = CommonService.createOrderID()
  1222. nowTime = int(time.time())
  1223. smqs = Store_Meal.objects.filter(id=rank,lang__lang=lang). \
  1224. values("day", "bucket_id", "bucket__storeDay", "expire", 'lang__content', 'price', 'currency', 'commodity_type')
  1225. if not smqs.exists():
  1226. return response.json(173)
  1227. bucketId = smqs[0]['bucket_id']
  1228. # ##
  1229. ubqs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id", "bucket__storeDay", "bucket__region",
  1230. "endTime", "use_status")
  1231. expire = smqs[0]['expire']
  1232. try:
  1233. with transaction.atomic():
  1234. if ubqs.exists():
  1235. ubq = ubqs[0]
  1236. if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId: #套餐使用中并且相同套餐叠加过期时间
  1237. endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
  1238. UID_Bucket.objects.filter(id=ubq['id']).update \
  1239. (uid=uid, channel=channel, bucket_id=bucketId,
  1240. endTime=endTime, updateTime=nowTime)
  1241. else: #已过期或者不相同的套餐加入未使用的关联套餐表
  1242. has_unused = Unused_Uid_Meal.objects.filter(uid=uid, bucket_id=bucketId).values("id")
  1243. nums = 1
  1244. if has_unused.exists():
  1245. Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
  1246. else:
  1247. Unused_Uid_Meal.objects.create(uid=uid,channel=channel,addTime=nowTime,num=nums,
  1248. expire=smqs[0]['expire'],bucket_id=bucketId)
  1249. UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
  1250. uid_bucket_id = ubq['id']
  1251. else:
  1252. endTime = CommonService.calcMonthLater(expire)
  1253. ub_cqs = UID_Bucket.objects.create \
  1254. (uid=uid, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
  1255. updateTime=nowTime,use_status=1)
  1256. uid_bucket_id = ub_cqs.id
  1257. Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
  1258. desc=smqs[0]['lang__content'], payType=pay_type, payTime=nowTime,
  1259. price=smqs[0]['price'], currency=smqs[0]['currency'], addTime=nowTime,
  1260. updTime=nowTime,
  1261. pay_url="体验版",
  1262. commodity_code=commodity_code, commodity_type=smqs[0]['commodity_type'],
  1263. rank_id=rank, status=1, uid_bucket_id=uid_bucket_id)
  1264. duq = Device_User.objects.filter(userID=userID).values('username')
  1265. dvq = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
  1266. if dvq.exists():
  1267. dvq_set_update_dict = {
  1268. 'vodPrimaryUserID': userID,
  1269. 'vodPrimaryMaster': duq[0]['username']
  1270. }
  1271. dvq.update(**dvq_set_update_dict)
  1272. sys_msg_text_list = ['成功购买云存', 'Successful purchase of cloud storage']
  1273. # return response.json(0)
  1274. returnurl = "{SERVER_DOMAIN}cloudstorage/payOK?lang={lang}".format(SERVER_DOMAIN=SERVER_DOMAIN,lang=lang)
  1275. if pay_type == 10:
  1276. ExperienceContextModel.objects.create(
  1277. experience_type=0,
  1278. uid=uid,
  1279. do_time=nowTime
  1280. )
  1281. returnurl = "{SERVER_DOMAIN}cloudstorage/payOK?paytype=10&lang={lang}".format(SERVER_DOMAIN=SERVER_DOMAIN,lang=lang)
  1282. sys_msg_text_list = ['成功体验云存', 'Successful experience of cloud storage']
  1283. if pay_type == 11:
  1284. update_dict = {}
  1285. update_dict['is_activate'] = 1
  1286. update_dict['order'] = orderID
  1287. CDKcontextModel.objects.filter(cdk=cdk).update(**update_dict)
  1288. returnurl = "{SERVER_DOMAIN}cloudstorage/payOK?paytype=11&lang={lang}".format(SERVER_DOMAIN=SERVER_DOMAIN,lang=lang)
  1289. sys_msg_text_list = ['成功兑换云存', 'Successful exchange of cloud storage']
  1290. self.do_vod_msg_Notice(uid, channel, userID, lang, sys_msg_text_list)
  1291. result = returnurl
  1292. return response.json(0, result)
  1293. except Exception:
  1294. return response.json(474)
  1295. # red_url =
  1296. # return JsonResponse(status=200, data={'red_url': red_url})
  1297. # return HttpResponseRedirect(red_url)
  1298. # 重置设备云存体验
  1299. def do_experience_reset(self, request_dict, userID, response):
  1300. bid = request_dict.get("id", None)
  1301. ubq = UID_Bucket.objects.filter(id=bid)
  1302. if ubq:
  1303. eq = ExperienceContextModel.objects.filter(uid=ubq[0].uid)
  1304. if eq:
  1305. eq.delete()
  1306. Order_Model.objects.filter(uid_bucket_id=bid).delete()
  1307. ubq.delete()
  1308. else:
  1309. return response.json(10007)
  1310. else:
  1311. return response.json(0, '重置云存体验失败')
  1312. return response.json(0, '重置云存体验成功')
  1313. def deleteVodList(self, request_dict, userID, response):
  1314. uid = request_dict.get('uid', None)
  1315. dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1) \
  1316. .values('vodPrimaryUserID')
  1317. if not dv_qs.exists() or dv_qs[0]['vodPrimaryUserID'] != userID:
  1318. return response.json(12)
  1319. vod_id_list = json.loads(request_dict.get('vod_id_list', None))
  1320. is_del_all = request_dict.get('is_del_all', 0)
  1321. try:
  1322. if is_del_all == 1:
  1323. VodHlsModel.objects.filter(uid=uid).delete()
  1324. else:
  1325. if type(vod_id_list).__name__ != 'list':
  1326. return response.json(444)
  1327. VodHlsModel.objects.filter(id__in=vod_id_list).delete()
  1328. except Exception as e:
  1329. return response.json(424, repr(e))
  1330. else:
  1331. return response.json(0)
  1332. # 设备关联套餐列表
  1333. def device_commodity(self, request_dict, userID, response):
  1334. uid = request_dict.get('uid', None)
  1335. lang = request_dict.get('lang', None)
  1336. dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1) \
  1337. .values('vodPrimaryUserID')
  1338. if not dv_qs.exists() or dv_qs[0]['vodPrimaryUserID'] != userID:
  1339. return response.json(12)
  1340. now_time = int(time.time())
  1341. bucket_id_list = []
  1342. store_list = []
  1343. uid_bucket = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time).values("id", "uid","bucket__content",
  1344. "use_status","endTime","has_unused","bucket__id")
  1345. if not uid_bucket:
  1346. return response.json(10030)
  1347. uid_bucket[0]['storage'] = 0
  1348. has_unused = uid_bucket[0]['has_unused']
  1349. del uid_bucket[0]['has_unused']
  1350. store_list.append(uid_bucket[0])
  1351. bucket_id_list.append(uid_bucket[0]['bucket__id'])
  1352. if has_unused == 1:
  1353. unuseds = Unused_Uid_Meal.objects.filter(uid=uid).annotate(unused_id=F('id')) \
  1354. .values("unused_id","uid","bucket__content","num","bucket__id","expire")
  1355. for ub in unuseds:
  1356. storage_time = ub['num'] * ub['expire']
  1357. storage = "{storage_time}个月".format(storage_time=storage_time)
  1358. unused_dict = {
  1359. "id":ub['unused_id'],
  1360. "uid":ub['uid'],
  1361. "bucket__content":ub['bucket__content'],
  1362. "use_status":0,
  1363. "endTime":0,
  1364. "bucket__id":ub['bucket__id'],
  1365. "storage":storage,
  1366. }
  1367. store_list.append(unused_dict)
  1368. bucket_id_list.append(ub['bucket__id'])
  1369. smqs = Store_Meal.objects.filter(bucket__id__in=bucket_id_list, lang__lang=lang).values('lang__lang','bucket__id','lang__title')
  1370. for index, value in enumerate(store_list):
  1371. for sm in smqs:
  1372. if value['bucket__id'] == sm['bucket__id']:
  1373. value['bucket__content'] = sm['lang__title']
  1374. return response.json(0, list(store_list))
  1375. # 提前使用设备关联套餐
  1376. def switch_device_commodity(self, request_dict, userID, response):
  1377. uid = request_dict.get('uid', None)
  1378. dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1) \
  1379. .values('vodPrimaryUserID')
  1380. if not dv_qs.exists() or dv_qs[0]['vodPrimaryUserID'] != userID:
  1381. return response.json(12)
  1382. unused_id = request_dict.get('switch_commodity_id', None)
  1383. if unused_id:
  1384. # 切换设备套餐关联
  1385. using_uid_bucket = UID_Bucket.objects.filter(uid=uid,has_unused=1).values("id", "uid", "endTime",
  1386. "bucket__content","addTime")
  1387. unuseds = Unused_Uid_Meal.objects.filter(id=unused_id).values("id","uid","channel","addTime","expire",
  1388. "num","bucket_id")
  1389. if not unuseds.exists() or not using_uid_bucket.exists():
  1390. return response.json(10030)
  1391. unused = unuseds[0]
  1392. nowTime = int(time.time())
  1393. try:
  1394. with transaction.atomic():
  1395. count_unused = Unused_Uid_Meal.objects.filter(uid=uid).count()
  1396. has_unused = 1 if count_unused>1 else 0
  1397. endTime = CommonService.calcMonthLater(unused['expire'] * unused['num'])
  1398. UID_Bucket.objects.filter(uid=uid).update(channel=unused['channel'],endTime=endTime,bucket_id=unused['bucket_id']
  1399. ,updateTime=nowTime,use_status=1, has_unused=has_unused)
  1400. Unused_Uid_Meal.objects.filter(id=unused_id).delete()
  1401. StsCrdModel.objects.filter(uid=uid).delete() # 删除sts记录
  1402. VodHlsModel.objects.filter(uid=uid).delete() # 删除播放列表,后期数据量多时应该考虑延后删除
  1403. except Exception:
  1404. return response.json(474)
  1405. return response.json(0)
  1406. return response.json(444)
  1407. # 云存操作系统消息
  1408. def do_vod_msg_Notice(self, uid, channel, userID, lang, sys_msg_text_list):
  1409. try:
  1410. logger = logging.getLogger('log')
  1411. logger.info('进来了')
  1412. # user = Device_User.objects.get(userID = userID)
  1413. # lang = user.language;
  1414. if lang == 'cn':
  1415. sys_msg_text = sys_msg_text_list[0]
  1416. else:
  1417. sys_msg_text = sys_msg_text_list[1]
  1418. nowTime = int(time.time())
  1419. create_data = {'userID_id': userID, 'msg': sys_msg_text, 'addTime': nowTime,
  1420. 'updTime': nowTime, 'uid': uid, 'eventType': 0}
  1421. SysMsgModel.objects.create(**create_data)
  1422. self.pushApp(nowTime, uid, channel, sys_msg_text)
  1423. logger.info('出去了')
  1424. except Exception as e:
  1425. return repr(e)
  1426. # 云存到期续费提醒 提前1天
  1427. def do_vod_msg_end(self, request_dict):
  1428. response = ResponseObject()
  1429. now_time = int(time.time())
  1430. list = UID_Bucket.objects.filter(Q(endTime__lte=(now_time - 3600 * 24)) & Q(endTime__gt=now_time)).values('id',
  1431. 'uid',
  1432. 'bucket__area','channel')
  1433. uq_list = []
  1434. ids = []
  1435. for ub in list:
  1436. ids.append(ub['id'])
  1437. oqlist = Order_Model.objects.filter(uid_bucket_id__in=ids).values('userID_id', 'uid_bucket_id')
  1438. for ub in list:
  1439. for oo in oqlist:
  1440. if ub['id'] == oo['uid_bucket_id']:
  1441. if ub['bucket__area'] == 'cn':
  1442. sys_msg_text = "云存即将过期,请您注意!"
  1443. else:
  1444. sys_msg_text = "Cloud storage is about to expire, please pay attention!"
  1445. uq_list.append(SysMsgModel(
  1446. userID_id=oo['userID_id'],
  1447. addTime=now_time,
  1448. updTime=now_time,
  1449. uid=ub['uid'],
  1450. eventType=0,
  1451. msg=sys_msg_text,
  1452. status=0
  1453. ))
  1454. self.pushApp(now_time, ub['uid'], ub['channel'], sys_msg_text)
  1455. SysMsgModel.objects.bulk_create(uq_list)
  1456. return response.json(0)
  1457. def pushApp(self, nowTime, uid, channel, sys_msg_text):
  1458. n_time = nowTime
  1459. kwag_args = {
  1460. 'uid': uid,
  1461. 'channel': channel,
  1462. 'event_type': 0,
  1463. 'n_time': n_time
  1464. }
  1465. # 从数据库查询出来
  1466. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  1467. values('token_val', 'app_type', 'appBundleId', 'm_code',
  1468. 'push_type', 'userID_id', 'userID__NickName',
  1469. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  1470. 'uid_set__channel')
  1471. print(uid_push_qs)
  1472. # 新建一个list接收数据
  1473. redis_list = []
  1474. # 把数据库数据追加进redis_list
  1475. for qs in uid_push_qs:
  1476. redis_list.append(qs)
  1477. nickname = redis_list[0]['uid_set__nickname']
  1478. for up in redis_list:
  1479. push_type = up['push_type']
  1480. appBundleId = up['appBundleId']
  1481. token_val = up['token_val']
  1482. lang = up['lang']
  1483. tz = up['tz']
  1484. if tz is None or tz == '':
  1485. tz = 0
  1486. package_title_config = FCM_CONFIG[appBundleId]
  1487. if appBundleId in package_title_config.keys():
  1488. msg_title = package_title_config[appBundleId] + '(' + nickname + ')'
  1489. else:
  1490. msg_title = nickname
  1491. # 发送内容
  1492. msg_text = sys_msg_text
  1493. kwag_args['appBundleId'] = appBundleId
  1494. kwag_args['token_val'] = token_val
  1495. kwag_args['msg_title'] = msg_title
  1496. kwag_args['msg_text'] = msg_text
  1497. push_server_status = 0
  1498. # 推送
  1499. if push_type == 0: # ios apns
  1500. try:
  1501. cli = apns2.APNSClient(mode=APNS_MODE,
  1502. client_cert=os.path.join(BASE_DIR,
  1503. APNS_CONFIG[appBundleId]['pem_path']))
  1504. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": 0, "msg": "",
  1505. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1",
  1506. "channel": channel}
  1507. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  1508. payload = apns2.Payload(alert=alert, custom=push_data)
  1509. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  1510. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  1511. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  1512. print(res.status_code)
  1513. if res.status_code == 200:
  1514. return res.status_code
  1515. else:
  1516. print('apns push fail')
  1517. print(res.reason)
  1518. return res.status_code
  1519. except (ValueError, ArithmeticError):
  1520. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  1521. except Exception as e:
  1522. print(repr(e))
  1523. return repr(e)
  1524. elif push_type == 1: # android gcm
  1525. try:
  1526. serverKey = FCM_CONFIG[appBundleId]
  1527. except Exception as e:
  1528. return 'serverKey abnormal'
  1529. push_service = FCMNotification(api_key=serverKey)
  1530. data = {"alert": "Motion ", "event_time": n_time, "event_type": 0, "msg": "",
  1531. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  1532. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  1533. message_body=msg_text, data_message=data,
  1534. extra_kwargs={
  1535. 'default_vibrate_timings': True,
  1536. 'default_sound': True,
  1537. 'default_light_settings': True
  1538. })
  1539. print('fcm push ing')
  1540. print(result)
  1541. return result
  1542. elif push_type == 2: # android jpush
  1543. print('do_jpush')
  1544. app_key = JPUSH_CONFIG[appBundleId]['Key']
  1545. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  1546. # 此处换成各自的app_key和master_secre
  1547. _jpush = jpush.JPush(app_key, master_secret)
  1548. push = _jpush.create_push()
  1549. # if you set the logging level to "DEBUG",it will show the debug logging.
  1550. # _jpush.set_logging("DEBUG")
  1551. # push.audience = jpush.all_
  1552. push.audience = jpush.registration_id(token_val)
  1553. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": 0, "msg": "",
  1554. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  1555. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  1556. big_text=msg_text, title=msg_title,
  1557. extras=push_data)
  1558. push.notification = jpush.notification(android=android)
  1559. push.platform = jpush.all_
  1560. res = push.send()
  1561. print(res)
  1562. return res.status_code
  1563. # 删除过期云存播放列表
  1564. def deleteVodHls(request):
  1565. # UID = 'DSXG7481JVA2JM94111A'
  1566. # channel = 1
  1567. # ubqs = UID_Bucket.objects.filter(uid=UID, channel=channel). \
  1568. # values("bucket_id", "endTime", "bucket__storeDay")
  1569. # nowTime = int(time.time())
  1570. # if ubqs.exists():
  1571. # ubqs_count = ubqs.count()
  1572. # ubq = ubqs[ubqs_count - 1, ubqs_count]
  1573. # new_starTime = ubq['endTime'] + 1
  1574. # print(new_starTime)
  1575. # exit()
  1576. #
  1577. # # ub_cqs = UID_Bucket.objects.create(uid=UID, channel=channel, bucket_id=bucketId,
  1578. # # endTime=new_starTime + addTime)
  1579. # # uid_bucket_id = ub_cqs.id
  1580. # exit()
  1581. response = ResponseObject()
  1582. i = int(request.GET.get('i', 5))
  1583. nowTime = int(time.time())
  1584. for i in range(i):
  1585. vh_qs = VodHlsModel.objects.filter(endTime__lte=str(nowTime))[0:10000]
  1586. id_list = vh_qs.values_list("id", flat=True)
  1587. print(id_list)
  1588. VodHlsModel.objects.filter(id__in=list(id_list)).delete()
  1589. return response.json(0)
  1590. # 更新过期云存关联套餐
  1591. def updateExpiredUidBucket(request):
  1592. response = ResponseObject()
  1593. now_time = int(time.time())
  1594. expired_uid_bucket = UID_Bucket.objects.filter(endTime__lte=now_time)
  1595. id_list = expired_uid_bucket.values_list("id", flat=True)
  1596. UID_Bucket.objects.filter(id__in=list(id_list)).update(use_status=2) # 更新过期云存关联套餐状态
  1597. return response.json(0)
  1598. # 如果云存关联套餐过期,更新未使用的关联套餐
  1599. def updateUnusedUidBucket(request):
  1600. response = ResponseObject()
  1601. now_time = int(time.time())
  1602. expired_uid_buckets = UID_Bucket.objects.filter(endTime__lte=now_time,has_unused=1).values("id","uid")[0:1000]
  1603. for expired_uid_bucket in expired_uid_buckets:
  1604. unuseds = Unused_Uid_Meal.objects.filter(uid=expired_uid_bucket['uid']).values("id","uid","channel","addTime","expire",
  1605. "num","bucket_id","userID_id").order_by('addTime')[0:1]
  1606. if not unuseds.exists():
  1607. continue
  1608. unused = unuseds[0]
  1609. try:
  1610. with transaction.atomic():
  1611. count_unused = Unused_Uid_Meal.objects.filter(uid=expired_uid_bucket['uid']).count()
  1612. has_unused = 1 if count_unused>1 else 0
  1613. endTime = CommonService.calcMonthLater(unused['expire'] * unused['num'])
  1614. UID_Bucket.objects.filter(uid=expired_uid_bucket['uid']).update(channel=unused['channel'],endTime=endTime,bucket_id=unused['bucket_id']
  1615. ,updateTime=now_time,use_status=1,userID_id=unused['userID_id'],
  1616. has_unused=has_unused)
  1617. Unused_Uid_Meal.objects.filter(id=unused['id']).delete()
  1618. StsCrdModel.objects.filter(uid=expired_uid_bucket['uid']).delete() # 删除sts记录
  1619. VodHlsModel.objects.filter(uid=expired_uid_bucket['uid']).delete() # 删除播放列表,后期数据量多时应该考虑延后删除
  1620. except Exception:
  1621. continue
  1622. # UID_Bucket.objects.filter(id__in=list(id_list)).update(use_status=2) # 更新过期云存关联套餐状态
  1623. return response.json(0)