CloudStorage.py 86 KB

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