CloudStorage.py 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001
  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. import sys
  30. from aliyunsdkcore import client
  31. from aliyunsdksts.request.v20150401 import AssumeRoleRequest
  32. from boto3.session import Session
  33. from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
  34. from django.db import transaction
  35. from django.views.generic.base import View
  36. import jwt
  37. from pyfcm import FCMNotification
  38. from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, OSS_ROLE_ARN, SERVER_DOMAIN, PAYPAL_CRD, \
  39. SERVER_DOMAIN_SSL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ARN, APNS_MODE, APNS_CONFIG, BASE_DIR, \
  40. JPUSH_CONFIG, FCM_CONFIG, OAUTH_ACCESS_TOKEN_SECRET
  41. from Controller.CheckUserData import DataValid
  42. from Model.models import Device_Info, Order_Model, Store_Meal, VodHlsModel, OssCrdModel, UID_Bucket, StsCrdModel, \
  43. ExperienceContextModel, Pay_Type, CDKcontextModel, Device_User, SysMassModel, SysMsgModel, UidPushModel, \
  44. Unused_Uid_Meal, UIDMainUser, UserModel, PromotionRuleModel, VideoPlaybackTimeModel, CloudLogModel, CouponModel, \
  45. VodBucketModel, UIDModel
  46. from Object.AWS.S3Email import S3Email
  47. from Object.AliPayObject import AliPayObject
  48. from Object.AliSmsObject import AliSmsObject
  49. from Object.RedisObject import RedisObject
  50. from Object.ResponseObject import ResponseObject
  51. from Object.TokenObject import TokenObject
  52. from Object.UidTokenObject import UidTokenObject
  53. from Service.CommonService import CommonService
  54. from Object.m3u8generate import PlaylistGenerator
  55. from Object.WechatPayObject import WechatPayObject
  56. from django.db.models import Q, F, Count
  57. from Controller.PaymentCycle import Paypal
  58. from decimal import Decimal
  59. from Ansjer.config import SERVER_TYPE
  60. from Service.ModelService import ModelService
  61. # SERVER_DOMAIN = 'http://test.dvema.com/'
  62. from Service.PayService import PaymentService
  63. '''
  64. 生成订单
  65. 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
  66. 开启开关
  67. http://test.dvema.com/cloudstorage/changevodstatus?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJleHAiOjE1ODk1MjM0OTIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCIsImxhbmciOiJlbiIsInVzZXIiOiIxMzExOTY1NzcxMyJ9.e2NdhJtbXrDngZTSmOX_52Y-oxyfUEXjZD_qNxg6VrU&uid=VVDHCVBYDKFMJRWA111A&channel=1&status=1
  68. # 获取播放列表
  69. http://localhost:8077/cloudstorage/queryvodlist?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJleHAiOjE1ODk1MjM0OTIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCIsImxhbmciOiJlbiIsInVzZXIiOiIxMzExOTY1NzcxMyJ9.e2NdhJtbXrDngZTSmOX_52Y-oxyfUEXjZD_qNxg6VrU&uid=VVDHCVBYDKFMJRWA111A&startTime=1&endTime=1954687458&channel=1
  70. # 存储视频列表信息
  71. http://test.dvema.com/cloudstorage/storeplaylist?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJWVkRIQ1ZCWURLRk1KUldBMTExQSIsImNoYW5uZWwiOiIxIn0.eGwi5QKyrXi4WSKRbrUG7iFTChv_Utec2hSnqZkDKt8&time=1586940120&sec=20&fg=10
  72. # 获取订单列表
  73. http://localhost:8077/cloudstorage/queryorder?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJsYW5nIjoiZW4iLCJ1c2VyIjoiMTMxMTk2NTc3MTMiLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJleHAiOjE1ODk1OTIyNzh9.u211DHiMKg-pqhXv4b2yR__eNyOcSwBZCyPUGjsxFLU&page=1&line=10&uid=VVDHCVBYDKFMJRWA111A
  74. # commoditylist
  75. http://test.dvema.com/cloudstorage/commoditylist?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiIxNTY3NzU4MjE4NjE5MTM4MDAxMzgwMDAiLCJleHAiOjE1ODk1MjM0OTIsIm1fY29kZSI6IjEyMzQxMzI0MzIxNCIsImxhbmciOiJlbiIsInVzZXIiOiIxMzExOTY1NzcxMyJ9.e2NdhJtbXrDngZTSmOX_52Y-oxyfUEXjZD_qNxg6VrU
  76. '''
  77. # 设备信息添加
  78. class CloudStorageView(View):
  79. def get(self, request, *args, **kwargs):
  80. request.encoding = 'utf-8'
  81. operation = kwargs.get('operation')
  82. return self.validation(request.GET, request, operation)
  83. def post(self, request, *args, **kwargs):
  84. request.encoding = 'utf-8'
  85. operation = kwargs.get('operation')
  86. return self.validation(request.POST, request, operation)
  87. def validation(self, request_dict, request, operation):
  88. lang = request_dict.get('lang', 'en')
  89. response = ResponseObject(lang)
  90. if operation is None:
  91. return response.json(444, 'error path')
  92. elif operation == 'dopaypalcallback': # paypal支付回调
  93. return self.do_pay_by_paypal_callback(request_dict, response)
  94. elif operation == 'doalicallback': # 阿里支付回调
  95. return self.do_pay_by_ali_callback(request)
  96. elif operation == 'dowechatnotify': # 微信支付回调
  97. return self.do_pay_by_wechat_callback(request, response)
  98. elif operation == 'getsignsts': # 设备调用,获取sts令牌
  99. ip = CommonService.get_ip_address(request)
  100. return self.do_get_sign_sts(request_dict, ip, response)
  101. elif operation == 'storeplaylist': # 设备调用,设备把视频上传到s3,同时把视频数据信息传给服务器,服务器存储播放内容
  102. return self.do_store_playlist(request_dict, response)
  103. elif operation == 'signplaym3u8': # 根据sts播放m3u8 视频流
  104. return self.do_sign_play_m3u8(request_dict, response)
  105. elif operation == 'payOK': # 支付成功
  106. return self.do_pay_ok(request_dict)
  107. elif operation == 'vodMsgEnd': # 云存到期续费提醒 提前1天
  108. return self.do_vod_msg_end(request_dict)
  109. elif operation == 'vodMsgNotice': # 云存操作系统消息
  110. return self.do_vod_msg_Notice(request_dict)
  111. elif operation == 'doRefund': # 退款
  112. return self.do_refund(request_dict, response)
  113. else:
  114. token = request_dict.get('token', None)
  115. # 设备主键uid
  116. tko = TokenObject(token)
  117. # response.lang = tko.lang
  118. if tko.code != 0:
  119. return response.json(tko.code)
  120. userID = tko.userID
  121. if operation == 'createpayorder': # 创建支付订单
  122. ip = CommonService.get_ip_address(request)
  123. return self.do_create_pay_order(request_dict, userID, ip, response)
  124. elif operation == 'changevodstatus': # 修改云存状态,传送两个url,即getsignsts接口和storeplaylist接口
  125. return self.do_change_vod_status(request_dict, userID, response)
  126. elif operation == 'queryvodlist': # 获取视频播放列表
  127. return self.do_query_vod_list(request_dict, userID, response)
  128. elif operation == 'commoditylist': # 查询套餐列表
  129. return self.do_commodity_list(request_dict, userID, response)
  130. elif operation == 'queryorder': # 查询订单列表
  131. return self.do_query_order(request_dict, userID, response)
  132. elif operation == 'experienceorder': # 生成体验订单
  133. return self.do_experience_order(request_dict, userID, response)
  134. elif operation == 'experiencereset': # 重置设备云存体验
  135. return self.do_experience_reset(request_dict, userID, response)
  136. elif operation == 'deletevodlist': # 删除播放列表
  137. return self.deleteVodList(request_dict, userID, response)
  138. elif operation == 'devicecommodity': # 设备关联套餐列表
  139. return self.device_commodity(request_dict, userID, response)
  140. elif operation == 'switchdevicecommodity': # 提前使用设备关联套餐
  141. return self.switch_device_commodity(request_dict, userID, response)
  142. elif operation == 'hasvod': # APP的回放界面,日历表显示当天有无录像
  143. return self.has_vod(request_dict, userID, response)
  144. elif operation == 'videoPlaybackTime': # 记录app播放时间
  145. return self.videoPlaybackTime(request_dict, userID, response)
  146. else:
  147. return response.json(414)
  148. def do_query_order(self, request_dict, userID, response): # 查询订单列表
  149. status = request_dict.get('status', None)
  150. page = int(request_dict.get('page', None))
  151. line = int(request_dict.get('line', None))
  152. uid = request_dict.get('uid', None)
  153. order_qs = Order_Model.objects.filter(userID_id=userID)
  154. if status:
  155. order_qs = order_qs.filter(status=status)
  156. # 筛选指定设备id的订单
  157. if uid:
  158. order_qs = order_qs.filter(UID=uid)
  159. if not order_qs.exists():
  160. return response.json(173)
  161. # return response.json(10, '订单不存在')
  162. count = order_qs.count()
  163. order_ql = order_qs[(page - 1) * line:page * line]. \
  164. values("orderID", "UID", "channel", "desc", "price", "currency",
  165. "addTime", "updTime", "endTime", "pay_url", "payType",
  166. "status", "commodity_type", "commodity_code")
  167. order_list = list(order_ql)
  168. data = []
  169. nowTime = int(time.time())
  170. # 这里需要进行优化
  171. uid_list = []
  172. for od in order_list:
  173. uid_list.append(od['UID'])
  174. didqs = Device_Info.objects.filter(userID_id=userID, UID__in=uid_list). \
  175. values('id', 'UID', 'Type')
  176. for d in order_list:
  177. if d['status'] == 0:
  178. if d['addTime'] + 3600 < nowTime:
  179. d['status'] = 3
  180. for did in didqs:
  181. if d['UID'] == did['UID']:
  182. d['did'] = did['id']
  183. d['Type'] = did['Type']
  184. data.append(d)
  185. return response.json(0, {'data': data, 'count': count})
  186. def do_commodity_list(self, request_dict, userID, response): # 查询套餐列表
  187. mold = request_dict.get('mold', None)
  188. uid = request_dict.get('uid', None)
  189. lang = request_dict.get('lang', 'en')
  190. nowTime = int(time.time())
  191. # DVR/NVR设备暂不返回云存套餐列表
  192. device_info_qs = Device_Info.objects.filter(Q(UID=uid), Q(Type__lte=4) | Q(Type=10001))
  193. if device_info_qs.exists():
  194. return response.json(0)
  195. qs = Store_Meal.objects
  196. eq = ExperienceContextModel.objects.filter(uid=uid, experience_type=0).values('id')
  197. if mold:
  198. qs = qs.filter(bucket__mold=mold, lang__lang=lang)
  199. else:
  200. qs = qs.filter(lang__lang=lang)
  201. if eq:
  202. qs = qs.filter(~Q(pay_type='10'))
  203. else:
  204. qs = qs.filter(pay_type='10')
  205. qs = qs.filter(~Q(pay_type='11')) # 过滤不显示激活码套餐
  206. qs = qs.filter(is_show=0) # 过滤隐藏套餐
  207. # qs = qs.filter(id='11111111')
  208. # qs = qs.filter(bucket__region_id=regionObj.region_id) # 过滤大洲
  209. qs = qs.annotate(title=F('lang__title'), content=F('lang__content'),
  210. discount_content=F('lang__discount_content'))
  211. qs = qs.order_by('sort').values("id", "title", "content", "price", "day", "currency", "bucket__storeDay",
  212. "bucket__bucket", "bucket__area", "commodity_code",
  213. "commodity_type", "is_discounts", "virtual_price", "expire",
  214. "discount_price", "discount_content", "symbol", "cycle_config_id")
  215. if qs.exists():
  216. ql = list(qs)
  217. from operator import itemgetter
  218. from itertools import groupby
  219. ql.sort(key=itemgetter('bucket__area'))
  220. res = []
  221. for area, items in groupby(ql, key=itemgetter('bucket__area')):
  222. items_list = list(items)
  223. for key, val in enumerate(items_list):
  224. pay_types = Pay_Type.objects.filter(store_meal=items_list[key]['id']).values("id", "payment")
  225. items_list[key]['pay_type'] = list(pay_types)
  226. items_list[key]['is_pay_cycle'] = 1 if items_list[key]['cycle_config_id'] else 0
  227. del items_list[key]['cycle_config_id']
  228. res_c = {'area': area, 'items': items_list}
  229. res.append(res_c)
  230. # 是否促销
  231. promotion = PromotionRuleModel.objects.filter(status=1, startTime__lte=nowTime,
  232. endTime__gte=nowTime).values('id', 'ruleConfig', 'ruleName',
  233. 'startTime', 'endTime',
  234. 'ruleDesc')
  235. if promotion.exists():
  236. promotion = {
  237. 'is_promotion': 1,
  238. 'promotionStartTime': promotion[0]['startTime'],
  239. 'promotionEndTime': promotion[0]['endTime'],
  240. 'promotionName': json.loads(promotion[0]['ruleName']).get(lang, ''),
  241. 'promotionDesc': json.loads(promotion[0]['ruleDesc']).get(lang, ''),
  242. 'nowTime': int(time.time())
  243. }
  244. else:
  245. promotion = {
  246. 'is_promotion': 0
  247. }
  248. result = {
  249. 'meals': res,
  250. 'extra':
  251. {
  252. 'cloud_banner': SERVER_DOMAIN + 'web/images/cloud_cn_banner.png',
  253. 'cloud_en_baner': SERVER_DOMAIN_SSL + 'web/images/cloud_en_banner.png'
  254. },
  255. 'promotion': promotion,
  256. }
  257. return response.json(0, result)
  258. else:
  259. return response.json(0)
  260. def do_sign_play_m3u8(self, request_dict, response): # 根据sts播放m3u8 视频流
  261. uid = request_dict.get('uid', None)
  262. uid = jwt.decode(uid, OAUTH_ACCESS_TOKEN_SECRET, algorithms='HS256').get('uid', '')
  263. channel = request_dict.get('channel', None)
  264. storeTime = request_dict.get('time', None)
  265. now_time = int(time.time())
  266. vh_qs = VodHlsModel.objects.filter(uid=uid, channel=channel, time=storeTime, endTime__gte=now_time). \
  267. values("sec", "fg", "bucket__bucket", "bucket__endpoint", "bucket__region", "bucket__mold")
  268. if not vh_qs.exists():
  269. return response.json(173)
  270. sec = vh_qs[0]['sec']
  271. fg = vh_qs[0]['fg']
  272. bucket__region = vh_qs[0]['bucket__region']
  273. bucket_name = vh_qs[0]['bucket__bucket']
  274. print(bucket__region)
  275. print(bucket_name)
  276. session = Session(
  277. aws_access_key_id=AWS_ACCESS_KEY_ID[vh_qs[0]["bucket__mold"]],
  278. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[vh_qs[0]["bucket__mold"]],
  279. region_name=bucket__region
  280. )
  281. '''
  282. http://test.dvema.com/cloudstorage/signplaym3u8?uid=VVDHCVBYDKFMJRWA111A&channel=1&time=1586940120&sign=tktktktk
  283. '''
  284. conn = session.client('s3')
  285. playlist_entries = []
  286. fg = int(fg)
  287. # ts_count = fg & 0xf
  288. # fg 64位整型,低四位代表ts文件总数,然后进行位运算,一次移四位,每四位转为十进制即为当前ts文件的秒数
  289. for i in range(15):
  290. shift = (i + 1) * 4
  291. duration = (fg >> shift) & 0xf
  292. if duration > 0:
  293. tsFile = '{uid}/vod{channel}/{time}/ts{i}.ts'. \
  294. format(uid=uid, channel=channel, time=storeTime, i=i)
  295. response_url = conn.generate_presigned_url(
  296. 'get_object',
  297. Params={
  298. 'Bucket': bucket_name,
  299. 'Key': tsFile
  300. },
  301. ExpiresIn=3600
  302. )
  303. # m3u8 = '{uid}/vod{channel}/{time}/{time}.m3u8'. \
  304. # format(uid=uid, channel=channel, time=vod['time'])
  305. playlist_entries.append({
  306. 'name': response_url,
  307. 'duration': duration,
  308. })
  309. playlist = PlaylistGenerator(playlist_entries).generate()
  310. response = HttpResponse(playlist)
  311. response['Content-Type'] = 'application/octet-stream'
  312. response['Content-Disposition'] = 'attachment;filename="play.m3u8"'
  313. return response
  314. # response = HttpResponse(playlist, content_type="application/vnd.apple.mpegurl")
  315. # response = HttpResponse(playlist, content_type="application/octet-stream")
  316. # return response
  317. def do_get_sign_sts(self, request_dict, ip, response): # 获取sts令牌
  318. uidToken = request_dict.get('uidToken', None)
  319. utko = UidTokenObject(uidToken)
  320. if utko.flag is False:
  321. return response.json(444, 'uidToken')
  322. uid = utko.UID
  323. channel = utko.channel
  324. print(channel)
  325. print(uid)
  326. now_time = int(time.time())
  327. ubqs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel). \
  328. values("bucket__mold", "bucket__bucket", "bucket__endpoint",
  329. "bucket__region", "endTime").order_by('addTime')[:1]
  330. if ubqs.exists():
  331. # 亚马逊 s3 sts
  332. sts_qs = StsCrdModel.objects.filter(uid=uid, channel=channel). \
  333. values("addTime", "data")
  334. if sts_qs.exists():
  335. endTime = int(sts_qs[0]["addTime"]) + 5000
  336. if endTime > now_time:
  337. print(endTime)
  338. print(now_time)
  339. res = json.loads(sts_qs[0]["data"])
  340. return JsonResponse(status=200, data=res)
  341. # 套餐id
  342. storage = '{uid}/vod{channel}/'.format(uid=uid, channel=channel)
  343. bucket_name = ubqs[0]['bucket__bucket']
  344. endpoint = ubqs[0]['bucket__endpoint']
  345. region_id = ubqs[0]['bucket__region']
  346. try:
  347. aws_access_key_id = AWS_ACCESS_KEY_ID[ubqs[0]["bucket__mold"]]
  348. aws_secret_access_key = AWS_SECRET_ACCESS_KEY[ubqs[0]["bucket__mold"]]
  349. aws_arn = AWS_ARN[ubqs[0]["bucket__mold"]]
  350. except:
  351. res = {'code': 404, 'msg': 'mold not exists!'}
  352. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  353. ###############
  354. boto3_sts = boto3.client(
  355. 'sts',
  356. aws_access_key_id=aws_access_key_id,
  357. aws_secret_access_key=aws_secret_access_key,
  358. region_name=region_id
  359. )
  360. Policy = {
  361. "Version": "2012-10-17",
  362. "Statement": [
  363. {
  364. "Effect": "Allow",
  365. "Action": "s3:*",
  366. "Resource": ["{aws_arn}:::{bucket_name}/{uid_channel}*".
  367. format(aws_arn=aws_arn, bucket_name=bucket_name, uid_channel=storage)]
  368. }
  369. ]
  370. }
  371. response = boto3_sts.get_federation_token(
  372. Name='{role_name}'.format(role_name=uid + '_' + str(channel)),
  373. Policy=json.dumps(Policy),
  374. DurationSeconds=7200
  375. )
  376. ##############
  377. res = {
  378. 'AccessKeyId': response['Credentials']['AccessKeyId'],
  379. 'AccessKeySecret': response['Credentials']['SecretAccessKey'],
  380. 'SessionToken': response['Credentials']['SessionToken'],
  381. 'Expiration': response['Credentials']['Expiration'],
  382. 'expire': 900,
  383. 'endpoint': endpoint,
  384. 'bucket_name': bucket_name,
  385. 'arn': response['FederatedUser']['Arn'],
  386. 'code': 0,
  387. 'storage': storage,
  388. 'endTime': ubqs[0]['endTime'],
  389. 'ip': ip,
  390. 'region': region_id,
  391. 'bucket_mold': ubqs[0]['bucket__mold']
  392. }
  393. if sts_qs.exists():
  394. sts_qs.update(data=json.dumps(res, default=str), addTime=now_time)
  395. else:
  396. StsCrdModel.objects.create(uid=uid, channel=channel, data=json.dumps(res, default=str),
  397. addTime=now_time, type=1)
  398. return JsonResponse(status=200, data=res)
  399. # else:
  400. # res = {'code': 404, 'msg': 'data not exists!'}
  401. # return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  402. res = {'code': 405, 'msg': 'Not purchased or expired!'}
  403. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  404. def do_query_vod_list(self, request_dict, userID, response): # 获取视频播放列表
  405. logger = logging.getLogger('info')
  406. intoTime = int(time.time())
  407. startTime = int(request_dict.get('startTime', None))
  408. endTime = int(request_dict.get('endTime', None))
  409. uid = request_dict.get('uid', None)
  410. channel = request_dict.get('channel', None)
  411. if uid == 'UWE2ZJ52SE4FX75U111A':
  412. logger.info({
  413. "intoTime": intoTime,
  414. })
  415. dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False).values('vodPrimaryUserID',
  416. 'vodPrimaryMaster')
  417. if not dv_qs.exists():
  418. return response.json(12)
  419. dvQsModelTimeOver = int(time.time())
  420. if uid == 'UWE2ZJ52SE4FX75U111A':
  421. logger.info({
  422. "intoTime": intoTime,
  423. "dvQsModelOverTime": dvQsModelTimeOver,
  424. })
  425. if dv_qs[0]['vodPrimaryUserID'] != userID:
  426. return response.json(10034)
  427. now_time = int(time.time())
  428. bv_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel).values('bucket_id').order_by(
  429. 'addTime')
  430. if not bv_qs.exists():
  431. return response.json(10030)
  432. UidBucketModelTimeOver = int(time.time())
  433. logger.info({
  434. "intoTime": intoTime,
  435. "dvQsModelOverTime": dvQsModelTimeOver,
  436. "UidBucketModelOverTime": UidBucketModelTimeOver,
  437. })
  438. # vh_qs = VodHlsModel.objects.filter \
  439. # (uid=uid, channel=channel, endTime__gte=now_time,time__range=(startTime, endTime), bucket_id=bv_qs[0]['bucket_id']). \
  440. # values("id", "time", "sec", "bucket__bucket", "fg", "bucket__endpoint", "bucket__region", "bucket__mold")
  441. vh_qs = VodHlsModel.objects.filter \
  442. (uid=uid, channel=channel, endTime__gte=now_time, time__range=(startTime, endTime)). \
  443. values("id", "time", "sec", "fg", "bucket_id")
  444. vod_play_list = []
  445. if not vh_qs.exists():
  446. return response.json(0, vod_play_list)
  447. # 不用关联外键查询,因为会查询非常慢
  448. bucket_qs = VodBucketModel.objects.values()
  449. regroup_bucket_qs = {}
  450. for bucket_dict in bucket_qs:
  451. regroup_bucket_qs[bucket_dict['id']] = bucket_dict
  452. vodHlsModelTimeOver = int(time.time())
  453. logger.info({
  454. "intoTime": intoTime,
  455. "dvQsModelOverTime": dvQsModelTimeOver,
  456. "UidBucketModelOverTime": UidBucketModelTimeOver,
  457. "vodHlsModelOverTime": vodHlsModelTimeOver,
  458. })
  459. bucket_mold = regroup_bucket_qs[vh_qs[0]['bucket_id']]['mold']
  460. bucket_region = regroup_bucket_qs[vh_qs[0]['bucket_id']]['region']
  461. aws_access_key_id = AWS_ACCESS_KEY_ID[bucket_mold]
  462. aws_secret_access_key = AWS_SECRET_ACCESS_KEY[bucket_mold]
  463. session = Session(
  464. aws_access_key_id=aws_access_key_id,
  465. aws_secret_access_key=aws_secret_access_key,
  466. region_name=bucket_region
  467. )
  468. conn = session.client('s3')
  469. uidToken = TokenObject().encryption(data={'uid': uid})
  470. awsObjectOverTime = int(time.time())
  471. logger.info({
  472. "intoTime": intoTime,
  473. "dvQsModelOverTime": dvQsModelTimeOver,
  474. "UidBucketModelOverTime": UidBucketModelTimeOver,
  475. "vodHlsModelOverTime": vodHlsModelTimeOver,
  476. "awsObjectOverTime": awsObjectOverTime,
  477. })
  478. for vod in vh_qs:
  479. # bucket__mold = vod["bucket__mold"]
  480. # bucket_name = vod["bucket__bucket"]
  481. # endpoint = vod["bucket__endpoint"]
  482. # bucket__region = vod["bucket__region"]
  483. bucket_name = regroup_bucket_qs[vod['bucket_id']]['bucket']
  484. thumbspng = '{uid}/vod{channel}/{time}/Thumb.jpeg'. \
  485. format(uid=uid, channel=channel, time=vod['time'])
  486. response_url = conn.generate_presigned_url(
  487. 'get_object',
  488. Params={
  489. 'Bucket': bucket_name,
  490. 'Key': thumbspng
  491. },
  492. ExpiresIn=3600
  493. )
  494. vod_url = '{server_domain}/cloudstorage/signplaym3u8?' \
  495. 'uid={uid}&channel={channel}&time={time}&sign=tktktktk'. \
  496. format(server_domain=SERVER_DOMAIN_SSL, uid=uidToken, channel=channel, time=vod['time'])
  497. ts_num = int(vod['fg']) & 0xf
  498. vod_play_list.append({
  499. 'start_time': vod['time'],
  500. 'sign_url': vod_url,
  501. 'thumb': response_url,
  502. 'sec': vod['sec'],
  503. 'ts_num': ts_num,
  504. 'vod_id': vod['id']
  505. }),
  506. generatePresignedOverTime = int(time.time())
  507. if uid == 'UWE2ZJ52SE4FX75U111A':
  508. logger.info({
  509. "intoTime": intoTime,
  510. "dvQsModelOverTime": dvQsModelTimeOver,
  511. "UidBucketModelOverTime": UidBucketModelTimeOver,
  512. "vodHlsModelOverTime": vodHlsModelTimeOver,
  513. "awsObjectOverTime": awsObjectOverTime,
  514. "generatePresignedOverTime": generatePresignedOverTime,
  515. })
  516. return response.json(0, vod_play_list)
  517. def do_store_playlist(self, request_dict, response): # 设备调用,上传视频到s3,同时把视频数据信息传给服务器,服务器存储播放内容
  518. uidToken = request_dict.get('uidToken', None)
  519. storeTime = request_dict.get('time', None)
  520. sec = request_dict.get('sec', None)
  521. fg = request_dict.get('fg', None)
  522. utko = UidTokenObject(uidToken)
  523. if utko.flag is False:
  524. return response.json(444, 'uidToken')
  525. if not uidToken or not storeTime or not sec:
  526. return response.json(0)
  527. pass
  528. UID = utko.UID
  529. channel = utko.channel
  530. print('UID:')
  531. print(UID)
  532. print('channel:')
  533. print(channel)
  534. now_time = int(time.time())
  535. ubqs = UID_Bucket.objects.filter(uid=UID, endTime__gte=now_time, channel=channel). \
  536. values("bucket__mold", "bucket__bucket", "bucket__endpoint",
  537. "bucket__region", "status", "bucket__storeDay", "bucket__id").order_by('addTime')[:1]
  538. if ubqs.exists():
  539. ub_qs_data = ubqs[0]
  540. store_day = ub_qs_data['bucket__storeDay']
  541. bucket_id = ub_qs_data['bucket__id']
  542. end_time = int(storeTime) + store_day * 86400
  543. if ub_qs_data['status'] == 1:
  544. VodHlsModel.objects.create(
  545. uid=UID,
  546. channel=channel,
  547. time=storeTime,
  548. endTime=end_time,
  549. bucket_id=bucket_id,
  550. fg=fg,
  551. sec=sec,
  552. )
  553. res = {'code': 0, 'msg': '存储成功'}
  554. return HttpResponse(json.dumps(res, ensure_ascii=False),
  555. content_type="application/json,charset=utf-8")
  556. else:
  557. res = {'code': 404, 'msg': '设备未开启'}
  558. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  559. else:
  560. res = {'code': 404, 'msg': '设备未购买'}
  561. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  562. def do_change_vod_status(self, request_dict, userID, response): # 修改云存状态
  563. uid = request_dict.get('uid', None)
  564. status = request_dict.get('status', None)
  565. channel = request_dict.get('channel', None)
  566. if not uid or not status or not channel:
  567. return response.json(444, 'uid,status,channel')
  568. dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1) \
  569. .values('vodPrimaryUserID')
  570. if not dv_qs.exists() or dv_qs[0]['vodPrimaryUserID'] != userID:
  571. return response.json(12)
  572. ubqs = UID_Bucket.objects.filter(channel=channel, uid=uid)
  573. if not ubqs.exists():
  574. return response.json(10030)
  575. now_time = int(time.time())
  576. if now_time > ubqs[0].endTime:
  577. return response.json(10031)
  578. ubqs.update(status=status)
  579. if status == 0:
  580. return response.json(0)
  581. utko = UidTokenObject()
  582. utko.generate(data={'uid': uid, 'channel': channel})
  583. uidTkUrl = "{SERVER_DOMAIN_SSL}cloudstorage/getsignsts?uidToken={uidToken}". \
  584. format(uidToken=utko.token, SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  585. storeHlsUrl = "{SERVER_DOMAIN_SSL}cloudstorage/storeplaylist?uidToken={uidToken}". \
  586. format(uidToken=utko.token, SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  587. return response.json(0, {'uidTkUrl': uidTkUrl, 'storeHlsUrl': storeHlsUrl})
  588. def do_pay_error(self):
  589. response = HttpResponse()
  590. response.content = PaymentService.get_pay_error_content()
  591. return response
  592. def do_pay_ok(self, request_dict): # 支付成功
  593. response = HttpResponse()
  594. lang = request_dict.get('lang', 'en')
  595. pay_type = request_dict.get('paytype', None)
  596. response.content = PaymentService.get_pay_ok_content(lang, pay_type)
  597. return response
  598. def do_pay_by_ali_callback(self, request): # 阿里支付回调
  599. response = ResponseObject()
  600. data = request.POST.dict()
  601. try:
  602. passback_params = data["passback_params"]
  603. parmap = dict([(k, v[0]) for k, v in parse_qs(unquote(passback_params)).items()])
  604. lang = parmap["lang"]
  605. signature = data["sign"]
  606. data.pop('sign')
  607. orderID = data['out_trade_no']
  608. # redis加锁,防止订单重复
  609. redisObj = RedisObject()
  610. isLock = redisObj.CONN.setnx(orderID + 'do_notify', 1)
  611. redisObj.CONN.expire(orderID + 'do_notify', 60)
  612. if not isLock:
  613. return response.json(5)
  614. order_qs = Order_Model.objects.filter(orderID=orderID, status=0)
  615. aliPayObj = AliPayObject()
  616. alipay = aliPayObj.conf()
  617. success = alipay.verify(data, signature)
  618. if success and data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
  619. print("trade succeed")
  620. nowTime = int(time.time())
  621. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  622. "userID__userID", "userID__username", "coupon_id")
  623. userid = order_list[0]['userID__userID']
  624. username = order_list[0]['userID__username']
  625. UID = order_list[0]['UID']
  626. channel = order_list[0]['channel']
  627. rank = order_list[0]['rank']
  628. smqs = Store_Meal.objects.filter(id=rank). \
  629. values("day", "bucket_id", "bucket__storeDay", "expire")
  630. bucketId = smqs[0]['bucket_id']
  631. if not smqs.exists():
  632. return response.json(173)
  633. ubqs = UID_Bucket.objects.filter(uid=UID).values("id", "bucket_id", "bucket__storeDay",
  634. "bucket__region",
  635. "endTime", "use_status")
  636. expire = smqs[0]['expire']
  637. if order_list[0]['isSelectDiscounts'] == 1:
  638. expire = smqs[0]['expire'] * 2
  639. # 是否有促销
  640. nowTime = int(time.time())
  641. promotion = PromotionRuleModel.objects.filter(status=1, startTime__lte=nowTime,
  642. endTime__gte=nowTime).values('id', 'ruleConfig')
  643. promotion_rule_id = ''
  644. if promotion.exists():
  645. promotion_rule_id = promotion[0]['id']
  646. expire = expire * 2
  647. with transaction.atomic():
  648. if ubqs.exists():
  649. ubq = ubqs[0]
  650. if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId: # 套餐使用中并且相同套餐叠加过期时间
  651. endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
  652. UID_Bucket.objects.filter(id=ubq['id']).update \
  653. (uid=UID, channel=channel, bucket_id=bucketId,
  654. endTime=endTime, updateTime=nowTime)
  655. else: # 已过期或者不相同的套餐加入未使用的关联套餐表
  656. has_unused = Unused_Uid_Meal.objects.filter(uid=UID, bucket_id=bucketId).values("id")
  657. nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
  658. if promotion.exists():
  659. nums = nums + 1
  660. if has_unused.exists():
  661. Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
  662. else:
  663. Unused_Uid_Meal.objects.create(uid=UID, channel=channel, addTime=nowTime, num=nums,
  664. expire=smqs[0]['expire'], bucket_id=bucketId)
  665. UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
  666. uid_bucket_id = ubq['id']
  667. else:
  668. endTime = CommonService.calcMonthLater(expire)
  669. ub_cqs = UID_Bucket.objects.create \
  670. (uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
  671. updateTime=nowTime, use_status=1)
  672. uid_bucket_id = ub_cqs.id
  673. dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
  674. if dvq.exists():
  675. dvq_set_update_dict = {
  676. 'vodPrimaryUserID': userid,
  677. 'vodPrimaryMaster': username
  678. }
  679. dvq.update(**dvq_set_update_dict)
  680. # uid_main_exist = UIDMainUser.objects.filter(UID=UID)
  681. # if not uid_main_exist.exists():
  682. # uid_main_dict = {
  683. # 'UID': UID,
  684. # 'user_id': userid
  685. # }
  686. # UIDMainUser.objects.create(**uid_main_dict)
  687. # 核销coupon
  688. if order_list[0]['coupon_id']:
  689. CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2,
  690. update_time=nowTime)
  691. order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id,
  692. promotion_rule_id=promotion_rule_id)
  693. datetime = time.strftime("%Y-%m-%d", time.localtime())
  694. # 如果存在序列号,消息提示用序列号
  695. device_info_qs = Device_Info.objects.filter(UID=UID).values('serial_number', 'Type')
  696. serial_number = device_info_qs[0]['serial_number']
  697. device_type = device_info_qs[0]['Type']
  698. if serial_number:
  699. device_name = CommonService.get_full_serial_number(UID, serial_number, device_type)
  700. else:
  701. device_name = UID
  702. sys_msg_text_list = ['温馨提示:尊敬的客户,您的' + device_name + '设备在' + datetime + '已成功购买云存套餐',
  703. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  704. "%b %dth,%Y", time.localtime())]
  705. self.do_vod_msg_Notice(UID, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
  706. red_url = "{SERVER_DOMAIN_SSL}web/paid2/success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  707. if lang != 'cn':
  708. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_success.html".format(
  709. SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  710. redisObj.del_data(key=orderID + 'do_notify')
  711. return HttpResponseRedirect(red_url)
  712. return response.json(0, signature)
  713. except Exception as e:
  714. logger = logging.getLogger('info')
  715. logger.info('alipay----notify---------')
  716. logger.info(repr(e))
  717. logger.info(sys.exc_info())
  718. logger.info('alipay支付失败:----')
  719. logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
  720. logger.info(repr(e))
  721. if order_qs:
  722. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  723. redisObj.del_data(key=orderID + 'do_notify')
  724. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  725. if lang != 'cn':
  726. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  727. return HttpResponseRedirect(red_url)
  728. def do_pay_by_paypal_callback(self, request_dict, response): # paypal支付回调
  729. logger = logging.getLogger('info')
  730. logger.info('---------进入paypal异步回调')
  731. paymentId = request_dict.get('paymentId', None)
  732. PayerID = request_dict.get('PayerID', None)
  733. orderID = request_dict.get('orderID', None)
  734. lang = request_dict.get('lang', 'en')
  735. logger.info("paymentID={paymentId},payerID={PayerID}".format(paymentId=paymentId, PayerID=PayerID))
  736. # redis加锁,防止订单重复
  737. redisObj = RedisObject()
  738. isLock = redisObj.CONN.setnx(orderID + 'do_notify', 1)
  739. redisObj.CONN.expire(orderID + 'do_notify', 60)
  740. if not isLock:
  741. return response.json(5)
  742. try:
  743. order_qs = Order_Model.objects.filter(orderID=orderID, status=0)
  744. if not orderID:
  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. # else:
  750. # order_qs.update(status=9)
  751. paypalrestsdk.configure(PAYPAL_CRD)
  752. # ID of the payment. This ID is provided when creating payment.
  753. payment = paypalrestsdk.Payment.find(paymentId)
  754. print(payment)
  755. logger.info("payment------")
  756. logger.info(payment)
  757. payres = payment.execute({"payer_id": PayerID})
  758. logger.info(payres)
  759. print(payres)
  760. if not payres:
  761. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  762. if lang != 'cn':
  763. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  764. redisObj.del_data(key=orderID + 'do_notify')
  765. return HttpResponseRedirect(red_url)
  766. print("Payment execute successfully")
  767. nowTime = int(time.time())
  768. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  769. "userID__userID",
  770. "userID__username", "coupon_id")
  771. userid = order_list[0]['userID__userID']
  772. username = order_list[0]['userID__username']
  773. UID = order_list[0]['UID']
  774. channel = order_list[0]['channel']
  775. rank = order_list[0]['rank']
  776. smqs = Store_Meal.objects.filter(id=rank). \
  777. values("day", "bucket_id", "bucket__storeDay", "expire")
  778. bucketId = smqs[0]['bucket_id']
  779. if not smqs.exists():
  780. return response.json(173)
  781. # ##
  782. ubqs = UID_Bucket.objects.filter(uid=UID).values("id", "bucket_id", "bucket__storeDay", "bucket__region",
  783. "endTime", "use_status")
  784. expire = smqs[0]['expire']
  785. if order_list[0]['isSelectDiscounts'] == 1:
  786. expire = smqs[0]['expire'] * 2
  787. # 是否有促销
  788. nowTime = int(time.time())
  789. promotion = PromotionRuleModel.objects.filter(status=1, startTime__lte=nowTime,
  790. endTime__gte=nowTime).values('id', 'ruleConfig')
  791. promotion_rule_id = ''
  792. if promotion.exists():
  793. promotion_rule_id = promotion[0]['id']
  794. expire = expire * 2
  795. with transaction.atomic():
  796. if ubqs.exists():
  797. ubq = ubqs[0]
  798. if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId: # 套餐使用中并且相同套餐叠加过期时间
  799. endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
  800. UID_Bucket.objects.filter(id=ubq['id']).update \
  801. (uid=UID, channel=channel, bucket_id=bucketId,
  802. endTime=endTime, updateTime=nowTime)
  803. else: # 已过期或者不相同的套餐加入未使用的关联套餐表
  804. has_unused = Unused_Uid_Meal.objects.filter(uid=UID, bucket_id=bucketId).values("id")
  805. nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
  806. if promotion.exists():
  807. nums = nums + 1
  808. if has_unused.exists():
  809. Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
  810. else:
  811. Unused_Uid_Meal.objects.create(uid=UID, channel=channel, addTime=nowTime, num=nums,
  812. expire=smqs[0]['expire'], bucket_id=bucketId)
  813. UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
  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,
  819. updateTime=nowTime, use_status=1)
  820. uid_bucket_id = ub_cqs.id
  821. dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
  822. if dvq.exists():
  823. dvq_set_update_dict = {
  824. 'vodPrimaryUserID': userid,
  825. 'vodPrimaryMaster': username
  826. }
  827. dvq.update(**dvq_set_update_dict)
  828. # uid_main_exist = UIDMainUser.objects.filter(UID=UID)
  829. # if not uid_main_exist.exists():
  830. # uid_main_dict = {
  831. # 'UID': UID,
  832. # 'user_id': userid
  833. # }
  834. # UIDMainUser.objects.create(**uid_main_dict)
  835. # 核销coupon
  836. if order_list[0]['coupon_id']:
  837. CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2, update_time=nowTime)
  838. order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id,
  839. promotion_rule_id=promotion_rule_id)
  840. datetime = time.strftime("%Y-%m-%d", time.localtime())
  841. # 如果存在序列号,消息提示用序列号
  842. device_info_qs = Device_Info.objects.filter(UID=UID).values('serial_number', 'Type')
  843. serial_number = device_info_qs[0]['serial_number']
  844. device_type = device_info_qs[0]['Type']
  845. if serial_number:
  846. device_name = CommonService.get_full_serial_number(UID, serial_number, device_type)
  847. else:
  848. device_name = UID
  849. sys_msg_text_list = ['温馨提示:尊敬的客户,您的' + device_name + '设备在' + datetime + '已成功购买云存套餐',
  850. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  851. "%b %dth,%Y", time.localtime())]
  852. self.do_vod_msg_Notice(UID, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
  853. # return response.json(0)
  854. red_url = "{SERVER_DOMAIN_SSL}web/paid2/success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  855. if lang != 'cn':
  856. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  857. redisObj.del_data(key=orderID + 'do_notify')
  858. return HttpResponseRedirect(red_url)
  859. except Exception as e:
  860. logger.info('paypal支付失败:----')
  861. logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
  862. logger.info(repr(e))
  863. if order_qs:
  864. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  865. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  866. if lang != 'cn':
  867. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  868. redisObj.del_data(key=orderID + 'do_notify')
  869. return HttpResponseRedirect(red_url)
  870. def do_pay_by_wechat_callback(self, request, response): # 微信支付回调
  871. logger = logging.getLogger('info')
  872. try:
  873. pay = WechatPayObject()
  874. data = pay.weixinpay_call_back(request.body)
  875. attach = data["attach"]
  876. parmap = dict([(k, v[0]) for k, v in parse_qs(unquote(attach)).items()])
  877. lang = parmap["lang"]
  878. trade_status = data['result_code'] # 业务结果 SUCCESS/FAIL
  879. out_trade_no = data['out_trade_no'] # 商户订单号
  880. order_qs = Order_Model.objects.filter(orderID=out_trade_no, status=0)
  881. promotion_rule_id = ''
  882. if trade_status == "SUCCESS":
  883. check_sign = pay.get_notifypay(data)
  884. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  885. "userID__userID", "userID__username", "status", "coupon_id")
  886. if not check_sign:
  887. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '签名失败'}))
  888. orderID = out_trade_no
  889. # redis加锁,防止订单重复
  890. redisObj = RedisObject()
  891. isLock = redisObj.CONN.setnx(orderID + 'do_notify', 1)
  892. redisObj.CONN.expire(orderID + 'do_notify', 60)
  893. if not isLock:
  894. return response.json(5)
  895. nowTime = int(time.time())
  896. logger.info(order_list[0]['UID'])
  897. logger.info(orderID)
  898. userid = order_list[0]['userID__userID']
  899. username = order_list[0]['userID__username']
  900. UID = order_list[0]['UID']
  901. channel = order_list[0]['channel']
  902. rank = order_list[0]['rank']
  903. smqs = Store_Meal.objects.filter(id=rank). \
  904. values("day", "bucket_id", "bucket__storeDay", "expire")
  905. bucketId = smqs[0]['bucket_id']
  906. if not smqs.exists():
  907. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '套餐不存在'}))
  908. # ##
  909. ubqs = UID_Bucket.objects.filter(uid=UID).values("id", "bucket_id", "bucket__storeDay",
  910. "bucket__region", "endTime", "use_status")
  911. expire = smqs[0]['expire']
  912. if order_list[0]['isSelectDiscounts'] == 1:
  913. expire = smqs[0]['expire'] * 2
  914. # 是否有促销
  915. nowTime = int(time.time())
  916. promotion = PromotionRuleModel.objects.filter(status=1, startTime__lte=nowTime,
  917. endTime__gte=nowTime).values('id', 'ruleConfig')
  918. if promotion.exists():
  919. promotion_rule_id = promotion[0]['id']
  920. expire = expire * 2
  921. with transaction.atomic():
  922. if ubqs.exists():
  923. ubq = ubqs[0]
  924. if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId: # 套餐使用中并且相同套餐叠加过期时间
  925. endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
  926. UID_Bucket.objects.filter(id=ubq['id']).update \
  927. (uid=UID, channel=channel, bucket_id=bucketId,
  928. endTime=endTime, updateTime=nowTime)
  929. else: # 已过期或者不相同的套餐加入未使用的关联套餐表
  930. has_unused = Unused_Uid_Meal.objects.filter(uid=UID, bucket_id=bucketId).values("id")
  931. nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
  932. if promotion.exists():
  933. nums = nums + 1
  934. if has_unused.exists():
  935. Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
  936. else:
  937. Unused_Uid_Meal.objects.create(uid=UID, channel=channel, addTime=nowTime, num=nums,
  938. expire=smqs[0]['expire'], bucket_id=bucketId)
  939. UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
  940. uid_bucket_id = ubq['id']
  941. else:
  942. endTime = CommonService.calcMonthLater(expire)
  943. ub_cqs = UID_Bucket.objects.create \
  944. (uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
  945. updateTime=nowTime, use_status=1)
  946. uid_bucket_id = ub_cqs.id
  947. dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
  948. if dvq.exists():
  949. dvq_set_update_dict = {
  950. 'vodPrimaryUserID': userid,
  951. 'vodPrimaryMaster': username
  952. }
  953. dvq.update(**dvq_set_update_dict)
  954. # uid_main_exist = UIDMainUser.objects.filter(UID=UID)
  955. # if not uid_main_exist.exists():
  956. # uid_main_dict = {
  957. # 'UID': UID,
  958. # 'user_id': userid
  959. # }
  960. # UIDMainUser.objects.create(**uid_main_dict)
  961. # 核销coupon
  962. if order_list[0]['coupon_id']:
  963. CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2,
  964. update_time=nowTime)
  965. order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id,
  966. promotion_rule_id=promotion_rule_id)
  967. datetime = time.strftime("%Y-%m-%d", time.localtime())
  968. # 如果存在序列号,消息提示用序列号
  969. device_info_qs = Device_Info.objects.filter(UID=UID).values('serial_number', 'Type')
  970. serial_number = device_info_qs[0]['serial_number']
  971. device_type = device_info_qs[0]['Type']
  972. if serial_number:
  973. device_name = CommonService.get_full_serial_number(UID, serial_number, device_type)
  974. else:
  975. device_name = UID
  976. sys_msg_text_list = ['温馨提示:尊敬的客户,您的' + device_name + '设备在' + datetime + '已成功购买云存套餐',
  977. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  978. "%b %dth,%Y", time.localtime())]
  979. self.do_vod_msg_Notice(UID, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
  980. redisObj.del_data(key=orderID + 'do_notify')
  981. return HttpResponse("<xml>\
  982. <return_code><![CDATA[SUCCESS]]></return_code>\
  983. <return_msg><![CDATA[OK]]></return_msg>\
  984. </xml>")
  985. else:
  986. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  987. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '参数格式校验错误'}))
  988. except Exception as e:
  989. logger.info('wechat支付失败:----')
  990. logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
  991. logger.info(repr(e))
  992. if order_qs:
  993. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  994. redisObj.del_data(key=orderID + 'do_notify')
  995. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': repr(e)}))
  996. def do_create_pay_order(self, request_dict, userID, ip, response): # 创建支付订单
  997. logger = logging.getLogger('info')
  998. uid = request_dict.get('uid', None)
  999. channel = request_dict.get('channel', None)
  1000. pay_type = int(request_dict.get('pay_type', None))
  1001. rank = request_dict.get('rank', None)
  1002. is_select_discount = request_dict.get('is_select_discount', 0)
  1003. coupon_id = request_dict.get('coupon_id', 0)
  1004. lang = request_dict.get('lang', 'en')
  1005. if not uid or not channel or not pay_type or not rank:
  1006. return response.json(444)
  1007. dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1).values(
  1008. 'vodPrimaryUserID',
  1009. 'vodPrimaryMaster')
  1010. if not dv_qs.exists():
  1011. return response.json(12)
  1012. dvq = Device_Info.objects.filter(UID=uid)
  1013. dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  1014. if dvq.exists():
  1015. if dvq[0]['vodPrimaryUserID'] != userID:
  1016. return response.json(10033)
  1017. nowTime = int(time.time())
  1018. # uq = UID_Bucket.objects.filter(uid=uid,endTime__gt=str(nowTime)).values('endTime')
  1019. # if uq.exists():
  1020. # return response.json(10033)
  1021. # if dv_qs[0]['vodPrimaryUserID'] != '' and dv_qs[0]['vodPrimaryUserID'] != userID:
  1022. # return response.json(10033)
  1023. smqs = Store_Meal.objects.filter(id=rank, pay_type=pay_type, lang__lang=lang, is_show=0). \
  1024. values('currency', 'price', 'lang__content', 'day',
  1025. 'commodity_type', 'lang__title',
  1026. 'expire', 'commodity_code', 'discount_price', 'bucket__mold', 'cycle_config_id')
  1027. if not smqs.exists():
  1028. return response.json(173)
  1029. currency = smqs[0]['currency']
  1030. price = smqs[0]['price']
  1031. if is_select_discount == '1':
  1032. price = float(smqs[0]['price']) + float(smqs[0]['discount_price'])
  1033. content = smqs[0]['lang__content']
  1034. day = smqs[0]['day']
  1035. commodity_code = smqs[0]['commodity_code']
  1036. commodity_type = smqs[0]['commodity_type']
  1037. # ubqs = UID_Bucket.objects.filter(uid=uid, channel=channel, endTime__gte=nowTime). \
  1038. # values("bucket__storeDay", "bucket__region", "endTime")
  1039. # if ubqs.exists():
  1040. # ubqs_count = ubqs.count()
  1041. # ubq = ubqs[ubqs_count - 1, ubqs_count]
  1042. # new_starTime = ubq['endTime'] + 1
  1043. is_mold = 0 # 判断国内外
  1044. if smqs[0]['bucket__mold'] == 0:
  1045. is_mold = 1
  1046. order_qs = Order_Model.objects.filter(UID=uid, rank__bucket__mold=is_mold)
  1047. if order_qs.exists():
  1048. return response.json(10041)
  1049. orderID = CommonService.createOrderID()
  1050. # 优惠券
  1051. if coupon_id:
  1052. couponObj = CouponModel.objects.filter(id=coupon_id, use_status=0, distribute_time__lte=nowTime,
  1053. valid_time__gt=nowTime)
  1054. couponQuery = couponObj.values("id", "coupon_config__type", "coupon_config__coupon_discount")
  1055. if not couponQuery.exists():
  1056. return response.json(10049)
  1057. price = Decimal(price)
  1058. coupon_discount = Decimal(couponQuery[0]['coupon_config__coupon_discount'])
  1059. if couponQuery[0]['coupon_config__type'] == 1: # 打折
  1060. price = coupon_discount / 10 * price
  1061. elif couponQuery[0]['coupon_config__type'] == 2: # 抵扣
  1062. price = price - coupon_discount
  1063. price = float(price)
  1064. if price < 0 or price == 0 or price < 0.01:
  1065. price = 0.01
  1066. price = round(price, 2)
  1067. if pay_type == 1:
  1068. # 订阅周期扣款
  1069. if (smqs[0]['cycle_config_id']):
  1070. # 查询是否有订阅过,活跃状态
  1071. # return HttpResponse(price)
  1072. checkHasSubscribe = Paypal.checkSubscriptions(userID, uid, rank)
  1073. if checkHasSubscribe is False:
  1074. return response.json(10050)
  1075. subInfo = Paypal.subscriptions(store_info=smqs[0], lang=lang, orderID=orderID, price=price)
  1076. if not subInfo:
  1077. return response.json(10048)
  1078. store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=1).values('lang__title',
  1079. 'lang__content')
  1080. if store_meal_qs.exists():
  1081. store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
  1082. else:
  1083. store_meal_name = '未知套餐'
  1084. Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
  1085. desc=content, payType=pay_type, payTime=nowTime,
  1086. price=price, currency=currency, addTime=nowTime, updTime=nowTime,
  1087. pay_url=subInfo['url'], isSelectDiscounts=is_select_discount,
  1088. commodity_code=commodity_code, commodity_type=commodity_type,
  1089. rank_id=rank, plan_id=subInfo['plan_id'], coupon_id=coupon_id, ai_rank_id=1,
  1090. store_meal_name=store_meal_name
  1091. )
  1092. # if coupon_id:
  1093. # #冻结优惠券
  1094. # CouponModel.objects.filter(id=coupon_id, use_status=0, distribute_time__lte=nowTime,
  1095. # valid_time__gt=nowTime).update(use_status=1)
  1096. return response.json(0, {"redirectUrl": subInfo['url'], "orderID": orderID})
  1097. # 正常扣款
  1098. cal_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  1099. if lang != 'cn':
  1100. cal_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  1101. call_sub_url = "{SERVER_DOMAIN_SSL}cloudstorage/dopaypalcallback?orderID={orderID}&lang={lang}". \
  1102. format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, orderID=orderID, lang=lang)
  1103. # call_sub_url = "http://binbin.uicp.vip/cloudstorage/dopaypalcallback?orderID={orderID}".format(
  1104. # SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, orderID=orderID)
  1105. call_clc_url = cal_url
  1106. paypalrestsdk.configure(PAYPAL_CRD)
  1107. payment = paypalrestsdk.Payment({
  1108. "intent": "sale",
  1109. "payer": {"payment_method": "paypal"},
  1110. "redirect_urls": {"return_url": call_sub_url, "cancel_url": call_clc_url},
  1111. "transactions": [{
  1112. "item_list": {"items": [
  1113. {"name": "Cloud video", "sku": "1", "price": price, "currency": "USD", "quantity": 1}]},
  1114. "amount": {"total": price, "currency": currency},
  1115. "description": content}]})
  1116. if payment.create():
  1117. print("Payment created successfully")
  1118. else:
  1119. print(payment.error)
  1120. return response.json(10, payment.error)
  1121. print(payment)
  1122. logger.info('paypal创建订单返回----------')
  1123. logger.info(payment)
  1124. paymentID = payment['id'] # 获取paymentID
  1125. for link in payment.links:
  1126. if link.rel == "approval_url":
  1127. approval_url = str(link.href)
  1128. print("Redirect for approval: %s" % (approval_url))
  1129. store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=1).values('lang__title',
  1130. 'lang__content')
  1131. if store_meal_qs.exists():
  1132. store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
  1133. else:
  1134. store_meal_name = '未知套餐'
  1135. Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
  1136. desc=content, payType=pay_type, payTime=nowTime,
  1137. price=price, currency=currency, addTime=nowTime, updTime=nowTime,
  1138. pay_url=approval_url, isSelectDiscounts=is_select_discount,
  1139. commodity_code=commodity_code, commodity_type=commodity_type,
  1140. rank_id=rank, paymentID=paymentID, coupon_id=coupon_id, ai_rank_id=1,
  1141. store_meal_name=store_meal_name)
  1142. return response.json(0, {"redirectUrl": approval_url, "orderID": orderID})
  1143. return response.json(10, 'generate_order_false')
  1144. elif pay_type == 2:
  1145. try:
  1146. aliPayObj = AliPayObject()
  1147. alipay = aliPayObj.conf()
  1148. subject = smqs[0]['lang__title'] + smqs[0]['lang__content']
  1149. # biz_content = {
  1150. # "subject": subject,
  1151. # "out_trade_no": orderID,
  1152. # "total_amount": price,
  1153. # "product_code": "QUICK_WAP_PAY",
  1154. # "quit_url": "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  1155. # # "qr_pay_mode":4
  1156. # }
  1157. order_string = alipay.api_alipay_trade_wap_pay(
  1158. out_trade_no=orderID,
  1159. total_amount=price,
  1160. subject=subject,
  1161. return_url="{SERVER_DOMAIN_SSL}web/paid2/success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL),
  1162. notify_url="{SERVER_DOMAIN_SSL}cloudstorage/doalicallback".format(
  1163. SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL),
  1164. quit_url="{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL),
  1165. passback_params=quote("lang=" + lang)
  1166. # return_url="http://192.168.136.40/cloudstorage/payOK",
  1167. # notify_url="http://192.168.136.40/cloudstorage/aliPayCallback"
  1168. )
  1169. except Exception as e:
  1170. print(repr(e))
  1171. return response.json(10, repr(e))
  1172. else:
  1173. if order_string:
  1174. redirectUrl = aliPayObj.alipay_prefix + order_string
  1175. print('---------tttt')
  1176. print(redirectUrl)
  1177. store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=1).values('lang__title',
  1178. 'lang__content')
  1179. if store_meal_qs.exists():
  1180. store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
  1181. else:
  1182. store_meal_name = '未知套餐'
  1183. Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
  1184. desc=content, payType=pay_type, payTime=nowTime,
  1185. price=price, currency=currency, addTime=nowTime, updTime=nowTime,
  1186. pay_url=redirectUrl, isSelectDiscounts=is_select_discount,
  1187. commodity_code=commodity_code, commodity_type=commodity_type,
  1188. rank_id=rank, coupon_id=coupon_id, ai_rank_id=1,
  1189. store_meal_name=store_meal_name)
  1190. return JsonResponse(status=200, data={'result_code': 0, 'reason': 'success',
  1191. 'result': {"redirectUrl": redirectUrl, "orderID": orderID},
  1192. 'error_code': 0})
  1193. else:
  1194. return response.json(10, '生成订单错误.')
  1195. elif pay_type == 3:
  1196. pay = WechatPayObject()
  1197. notify_url = "{SERVER_DOMAIN_SSL}cloudstorage/dowechatnotify".format(
  1198. SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  1199. # 获取参数
  1200. response = ResponseObject()
  1201. parameter_dict = pay.get_parameter(orderID, content, float(price) * 100, ip, notify_url,
  1202. quote("lang=" + lang))
  1203. print('parameter_dict', parameter_dict)
  1204. # parameter_dict 参数中获取MWEB_URL 调转页面在路径后面添加redirect_url
  1205. # 统一调用接口
  1206. response = pay.re_finall(orderid=orderID)
  1207. if not response:
  1208. return response.json(10, '生成订单错误.')
  1209. # 回调函数
  1210. store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=1).values('lang__title',
  1211. 'lang__content')
  1212. if store_meal_qs.exists():
  1213. store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
  1214. else:
  1215. store_meal_name = '未知套餐'
  1216. Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
  1217. desc=content, payType=pay_type, payTime=nowTime,
  1218. price=price, currency=currency, addTime=nowTime, updTime=nowTime,
  1219. pay_url=notify_url, isSelectDiscounts=is_select_discount,
  1220. commodity_code=commodity_code, commodity_type=commodity_type, rank_id=rank,
  1221. ai_rank_id=1, store_meal_name=store_meal_name)
  1222. return JsonResponse(status=200, data={'result_code': 0, 'reason': 'success',
  1223. 'result': response,
  1224. 'orderId': orderID,
  1225. 'error_code': 0})
  1226. # 调起支付接口
  1227. # 生成体验订单
  1228. def do_experience_order(self, request_dict, userID, response):
  1229. uid = request_dict.get('uid', None)
  1230. channel = request_dict.get('channel', None)
  1231. commodity_code = request_dict.get('commodity_code', None)
  1232. pay_type = int(request_dict.get('pay_type', None))
  1233. rank = request_dict.get('rank', None)
  1234. cdk = request_dict.get('cdk', None)
  1235. lang = request_dict.get('lang', 'en')
  1236. redisObj = RedisObject()
  1237. isLock = redisObj.CONN.setnx(uid + 'do_experience_order', 1)
  1238. redisObj.CONN.expire(uid + 'do_experience_order', 60)
  1239. logger = logging.getLogger('info')
  1240. if not isLock:
  1241. return response.json(5)
  1242. if pay_type == 10: # 判断是否已体验过套餐
  1243. ec_qs = ExperienceContextModel.objects.filter(uid=uid, experience_type=0)
  1244. if ec_qs.exists():
  1245. return response.json(5)
  1246. if cdk is not None and pay_type == 11:
  1247. cdk_qs = CDKcontextModel.objects.filter(cdk=cdk).values('is_activate', 'rank__id', 'rank__commodity_code')
  1248. if not cdk_qs.exists():
  1249. return response.json(10040)
  1250. if cdk_qs[0]['is_activate'] == 1:
  1251. return response.json(10039)
  1252. rank = cdk_qs[0]['rank__id']
  1253. commodity_code = cdk_qs[0]['rank__commodity_code']
  1254. if uid is None or channel is None or commodity_code is None or pay_type is None or rank is None:
  1255. redisObj.del_data(key=uid + 'do_experience_order')
  1256. return response.json(13, '参数有误.')
  1257. dvq = Device_Info.objects.filter(UID=uid)
  1258. dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  1259. if dvq.exists():
  1260. if dvq[0]['vodPrimaryUserID'] != userID:
  1261. if pay_type == 10:
  1262. return response.json(10035)
  1263. if pay_type == 11:
  1264. return response.json(10036)
  1265. dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1)
  1266. if not dv_qs.exists():
  1267. return response.json(12)
  1268. orderID = CommonService.createOrderID()
  1269. nowTime = int(time.time())
  1270. smqs = Store_Meal.objects.filter(id=rank, lang__lang=lang, is_show=0). \
  1271. values("day", "bucket_id", "bucket__storeDay", "expire", 'lang__content', 'price', 'currency',
  1272. 'commodity_type')
  1273. if not smqs.exists():
  1274. return response.json(173)
  1275. bucketId = smqs[0]['bucket_id']
  1276. # ##
  1277. ubqs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id", "bucket__storeDay", "bucket__region",
  1278. "endTime", "use_status")
  1279. expire = smqs[0]['expire']
  1280. try:
  1281. with transaction.atomic():
  1282. if ubqs.exists():
  1283. ubq = ubqs[0]
  1284. if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId: # 套餐使用中并且相同套餐叠加过期时间
  1285. endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
  1286. UID_Bucket.objects.filter(id=ubq['id']).update \
  1287. (uid=uid, channel=channel, bucket_id=bucketId,
  1288. endTime=endTime, updateTime=nowTime)
  1289. else: # 已过期或者不相同的套餐加入未使用的关联套餐表
  1290. has_unused = Unused_Uid_Meal.objects.filter(uid=uid, bucket_id=bucketId).values("id")
  1291. nums = 1
  1292. if has_unused.exists():
  1293. Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
  1294. else:
  1295. Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=nowTime, num=nums,
  1296. expire=smqs[0]['expire'], bucket_id=bucketId)
  1297. UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
  1298. uid_bucket_id = ubq['id']
  1299. else:
  1300. endTime = CommonService.calcMonthLater(expire)
  1301. ub_cqs = UID_Bucket.objects.create \
  1302. (uid=uid, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
  1303. updateTime=nowTime, use_status=1)
  1304. uid_bucket_id = ub_cqs.id
  1305. store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=0).values('lang__title',
  1306. 'lang__content')
  1307. if store_meal_qs.exists():
  1308. store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
  1309. else:
  1310. store_meal_name = '未知套餐'
  1311. Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
  1312. desc=smqs[0]['lang__content'], payType=pay_type, payTime=nowTime,
  1313. price=smqs[0]['price'], currency=smqs[0]['currency'], addTime=nowTime,
  1314. updTime=nowTime,
  1315. pay_url="体验版", store_meal_name=store_meal_name,
  1316. commodity_code=commodity_code, commodity_type=smqs[0]['commodity_type'],
  1317. rank_id=rank, status=1, uid_bucket_id=uid_bucket_id, ai_rank_id=1)
  1318. duq = Device_User.objects.filter(userID=userID).values('username')
  1319. dvq = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
  1320. if dvq.exists():
  1321. dvq_set_update_dict = {
  1322. 'vodPrimaryUserID': userID,
  1323. 'vodPrimaryMaster': duq[0]['username']
  1324. }
  1325. dvq.update(**dvq_set_update_dict)
  1326. # uid_main_exist = UIDMainUser.objects.filter(UID=uid)
  1327. # if not uid_main_exist.exists():
  1328. # uid_main_dict = {
  1329. # 'UID': uid,
  1330. # 'user_id': userID
  1331. # }
  1332. # UIDMainUser.objects.create(**uid_main_dict)
  1333. sms = 'SMS_219738485'
  1334. datetime = time.strftime("%Y-%m-%d", time.localtime())
  1335. # 如果存在序列号,消息提示用序列号
  1336. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  1337. serial_number = device_info_qs[0]['serial_number']
  1338. device_type = device_info_qs[0]['Type']
  1339. if serial_number:
  1340. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1341. else:
  1342. device_name = uid
  1343. sys_msg_text_list = ['温馨提示:尊敬的客户,您的' + device_name + '设备在' + datetime + '已成功购买云存套餐',
  1344. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  1345. "%b %dth,%Y", time.localtime())]
  1346. returnurl = "{SERVER_DOMAIN_SSL}cloudstorage/payOK?lang={lang}".format(
  1347. SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, lang=lang)
  1348. if pay_type == 10:
  1349. ExperienceContextModel.objects.create(
  1350. experience_type=0,
  1351. uid=uid,
  1352. do_time=nowTime
  1353. )
  1354. returnurl = "{SERVER_DOMAIN_SSL}cloudstorage/payOK?paytype=10&lang={lang}".format(
  1355. SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, lang=lang)
  1356. datetime = time.strftime("%Y-%m-%d", time.localtime())
  1357. sys_msg_text_list = ['温馨提示:尊敬的客户,您的' + device_name + '设备在' + datetime + '已成功开通云存体验套餐',
  1358. 'Dear customer,you already subscribed the free trial cloud storage service successfully for device ' + device_name + ' on ' + time.strftime(
  1359. "%b %dth,%Y", time.localtime())]
  1360. sms = 'SMS_222870823'
  1361. if pay_type == 11:
  1362. update_dict = {}
  1363. update_dict['is_activate'] = 1
  1364. update_dict['order'] = orderID
  1365. CDKcontextModel.objects.filter(cdk=cdk).update(**update_dict)
  1366. returnurl = "{SERVER_DOMAIN_SSL}cloudstorage/payOK?paytype=11&lang={lang}".format(
  1367. SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, lang=lang)
  1368. datetime = time.strftime("%Y-%m-%d", time.localtime())
  1369. sys_msg_text_list = ['温馨提示:尊敬的客户,您的' + device_name + '设备在' + datetime + '已成功兑换云存套餐',
  1370. 'Dear customer, you already redeemed for the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  1371. "%b %dth,%Y", time.localtime())]
  1372. sms = 'SMS_219748439'
  1373. self.do_vod_msg_Notice(uid, channel, userID, lang, sys_msg_text_list, sms)
  1374. result = returnurl
  1375. redisObj.del_data(key=uid + 'do_experience_order')
  1376. return response.json(0, result)
  1377. except Exception as e:
  1378. logger.info('出错了~体验云存异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1379. redisObj.del_data(key=uid + 'do_experience_order')
  1380. return response.json(474)
  1381. # red_url =
  1382. # return JsonResponse(status=200, data={'red_url': red_url})
  1383. # return HttpResponseRedirect(red_url)
  1384. # 重置设备云存体验
  1385. def do_experience_reset(self, request_dict, userID, response):
  1386. bid = request_dict.get("id", None)
  1387. ubq = UID_Bucket.objects.filter(id=bid)
  1388. if ubq:
  1389. eq = ExperienceContextModel.objects.filter(uid=ubq[0].uid)
  1390. if eq:
  1391. eq.delete()
  1392. Order_Model.objects.filter(uid_bucket_id=bid).delete()
  1393. ubq.delete()
  1394. else:
  1395. return response.json(10007)
  1396. else:
  1397. return response.json(0, '重置云存体验失败')
  1398. return response.json(0, '重置云存体验成功')
  1399. def deleteVodList(self, request_dict, userID, response): # 删除播放列表
  1400. uid = request_dict.get('uid', None)
  1401. dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1) \
  1402. .values('vodPrimaryUserID')
  1403. if not dv_qs.exists() or dv_qs[0]['vodPrimaryUserID'] != userID:
  1404. return response.json(12)
  1405. vod_id_list = json.loads(request_dict.get('vod_id_list', None))
  1406. is_del_all = request_dict.get('is_del_all', 0)
  1407. try:
  1408. if is_del_all == 1:
  1409. VodHlsModel.objects.filter(uid=uid).delete()
  1410. else:
  1411. if type(vod_id_list).__name__ != 'list':
  1412. return response.json(444)
  1413. VodHlsModel.objects.filter(id__in=vod_id_list).delete()
  1414. except Exception as e:
  1415. return response.json(424, repr(e))
  1416. else:
  1417. return response.json(0)
  1418. # 设备关联套餐列表
  1419. def device_commodity(self, request_dict, userID, response):
  1420. uid = request_dict.get('uid', None)
  1421. lang = request_dict.get('lang', 'en')
  1422. dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1) \
  1423. .values('vodPrimaryUserID', 'serial_number', 'Type')
  1424. if not dv_qs.exists() or dv_qs[0]['vodPrimaryUserID'] != userID:
  1425. return response.json(12)
  1426. now_time = int(time.time())
  1427. bucket_id_list = []
  1428. store_list = []
  1429. uid_bucket = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time).values("id", "uid", "bucket__content",
  1430. "use_status", "endTime",
  1431. "has_unused", "bucket__id")
  1432. if not uid_bucket:
  1433. return response.json(10030)
  1434. # 如果存在序列号返回完整序列号
  1435. device_id = uid
  1436. serial_number = dv_qs[0]['serial_number']
  1437. device_type = dv_qs[0]['Type']
  1438. if serial_number:
  1439. device_id = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1440. uid_bucket[0]['uid'] = device_id
  1441. uid_bucket[0]['storage'] = 0
  1442. has_unused = uid_bucket[0]['has_unused']
  1443. del uid_bucket[0]['has_unused']
  1444. store_list.append(uid_bucket[0])
  1445. bucket_id_list.append(uid_bucket[0]['bucket__id'])
  1446. if has_unused == 1:
  1447. unuseds = Unused_Uid_Meal.objects.filter(uid=uid).annotate(unused_id=F('id')) \
  1448. .values("unused_id", "uid", "bucket__content", "num", "bucket__id", "expire")
  1449. month = 'month' if lang != 'cn' else '个月'
  1450. for ub in unuseds:
  1451. storage_time = ub['num'] * ub['expire']
  1452. if lang != 'cn' and storage_time > 1: # 英文大于一个月使用复数
  1453. month += 's'
  1454. storage = "{storage_time}{month}".format(storage_time=storage_time, month=month)
  1455. unused_dict = {
  1456. "id": ub['unused_id'],
  1457. "uid": device_id,
  1458. "bucket__content": ub['bucket__content'],
  1459. "use_status": 0,
  1460. "endTime": 0,
  1461. "bucket__id": ub['bucket__id'],
  1462. "storage": storage,
  1463. }
  1464. store_list.append(unused_dict)
  1465. bucket_id_list.append(ub['bucket__id'])
  1466. smqs = Store_Meal.objects.filter(bucket__id__in=bucket_id_list, lang__lang=lang).values('lang__lang',
  1467. 'bucket__id',
  1468. 'lang__title')
  1469. for index, value in enumerate(store_list):
  1470. for sm in smqs:
  1471. if value['bucket__id'] == sm['bucket__id']:
  1472. value['bucket__content'] = sm['lang__title']
  1473. return response.json(0, list(store_list))
  1474. # 提前使用设备关联套餐
  1475. def switch_device_commodity(self, request_dict, userID, response):
  1476. uid = request_dict.get('uid', None)
  1477. dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1) \
  1478. .values('vodPrimaryUserID')
  1479. if not dv_qs.exists() or dv_qs[0]['vodPrimaryUserID'] != userID:
  1480. return response.json(12)
  1481. unused_id = request_dict.get('switch_commodity_id', None)
  1482. if unused_id:
  1483. # 切换设备套餐关联
  1484. using_uid_bucket = UID_Bucket.objects.filter(uid=uid, has_unused=1).values("id", "uid", "endTime",
  1485. "bucket__content", "addTime")
  1486. unuseds = Unused_Uid_Meal.objects.filter(id=unused_id).values("id", "uid", "channel", "addTime", "expire",
  1487. "num", "bucket_id")
  1488. if not unuseds.exists() or not using_uid_bucket.exists():
  1489. return response.json(10030)
  1490. unused = unuseds[0]
  1491. nowTime = int(time.time())
  1492. try:
  1493. with transaction.atomic():
  1494. count_unused = Unused_Uid_Meal.objects.filter(uid=uid).count()
  1495. has_unused = 1 if count_unused > 1 else 0
  1496. endTime = CommonService.calcMonthLater(unused['expire'] * unused['num'])
  1497. UID_Bucket.objects.filter(uid=uid).update(channel=unused['channel'], endTime=endTime,
  1498. bucket_id=unused['bucket_id']
  1499. , updateTime=nowTime, use_status=1, has_unused=has_unused)
  1500. Unused_Uid_Meal.objects.filter(id=unused_id).delete()
  1501. StsCrdModel.objects.filter(uid=uid).delete() # 删除sts记录
  1502. # VodHlsModel.objects.filter(uid=uid).delete() # 删除播放列表,后期数据量多时应该考虑延后删除
  1503. except Exception:
  1504. return response.json(474)
  1505. return response.json(0)
  1506. return response.json(444)
  1507. def has_vod(self, request_dict, userID, response):
  1508. uid = request_dict.get('uid', None)
  1509. channel = request_dict.get('channel', 1)
  1510. dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False).values('vodPrimaryUserID',
  1511. 'vodPrimaryMaster')
  1512. if not dv_qs.exists():
  1513. return response.json(12)
  1514. if dv_qs[0]['vodPrimaryUserID'] != userID:
  1515. return response.json(10034)
  1516. now_time = int(time.time())
  1517. bv_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel).values('bucket_id').order_by(
  1518. 'addTime')
  1519. if not bv_qs.exists():
  1520. return response.json(10030)
  1521. had_vod_query = VodHlsModel.objects.extra(select={'date': "FROM_UNIXTIME(time,'%%Y-%%m-%%d')"}).values(
  1522. 'date').filter(uid=uid, endTime__gte=now_time, channel=channel).annotate(count=Count('time')).order_by(
  1523. '-date')[:31]
  1524. had_vod_list = []
  1525. for vod in had_vod_query:
  1526. had_vod_list.append({
  1527. 'timestamp': CommonService.str_to_timestamp(vod['date'], '%Y-%m-%d'),
  1528. 'vod_count': vod['count'],
  1529. 'date_format': vod['date'],
  1530. })
  1531. return response.json(0, had_vod_list)
  1532. def videoPlaybackTime(self, request_dict, userID, response):
  1533. parms = request_dict.get('parms', None)
  1534. if not parms:
  1535. return response.json(444)
  1536. try:
  1537. parms = eval(parms)
  1538. bulk = []
  1539. for parm in parms:
  1540. parm['userID'] = userID
  1541. # 解密uid
  1542. for i in range(1, 4):
  1543. parm['uid'] = base64.b64decode(parm['uid'])
  1544. parm['uid'] = parm['uid'].decode('utf-8')
  1545. parm['uid'] = parm['uid'][i:-i]
  1546. VideoPlaybackTime = VideoPlaybackTimeModel(**parm)
  1547. bulk.append(VideoPlaybackTime)
  1548. VideoPlaybackTimeModel.objects.bulk_create(bulk)
  1549. return response.json(0)
  1550. except Exception as e:
  1551. print(e)
  1552. return response.json(500, repr(e))
  1553. # 云存操作系统消息
  1554. def do_vod_msg_Notice(self, uid, channel, userID, lang, sys_msg_text_list, sms):
  1555. try:
  1556. logger = logging.getLogger('log')
  1557. logger.info('进来了')
  1558. # user = Device_User.objects.get(userID = userID)
  1559. # lang = user.language;
  1560. if lang == 'cn':
  1561. sys_msg_text = sys_msg_text_list[0]
  1562. else:
  1563. sys_msg_text = sys_msg_text_list[1]
  1564. nowTime = int(time.time())
  1565. create_data = {'userID_id': userID, 'msg': sys_msg_text, 'addTime': nowTime,
  1566. 'updTime': nowTime, 'uid': uid, 'eventType': 0}
  1567. SysMsgModel.objects.create(**create_data)
  1568. user_qs = Device_User.objects.filter(userID=userID)
  1569. if user_qs.exists():
  1570. user = user_qs[0]
  1571. username = user.username
  1572. data_valid = DataValid()
  1573. if data_valid.email_validate(username):
  1574. S3Email().faEmail(sys_msg_text, username)
  1575. elif data_valid.mobile_validate(username):
  1576. # 如果存在序列号,消息提示用序列号
  1577. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  1578. serial_number = device_info_qs[0]['serial_number']
  1579. device_type = device_info_qs[0]['Type']
  1580. if serial_number:
  1581. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1582. else:
  1583. device_name = uid
  1584. params = u'{"devname":"' + device_name + '","submittime":"' + time.strftime("%Y-%m-%d",
  1585. time.localtime()) + '"}'
  1586. self.sendMessage(username, params, sms)
  1587. self.pushApp(nowTime, uid, channel, sys_msg_text)
  1588. logger.info('出去了')
  1589. except Exception as e:
  1590. return repr(e)
  1591. # 云存到期续费提醒 提前3天
  1592. def do_vod_msg_end(self, request_dict):
  1593. response = ResponseObject()
  1594. now_time = int(time.time())
  1595. # 过期前第365天提示一次,测试用
  1596. # 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')
  1597. # self.do_vod_msg(now_time,list)
  1598. # 过期前第7天提示一次
  1599. list = UID_Bucket.objects.filter(
  1600. Q(endTime__gt=now_time + 3600 * 144) & Q(endTime__lte=(now_time + 3600 * 168))).values('id', 'uid',
  1601. 'bucket__area',
  1602. 'channel', 'endTime')
  1603. self.do_vod_msg(now_time, list)
  1604. # 过期前第3天提示一次
  1605. list = UID_Bucket.objects.filter(
  1606. Q(endTime__gt=now_time + 3600 * 48) & Q(endTime__lte=(now_time + 3600 * 72))).values('id', 'uid',
  1607. 'bucket__area',
  1608. 'channel', 'endTime')
  1609. self.do_vod_msg(now_time, list)
  1610. return response.json(0)
  1611. def do_vod_msg(self, now_time, list):
  1612. uq_list = []
  1613. ids = []
  1614. for ub in list:
  1615. ids.append(ub['id'])
  1616. oqlist = Order_Model.objects.filter(uid_bucket_id__in=ids).values('userID_id', 'uid_bucket_id')
  1617. for ub in list:
  1618. for oo in oqlist:
  1619. if ub['id'] == oo['uid_bucket_id']:
  1620. # 如果存在序列号,消息提示用序列号
  1621. uid = ub['uid']
  1622. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  1623. serial_number = device_info_qs[0]['serial_number']
  1624. device_type = device_info_qs[0]['Type']
  1625. if serial_number and device_type == 101:
  1626. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1627. else:
  1628. device_name = uid
  1629. if ub['bucket__area'] == 'cn':
  1630. sys_msg_text = "温馨提示:尊敬的客户,您" + device_name + "设备的云存套餐将在" + time.strftime("%Y-%m-%d",
  1631. time.localtime(ub[
  1632. 'endTime'])) + "到期"
  1633. else:
  1634. sys_msg_text = 'Dear customer,the cloud storage package for your device ' + device_name + ' will expire on ' + time.strftime(
  1635. '%m-%d-%y', time.localtime(ub['endTime']))
  1636. uq_list.append(SysMsgModel(
  1637. userID_id=oo['userID_id'],
  1638. addTime=now_time,
  1639. updTime=now_time,
  1640. uid=ub['uid'],
  1641. eventType=0,
  1642. msg=sys_msg_text,
  1643. status=0
  1644. ))
  1645. SysMsgModel.objects.bulk_create(uq_list)
  1646. user_qs = Device_User.objects.filter(userID=oo['userID_id'])
  1647. if user_qs.exists():
  1648. user = user_qs[0]
  1649. username = user.username
  1650. data_valid = DataValid()
  1651. if data_valid.email_validate(username):
  1652. S3Email().faEmail(sys_msg_text, username)
  1653. elif data_valid.mobile_validate(username):
  1654. params = u'{"devname":"' + device_name + '","submittime":"' + time.strftime("%Y-%m-%d",
  1655. time.localtime(
  1656. ub[
  1657. 'endTime'])) + '"}'
  1658. self.sendMessage(username, params, 'SMS_219748440')
  1659. self.pushApp(now_time, ub['uid'], ub['channel'], sys_msg_text)
  1660. def pushApp(self, nowTime, uid, channel, sys_msg_text):
  1661. n_time = nowTime
  1662. kwag_args = {
  1663. 'uid': uid,
  1664. 'channel': channel,
  1665. 'event_type': 0,
  1666. 'n_time': n_time
  1667. }
  1668. # 从数据库查询出来
  1669. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  1670. values('token_val', 'app_type', 'appBundleId', 'm_code',
  1671. 'push_type', 'userID_id', 'userID__NickName',
  1672. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  1673. 'uid_set__channel')
  1674. print(uid_push_qs)
  1675. # 新建一个list接收数据
  1676. redis_list = []
  1677. # 把数据库数据追加进redis_list
  1678. for qs in uid_push_qs:
  1679. redis_list.append(qs)
  1680. nickname = redis_list[0]['uid_set__nickname']
  1681. for up in redis_list:
  1682. push_type = up['push_type']
  1683. appBundleId = up['appBundleId']
  1684. token_val = up['token_val']
  1685. lang = up['lang']
  1686. tz = up['tz']
  1687. if tz is None or tz == '':
  1688. tz = 0
  1689. package_title_config = FCM_CONFIG[appBundleId]
  1690. if appBundleId in package_title_config.keys():
  1691. msg_title = package_title_config[appBundleId] + '(' + nickname + ')'
  1692. else:
  1693. msg_title = nickname
  1694. # 发送内容
  1695. msg_text = sys_msg_text
  1696. kwag_args['appBundleId'] = appBundleId
  1697. kwag_args['token_val'] = token_val
  1698. kwag_args['msg_title'] = msg_title
  1699. kwag_args['msg_text'] = msg_text
  1700. push_server_status = 0
  1701. # 推送
  1702. if push_type == 0: # ios apns
  1703. try:
  1704. cli = apns2.APNSClient(mode=APNS_MODE,
  1705. client_cert=os.path.join(BASE_DIR,
  1706. APNS_CONFIG[appBundleId]['pem_path']))
  1707. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": 0, "msg": "",
  1708. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1",
  1709. "channel": channel}
  1710. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  1711. payload = apns2.Payload(alert=alert, custom=push_data)
  1712. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  1713. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  1714. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  1715. print(res.status_code)
  1716. if res.status_code == 200:
  1717. return res.status_code
  1718. else:
  1719. print('apns push fail')
  1720. print(res.reason)
  1721. return res.status_code
  1722. except (ValueError, ArithmeticError):
  1723. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  1724. except Exception as e:
  1725. print(repr(e))
  1726. return repr(e)
  1727. elif push_type == 1: # android gcm
  1728. try:
  1729. serverKey = FCM_CONFIG[appBundleId]
  1730. except Exception as e:
  1731. return 'serverKey abnormal'
  1732. push_service = FCMNotification(api_key=serverKey)
  1733. data = {"alert": "Motion ", "event_time": n_time, "event_type": 0, "msg": "",
  1734. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  1735. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  1736. message_body=msg_text, data_message=data,
  1737. extra_kwargs={
  1738. 'default_vibrate_timings': True,
  1739. 'default_sound': True,
  1740. 'default_light_settings': True
  1741. })
  1742. print('fcm push ing')
  1743. print(result)
  1744. return result
  1745. elif push_type == 2: # android jpush
  1746. print('do_jpush')
  1747. app_key = JPUSH_CONFIG[appBundleId]['Key']
  1748. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  1749. # 此处换成各自的app_key和master_secre
  1750. _jpush = jpush.JPush(app_key, master_secret)
  1751. push = _jpush.create_push()
  1752. # if you set the logging level to "DEBUG",it will show the debug logging.
  1753. # _jpush.set_logging("DEBUG")
  1754. # push.audience = jpush.all_
  1755. push.audience = jpush.registration_id(token_val)
  1756. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": 0, "msg": "",
  1757. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  1758. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  1759. big_text=msg_text, title=msg_title,
  1760. extras=push_data)
  1761. push.notification = jpush.notification(android=android)
  1762. push.platform = jpush.all_
  1763. res = push.send()
  1764. print(res)
  1765. return res.status_code
  1766. def sendMessage(self, phone, params, temp_msg):
  1767. # 购买成功
  1768. sign_ms = '周视'
  1769. # 发送手机验证码
  1770. aliSms = AliSmsObject()
  1771. res = aliSms.send_code_sms_cloud(phone=phone, params=params, sign_name=sign_ms,
  1772. temp_msg=temp_msg)
  1773. def do_refund(self, request_dict, response):
  1774. orderID = request_dict.get('orderID', None) # 商户订单号
  1775. refund_amount = request_dict.get('refund_amount', None) # 退款金额
  1776. if not all([orderID, refund_amount]):
  1777. return response.json(444)
  1778. try:
  1779. order_qs = Order_Model.objects.filter(orderID=orderID). \
  1780. values('status', 'payType', 'price', 'refunded_amount', 'currency', 'paymentID')
  1781. if not order_qs.exists():
  1782. return response.json(173)
  1783. # 支付状态不为支付成功和退款失败和部分退款
  1784. status = order_qs[0]['status']
  1785. if status != 1 and status != 4 and status != 6:
  1786. return response.json(805)
  1787. refund_amount = float(refund_amount)
  1788. now_time = int(time.time())
  1789. payType = order_qs[0]['payType']
  1790. price = order_qs[0]['price'] # 订单金额
  1791. refunded_amount = order_qs[0]['refunded_amount'] # 已退款金额
  1792. currency = order_qs[0]['currency'] # 货币
  1793. # 判断是否符合付款条件
  1794. if refunded_amount == float(price): # 已全额退款
  1795. return response.json(805)
  1796. if refund_amount + refunded_amount > float(price): # 退款金额超出订单价格
  1797. return response.json(805)
  1798. # 部分退款标识
  1799. is_partial_refund = True if (float(price) > refund_amount + refunded_amount) else False
  1800. out_request_no = str(time.strftime('%Y%m%d%H%M%S', time.localtime(now_time))) # 退款请求号
  1801. # 根据支付类型处理退款
  1802. if payType == 1: # PayPal
  1803. paymentID = order_qs[0]['paymentID'] # PayPal PAYMENT_ID
  1804. if not paymentID:
  1805. return response.json(805)
  1806. paypalrestsdk.configure(PAYPAL_CRD)
  1807. payment = paypalrestsdk.Payment.find(paymentID)
  1808. print('payment', payment)
  1809. related_resources = payment['transactions'][0]['related_resources']
  1810. print('related_resources: ', related_resources)
  1811. if not related_resources:
  1812. return response.json(805)
  1813. sale = related_resources[0]['sale']
  1814. print('sale: ', sale)
  1815. # 没退款过 'state' 不为 'completed' 或 已退款过但 'state' 不为 'partially_refunded'
  1816. if (refunded_amount == 0 and sale['state'] != 'completed') or \
  1817. (refunded_amount != 0 and sale['state'] != 'partially_refunded'):
  1818. return response.json(805)
  1819. sale_id = sale['id']
  1820. paypalSale = paypalrestsdk.Sale.find(sale_id)
  1821. refund = paypalSale.refund({
  1822. 'amount': {
  1823. 'total': refund_amount,
  1824. 'currency': currency
  1825. }
  1826. })
  1827. refund_success = True if refund.success() else False
  1828. elif payType == 2: # 支付宝
  1829. aliPayObj = AliPayObject()
  1830. alipay = aliPayObj.conf()
  1831. refund_response = alipay.api_alipay_trade_refund(refund_amount=refund_amount, out_trade_no=orderID,
  1832. out_request_no=out_request_no)
  1833. refund_success = True if (refund_response['code'] == '10000') else False
  1834. elif payType == 3: # 微信
  1835. wechatPayObj = WechatPayObject()
  1836. refund_fee = int(refund_amount * 100) # 退款金额,单位为分,只能为整数
  1837. success = wechatPayObj.refund(out_trade_no=orderID, out_refund_no=out_request_no,
  1838. total_fee=refund_fee, refund_fee=refund_fee)
  1839. refund_success = True if success else False
  1840. else: # 不支持退款的支付类型
  1841. return response.json(805)
  1842. # 更新订单状态和已退款金额
  1843. update_dict = {'updTime': now_time}
  1844. if refund_success:
  1845. update_dict['status'] = 6 if is_partial_refund else 5
  1846. update_dict['refunded_amount'] = refunded_amount + refund_amount
  1847. else:
  1848. update_dict['status'] = 4
  1849. order_qs.update(**update_dict)
  1850. return response.json(0)
  1851. except Exception as e:
  1852. print(e)
  1853. return response.json(500, repr(e))