CloudStorage.py 80 KB

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