CloudStorage.py 80 KB

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