CloudStorage.py 102 KB

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