CloudStorage.py 71 KB

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