CloudStorage.py 130 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import base64
  4. import datetime
  5. import json
  6. import logging
  7. import sys
  8. import time
  9. import ssl
  10. from decimal import Decimal
  11. from itertools import groupby
  12. from operator import itemgetter
  13. from urllib.parse import quote, parse_qs, unquote
  14. import boto3
  15. import jwt
  16. import paypalrestsdk
  17. from django.db import transaction
  18. from django.db.models import Q, F
  19. from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
  20. from django.views.generic.base import View
  21. from Ansjer.config import SERVER_DOMAIN, PAYPAL_CRD, SERVER_DOMAIN_SSL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, \
  22. AWS_ARN, OAUTH_ACCESS_TOKEN_SECRET, DETECT_PUSH_DOMAINS, CONFIG_INFO, CONFIG_CN
  23. from Controller.CheckUserData import DataValid
  24. from Controller.CloudPhoto.CloudServiceController import CloudServiceController
  25. from Controller.PaymentCycle import Paypal
  26. from Model.models import Device_Info, Order_Model, Store_Meal, VodHlsModel, UID_Bucket, StsCrdModel, \
  27. ExperienceContextModel, Pay_Type, CDKcontextModel, Device_User, SysMsgModel, Unused_Uid_Meal, PromotionRuleModel, \
  28. VideoPlaybackTimeModel, CouponModel, VodBucketModel, VodHlsSummary, AiService, UidSetModel, UidPushModel, \
  29. VodHlsTagType, ICloudStoreMeal, IcloudUseDetails, IcloudService
  30. from Object.AWS.AmazonS3Util import AmazonS3Util
  31. from Object.AWS.S3Email import S3Email
  32. from Object.AliPayObject import AliPayObject
  33. from Object.AliSmsObject import AliSmsObject
  34. from Object.ETkObject import ETkObject
  35. from Object.RedisObject import RedisObject
  36. from Object.ResponseObject import ResponseObject
  37. from Object.TokenObject import TokenObject
  38. from Object.UidTokenObject import UidTokenObject
  39. from Object.WechatPayObject import WechatPayObject
  40. from Object.m3u8generate import PlaylistGenerator
  41. from Service.CommonService import CommonService
  42. from Service.PayService import PaymentService
  43. from Service.VodHlsService import SplitVodHlsObject
  44. from Object.ApplePayObject import ApplePayObject
  45. ssl._create_default_https_context = ssl._create_unverified_context
  46. LOGGER = logging.getLogger('info')
  47. # 设备信息添加
  48. class CloudStorageView(View):
  49. def get(self, request, *args, **kwargs):
  50. request.encoding = 'utf-8'
  51. operation = kwargs.get('operation')
  52. return self.validation(request.GET, request, operation)
  53. def post(self, request, *args, **kwargs):
  54. request.encoding = 'utf-8'
  55. operation = kwargs.get('operation')
  56. return self.validation(request.POST, request, operation)
  57. def validation(self, request_dict, request, operation):
  58. lang = request_dict.get('lang', 'en')
  59. response = ResponseObject(lang)
  60. if operation is None:
  61. return response.json(444, 'error path')
  62. elif operation == 'dopaypalcallback': # paypal支付回调
  63. return self.do_pay_by_paypal_callback(request_dict, response)
  64. elif operation == 'doalicallback': # 阿里支付回调
  65. return self.do_pay_by_ali_callback(request_dict, response)
  66. elif operation == 'dowechatnotify': # 微信支付回调
  67. return self.do_pay_by_wechat_callback(request, response)
  68. elif operation == 'doapplenotify': # 苹果支付回调
  69. return self.do_pay_by_apple_callback(request_dict, response)
  70. elif operation == 'getsignsts': # 设备调用,获取sts令牌
  71. ip = CommonService.get_ip_address(request)
  72. return self.do_get_sign_sts(request_dict, ip, response)
  73. elif operation == 'storeplaylist': # 设备调用,设备把视频上传到s3,同时把视频数据信息传给服务器,服务器存储播放内容
  74. return self.do_store_playlist(request_dict, response)
  75. elif operation == 'signplaym3u8': # 根据sts播放m3u8 视频流
  76. return self.do_sign_play_m3u8(request_dict, response)
  77. elif operation == 'payOK': # 支付成功
  78. return self.do_pay_ok(request_dict)
  79. elif operation == 'vodMsgEnd': # 云存到期续费提醒 提前1天
  80. return self.do_vod_msg_end(response)
  81. elif operation == 'doRefund': # 退款
  82. return self.do_refund(request_dict, response)
  83. else:
  84. token = request_dict.get('token', None)
  85. # 设备主键uid
  86. tko = TokenObject(token)
  87. if tko.code != 0:
  88. return response.json(tko.code)
  89. user_id = tko.userID
  90. if operation == 'createpayorder': # 创建支付订单
  91. ip = CommonService.get_ip_address(request)
  92. return self.do_create_pay_order(request_dict, user_id, ip, response)
  93. elif operation == 'changevodstatus': # 修改云存状态,传送两个url,即getsignsts接口和storeplaylist接口
  94. return self.do_change_vod_status(request_dict, user_id, response)
  95. elif operation == 'changevodaistatus': # 修改云存AI状态
  96. return self.do_change_vod_ai_status(request_dict, user_id, response)
  97. elif operation == 'queryvodlist': # 获取视频播放列表
  98. return self.do_query_vod_list(request_dict, user_id, response)
  99. elif operation == 'commoditylist': # 查询套餐列表
  100. return self.do_commodity_list(request_dict, user_id, response)
  101. elif operation == 'queryorder': # 查询订单列表
  102. return self.do_query_order(request_dict, user_id, response)
  103. elif operation == 'experienceorder': # 生成体验订单
  104. return self.do_experience_order(request_dict, user_id, response)
  105. elif operation == 'experiencereset': # 重置设备云存体验
  106. return self.do_experience_reset(request_dict, response)
  107. elif operation == 'deletevodlist': # 删除播放列表
  108. return self.delete_vod_list(request_dict, user_id, response)
  109. elif operation == 'devicecommodity': # 设备关联套餐列表
  110. return self.device_commodity(request_dict, user_id, response)
  111. elif operation == 'switchdevicecommodity': # 提前使用设备关联套餐
  112. return self.switch_device_commodity(request_dict, user_id, response)
  113. elif operation == 'hasvod': # APP的回放界面,日历表显示当天有无录像
  114. return self.has_vod(request_dict, user_id, response)
  115. elif operation == 'videoPlaybackTime': # 记录app播放时间
  116. return self.video_playback_time(request_dict, user_id, response)
  117. else:
  118. return response.json(414)
  119. @staticmethod
  120. def do_query_order(request_dict, user_id, response): # 查询订单列表
  121. """
  122. 查询订单列表
  123. @param request_dict: 请求数据
  124. @request_dict status: uid
  125. @request_dict page: 通道
  126. @request_dict line: 支付类型
  127. @request_dict uid: 套餐id
  128. @param user_id: 用户id
  129. @param response: 响应
  130. @return: response
  131. """
  132. status = request_dict.get('status', None)
  133. page = request_dict.get('page', None)
  134. line = request_dict.get('line', None)
  135. uid = request_dict.get('uid', None)
  136. if not all([page, line]):
  137. return response.json(444)
  138. page = int(page)
  139. line = int(line)
  140. order_qs = Order_Model.objects.filter(userID_id=user_id)
  141. if status:
  142. order_qs = order_qs.filter(status=status)
  143. # 筛选指定设备id的订单
  144. if uid:
  145. order_qs = order_qs.filter(UID=uid)
  146. if not order_qs.exists():
  147. return response.json(173)
  148. count = order_qs.count()
  149. order_list = order_qs[(page - 1) * line:page * line].values("orderID", "UID", "channel", "desc", "price",
  150. "currency", "addTime", "updTime", "endTime",
  151. "pay_url", "payType", "status", "commodity_type",
  152. "commodity_code")
  153. data = []
  154. now_time = int(time.time())
  155. for order in order_list:
  156. if order['status'] == 0:
  157. if order['addTime'] + 3600 < now_time:
  158. order['status'] = 3
  159. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=order['UID']).values('id', 'Type')
  160. order['did'] = device_info_qs[0]['id'] if device_info_qs.exists() else ''
  161. order['Type'] = device_info_qs[0]['Type'] if device_info_qs.exists() else ''
  162. data.append(order)
  163. return response.json(0, {'data': data, 'count': count})
  164. @staticmethod
  165. def do_commodity_list(request_dict, user_id, response): # 查询套餐列表
  166. """
  167. 查询套餐列表
  168. @param user_id: 用户id
  169. @param request_dict: 请求数据
  170. @request_dict mold: 存储区域类型
  171. @request_dict uid: uid
  172. @request_dict lang: 语言
  173. @param response: 响应
  174. @return: response
  175. """
  176. mold = request_dict.get('mold', None)
  177. uid = request_dict.get('uid', None)
  178. lang = request_dict.get('lang', 'en')
  179. is_ai = request_dict.get('is_ai', 0)
  180. if not all([uid]):
  181. return response.json(444)
  182. is_ai = int(is_ai)
  183. now_time = int(time.time())
  184. # DVR/NVR设备暂不返回云存套餐列表
  185. device_info_qs = Device_Info.objects.filter(Q(UID=uid), Q(Type__lte=4) | Q(Type=10001))
  186. if device_info_qs.exists():
  187. return response.json(0)
  188. # 查询设备像素
  189. uid_set_qs = UidSetModel.objects.filter(uid=uid).values('ucode', 'is_ai')
  190. if not uid_set_qs.exists():
  191. return response.json(173)
  192. ucode = uid_set_qs[0]['ucode']
  193. pixel_level = 1 if ucode and int(ucode[-5]) >= 8 else 0
  194. store_qs = Store_Meal.objects.filter(Q(lang__lang=lang), Q(is_show=0), ~Q(pay_type='11')) # 过滤激活码、隐藏套餐
  195. experience_context_qs = ExperienceContextModel.objects.filter(uid=uid, experience_type=0)
  196. if mold:
  197. store_qs = store_qs.filter(bucket__mold=mold)
  198. # 没体验过的设备只返回体验套餐,体验过的不返回体验套餐
  199. if experience_context_qs.exists():
  200. if not is_ai: # 返回云存套餐
  201. store_qs = store_qs.filter(~Q(pay_type='10'), Q(pixel_level=pixel_level), Q(is_ai=0)) # 筛选像素等级
  202. else: # 返回云存+AI套餐
  203. is_ai = uid_set_qs[0]['is_ai']
  204. is_ai = 1 if is_ai != 2 and CONFIG_INFO != CONFIG_CN else 0 # 国内不支持AI服务
  205. if not is_ai:
  206. return response.json(0)
  207. store_qs = store_qs.filter(~Q(pay_type='10'), Q(pixel_level=pixel_level), Q(is_ai=1)) # 筛选像素等级
  208. else:
  209. store_qs = store_qs.filter(pay_type='10') # 体验套餐不区分像素等级
  210. store_qs = store_qs.annotate(title=F('lang__title'), content=F('lang__content'),
  211. discount_content=F('lang__discount_content'))
  212. store_qs = store_qs.order_by('sort').values("id", "title", "content", "price", "day", "currency",
  213. "bucket__storeDay",
  214. "bucket__bucket", "bucket__area", "commodity_code",
  215. "commodity_type", "is_discounts", "virtual_price", "expire",
  216. "discount_price", "discount_content", "symbol", "cycle_config_id")
  217. if not store_qs.exists():
  218. return response.json(0)
  219. store_list = list(store_qs)
  220. store_list.sort(key=itemgetter('bucket__area'))
  221. res = []
  222. coupon_qs = '' if not user_id else CloudServiceController.get_user_coupon_list(user_id)
  223. for area, items in groupby(store_list, key=itemgetter('bucket__area')):
  224. items_list = list(items)
  225. for item in items_list:
  226. pay_type_qs = Pay_Type.objects.filter(store_meal=item['id']).values("id", "payment")
  227. item['pay_type'] = list(pay_type_qs)
  228. item['is_pay_cycle'] = 1 if item['cycle_config_id'] else 0
  229. del item['cycle_config_id']
  230. item['isCoupon'] = False if not coupon_qs or not coupon_qs.exists() else \
  231. CloudStorageView.check_user_coupon_is_available(coupon_qs, item['id'])
  232. res_c = {'area': area, 'items': items_list}
  233. res.append(res_c)
  234. # 是否促销
  235. promotion_rule_qs = PromotionRuleModel.objects.filter(status=1, startTime__lte=now_time,
  236. endTime__gte=now_time).values('id', 'ruleConfig',
  237. 'ruleName',
  238. 'startTime', 'endTime',
  239. 'ruleDesc')
  240. if promotion_rule_qs.exists():
  241. promotion = {
  242. 'is_promotion': 1,
  243. 'promotionStartTime': promotion_rule_qs[0]['startTime'],
  244. 'promotionEndTime': promotion_rule_qs[0]['endTime'],
  245. 'promotionName': json.loads(promotion_rule_qs[0]['ruleName']).get(lang, ''),
  246. 'promotionDesc': json.loads(promotion_rule_qs[0]['ruleDesc']).get(lang, ''),
  247. 'nowTime': now_time
  248. }
  249. else:
  250. promotion = {
  251. 'is_promotion': 0
  252. }
  253. result = {
  254. 'meals': res,
  255. 'extra':
  256. {
  257. 'cloud_banner': SERVER_DOMAIN + 'web/images/cloud_cn_banner.png',
  258. 'cloud_en_baner': SERVER_DOMAIN_SSL + 'web/images/cloud_en_banner.png'
  259. },
  260. 'promotion': promotion,
  261. }
  262. return response.json(0, result)
  263. @staticmethod
  264. def check_user_coupon_is_available(coupon_qs, combo_id):
  265. """
  266. 查看用户优惠券是否可用
  267. @param coupon_qs: 优惠券列表
  268. @param combo_id: 套餐id
  269. @return:
  270. """
  271. if not coupon_qs.exists():
  272. return False
  273. result = False
  274. for item in coupon_qs:
  275. if result:
  276. break
  277. combo_list = CloudServiceController.get_combo_list(0, item['coupon_config__id'])
  278. if not combo_list:
  279. continue
  280. if combo_id in combo_list:
  281. result = True
  282. return result
  283. @staticmethod
  284. def do_sign_play_m3u8(request_dict, response): # 根据sts播放m3u8 视频流
  285. """
  286. 获取m3u8视频流
  287. @param request_dict: 请求数据
  288. @request_dict uid: uid_token
  289. @request_dict channel: 通道
  290. @request_dict time: 播放列表名字时间戳
  291. @param response: 响应
  292. @return: response
  293. """
  294. uid_token = request_dict.get('uid', None)
  295. channel = request_dict.get('channel', None)
  296. start_time = request_dict.get('time', None)
  297. if not all([uid_token, channel, start_time]):
  298. return response.json(444)
  299. uid = jwt.decode(uid_token, OAUTH_ACCESS_TOKEN_SECRET, algorithms='HS256').get('uid', '')
  300. now_time = int(time.time())
  301. split_vod_hls_obj = SplitVodHlsObject()
  302. vod_hls_qs = split_vod_hls_obj.get_vod_hls_data(uid=uid, channel=channel, start_time__gte=start_time,
  303. end_time__gte=now_time).values("sec", "fg", "bucket_id",
  304. 'start_time')[:10]
  305. if not vod_hls_qs.exists():
  306. return response.json(173)
  307. vod_hls_qs = sorted(vod_hls_qs, key=lambda item: item['start_time'])[:10]
  308. bucket_id = vod_hls_qs[0]['bucket_id']
  309. vod_bucket_qs = VodBucketModel.objects.filter(id=bucket_id).values('bucket', 'region', 'mold')
  310. if not vod_bucket_qs.exists():
  311. return response.json(173)
  312. bucket_region = vod_bucket_qs[0]['region']
  313. bucket_name = vod_bucket_qs[0]['bucket']
  314. mold = vod_bucket_qs[0]["mold"]
  315. s3_obj = AmazonS3Util(
  316. AWS_ACCESS_KEY_ID[mold],
  317. AWS_SECRET_ACCESS_KEY[mold],
  318. bucket_region
  319. )
  320. playlist_entries = []
  321. # ts_count = fg & 0xf
  322. # fg 64位整型,低四位代表ts文件总数,然后进行位运算,一次移四位,每四位转为十进制即为当前ts文件的秒数
  323. for item in vod_hls_qs:
  324. fg = int(item['fg'])
  325. temp_time = item['start_time']
  326. for i in range(15):
  327. shift = (i + 1) * 4
  328. duration = (fg >> shift) & 0xf
  329. if duration > 0:
  330. ts_file = '{uid}/vod{channel}/{time}/ts{i}.ts'.format(uid=uid, channel=channel, time=temp_time,
  331. i=i)
  332. response_url = s3_obj.generate_file_obj_url(bucket_name, ts_file)
  333. playlist_entries.append({
  334. 'name': response_url,
  335. 'duration': duration,
  336. })
  337. playlist = PlaylistGenerator(playlist_entries).generate()
  338. response = HttpResponse(playlist)
  339. response['Content-Type'] = 'application/octet-stream'
  340. response['Content-Disposition'] = 'attachment;filename="play.m3u8"'
  341. return response
  342. @staticmethod
  343. def do_get_sign_sts(request_dict, ip, response): # 获取sts令牌
  344. """
  345. 获取sts令牌
  346. @param request_dict: 请求数据
  347. @param ip: ip地址
  348. @request_dict uidToken: uid_token
  349. @param response: 响应
  350. @return: response
  351. """
  352. uid_token = request_dict.get('uidToken', None)
  353. uid_obj = UidTokenObject(uid_token)
  354. if uid_obj.flag is False:
  355. return response.json(444, 'uidToken')
  356. uid = uid_obj.UID
  357. channel = uid_obj.channel
  358. now_time = int(time.time())
  359. try:
  360. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel).values(
  361. "bucket__mold",
  362. "bucket__bucket",
  363. "bucket__endpoint",
  364. "bucket__region",
  365. "endTime").order_by(
  366. 'addTime')
  367. if not uid_bucket_qs.exists():
  368. res = {'code': 405, 'msg': 'Not purchased or expired!'}
  369. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  370. # 亚马逊 s3 sts
  371. sts_crd_qs = StsCrdModel.objects.filter(uid=uid, channel=channel).values("addTime", "data")
  372. if sts_crd_qs.exists():
  373. end_time = int(sts_crd_qs[0]["addTime"]) + 5000
  374. if end_time > now_time:
  375. res = json.loads(sts_crd_qs[0]["data"])
  376. return JsonResponse(status=200, data=res)
  377. storage = '{uid}/vod{channel}/'.format(uid=uid, channel=channel)
  378. bucket_name = uid_bucket_qs[0]['bucket__bucket']
  379. endpoint = uid_bucket_qs[0]['bucket__endpoint']
  380. region_id = uid_bucket_qs[0]['bucket__region']
  381. try:
  382. aws_access_key_id = AWS_ACCESS_KEY_ID[uid_bucket_qs[0]["bucket__mold"]]
  383. aws_secret_access_key = AWS_SECRET_ACCESS_KEY[uid_bucket_qs[0]["bucket__mold"]]
  384. aws_arn = AWS_ARN[uid_bucket_qs[0]["bucket__mold"]]
  385. except:
  386. res = {'code': 404, 'msg': 'mold not exists!'}
  387. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  388. boto3_sts = boto3.client(
  389. 'sts',
  390. aws_access_key_id=aws_access_key_id,
  391. aws_secret_access_key=aws_secret_access_key,
  392. region_name=region_id
  393. )
  394. policy = {
  395. "Version": "2012-10-17",
  396. "Statement": [
  397. {
  398. "Effect": "Allow",
  399. "Action": "s3:*",
  400. "Resource": ["{aws_arn}:::{bucket_name}/{uid_channel}*".
  401. format(aws_arn=aws_arn, bucket_name=bucket_name, uid_channel=storage)]
  402. }
  403. ]
  404. }
  405. response = boto3_sts.get_federation_token(
  406. Name='{role_name}'.format(role_name=uid + '_' + str(channel)),
  407. Policy=json.dumps(policy),
  408. DurationSeconds=7200
  409. )
  410. res = {
  411. 'AccessKeyId': response['Credentials']['AccessKeyId'],
  412. 'AccessKeySecret': response['Credentials']['SecretAccessKey'],
  413. 'SessionToken': response['Credentials']['SessionToken'],
  414. 'Expiration': response['Credentials']['Expiration'],
  415. 'expire': 900,
  416. 'endpoint': endpoint,
  417. 'bucket_name': bucket_name,
  418. 'arn': response['FederatedUser']['Arn'],
  419. 'code': 0,
  420. 'storage': storage,
  421. 'endTime': uid_bucket_qs[0]['endTime'],
  422. 'ip': ip,
  423. 'region': region_id,
  424. 'bucket_mold': uid_bucket_qs[0]['bucket__mold']
  425. }
  426. if sts_crd_qs.exists():
  427. sts_crd_qs.update(data=json.dumps(res, default=str), addTime=now_time)
  428. else:
  429. StsCrdModel.objects.create(uid=uid, channel=channel, data=json.dumps(res, default=str),
  430. addTime=now_time, type=1)
  431. return JsonResponse(status=200, data=res)
  432. except Exception as e:
  433. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  434. @staticmethod
  435. def do_query_vod_list(request_dict, user_id, response): # 获取视频播放列表
  436. """
  437. 获取视频播放列表
  438. @param request_dict: 请求数据
  439. @param user_id: 用户id
  440. @request_dict startTime: 开始时间
  441. @request_dict endTime: 结束时间
  442. @request_dict uid: uid
  443. @request_dict channel: 通道
  444. @param response: 响应
  445. @return: response
  446. """
  447. logger = logging.getLogger('info')
  448. into_time = int(time.time())
  449. start_time = request_dict.get('startTime', None)
  450. end_time = request_dict.get('endTime', None)
  451. uid = request_dict.get('uid', None)
  452. channel = request_dict.get('channel', None)
  453. event_types = request_dict.get('eventTypes', None)
  454. if not all([uid, channel, start_time, end_time]):
  455. return response.json(444)
  456. if uid == 'UWE2ZJ52SE4FX75U111A':
  457. logger.info({
  458. "intoTime": into_time,
  459. })
  460. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False).values(
  461. 'vodPrimaryUserID', 'Type', 'vodPrimaryMaster')
  462. if not device_info_qs.exists():
  463. return response.json(12)
  464. device_type = device_info_qs[0]['Type']
  465. device_info_qs_time_over = int(time.time())
  466. if uid == 'UWE2ZJ52SE4FX75U111A':
  467. logger.info({
  468. "intoTime": into_time,
  469. "dvQsModelOverTime": device_info_qs_time_over,
  470. })
  471. if device_info_qs[0]['vodPrimaryUserID'] != user_id:
  472. return response.json(10034)
  473. now_time = int(time.time())
  474. if device_type in [34, 37]: # 枪球设备开通云存不区分通道
  475. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time)
  476. else:
  477. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel)
  478. if not uid_bucket_qs.exists():
  479. return response.json(10030)
  480. uid_bucket_qs_time_over = int(time.time())
  481. logger.info({
  482. "intoTime": into_time,
  483. "dvQsModelOverTime": device_info_qs_time_over,
  484. "UidBucketModelOverTime": uid_bucket_qs_time_over,
  485. })
  486. type_list = []
  487. if event_types:
  488. if ',' in event_types:
  489. type_list = event_types.split(',')
  490. type_list = [int(i.strip()) for i in type_list]
  491. else:
  492. type_list = [int(event_types)]
  493. split_vod_hls_obj = SplitVodHlsObject()
  494. if device_type in [34, 37]:
  495. vod_hls_qs = split_vod_hls_obj.get_vod_hls_data(uid=uid,
  496. end_time__gte=now_time,
  497. start_time__range=(start_time, end_time),
  498. type_list=type_list) \
  499. .values("id", "start_time", "sec", "fg", "bucket_id", "channel")
  500. else:
  501. vod_hls_qs = split_vod_hls_obj.get_vod_hls_data(uid=uid, channel=channel,
  502. end_time__gte=now_time,
  503. start_time__range=(start_time, end_time),
  504. type_list=type_list) \
  505. .values("id", "start_time", "sec", "fg", "bucket_id", "channel")
  506. vod_play_list = []
  507. if not vod_hls_qs.exists():
  508. return response.json(0, vod_play_list)
  509. # 不用关联外键查询,因为会查询非常慢
  510. vod_bucket_qs = VodBucketModel.objects.values()
  511. regroup_bucket_qs = {}
  512. for bucket_dict in vod_bucket_qs:
  513. regroup_bucket_qs[bucket_dict['id']] = bucket_dict
  514. vod_hls_qs_time_over = int(time.time())
  515. logger.info({
  516. "intoTime": into_time,
  517. "dvQsModelOverTime": device_info_qs_time_over,
  518. "UidBucketModelOverTime": uid_bucket_qs_time_over,
  519. "vodHlsModelOverTime": vod_hls_qs_time_over,
  520. })
  521. bucket_mold = regroup_bucket_qs[vod_hls_qs[0]['bucket_id']]['mold']
  522. bucket_region = regroup_bucket_qs[vod_hls_qs[0]['bucket_id']]['region']
  523. aws_access_key_id = AWS_ACCESS_KEY_ID[bucket_mold]
  524. aws_secret_access_key = AWS_SECRET_ACCESS_KEY[bucket_mold]
  525. s3_obj = AmazonS3Util(aws_access_key_id, aws_secret_access_key, bucket_region)
  526. uid_token = TokenObject().encryption(data={'uid': uid})
  527. aws_object_over_time = int(time.time())
  528. logger.info({
  529. "intoTime": into_time,
  530. "dvQsModelOverTime": device_info_qs_time_over,
  531. "UidBucketModelOverTime": uid_bucket_qs_time_over,
  532. "vodHlsModelOverTime": vod_hls_qs_time_over,
  533. "awsObjectOverTime": aws_object_over_time,
  534. })
  535. ids = [val['id'] for val in vod_hls_qs]
  536. tag_type_list = SplitVodHlsObject.query_tag_type_list(start_time, ids)
  537. for vod in vod_hls_qs:
  538. bucket_name = regroup_bucket_qs[vod['bucket_id']]['bucket']
  539. thumbs_png = '{uid}/vod{channel}/{time}/Thumb.jpeg'.format(uid=uid, channel=vod['channel'],
  540. time=vod['start_time'])
  541. response_url = s3_obj.generate_file_obj_url(bucket_name, thumbs_png)
  542. vod_url = '{server_domain}cloudstorage/signplaym3u8?' \
  543. 'uid={uid}&channel={channel}&time={time}&sign=tktktktk'. \
  544. format(server_domain=SERVER_DOMAIN_SSL, uid=uid_token, channel=vod['channel'], time=vod['start_time'])
  545. ts_num = int(vod['fg']) & 0xf
  546. # dict_item = [item for item in tag_type_list if item['vod_hls_id'] == vod['id']]
  547. types = []
  548. # if dict_item:
  549. # tag_qs = VodHlsTagType.objects.filter(tag_id=dict_item[0]['id']).values('type')
  550. # types = [val['type'] for val in tag_qs]
  551. vod_play_list.append({
  552. 'start_time': vod['start_time'],
  553. 'sign_url': vod_url,
  554. 'thumb': response_url,
  555. 'sec': vod['sec'],
  556. 'ts_num': ts_num,
  557. 'vod_id': vod['id'],
  558. 'types': types
  559. })
  560. vod_play_list = sorted(vod_play_list, key=lambda item: -item['start_time'])
  561. generate_presigned_over_time = int(time.time())
  562. if uid == 'UWE2ZJ52SE4FX75U111A':
  563. logger.info({
  564. "intoTime": into_time,
  565. "dvQsModelOverTime": device_info_qs_time_over,
  566. "UidBucketModelOverTime": uid_bucket_qs_time_over,
  567. "vodHlsModelOverTime": vod_hls_qs_time_over,
  568. "awsObjectOverTime": aws_object_over_time,
  569. "generatePresignedOverTime": generate_presigned_over_time,
  570. })
  571. return response.json(0, vod_play_list)
  572. @staticmethod
  573. def do_store_playlist(request_dict, response):
  574. """
  575. 存储设备上传云存信息数据
  576. @param request_dict: 请求数据
  577. @request_dict uidToken: uid_token
  578. @request_dict time: 播放列表名字时间戳
  579. @request_dict sec: 秒数
  580. @request_dict fg: ts个数,时间描述片段数
  581. @param response: 响应
  582. @return: response
  583. """
  584. uid_token = request_dict.get('uidToken', None)
  585. start_time = request_dict.get('time', None)
  586. sec = request_dict.get('sec', None)
  587. fg = request_dict.get('fg', None)
  588. if not all([uid_token, start_time, sec]):
  589. return response.json(0)
  590. uid_obj = UidTokenObject(uid_token)
  591. if uid_obj.flag is False:
  592. return response.json(444, 'uidToken')
  593. try:
  594. sec = int(sec)
  595. uid = uid_obj.UID
  596. channel = uid_obj.channel
  597. now_time = int(time.time())
  598. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel).values(
  599. "bucket__mold",
  600. "bucket__bucket",
  601. "bucket__endpoint",
  602. "bucket__region",
  603. "status",
  604. "bucket__storeDay",
  605. "bucket__id").order_by(
  606. 'addTime')
  607. if not uid_bucket_qs.exists():
  608. return response.json(10030)
  609. # 判断设备是否开启云存
  610. uid_bucket = uid_bucket_qs.first()
  611. store_day = uid_bucket['bucket__storeDay']
  612. bucket_id = uid_bucket['bucket__id']
  613. end_time = int(start_time) + store_day * 86400
  614. if uid_bucket['status'] != 1:
  615. return response.json(10, {'msg': '设备未开启云存'})
  616. # 保存云存信息数据
  617. # 创建分表数据
  618. split_vod_hls_obj = SplitVodHlsObject()
  619. vod_vo, week = split_vod_hls_obj.creat_vod_hls_data(uid=uid, channel=channel, start_time=start_time,
  620. end_time=end_time, bucket_id=bucket_id, fg=fg, sec=sec)
  621. split_vod_hls_obj.cloud_vod_hls_tag(vod_vo.id, week, uid, start_time, sec) # 云存关联AI标签
  622. end_time_stamp = datetime.datetime.fromtimestamp(int(start_time))
  623. end_time_str = datetime.datetime(end_time_stamp.year, end_time_stamp.month, 1)
  624. end_time_stamp = CommonService.str_to_timestamp(end_time_str.strftime('%Y-%m-%d %H:%M:%S'))
  625. vod_hls_sum_qs = VodHlsSummary.objects.filter(uid=uid, time=end_time_stamp)
  626. if vod_hls_sum_qs.exists():
  627. vod_hls_sum = vod_hls_sum_qs.first()
  628. vod_hls_sum.upload_frequency += 1
  629. vod_hls_sum.upload_duration += sec
  630. vod_hls_sum.updated_time = now_time
  631. vod_hls_sum.save()
  632. else:
  633. VodHlsSummary.objects.create(uid=uid, time=end_time_stamp, created_time=now_time, updated_time=now_time,
  634. upload_duration=sec, upload_frequency=1)
  635. res = {'code': 0, 'msg': '存储成功'}
  636. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json,charset=utf-8')
  637. except Exception as e:
  638. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  639. @staticmethod
  640. def do_change_vod_status(request_dict, user_id, response): # 修改云存状态
  641. """
  642. 修改云存状态
  643. @param request_dict: 请求数据
  644. @param user_id: 用户id
  645. @request_dict uid: uid
  646. @request_dict status: 套餐状态
  647. @request_dict channel: 通道
  648. @param response: 响应
  649. @return: response
  650. """
  651. uid = request_dict.get('uid', None)
  652. status = request_dict.get('status', None)
  653. channel = request_dict.get('channel', None)
  654. domain_name = request_dict.get('domain_name', None)
  655. if not all([uid, status, channel]):
  656. return response.json(444, 'uid,status,channel')
  657. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
  658. 'vodPrimaryUserID', 'Type')
  659. if not device_info_qs.exists() or device_info_qs[0]['vodPrimaryUserID'] != user_id:
  660. return response.json(12)
  661. device_type = device_info_qs[0]['Type']
  662. if device_type in [34, 37]: # 枪球设备开通云存不区分通道
  663. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid)
  664. else:
  665. uid_bucket_qs = UID_Bucket.objects.filter(channel=channel, uid=uid)
  666. if not uid_bucket_qs.exists():
  667. return response.json(10030)
  668. now_time = int(time.time())
  669. if now_time > uid_bucket_qs[0].endTime:
  670. return response.json(10031)
  671. if status == 0:
  672. uid_bucket_qs.update(status=status)
  673. return response.json(0)
  674. uid_bucket_qs.update(status=status, channel=channel)
  675. uid_obj = UidTokenObject()
  676. uid_obj.generate(data={'uid': uid, 'channel': channel})
  677. # 欧洲域名固定返回欧洲域名
  678. urls = SERVER_DOMAIN_SSL
  679. if domain_name in ['api.zositeche.com', 'api.loocam3.com', 'common.neutral3.com']:
  680. urls = 'https://api.zositeche.com/'
  681. uid_tk_url = '{}cloudstorage/getsignsts?uidToken={}'.format(urls, uid_obj.token)
  682. store_hls_url = '{}cloudstorage/storeplaylist?uidToken={}'.format(urls, uid_obj.token)
  683. return response.json(0, {'uidTkUrl': uid_tk_url, 'storeHlsUrl': store_hls_url})
  684. @staticmethod
  685. def do_change_vod_ai_status(request_dict, user_id, response): # 修改云存状态
  686. """
  687. 修改云存状态
  688. @param request_dict: 请求数据
  689. @param user_id: 用户id
  690. @request_dict uid: uid
  691. @request_dict status: 套餐状态
  692. @request_dict channel: 通道
  693. @param response: 响应
  694. @return: response
  695. """
  696. uid = request_dict.get('uid', None)
  697. vod_status = request_dict.get('vod_status', None)
  698. channel = request_dict.get('channel', None)
  699. domain_name = request_dict.get('domain_name', None)
  700. token_val = request_dict.get('token_val', None)
  701. appBundleId = request_dict.get('appBundleId', None)
  702. app_type = request_dict.get('app_type', None)
  703. push_type = request_dict.get('push_type', None)
  704. ai_status = request_dict.get('ai_status', None)
  705. m_code = request_dict.get('m_code', None)
  706. lang = request_dict.get('lang', 'en')
  707. tz = request_dict.get('tz', '0')
  708. detect_group = request_dict.get('detect_group', None)
  709. interval = request_dict.get('interval', None)
  710. if not all([uid, vod_status, channel]):
  711. return response.json(444, 'uid,vod_status,channel')
  712. vod_status = int(vod_status)
  713. ai_status = int(ai_status)
  714. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
  715. 'vodPrimaryUserID', 'Type')
  716. if not device_info_qs.exists() or device_info_qs[0]['vodPrimaryUserID'] != user_id:
  717. return response.json(12)
  718. device_type = device_info_qs[0]['Type']
  719. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  720. if not uid_set_qs.exists():
  721. return response.json(12)
  722. if device_type in [34, 37]: # 枪球设备开通云存不区分通道
  723. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid)
  724. else:
  725. uid_bucket_qs = UID_Bucket.objects.filter(channel=channel, uid=uid)
  726. if not uid_bucket_qs.exists():
  727. return response.json(10030)
  728. now_time = int(time.time())
  729. end_time = uid_bucket_qs[0].endTime
  730. if now_time > end_time:
  731. return response.json(10031)
  732. try:
  733. with transaction.atomic():
  734. if vod_status == 0: # 关闭云存开关
  735. uid_bucket_qs.update(status=vod_status)
  736. return response.json(0)
  737. uid_obj = UidTokenObject()
  738. uid_obj.generate(data={'uid': uid, 'channel': channel})
  739. # 欧洲域名固定返回欧洲域名
  740. urls = SERVER_DOMAIN_SSL
  741. if domain_name in ['api.zositeche.com', 'api.loocam3.com', 'common.neutral3.com']:
  742. urls = 'https://api.zositeche.com/'
  743. uid_tk_url = '{}cloudstorage/getsignsts?uidToken={}'.format(urls, uid_obj.token)
  744. store_hls_url = '{}cloudstorage/storeplaylist?uidToken={}'.format(urls, uid_obj.token)
  745. thing_name = CommonService.query_serial_with_uid(uid) # 存在序列号则为使用序列号作为物品名
  746. topic_name = 'ansjer/generic/{}'.format(thing_name)
  747. ai_service_qs = AiService.objects.filter(uid=uid, use_status=1)
  748. if ai_status == 0: # 关闭
  749. # mqtt通知设备关闭AI识别功能
  750. msg = {'commandType': 'AIDisable'}
  751. req_success = CommonService.req_publish_mqtt_msg(thing_name, topic_name, msg)
  752. if not req_success:
  753. return response.json(10044)
  754. ai_service_qs.update(detect_status=ai_status, endTime=end_time)
  755. return response.json(0, {'uidTkUrl': uid_tk_url, 'storeHlsUrl': store_hls_url})
  756. elif ai_status == 1: # 开启
  757. if not all([appBundleId, app_type, token_val, uid, m_code, ai_status]):
  758. return response.json(444, 'appBundleId, app_type, token_val, uid,m_code, ai_status')
  759. # 如果传空上来,就默认为0
  760. tz = '0' if tz == '' else tz.replace('GMT', '')
  761. uid_set_id = uid_set_qs[0].id
  762. qs_data = {
  763. 'updTime': now_time,
  764. 'detect_interval': uid_set_qs[0].new_detect_interval if not interval else interval,
  765. 'detect_group': detect_group if detect_group else ''
  766. }
  767. # 更新或创建uid_push数据
  768. uid_push_qs = UidPushModel.objects.filter(userID_id=user_id, m_code=m_code, uid_set__uid=uid)
  769. uid_push_data = {
  770. 'appBundleId': appBundleId,
  771. 'app_type': app_type,
  772. 'push_type': push_type,
  773. 'token_val': token_val,
  774. 'updTime': now_time,
  775. 'lang': lang,
  776. 'tz': tz
  777. }
  778. if uid_push_qs.exists():
  779. uid_push_qs.update(**uid_push_data)
  780. else:
  781. uid_push_data['uid_set_id'] = uid_set_id
  782. uid_push_data['userID_id'] = user_id
  783. uid_push_data['m_code'] = m_code
  784. uid_push_data['addTime'] = now_time
  785. UidPushModel.objects.create(**uid_push_data)
  786. etkObj = ETkObject(etk='')
  787. etk = etkObj.encrypt(uid)
  788. # mqtt通知设备开启AI识别功能
  789. push_url = DETECT_PUSH_DOMAINS
  790. # 欧洲域名固定返回欧洲域名
  791. if domain_name in ['api.zositeche.com', 'api.loocam3.com', 'common.neutral3.com']:
  792. push_url = 'https://push.zositeche.com/'
  793. aiIdentificationUrl = '{}AiService/identification'.format(push_url)
  794. msg = {
  795. 'commandType': 'AIEnable',
  796. 'payload': {
  797. 'etk': etk,
  798. 'endTime': end_time,
  799. 'aiIdentificationUrl': aiIdentificationUrl,
  800. }
  801. }
  802. req_success = CommonService.req_publish_mqtt_msg(thing_name, topic_name, msg)
  803. if not req_success:
  804. return response.json(10044)
  805. uid_set_qs.update(**qs_data)
  806. qs_data['detect_status'] = ai_status # ai开关状态
  807. qs_data['endTime'] = end_time
  808. ai_service_qs.update(**qs_data)
  809. return response.json(0, {'uidTkUrl': uid_tk_url, 'storeHlsUrl': store_hls_url,
  810. 'aiIdentificationUrl': aiIdentificationUrl, 'endTime': end_time,
  811. 'etk': etk})
  812. uid_bucket_qs.update(status=vod_status, channel=channel)
  813. except Exception as e:
  814. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  815. @staticmethod
  816. def do_pay_error():
  817. response = HttpResponse()
  818. response.content = PaymentService.get_pay_error_content()
  819. return response
  820. @staticmethod
  821. def do_pay_ok(request_dict): # 支付成功
  822. """
  823. 支付成功
  824. @param request_dict: 请求数据
  825. @request_dict paytype: 支付类型
  826. @request_dict lang: 语言
  827. @return: response
  828. """
  829. lang = request_dict.get('lang', 'en')
  830. pay_type = request_dict.get('paytype', None)
  831. response = HttpResponse()
  832. response.content = PaymentService.get_pay_ok_content(lang, pay_type)
  833. return response
  834. def do_pay_by_ali_callback(self, request_dict, response): # 阿里支付回调
  835. """
  836. 阿里支付回调
  837. @param request_dict: 请求数据
  838. @request_dict out_trade_no: 订单id
  839. @request_dict sign: 语言
  840. @request_dict trade_status: 语言
  841. @request_dict passback_params: 语言
  842. @param response: 响应
  843. @return: response
  844. """
  845. request_dict = request_dict.dict()
  846. pass_back_params = request_dict["passback_params"]
  847. signature = request_dict["sign"]
  848. request_dict.pop('sign')
  849. order_id = request_dict['out_trade_no']
  850. trade_status = request_dict["trade_status"]
  851. if not all([pass_back_params, signature, order_id, trade_status]):
  852. return response.json(444)
  853. parmap = dict([(k, v[0]) for k, v in parse_qs(unquote(pass_back_params)).items()])
  854. lang = parmap["lang"]
  855. order_qs = Order_Model.objects.filter(orderID=order_id, status=0)
  856. if not order_qs.exists():
  857. return response.json(173)
  858. # redis加锁,防止订单重复
  859. redis_obj = RedisObject()
  860. is_lock = redis_obj.CONN.setnx(order_id + 'do_notify', 1)
  861. redis_obj.CONN.expire(order_id + 'do_notify', 60)
  862. if not is_lock:
  863. return response.json(5)
  864. promotion_rule_id = ''
  865. try:
  866. # 验证阿里支付链接
  867. ali_pay_obj = AliPayObject()
  868. alipay = ali_pay_obj.conf()
  869. success = alipay.verify(request_dict, signature)
  870. if success and trade_status in ("TRADE_SUCCESS", "TRADE_FINISHED"):
  871. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  872. "userID__userID", "userID__username", "coupon_id")
  873. userid = order_list[0]['userID__userID']
  874. username = order_list[0]['userID__username']
  875. uid = order_list[0]['UID']
  876. channel = order_list[0]['channel']
  877. rank = order_list[0]['rank']
  878. store_qs = Store_Meal.objects.filter(id=rank).values('day', 'bucket_id', 'expire',
  879. 'icloud_store_meal_id')
  880. if not store_qs.exists():
  881. return response.json(173)
  882. bucket_id = store_qs[0]['bucket_id']
  883. expire = store_qs[0]['expire']
  884. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id",
  885. "bucket__region", "endTime", "use_status")
  886. # icloud_store_meal_id = store_qs[0]['icloud_store_meal_id']
  887. # icloud_meal_qs = ICloudStoreMeal.objects.filter(id=icloud_store_meal_id).values('size')
  888. # if not icloud_meal_qs.exists():
  889. # return response.json(173)
  890. # size = icloud_meal_qs[0]['size']
  891. if order_list[0]['isSelectDiscounts'] == 1:
  892. expire = store_qs[0]['expire'] * 2
  893. # 是否有促销
  894. now_time = int(time.time())
  895. promotion = PromotionRuleModel.objects.filter(status=1, startTime__lte=now_time,
  896. endTime__gte=now_time).values('id', 'ruleConfig')
  897. if promotion.exists():
  898. promotion_rule_id = promotion[0]['id']
  899. expire = expire * 2
  900. end_time = CommonService.calcMonthLater(expire)
  901. with transaction.atomic():
  902. if uid_bucket_qs.exists():
  903. uid_bucket = uid_bucket_qs.first()
  904. uid_bucket_id = uid_bucket['id']
  905. if uid_bucket['use_status'] == 1 and uid_bucket['endTime'] > now_time: # 套餐使用中并且相同套餐叠加过期时间
  906. Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, is_ai=0,
  907. expire=expire, bucket_id=bucket_id, order_id=order_id)
  908. UID_Bucket.objects.filter(id=uid_bucket_id).update(has_unused=1)
  909. else:
  910. UID_Bucket.objects.filter(id=uid_bucket_id).update(channel=channel, bucket_id=bucket_id,
  911. endTime=end_time, updateTime=now_time,
  912. use_status=1)
  913. else:
  914. uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
  915. endTime=end_time, addTime=now_time, updateTime=now_time,
  916. use_status=1)
  917. uid_bucket_id = uid_bucket.id
  918. device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
  919. if device_info_qs.exists():
  920. dvq_set_update_dict = {
  921. 'vodPrimaryUserID': userid,
  922. 'vodPrimaryMaster': username
  923. }
  924. device_info_qs.update(**dvq_set_update_dict)
  925. # 核销coupon
  926. if order_list[0]['coupon_id']:
  927. CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2,
  928. update_time=now_time)
  929. order_qs.update(status=1, updTime=now_time, uid_bucket_id=uid_bucket_id,
  930. promotion_rule_id=promotion_rule_id)
  931. date_time = time.strftime("%Y-%m-%d", time.localtime())
  932. # 开通云盘服务
  933. # icloud_use_qs = IcloudUseDetails.objects.filter(user_id=userid).values('id')
  934. # if not icloud_use_qs.exists():
  935. # bucket_qs = VodBucketModel.objects.filter(bucket='icloud').values('id')
  936. # icloud_use_qs = IcloudUseDetails.objects.create(add_time=now_time, upd_time=now_time,
  937. # detect_status=1, user_id=userid,
  938. # bucket_id=bucket_qs[0]['id'])
  939. # use_details_id = icloud_use_qs.id
  940. # IcloudService.objects.create(add_time=now_time, upd_time=now_time, type=0,
  941. # size=1, use_details_id=use_details_id)
  942. # else:
  943. # use_details_id = icloud_use_qs[0]['id']
  944. # IcloudService.objects.create(order_id=order_id, add_time=now_time, upd_time=now_time, type=1,
  945. # size=size, end_time=end_time, use_details_id=use_details_id)
  946. # 如果存在序列号,消息提示用序列号
  947. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  948. serial_number = device_info_qs[0]['serial_number']
  949. device_type = device_info_qs[0]['Type']
  950. if serial_number:
  951. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  952. else:
  953. device_name = uid
  954. sys_msg_text_list = [
  955. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
  956. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  957. "%b %dth,%Y", time.localtime())]
  958. self.do_vod_msg_notice(uid, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
  959. red_url = "{}web/paid2/success.html".format(SERVER_DOMAIN_SSL)
  960. if lang != 'cn':
  961. red_url = red_url.replace('success.html', 'en_success.html')
  962. redis_obj.del_data(key=order_id + 'do_notify')
  963. return HttpResponseRedirect(red_url)
  964. return response.json(0, signature)
  965. except Exception as e:
  966. logger = logging.getLogger('info')
  967. logger.info('alipay----notify---------')
  968. logger.info(repr(e))
  969. logger.info(sys.exc_info())
  970. logger.info('alipay支付失败:----')
  971. logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
  972. logger.info(repr(e))
  973. if order_qs:
  974. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  975. redis_obj.del_data(key=order_id + 'do_notify')
  976. red_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
  977. if lang != 'cn':
  978. red_url = red_url.replace('fail.html', 'en_fail.html')
  979. return HttpResponseRedirect(red_url)
  980. def do_pay_by_paypal_callback(self, request_dict, response): # paypal支付回调
  981. """
  982. paypal支付回调
  983. @param request_dict: 请求数据
  984. @request_dict paymentId: 支付id
  985. @request_dict PayerID: 支付人id
  986. @request_dict orderID: 订单id
  987. @request_dict lang: 语言
  988. @param response: 响应
  989. @return: response
  990. """
  991. logger = logging.getLogger('info')
  992. logger.info('---------进入paypal异步回调')
  993. payment_id = request_dict.get('paymentId', None)
  994. payer_id = request_dict.get('PayerID', None)
  995. order_id = request_dict.get('orderID', None)
  996. lang = request_dict.get('lang', 'en')
  997. if not all([payer_id, payment_id]):
  998. return response.json(444)
  999. logger.info("paymentID={paymentId},payerID={PayerID}".format(paymentId=payment_id, PayerID=payer_id))
  1000. # redis加锁,防止订单重复
  1001. redis_obj = RedisObject()
  1002. is_lock = redis_obj.CONN.setnx(order_id + 'do_notify', 1)
  1003. redis_obj.CONN.expire(order_id + 'do_notify', 60)
  1004. if not is_lock:
  1005. return response.json(5)
  1006. order_qs = Order_Model.objects.filter(orderID=order_id, status=0)
  1007. if not order_qs.exists():
  1008. return response.json(173)
  1009. promotion_rule_id = ''
  1010. try:
  1011. if not order_id:
  1012. red_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
  1013. if lang != 'cn':
  1014. red_url = red_url.replace('fail.html', 'en_fail.html')
  1015. return HttpResponseRedirect(red_url)
  1016. paypalrestsdk.configure(PAYPAL_CRD)
  1017. payment = paypalrestsdk.Payment.find(payment_id)
  1018. logger.info("payment------")
  1019. logger.info(payment)
  1020. payers = payment.execute({"payer_id": payer_id})
  1021. logger.info(payers)
  1022. if not payers:
  1023. red_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
  1024. if lang != 'cn':
  1025. red_url = red_url.replace('fail.html', 'en_fail.html')
  1026. redis_obj.del_data(key=order_id + 'do_notify')
  1027. return HttpResponseRedirect(red_url)
  1028. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  1029. "userID__userID", "userID__username", "coupon_id")
  1030. userid = order_list[0]['userID__userID']
  1031. username = order_list[0]['userID__username']
  1032. uid = order_list[0]['UID']
  1033. channel = order_list[0]['channel']
  1034. rank = order_list[0]['rank']
  1035. store_qs = Store_Meal.objects.filter(id=rank).values("day", "bucket_id", "expire", "is_ai",
  1036. 'icloud_store_meal_id')
  1037. if not store_qs.exists():
  1038. return response.json(173)
  1039. bucket_id = store_qs[0]['bucket_id']
  1040. is_ai = store_qs[0]['is_ai']
  1041. expire = store_qs[0]['expire']
  1042. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id",
  1043. "bucket__region", "endTime", "use_status")
  1044. # icloud_store_meal_id = store_qs[0]['icloud_store_meal_id']
  1045. # icloud_meal_qs = ICloudStoreMeal.objects.filter(id=icloud_store_meal_id).values('size')
  1046. # if not icloud_meal_qs.exists():
  1047. # return response.json(173)
  1048. # size = icloud_meal_qs[0]['size']
  1049. if order_list[0]['isSelectDiscounts'] == 1:
  1050. expire = store_qs[0]['expire'] * 2
  1051. # 是否有促销
  1052. now_time = int(time.time())
  1053. promotion_rule_qs = PromotionRuleModel.objects.filter(status=1, startTime__lte=now_time,
  1054. endTime__gte=now_time).values('id', 'ruleConfig')
  1055. if promotion_rule_qs.exists():
  1056. promotion_rule_id = promotion_rule_qs[0]['id']
  1057. expire = expire * 2
  1058. end_time = CommonService.calcMonthLater(expire)
  1059. use_flag = True
  1060. with transaction.atomic():
  1061. if uid_bucket_qs.exists():
  1062. uid_bucket = uid_bucket_qs.first()
  1063. uid_bucket_id = uid_bucket['id']
  1064. if uid_bucket['use_status'] == 1 and uid_bucket['endTime'] > now_time: # 套餐使用中并且相同套餐叠加过期时间
  1065. Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, order_id=order_id,
  1066. expire=expire, is_ai=is_ai, bucket_id=bucket_id)
  1067. update_status = UID_Bucket.objects.filter(id=uid_bucket_id).update(has_unused=1)
  1068. use_flag = False
  1069. else:
  1070. update_status = UID_Bucket.objects.filter(id=uid_bucket_id).update(channel=channel,
  1071. bucket_id=bucket_id,
  1072. endTime=end_time,
  1073. updateTime=now_time,
  1074. use_status=1)
  1075. else:
  1076. uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
  1077. endTime=end_time, addTime=now_time, updateTime=now_time,
  1078. use_status=1)
  1079. update_status = True
  1080. uid_bucket_id = uid_bucket.id
  1081. device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
  1082. if device_info_qs.exists():
  1083. dvq_set_update_dict = {
  1084. 'vodPrimaryUserID': userid,
  1085. 'vodPrimaryMaster': username
  1086. }
  1087. device_info_qs.update(**dvq_set_update_dict)
  1088. # 核销coupon
  1089. if order_list[0]['coupon_id']:
  1090. CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2, update_time=now_time)
  1091. logger.info(
  1092. 'uid:{},uid_bucket_id:{},update_status:{},order_id:{}'.format(uid, uid_bucket_id, update_status,
  1093. order_id))
  1094. order_qs.update(status=1, updTime=now_time, uid_bucket_id=uid_bucket_id,
  1095. promotion_rule_id=promotion_rule_id)
  1096. date_time = time.strftime("%Y-%m-%d", time.localtime())
  1097. # 开通AI服务
  1098. if is_ai and use_flag:
  1099. ai_service = AiService.objects.filter(uid=uid, channel=channel)
  1100. if ai_service.exists(): # 有正在使用的套餐,套餐结束时间保存为套餐有效期
  1101. ai_service.update(updTime=now_time, use_status=1, orders_id=order_id, endTime=end_time)
  1102. else:
  1103. AiService.objects.create(uid=uid, channel=channel, detect_status=1, addTime=now_time,
  1104. updTime=now_time, endTime=end_time, use_status=1, orders_id=order_id)
  1105. # 开通云盘服务
  1106. # icloud_use_qs = IcloudUseDetails.objects.filter(user_id=userid).values('id')
  1107. # if not icloud_use_qs.exists():
  1108. # bucket_qs = VodBucketModel.objects.filter(bucket='icloud').values('id')
  1109. # icloud_use_qs = IcloudUseDetails.objects.create(add_time=now_time, upd_time=now_time,
  1110. # detect_status=1, user_id=userid,
  1111. # bucket_id=bucket_qs[0]['id'])
  1112. # use_details_id = icloud_use_qs.id
  1113. # IcloudService.objects.create(add_time=now_time, upd_time=now_time, type=0,
  1114. # size=1, use_details_id=use_details_id)
  1115. # else:
  1116. # use_details_id = icloud_use_qs[0]['id']
  1117. # IcloudService.objects.create(order_id=order_id, add_time=now_time, upd_time=now_time, type=1,
  1118. # size=size, end_time=end_time, use_details_id=use_details_id)
  1119. # 如果存在序列号,消息提示用序列号
  1120. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  1121. serial_number = device_info_qs[0]['serial_number']
  1122. device_type = device_info_qs[0]['Type']
  1123. if serial_number:
  1124. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1125. else:
  1126. device_name = uid
  1127. sys_msg_text_list = [
  1128. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
  1129. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  1130. "%b %dth,%Y", time.localtime())]
  1131. self.do_vod_msg_notice(uid, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
  1132. red_url = "{}web/paid2/success.html".format(SERVER_DOMAIN_SSL)
  1133. if lang != 'cn':
  1134. red_url = red_url.replace('success.html', 'en_success.html')
  1135. redis_obj.del_data(key=order_id + 'do_notify')
  1136. return HttpResponseRedirect(red_url)
  1137. except Exception as e:
  1138. logger.info('paypal支付失败:----')
  1139. logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
  1140. logger.info(repr(e))
  1141. if order_qs:
  1142. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  1143. red_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
  1144. if lang != 'cn':
  1145. red_url = red_url.replace('fail.html', 'en_fail.html')
  1146. redis_obj.del_data(key=order_id + 'do_notify')
  1147. return HttpResponseRedirect(red_url)
  1148. def do_pay_by_wechat_callback(self, request, response): # 微信支付回调
  1149. """
  1150. 微信支付回调
  1151. @param request: 请求体
  1152. @request_dict result_code: 业务结果
  1153. @request_dict out_trade_no: 商户订单号
  1154. @request_dict lang: 语言
  1155. @param response: 响应
  1156. @return: response
  1157. """
  1158. logger = logging.getLogger('info')
  1159. pay = WechatPayObject()
  1160. data = pay.weixinpay_call_back(request.body)
  1161. attach = data["attach"]
  1162. parmap = dict([(k, v[0]) for k, v in parse_qs(unquote(attach)).items()])
  1163. lang = parmap["lang"]
  1164. trade_status = data['result_code'] # 业务结果 SUCCESS/FAIL
  1165. order_id = data['out_trade_no'] # 商户订单号
  1166. if not all([attach, trade_status, order_id]):
  1167. return response.json(444)
  1168. logger.info(order_id)
  1169. order_qs = Order_Model.objects.filter(orderID=order_id, status=0)
  1170. if not order_qs.exists():
  1171. return response.json(173)
  1172. # redis加锁,防止订单重复
  1173. redis_obj = RedisObject()
  1174. is_lock = redis_obj.CONN.setnx(order_id + 'do_notify', 1)
  1175. redis_obj.CONN.expire(order_id + 'do_notify', 60)
  1176. if not is_lock:
  1177. return response.json(5)
  1178. promotion_rule_id = ''
  1179. try:
  1180. if trade_status == "SUCCESS":
  1181. check_sign = pay.get_notifypay(data)
  1182. if not check_sign:
  1183. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '签名失败'}))
  1184. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  1185. "userID__userID", "userID__username", "status", "coupon_id")
  1186. logger.info(order_list[0]['UID'])
  1187. userid = order_list[0]['userID__userID']
  1188. username = order_list[0]['userID__username']
  1189. uid = order_list[0]['UID']
  1190. channel = order_list[0]['channel']
  1191. rank = order_list[0]['rank']
  1192. store_qs = Store_Meal.objects.filter(id=rank).values("day", "bucket_id", "expire",
  1193. 'icloud_store_meal_id')
  1194. if not store_qs.exists():
  1195. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '套餐不存在'}))
  1196. bucket_id = store_qs[0]['bucket_id']
  1197. expire = store_qs[0]['expire']
  1198. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id",
  1199. "bucket__region", "endTime", "use_status")
  1200. # icloud_store_meal_id = store_qs[0]['icloud_store_meal_id']
  1201. # icloud_meal_qs = ICloudStoreMeal.objects.filter(id=icloud_store_meal_id).values('size')
  1202. # if not icloud_meal_qs.exists():
  1203. # return response.json(173)
  1204. # size = icloud_meal_qs[0]['size']
  1205. if order_list[0]['isSelectDiscounts'] == 1:
  1206. expire = store_qs[0]['expire'] * 2
  1207. # 是否有促销
  1208. now_time = int(time.time())
  1209. promotion_rule_qs = PromotionRuleModel.objects.filter(status=1, startTime__lte=now_time,
  1210. endTime__gte=now_time).values('id', 'ruleConfig')
  1211. if promotion_rule_qs.exists():
  1212. promotion_rule_id = promotion_rule_qs[0]['id']
  1213. expire = expire * 2
  1214. end_time = CommonService.calcMonthLater(expire)
  1215. with transaction.atomic():
  1216. if uid_bucket_qs.exists():
  1217. uid_bucket = uid_bucket_qs.first()
  1218. uid_bucket_id = uid_bucket['id']
  1219. if uid_bucket['use_status'] == 1 and uid_bucket['endTime'] > now_time: # 套餐使用中并且相同套餐叠加过期时间
  1220. Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, is_ai=0,
  1221. expire=expire, bucket_id=bucket_id, order_id=order_id)
  1222. UID_Bucket.objects.filter(id=uid_bucket['id']).update(has_unused=1)
  1223. else:
  1224. UID_Bucket.objects.filter(id=uid_bucket_id).update(channel=channel, bucket_id=bucket_id,
  1225. endTime=end_time, updateTime=now_time,
  1226. use_status=1)
  1227. else:
  1228. uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
  1229. endTime=end_time, addTime=now_time,
  1230. updateTime=now_time, use_status=1)
  1231. uid_bucket_id = uid_bucket.id
  1232. device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
  1233. if device_info_qs.exists():
  1234. dvq_set_update_dict = {
  1235. 'vodPrimaryUserID': userid,
  1236. 'vodPrimaryMaster': username
  1237. }
  1238. device_info_qs.update(**dvq_set_update_dict)
  1239. # 核销coupon
  1240. if order_list[0]['coupon_id']:
  1241. CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2,
  1242. update_time=now_time)
  1243. order_qs.update(status=1, updTime=now_time, uid_bucket_id=uid_bucket_id,
  1244. promotion_rule_id=promotion_rule_id)
  1245. date_time = time.strftime("%Y-%m-%d", time.localtime())
  1246. # 开通云盘服务
  1247. # icloud_use_qs = IcloudUseDetails.objects.filter(user_id=userid).values('id')
  1248. # if not icloud_use_qs.exists():
  1249. # bucket_qs = VodBucketModel.objects.filter(bucket='icloud').values('id')
  1250. # icloud_use_qs = IcloudUseDetails.objects.create(add_time=now_time, upd_time=now_time,
  1251. # detect_status=1, user_id=userid,
  1252. # bucket_id=bucket_qs[0]['id'])
  1253. # use_details_id = icloud_use_qs.id
  1254. # IcloudService.objects.create(add_time=now_time, upd_time=now_time, type=0,
  1255. # size=1, use_details_id=use_details_id)
  1256. # else:
  1257. # use_details_id = icloud_use_qs[0]['id']
  1258. # IcloudService.objects.create(order_id=order_id, add_time=now_time, upd_time=now_time, type=1,
  1259. # size=size, end_time=end_time, use_details_id=use_details_id)
  1260. # 如果存在序列号,消息提示用序列号
  1261. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  1262. serial_number = device_info_qs[0]['serial_number']
  1263. device_type = device_info_qs[0]['Type']
  1264. if serial_number:
  1265. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1266. else:
  1267. device_name = uid
  1268. sys_msg_text_list = [
  1269. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
  1270. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  1271. "%b %dth,%Y", time.localtime())]
  1272. self.do_vod_msg_notice(uid, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
  1273. redis_obj.del_data(key=order_id + 'do_notify')
  1274. return HttpResponse("<xml>\
  1275. <return_code><![CDATA[SUCCESS]]></return_code>\
  1276. <return_msg><![CDATA[OK]]></return_msg>\
  1277. </xml>")
  1278. else:
  1279. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  1280. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '参数格式校验错误'}))
  1281. except Exception as e:
  1282. logger.info('wechat支付失败:----')
  1283. logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
  1284. logger.info(repr(e))
  1285. if order_qs:
  1286. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  1287. redis_obj.del_data(key=order_id + 'do_notify')
  1288. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': repr(e)}))
  1289. def do_pay_by_apple_callback(self, request_dict, response):
  1290. """
  1291. apple支付回调
  1292. @param request_dict: 请求数据
  1293. @request_dict paymentId: 支付id
  1294. @request_dict PayerID: 支付人id
  1295. @request_dict orderID: 订单id
  1296. @request_dict lang: 语言
  1297. @param response: 响应
  1298. @return: response
  1299. """
  1300. logger = logging.getLogger('info')
  1301. logger.info('---------进入apple异步回调')
  1302. receipt_data = request_dict.get('receipt_data', None)
  1303. order_id = request_dict.get('order_id', None)
  1304. lang = request_dict.get('lang', 'en')
  1305. if not all([receipt_data, order_id]):
  1306. return response.json(444)
  1307. logger.info("receipt_data={},order_id={}".format(receipt_data, order_id))
  1308. # redis加锁,防止订单重复
  1309. redis_obj = RedisObject()
  1310. is_lock = redis_obj.CONN.setnx(order_id + 'do_notify', 1)
  1311. redis_obj.CONN.expire(order_id + 'do_notify', 60)
  1312. if not is_lock:
  1313. return response.json(5)
  1314. order_qs = Order_Model.objects.filter(orderID=order_id, status=0)
  1315. if not order_qs.exists():
  1316. return response.json(173)
  1317. promotion_rule_id = ''
  1318. try:
  1319. apple_obj = ApplePayObject()
  1320. verify_result = apple_obj.verify(receipt_data)
  1321. logger.info("verify_result:{}".format(verify_result))
  1322. if not verify_result:
  1323. red_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
  1324. if lang != 'cn':
  1325. red_url = red_url.replace('fail.html', 'en_fail.html')
  1326. redis_obj.del_data(key=order_id + 'do_notify')
  1327. return response.json(0, {'url': red_url})
  1328. trade_no = verify_result['transactionId']
  1329. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  1330. "userID__userID", "userID__username", "coupon_id")
  1331. userid = order_list[0]['userID__userID']
  1332. username = order_list[0]['userID__username']
  1333. uid = order_list[0]['UID']
  1334. channel = order_list[0]['channel']
  1335. rank = order_list[0]['rank']
  1336. store_qs = Store_Meal.objects.filter(id=rank).values("day", "bucket_id", "expire", "is_ai",
  1337. 'icloud_store_meal_id')
  1338. if not store_qs.exists():
  1339. return response.json(173)
  1340. bucket_id = store_qs[0]['bucket_id']
  1341. is_ai = store_qs[0]['is_ai']
  1342. expire = store_qs[0]['expire']
  1343. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id",
  1344. "bucket__region", "endTime", "use_status")
  1345. # icloud_store_meal_id = store_qs[0]['icloud_store_meal_id']
  1346. # icloud_meal_qs = ICloudStoreMeal.objects.filter(id=icloud_store_meal_id).values('size')
  1347. # if not icloud_meal_qs.exists():
  1348. # return response.json(173)
  1349. # size = icloud_meal_qs[0]['size']
  1350. if order_list[0]['isSelectDiscounts'] == 1:
  1351. expire = store_qs[0]['expire'] * 2
  1352. # 是否有促销
  1353. now_time = int(time.time())
  1354. promotion_rule_qs = PromotionRuleModel.objects.filter(status=1, startTime__lte=now_time,
  1355. endTime__gte=now_time).values('id', 'ruleConfig')
  1356. if promotion_rule_qs.exists():
  1357. promotion_rule_id = promotion_rule_qs[0]['id']
  1358. expire = expire * 2
  1359. end_time = CommonService.calcMonthLater(expire)
  1360. use_flag = True
  1361. with transaction.atomic():
  1362. if uid_bucket_qs.exists():
  1363. uid_bucket = uid_bucket_qs.first()
  1364. uid_bucket_id = uid_bucket['id']
  1365. if uid_bucket['use_status'] == 1 and uid_bucket['endTime'] > now_time: # 套餐使用中并且相同套餐叠加过期时间
  1366. Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, order_id=order_id,
  1367. expire=expire, is_ai=is_ai, bucket_id=bucket_id)
  1368. update_status = UID_Bucket.objects.filter(id=uid_bucket_id).update(has_unused=1)
  1369. use_flag = False
  1370. else:
  1371. update_status = UID_Bucket.objects.filter(id=uid_bucket_id).update(channel=channel,
  1372. bucket_id=bucket_id,
  1373. endTime=end_time,
  1374. updateTime=now_time,
  1375. use_status=1)
  1376. else:
  1377. uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
  1378. endTime=end_time, addTime=now_time, updateTime=now_time,
  1379. use_status=1)
  1380. update_status = True
  1381. uid_bucket_id = uid_bucket.id
  1382. device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
  1383. if device_info_qs.exists():
  1384. dvq_set_update_dict = {
  1385. 'vodPrimaryUserID': userid,
  1386. 'vodPrimaryMaster': username
  1387. }
  1388. device_info_qs.update(**dvq_set_update_dict)
  1389. # 核销coupon
  1390. if order_list[0]['coupon_id']:
  1391. CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2, update_time=now_time)
  1392. logger.info(
  1393. 'uid:{},uid_bucket_id:{},update_status:{},order_id:{}'.format(uid, uid_bucket_id, update_status,
  1394. order_id))
  1395. order_qs.update(status=1, updTime=now_time, uid_bucket_id=uid_bucket_id, trade_no=trade_no,
  1396. promotion_rule_id=promotion_rule_id)
  1397. date_time = time.strftime("%Y-%m-%d", time.localtime())
  1398. # 开通AI服务
  1399. if is_ai and use_flag:
  1400. ai_service = AiService.objects.filter(uid=uid, channel=channel)
  1401. if ai_service.exists(): # 有正在使用的套餐,套餐结束时间保存为套餐有效期
  1402. ai_service.update(updTime=now_time, use_status=1, orders_id=order_id, endTime=end_time)
  1403. else:
  1404. AiService.objects.create(uid=uid, channel=channel, detect_status=1, addTime=now_time,
  1405. updTime=now_time, endTime=end_time, use_status=1, orders_id=order_id)
  1406. # 开通云盘服务
  1407. # icloud_use_qs = IcloudUseDetails.objects.filter(user_id=userid).values('id')
  1408. # if not icloud_use_qs.exists():
  1409. # bucket_qs = VodBucketModel.objects.filter(bucket='icloud').values('id')
  1410. # icloud_use_qs = IcloudUseDetails.objects.create(add_time=now_time, upd_time=now_time,
  1411. # detect_status=1, user_id=userid,
  1412. # bucket_id=bucket_qs[0]['id'])
  1413. # use_details_id = icloud_use_qs.id
  1414. # IcloudService.objects.create(add_time=now_time, upd_time=now_time, type=0,
  1415. # size=1, use_details_id=use_details_id)
  1416. # else:
  1417. # use_details_id = icloud_use_qs[0]['id']
  1418. # IcloudService.objects.create(order_id=order_id, add_time=now_time, upd_time=now_time, type=1,
  1419. # size=size, end_time=end_time, use_details_id=use_details_id)
  1420. # 如果存在序列号,消息提示用序列号
  1421. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  1422. serial_number = device_info_qs[0]['serial_number']
  1423. device_type = device_info_qs[0]['Type']
  1424. if serial_number:
  1425. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1426. else:
  1427. device_name = uid
  1428. sys_msg_text_list = [
  1429. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
  1430. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  1431. "%b %dth,%Y", time.localtime())]
  1432. self.do_vod_msg_notice(uid, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
  1433. red_url = "{}web/paid2/success.html".format(SERVER_DOMAIN_SSL)
  1434. if lang != 'cn':
  1435. red_url = red_url.replace('success.html', 'en_success.html')
  1436. redis_obj.del_data(key=order_id + 'do_notify')
  1437. return response.json(0, {'url': red_url})
  1438. except Exception as e:
  1439. logger.info('apple支付失败:----')
  1440. logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
  1441. logger.info(repr(e))
  1442. if order_qs:
  1443. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  1444. red_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
  1445. if lang != 'cn':
  1446. red_url = red_url.replace('fail.html', 'en_fail.html')
  1447. redis_obj.del_data(key=order_id + 'do_notify')
  1448. return response.json(0, {'url': red_url})
  1449. @staticmethod
  1450. def do_create_pay_order(request_dict, user_id, ip, response): # 创建支付订单
  1451. """
  1452. 创建支付订单
  1453. @param request_dict: 请求数据
  1454. @param user_id: 用户id
  1455. @param ip: ip地址
  1456. @request_dict uid: uid
  1457. @request_dict channel: 通道
  1458. @request_dict pay_type: 支付类型
  1459. @request_dict rank: 套餐id
  1460. @request_dict is_select_discount: 用户是否选择了第二年优惠
  1461. @request_dict coupon_id: 优惠券id
  1462. @request_dict lang: 语言
  1463. @param response: 响应
  1464. @return: response
  1465. """
  1466. logger = logging.getLogger('info')
  1467. uid = request_dict.get('uid', None)
  1468. channel = request_dict.get('channel', None)
  1469. pay_type = request_dict.get('pay_type', None)
  1470. rank = request_dict.get('rank', None)
  1471. is_select_discount = request_dict.get('is_select_discount', 0)
  1472. coupon_id = request_dict.get('coupon_id', 0)
  1473. lang = request_dict.get('lang', 'en')
  1474. if not all([uid, channel, pay_type, rank]):
  1475. return response.json(444)
  1476. pay_type = int(pay_type)
  1477. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
  1478. 'vodPrimaryUserID',
  1479. 'vodPrimaryMaster')
  1480. if not device_info_qs.exists():
  1481. return response.json(12)
  1482. device_info_qs = Device_Info.objects.filter(Q(UID=uid), ~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  1483. if device_info_qs.exists():
  1484. if device_info_qs[0]['vodPrimaryUserID'] != user_id:
  1485. return response.json(10033)
  1486. now_time = int(time.time())
  1487. store_qs = Store_Meal.objects.filter(id=rank, pay_type=pay_type, lang__lang=lang, is_show=0). \
  1488. values('currency', 'price', 'lang__content', 'day', 'commodity_type', 'lang__title', 'expire',
  1489. 'commodity_code', 'discount_price', 'bucket__mold', 'cycle_config_id')
  1490. if not store_qs.exists():
  1491. return response.json(173)
  1492. store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=0).values('lang__title',
  1493. 'lang__content')
  1494. if store_meal_qs.exists():
  1495. store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
  1496. else:
  1497. store_meal_name = '未知套餐'
  1498. currency = store_qs[0]['currency']
  1499. price = store_qs[0]['price']
  1500. if is_select_discount == '1':
  1501. price = float(store_qs[0]['price']) + float(store_qs[0]['discount_price'])
  1502. content = store_qs[0]['lang__content']
  1503. commodity_code = store_qs[0]['commodity_code']
  1504. commodity_type = store_qs[0]['commodity_type']
  1505. is_mold = 1 if store_qs[0]['bucket__mold'] == 0 else 0 # 判断国内外
  1506. order_qs = Order_Model.objects.filter(UID=uid, rank__bucket__mold=is_mold)
  1507. if order_qs.exists():
  1508. if is_mold == 1:
  1509. return response.json(10060)
  1510. return response.json(10041)
  1511. order_id = CommonService.createOrderID()
  1512. # 优惠券
  1513. if coupon_id:
  1514. coupon_qs = CouponModel.objects.filter(id=coupon_id, use_status=0, distribute_time__lte=now_time,
  1515. valid_time__gt=now_time).values("id", "coupon_config__type",
  1516. "coupon_config__coupon_discount")
  1517. if not coupon_qs.exists():
  1518. return response.json(10049)
  1519. price = Decimal(price)
  1520. coupon_discount = Decimal(coupon_qs[0]['coupon_config__coupon_discount'])
  1521. if coupon_qs[0]['coupon_config__type'] == 1: # 打折
  1522. price = coupon_discount / 10 * price
  1523. elif coupon_qs[0]['coupon_config__type'] == 2: # 抵扣
  1524. price = price - coupon_discount
  1525. price = float(price)
  1526. if price < 0 or price == 0 or price < 0.01:
  1527. price = 0.01
  1528. price = round(price, 2)
  1529. if pay_type == 1:
  1530. # 订阅周期扣款
  1531. if store_qs[0]['cycle_config_id']:
  1532. # 查询是否有订阅过,活跃状态
  1533. check_has_subscribe = Paypal.checkSubscriptions(user_id, uid, rank)
  1534. if not check_has_subscribe:
  1535. return response.json(10050)
  1536. sub_info = Paypal.subscriptions(store_info=store_qs[0], lang=lang, orderID=order_id, price=price)
  1537. if not sub_info:
  1538. return response.json(10048)
  1539. Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
  1540. desc=content, payType=pay_type, payTime=now_time,
  1541. price=price, currency=currency, addTime=now_time,
  1542. updTime=now_time,
  1543. pay_url=sub_info['url'], isSelectDiscounts=is_select_discount,
  1544. commodity_code=commodity_code, commodity_type=commodity_type,
  1545. rank_id=rank, plan_id=sub_info['plan_id'], coupon_id=coupon_id,
  1546. ai_rank_id=1,
  1547. store_meal_name=store_meal_name)
  1548. return response.json(0, {"redirectUrl": sub_info['url'], "orderID": order_id})
  1549. # 正常扣款
  1550. call_clc_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
  1551. if lang != 'cn':
  1552. call_clc_url = call_clc_url.replace('fail.html', 'en_fail.html')
  1553. call_sub_url = "{}cloudstorage/dopaypalcallback?orderID={}&lang={}".format(SERVER_DOMAIN_SSL, order_id,
  1554. lang)
  1555. paypalrestsdk.configure(PAYPAL_CRD)
  1556. payment = paypalrestsdk.Payment({
  1557. "intent": "sale",
  1558. "payer": {"payment_method": "paypal"},
  1559. "redirect_urls": {"return_url": call_sub_url, "cancel_url": call_clc_url},
  1560. "transactions": [{
  1561. "item_list": {"items": [
  1562. {"name": "Cloud video", "sku": "1", "price": price, "currency": "USD", "quantity": 1}]},
  1563. "amount": {"total": price, "currency": currency},
  1564. "description": content}]})
  1565. if not payment.create():
  1566. return response.json(10, payment.error)
  1567. logger.info('paypal创建订单返回----------')
  1568. logger.info(payment)
  1569. payment_id = payment['id'] # 获取paymentID
  1570. for link in payment.links:
  1571. if link.rel == "approval_url":
  1572. approval_url = str(link.href)
  1573. Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
  1574. desc=content, payType=pay_type, payTime=now_time,
  1575. price=price, currency=currency, addTime=now_time,
  1576. updTime=now_time,
  1577. pay_url=approval_url, isSelectDiscounts=is_select_discount,
  1578. commodity_code=commodity_code, commodity_type=commodity_type,
  1579. rank_id=rank, paymentID=payment_id, coupon_id=coupon_id,
  1580. ai_rank_id=1,
  1581. store_meal_name=store_meal_name)
  1582. return response.json(0, {"redirectUrl": approval_url, "orderID": order_id})
  1583. return response.json(10, 'generate_order_false')
  1584. elif pay_type == 2:
  1585. try:
  1586. ali_pay_obj = AliPayObject()
  1587. alipay = ali_pay_obj.conf()
  1588. subject = store_qs[0]['lang__title'] + store_qs[0]['lang__content']
  1589. order_string = alipay.api_alipay_trade_wap_pay(
  1590. out_trade_no=order_id,
  1591. total_amount=price,
  1592. subject=subject,
  1593. return_url="{}web/paid2/success.html".format(SERVER_DOMAIN_SSL),
  1594. notify_url="{}cloudstorage/doalicallback".format(SERVER_DOMAIN_SSL),
  1595. quit_url="{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL),
  1596. passback_params=quote("lang=" + lang)
  1597. )
  1598. except Exception as e:
  1599. print(repr(e))
  1600. return response.json(10, repr(e))
  1601. else:
  1602. if order_string:
  1603. redirect_url = ali_pay_obj.alipay_prefix + order_string
  1604. Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
  1605. desc=content, payType=pay_type, payTime=now_time,
  1606. price=price, currency=currency, addTime=now_time,
  1607. updTime=now_time,
  1608. pay_url=redirect_url, isSelectDiscounts=is_select_discount,
  1609. commodity_code=commodity_code, commodity_type=commodity_type,
  1610. rank_id=rank, coupon_id=coupon_id, ai_rank_id=1,
  1611. store_meal_name=store_meal_name)
  1612. return JsonResponse(status=200, data={'result_code': 0, 'reason': 'success',
  1613. 'result': {"redirectUrl": redirect_url, "orderID": order_id},
  1614. 'error_code': 0})
  1615. else:
  1616. return response.json(10, '生成订单错误.')
  1617. elif pay_type == 3:
  1618. pay = WechatPayObject()
  1619. notify_url = "{}cloudstorage/dowechatnotify".format(SERVER_DOMAIN_SSL)
  1620. content = CommonService.Package_Type(0, content) # 云存套餐
  1621. # 获取参数
  1622. parameter_dict = pay.get_parameter(order_id, content, float(price) * 100, ip, notify_url,
  1623. quote("lang=" + lang))
  1624. print('parameter_dict', parameter_dict)
  1625. # parameter_dict 参数中获取MWEB_URL 调转页面在路径后面添加redirect_url
  1626. # 统一调用接口
  1627. response = pay.re_finall(orderid=order_id)
  1628. if not response:
  1629. return response.json(10, '生成订单错误.')
  1630. # 回调函数
  1631. Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
  1632. desc=content, payType=pay_type, payTime=now_time,
  1633. price=price, currency=currency, addTime=now_time, updTime=now_time,
  1634. pay_url=notify_url, isSelectDiscounts=is_select_discount,
  1635. commodity_code=commodity_code, commodity_type=commodity_type,
  1636. rank_id=rank,
  1637. ai_rank_id=1, store_meal_name=store_meal_name)
  1638. return JsonResponse(status=200, data={'result_code': 0, 'reason': 'success',
  1639. 'result': response,
  1640. 'orderId': order_id,
  1641. 'error_code': 0})
  1642. elif pay_type == 4:
  1643. notify_url = "{}cloudstorage/doapplenotify".format(SERVER_DOMAIN_SSL)
  1644. content = CommonService.Package_Type(0, content) # 云存套餐
  1645. # 回调函数
  1646. Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
  1647. desc=content, payType=pay_type, payTime=now_time,
  1648. price=price, currency=currency, addTime=now_time, updTime=now_time,
  1649. isSelectDiscounts=is_select_discount,
  1650. commodity_code=commodity_code, commodity_type=commodity_type,
  1651. rank_id=rank,
  1652. ai_rank_id=1, store_meal_name=store_meal_name)
  1653. return JsonResponse(status=200, data={'result_code': 0, 'reason': 'success',
  1654. 'result': {"redirectUrl": notify_url, "orderID": order_id},
  1655. 'error_code': 0})
  1656. def do_experience_order(self, request_dict, user_id, response): # 生成体验订单
  1657. """
  1658. 生成体验订单
  1659. @param request_dict: 请求数据
  1660. @param user_id: 用户id
  1661. @request_dict uid: uid
  1662. @request_dict channel: 通道
  1663. @request_dict commodity_code: 套餐规格码
  1664. @request_dict pay_type: 支付类型
  1665. @request_dict rank: 存储套餐id
  1666. @request_dict cdk: 激活码
  1667. @request_dict lang: 语言
  1668. @param response: 响应
  1669. @return: response
  1670. """
  1671. uid = request_dict.get('uid', None)
  1672. channel = request_dict.get('channel', None)
  1673. commodity_code = request_dict.get('commodity_code', '')
  1674. pay_type = int(request_dict.get('pay_type', None))
  1675. rank = request_dict.get('rank', None)
  1676. cdk = request_dict.get('cdk', None)
  1677. lang = request_dict.get('lang', 'en')
  1678. if uid is None:
  1679. return response.json(444, 'uid.')
  1680. redis_obj = RedisObject()
  1681. is_lock = redis_obj.CONN.setnx(uid + 'do_experience_order', 1)
  1682. redis_obj.CONN.expire(uid + 'do_experience_order', 60)
  1683. logger = logging.getLogger('info')
  1684. if not is_lock:
  1685. return response.json(5)
  1686. if pay_type == 10: # 判断是否已体验过套餐
  1687. experience_context_qs = ExperienceContextModel.objects.filter(uid=uid, experience_type=0)
  1688. if experience_context_qs.exists():
  1689. return response.json(5)
  1690. if cdk is not None and pay_type == 11:
  1691. cdk_qs = CDKcontextModel.objects.filter(cdk=cdk).values('is_activate', 'rank__id', 'rank__commodity_code')
  1692. if not cdk_qs.exists():
  1693. return response.json(10040)
  1694. if cdk_qs[0]['is_activate'] == 1:
  1695. return response.json(10039)
  1696. rank = cdk_qs[0]['rank__id']
  1697. commodity_code = cdk_qs[0]['rank__commodity_code']
  1698. if not all([channel, pay_type, rank]):
  1699. redis_obj.del_data(key=uid + 'do_experience_order')
  1700. return response.json(444, 'channel, pay_type, rank')
  1701. device_info_qs = Device_Info.objects.filter(Q(UID=uid), ~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  1702. if device_info_qs.exists():
  1703. if device_info_qs[0]['vodPrimaryUserID'] != user_id:
  1704. if pay_type == 10:
  1705. return response.json(10035)
  1706. if pay_type == 11:
  1707. return response.json(10036)
  1708. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1)
  1709. if not device_info_qs.exists():
  1710. return response.json(12)
  1711. device_vo = device_info_qs.first()
  1712. if device_vo.Type == 103 or device_vo.Type == 26:
  1713. return response.json(10064)
  1714. order_id = CommonService.createOrderID()
  1715. now_time = int(time.time())
  1716. store_qs = Store_Meal.objects.filter(id=rank, lang__lang=lang, is_show=0).values("day", "bucket_id",
  1717. "expire",
  1718. 'lang__content', 'price',
  1719. 'currency', 'commodity_type',
  1720. 'icloud_store_meal_id')
  1721. if not store_qs.exists():
  1722. return response.json(173)
  1723. bucket_id = store_qs[0]['bucket_id']
  1724. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id", "bucket__region",
  1725. "endTime", "use_status")
  1726. expire = store_qs[0]['expire']
  1727. uid_set_qs = UidSetModel.objects.filter(uid=uid).values('is_ai')
  1728. if not uid_set_qs.exists():
  1729. return response.json(173)
  1730. is_ai = 1 if uid_set_qs[0]['is_ai'] != 2 else 0
  1731. use_flag = True
  1732. end_time = CommonService.calcMonthLater(expire)
  1733. # icloud_store_meal_id = store_qs[0]['icloud_store_meal_id']
  1734. # icloud_meal_qs = ICloudStoreMeal.objects.filter(id=icloud_store_meal_id).values('size')
  1735. # if not icloud_meal_qs.exists():
  1736. # return response.json(173)
  1737. # size = icloud_meal_qs[0]['size']
  1738. try:
  1739. with transaction.atomic():
  1740. if uid_bucket_qs.exists():
  1741. uid_bucket = uid_bucket_qs.first()
  1742. uid_bucket_id = uid_bucket['id']
  1743. if uid_bucket['use_status'] == 1 and uid_bucket['endTime'] > now_time:
  1744. Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, is_ai=is_ai,
  1745. order_id=order_id, expire=expire, bucket_id=bucket_id)
  1746. UID_Bucket.objects.filter(id=uid_bucket_id).update(has_unused=1)
  1747. use_flag = False
  1748. else:
  1749. UID_Bucket.objects.filter(id=uid_bucket_id).update(channel=channel, bucket_id=bucket_id,
  1750. endTime=end_time, updateTime=now_time,
  1751. use_status=1)
  1752. else:
  1753. uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
  1754. endTime=end_time, addTime=now_time, updateTime=now_time,
  1755. use_status=1)
  1756. uid_bucket_id = uid_bucket.id
  1757. # 开通云盘体验
  1758. # icloud_use_qs = IcloudUseDetails.objects.filter(user_id=user_id).values('id')
  1759. # if not icloud_use_qs.exists():
  1760. # bucket_qs = VodBucketModel.objects.filter(bucket='icloud').values('id')
  1761. # icloud_use_qs = IcloudUseDetails.objects.create(add_time=now_time, upd_time=now_time,
  1762. # detect_status=1, user_id=user_id,
  1763. # bucket_id=bucket_qs[0]['id'])
  1764. # use_details_id = icloud_use_qs.id
  1765. # IcloudService.objects.create(add_time=now_time, upd_time=now_time, type=0,
  1766. # size=1, use_details_id=use_details_id)
  1767. # else:
  1768. # use_details_id = icloud_use_qs[0]['id']
  1769. # IcloudService.objects.create(order_id=order_id, add_time=now_time, upd_time=now_time, type=1,
  1770. # size=size, end_time=end_time, use_details_id=use_details_id)
  1771. store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=0).values('lang__title',
  1772. 'lang__content')
  1773. if store_meal_qs.exists():
  1774. store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
  1775. else:
  1776. store_meal_name = '未知套餐'
  1777. Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
  1778. desc=store_qs[0]['lang__content'], payType=pay_type, payTime=now_time,
  1779. price=store_qs[0]['price'], currency=store_qs[0]['currency'],
  1780. addTime=now_time,
  1781. updTime=now_time,
  1782. pay_url="体验版", store_meal_name=store_meal_name,
  1783. commodity_code=commodity_code, commodity_type=store_qs[0]['commodity_type'],
  1784. rank_id=rank, status=1, uid_bucket_id=uid_bucket_id, ai_rank_id=1)
  1785. # 开通AI服务,国内不支持AI
  1786. if is_ai and use_flag and CONFIG_INFO != CONFIG_CN:
  1787. ai_service = AiService.objects.filter(uid=uid, channel=channel)
  1788. if ai_service.exists(): # 有正在使用的套餐,套餐结束时间保存为套餐有效期
  1789. ai_service.update(updTime=now_time, use_status=1, orders_id=order_id, endTime=end_time)
  1790. else:
  1791. AiService.objects.create(uid=uid, channel=channel, detect_status=1, addTime=now_time,
  1792. updTime=now_time, endTime=end_time, use_status=1, orders_id=order_id)
  1793. device_user_qs = Device_User.objects.filter(userID=user_id).values('username')
  1794. device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
  1795. if device_info_qs.exists():
  1796. dvq_set_update_dict = {
  1797. 'vodPrimaryUserID': user_id,
  1798. 'vodPrimaryMaster': device_user_qs[0]['username']
  1799. }
  1800. device_info_qs.update(**dvq_set_update_dict)
  1801. sms = 'SMS_219738485'
  1802. date_time = time.strftime("%Y-%m-%d", time.localtime())
  1803. # 如果存在序列号,消息提示用序列号
  1804. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  1805. serial_number = device_info_qs[0]['serial_number']
  1806. device_type = device_info_qs[0]['Type']
  1807. if serial_number:
  1808. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1809. else:
  1810. device_name = uid
  1811. sys_msg_text_list = [
  1812. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
  1813. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  1814. "%b %dth,%Y", time.localtime())]
  1815. return_url = "{}cloudstorage/payOK?lang={}".format(SERVER_DOMAIN_SSL, lang)
  1816. if pay_type == 10:
  1817. ExperienceContextModel.objects.create(
  1818. experience_type=0,
  1819. uid=uid,
  1820. do_time=now_time
  1821. )
  1822. return_url = "{}cloudstorage/payOK?paytype=10&lang={}".format(SERVER_DOMAIN_SSL, lang)
  1823. date_time = time.strftime("%Y-%m-%d", time.localtime())
  1824. sys_msg_text_list = [
  1825. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功开通云存体验套餐',
  1826. 'Dear customer,you already subscribed the free trial cloud storage service successfully for device ' + device_name + ' on ' + time.strftime(
  1827. "%b %dth,%Y", time.localtime())]
  1828. sms = 'SMS_222870823'
  1829. if pay_type == 11:
  1830. update_dict = {'is_activate': 1, 'order': order_id}
  1831. CDKcontextModel.objects.filter(cdk=cdk).update(**update_dict)
  1832. return_url = "{}cloudstorage/payOK?paytype=11&lang={}".format(SERVER_DOMAIN_SSL, lang)
  1833. date_time = time.strftime("%Y-%m-%d", time.localtime())
  1834. sys_msg_text_list = [
  1835. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功兑换云存套餐',
  1836. 'Dear customer, you already redeemed for the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  1837. "%b %dth,%Y", time.localtime())]
  1838. sms = 'SMS_219748439'
  1839. self.do_vod_msg_notice(uid, channel, user_id, lang, sys_msg_text_list, sms)
  1840. result = return_url
  1841. redis_obj.del_data(key=uid + 'do_experience_order')
  1842. return response.json(0, result)
  1843. except Exception as e:
  1844. logger.info('出错了~体验云存异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1845. redis_obj.del_data(key=uid + 'do_experience_order')
  1846. return response.json(474)
  1847. @staticmethod
  1848. def do_experience_reset(request_dict, response): # 重置设备云存体验
  1849. """
  1850. 重置设备云存体验
  1851. @param request_dict: 请求数据
  1852. @request_dict id: 关联套餐id
  1853. @param response: 响应
  1854. @return: response
  1855. """
  1856. bucket_id = request_dict.get("id", None)
  1857. uid_bucket_qs = UID_Bucket.objects.filter(id=bucket_id)
  1858. if uid_bucket_qs.exists():
  1859. experience_context_qs = ExperienceContextModel.objects.filter(uid=uid_bucket_qs[0].uid)
  1860. if experience_context_qs.exists():
  1861. experience_context_qs.delete()
  1862. Order_Model.objects.filter(uid_bucket_id=bucket_id).delete()
  1863. uid_bucket_qs.delete()
  1864. else:
  1865. return response.json(10007)
  1866. else:
  1867. return response.json(0, '重置云存体验失败')
  1868. return response.json(0, '重置云存体验成功')
  1869. @staticmethod
  1870. def delete_vod_list(request_dict, user_id, response): # 删除播放列表
  1871. """
  1872. 删除播放列表
  1873. @param request_dict: 请求数据
  1874. @param user_id: 用户id
  1875. @request_dict uid: uid
  1876. @request_dict vod_id_list: 云存视频id列表
  1877. @param response: 响应
  1878. @return: response
  1879. """
  1880. uid = request_dict.get('uid', None)
  1881. vod_id_list = request_dict.get('vod_id_list', None)
  1882. is_del_all = request_dict.get('is_del_all', 0)
  1883. if not all([uid, vod_id_list]):
  1884. return response.json(444)
  1885. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
  1886. 'vodPrimaryUserID')
  1887. if not device_info_qs.exists() or device_info_qs[0]['vodPrimaryUserID'] != user_id:
  1888. return response.json(12)
  1889. vod_id_list = json.loads(vod_id_list)
  1890. try:
  1891. if is_del_all == 1:
  1892. VodHlsModel.objects.filter(uid=uid).delete()
  1893. # 删除vod_hls分表数据
  1894. split_vod_hls_obj = SplitVodHlsObject()
  1895. split_vod_hls_obj.del_vod_hls_data(uid=uid)
  1896. else:
  1897. if type(vod_id_list).__name__ != 'list':
  1898. return response.json(444)
  1899. VodHlsModel.objects.filter(id__in=vod_id_list).delete()
  1900. # 删除vod_hls分表数据
  1901. split_vod_hls_obj = SplitVodHlsObject()
  1902. split_vod_hls_obj.del_vod_hls_data(id__in=vod_id_list)
  1903. except Exception as e:
  1904. return response.json(424, repr(e))
  1905. else:
  1906. return response.json(0)
  1907. @staticmethod
  1908. def device_commodity(request_dict, user_id, response): # 设备关联套餐列表
  1909. """
  1910. 设备关联套餐列表
  1911. @param request_dict: 请求数据
  1912. @param user_id: 用户id
  1913. @request_dict uid: uid
  1914. @request_dict lang: 语言
  1915. @param response: 响应
  1916. @return: response
  1917. """
  1918. uid = request_dict.get('uid', None)
  1919. lang = request_dict.get('lang', 'en')
  1920. if not uid:
  1921. return response.json(444)
  1922. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
  1923. 'vodPrimaryUserID', 'serial_number', 'Type')
  1924. if not device_info_qs.exists() or device_info_qs[0]['vodPrimaryUserID'] != user_id:
  1925. return response.json(12)
  1926. now_time = int(time.time())
  1927. bucket_id_list = []
  1928. store_list = []
  1929. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time).values("id", "uid", "bucket__content",
  1930. "use_status", "endTime",
  1931. "has_unused", "bucket__id")
  1932. if not uid_bucket_qs:
  1933. return response.json(10030)
  1934. # 如果存在序列号返回完整序列号
  1935. device_id = uid
  1936. serial_number = device_info_qs[0]['serial_number']
  1937. device_type = device_info_qs[0]['Type']
  1938. if serial_number:
  1939. device_id = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1940. uid_bucket_qs[0]['uid'] = device_id
  1941. uid_bucket_qs[0]['storage'] = 0
  1942. has_unused = uid_bucket_qs[0]['has_unused']
  1943. del uid_bucket_qs[0]['has_unused']
  1944. store_list.append(uid_bucket_qs[0])
  1945. bucket_id_list.append(uid_bucket_qs[0]['bucket__id'])
  1946. if has_unused == 1:
  1947. unused_uid_qs = Unused_Uid_Meal.objects.filter(uid=uid).annotate(unused_id=F('id')).values("unused_id",
  1948. "uid",
  1949. "bucket__content",
  1950. "bucket__id",
  1951. "expire")
  1952. month = 'month' if lang != 'cn' else '个月'
  1953. for unused_uid in unused_uid_qs:
  1954. storage_time = unused_uid['expire']
  1955. if lang != 'cn' and storage_time > 1: # 英文大于一个月使用复数
  1956. month += 's'
  1957. storage = str(storage_time) + month
  1958. unused_dict = {
  1959. "id": unused_uid['unused_id'],
  1960. "uid": device_id,
  1961. "bucket__content": unused_uid['bucket__content'],
  1962. "use_status": 0,
  1963. "endTime": 0,
  1964. "bucket__id": unused_uid['bucket__id'],
  1965. "storage": storage,
  1966. }
  1967. store_list.append(unused_dict)
  1968. bucket_id_list.append(unused_uid['bucket__id'])
  1969. store_qs = Store_Meal.objects.filter(bucket__id__in=bucket_id_list, lang__lang=lang).annotate(
  1970. title=F('lang__title'), content=F('lang__content')).values('lang__content', 'lang__lang',
  1971. 'bucket__id', 'lang__title')
  1972. for index, value in enumerate(store_list):
  1973. for store in store_qs:
  1974. if value['bucket__id'] == store['bucket__id']:
  1975. value['bucket__content'] = store['lang__title'] + '-' + store['lang__content']
  1976. return response.json(0, list(store_list))
  1977. @staticmethod
  1978. def switch_device_commodity(request_dict, user_id, response): # 提前使用设备关联套餐
  1979. """
  1980. 提前使用设备关联套餐
  1981. @param request_dict: 请求数据
  1982. @param user_id: 用户id
  1983. @request_dict uid: uid
  1984. @request_dict switch_commodity_id: 未使用关联套餐id
  1985. @param response: 响应
  1986. @return: response
  1987. """
  1988. uid = request_dict.get('uid', None)
  1989. unused_id = request_dict.get('switch_commodity_id', None)
  1990. if not all([uid, unused_id]):
  1991. return response.json(444)
  1992. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
  1993. 'vodPrimaryUserID')
  1994. if not device_info_qs.exists() or device_info_qs[0]['vodPrimaryUserID'] != user_id:
  1995. return response.json(12)
  1996. # 切换设备套餐关联
  1997. using_uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, has_unused=1).values("id", "uid", "endTime",
  1998. "bucket__content", "addTime")
  1999. unused_uid_bucket_qs = Unused_Uid_Meal.objects.filter(id=unused_id).values("id", "uid", "channel", "addTime",
  2000. "expire", "is_ai", "bucket_id",
  2001. "order_id")
  2002. if not unused_uid_bucket_qs.exists() or not using_uid_bucket_qs.exists():
  2003. return response.json(10030)
  2004. unused_uid_bucket = unused_uid_bucket_qs.first()
  2005. now_time = int(time.time())
  2006. try:
  2007. with transaction.atomic():
  2008. count_unused = Unused_Uid_Meal.objects.filter(uid=uid).count()
  2009. has_unused = 1 if count_unused > 1 else 0
  2010. end_time = CommonService.calcMonthLater(unused_uid_bucket['expire'])
  2011. UID_Bucket.objects.filter(uid=uid).update(channel=unused_uid_bucket['channel'], endTime=end_time,
  2012. bucket_id=unused_uid_bucket['bucket_id']
  2013. , updateTime=now_time, use_status=1,
  2014. has_unused=has_unused)
  2015. # 开通AI服务
  2016. if unused_uid_bucket['is_ai']:
  2017. ai_service = AiService.objects.filter(uid=uid, channel=unused_uid_bucket['channel'])
  2018. if ai_service.exists(): # 有正在使用的套餐,套餐结束时间保存为套餐有效期
  2019. ai_service.update(updTime=now_time, use_status=1, orders_id=unused_uid_bucket['order_id'],
  2020. endTime=end_time)
  2021. else:
  2022. AiService.objects.create(uid=uid, channel=unused_uid_bucket['channel'], detect_status=1,
  2023. addTime=now_time, updTime=now_time, endTime=end_time, use_status=1,
  2024. orders_id=unused_uid_bucket['order_id'])
  2025. Unused_Uid_Meal.objects.filter(id=unused_id).delete()
  2026. StsCrdModel.objects.filter(uid=uid).delete() # 删除sts记录
  2027. # VodHlsModel.objects.filter(uid=uid).delete() # 删除播放列表,后期数据量多时应该考虑延后删除
  2028. return response.json(0)
  2029. except Exception:
  2030. return response.json(474)
  2031. @staticmethod
  2032. def has_vod(request_dict, user_id, response):
  2033. """
  2034. 云存日期
  2035. @param request_dict: 请求数据
  2036. @param user_id: 用户id
  2037. @request_dict uid: uid
  2038. @request_dict channel: 通道
  2039. @param response: 响应
  2040. @return: response
  2041. """
  2042. uid = request_dict.get('uid', None)
  2043. channel = request_dict.get('channel', 1)
  2044. if not uid:
  2045. return response.json(444)
  2046. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False).values(
  2047. 'vodPrimaryUserID',
  2048. 'vodPrimaryMaster')
  2049. if not device_info_qs.exists():
  2050. return response.json(12)
  2051. if device_info_qs[0]['vodPrimaryUserID'] != user_id:
  2052. return response.json(10034)
  2053. now_time = int(time.time())
  2054. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel).values(
  2055. 'bucket_id').order_by(
  2056. 'addTime')
  2057. if not uid_bucket_qs.exists():
  2058. return response.json(10030)
  2059. # vod_hls_qs = VodHlsModel.objects.extra(select={'date': "FROM_UNIXTIME(time,'%%Y-%%m-%%d')"}).values(
  2060. # 'date').filter(uid=uid, endTime__gte=now_time, channel=channel).annotate(count=Count('time')).order_by(
  2061. # '-date')[:31]
  2062. split_vod_hls_obj = SplitVodHlsObject()
  2063. vod_hls_qs = split_vod_hls_obj.get_vod_hls_date(uid=uid, end_time__gte=now_time, channel=channel)
  2064. had_vod_list = []
  2065. for vod in vod_hls_qs:
  2066. had_vod_list.append({
  2067. 'timestamp': CommonService.str_to_timestamp(vod['date'], '%Y-%m-%d'),
  2068. 'vod_count': vod['count'],
  2069. 'date_format': vod['date'],
  2070. })
  2071. had_vod_list = sorted(had_vod_list, key=lambda item: -item['timestamp'])[:31]
  2072. return response.json(0, had_vod_list)
  2073. @staticmethod
  2074. def video_playback_time(request_dict, user_id, response):
  2075. """
  2076. 存储视频播放数据
  2077. @param request_dict: 请求数据
  2078. @param user_id: 用户id
  2079. @request_dict parms: 参数列表
  2080. @param response: 响应
  2081. @return: response
  2082. """
  2083. params = request_dict.get('parms', None)
  2084. if not params:
  2085. return response.json(444)
  2086. try:
  2087. params = eval(params)
  2088. bulk = []
  2089. for parm in params:
  2090. parm['userID'] = user_id
  2091. # 解密uid
  2092. for i in range(1, 4):
  2093. parm['uid'] = base64.b64decode(parm['uid'])
  2094. parm['uid'] = parm['uid'].decode('utf-8')
  2095. parm['uid'] = parm['uid'][i:-i]
  2096. video_playback_time = VideoPlaybackTimeModel(**parm)
  2097. bulk.append(video_playback_time)
  2098. VideoPlaybackTimeModel.objects.bulk_create(bulk)
  2099. return response.json(0)
  2100. except Exception as e:
  2101. print(e)
  2102. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  2103. def do_vod_msg_notice(self, uid, channel, user_id, lang, sys_msg_text_list, sms): # 云存操作系统消息
  2104. """
  2105. 云存操作系统消息
  2106. @param uid: uid
  2107. @param channel: 通道
  2108. @param user_id: 用户id
  2109. @param lang: 语言
  2110. @param sys_msg_text_list: 消息列表
  2111. @param sms: sms码
  2112. @return: response
  2113. """
  2114. try:
  2115. logger = logging.getLogger('log')
  2116. logger.info('进来了')
  2117. if lang == 'cn':
  2118. sys_msg_text = sys_msg_text_list[0]
  2119. else:
  2120. sys_msg_text = sys_msg_text_list[1]
  2121. now_time = int(time.time())
  2122. create_data = {'userID_id': user_id, 'msg': sys_msg_text, 'addTime': now_time,
  2123. 'updTime': now_time, 'uid': uid, 'eventType': 0}
  2124. SysMsgModel.objects.create(**create_data)
  2125. user_qs = Device_User.objects.filter(userID=user_id)
  2126. if user_qs.exists():
  2127. user = user_qs.first()
  2128. username = user.username
  2129. data_valid = DataValid()
  2130. if data_valid.email_validate(username):
  2131. S3Email().faEmail(sys_msg_text, username)
  2132. elif data_valid.mobile_validate(username):
  2133. # 如果存在序列号,消息提示用序列号
  2134. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  2135. if device_info_qs.exists():
  2136. serial_number = device_info_qs[0]['serial_number']
  2137. device_type = device_info_qs[0]['Type']
  2138. if serial_number:
  2139. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  2140. else:
  2141. device_name = uid
  2142. params = '{"devname":"%s","submittime":"%s"}' % (
  2143. device_name, time.strftime("%Y-%m-%d", time.localtime()))
  2144. self.send_message(username, params, sms)
  2145. logger.info('出去了')
  2146. except Exception as e:
  2147. return repr(e)
  2148. def do_vod_msg_end(self, response): # 云存到期续费提醒 提前3天
  2149. """
  2150. 云存到期续费提醒
  2151. @param response: 响应
  2152. @return: response
  2153. """
  2154. now_time = int(time.time())
  2155. # 过期前第7天提示一次
  2156. uid_bucket_qs = UID_Bucket.objects.filter(
  2157. Q(endTime__gt=now_time + 3600 * 144) & Q(endTime__lte=(now_time + 3600 * 168))).values('id', 'uid',
  2158. 'bucket__area',
  2159. 'channel', 'endTime')
  2160. self.do_vod_msg(now_time, uid_bucket_qs)
  2161. # 过期前第3天提示一次
  2162. uid_bucket_qs = UID_Bucket.objects.filter(
  2163. Q(endTime__gt=now_time + 3600 * 48) & Q(endTime__lte=(now_time + 3600 * 72))).values('id', 'uid',
  2164. 'bucket__area',
  2165. 'channel', 'endTime')
  2166. self.do_vod_msg(now_time, uid_bucket_qs)
  2167. return response.json(0)
  2168. def do_vod_msg(self, now_time, qs):
  2169. """
  2170. 云存到期续费提醒
  2171. @param now_time: 现在时间
  2172. @param qs: 查询集
  2173. @return: response
  2174. """
  2175. msg_list = []
  2176. ids = []
  2177. for item in qs:
  2178. ids.append(item['id'])
  2179. order_qs = Order_Model.objects.filter(uid_bucket_id__in=ids).values('userID_id', 'uid_bucket_id')
  2180. for item in qs:
  2181. for order in order_qs:
  2182. if item['id'] == order['uid_bucket_id']:
  2183. # 如果存在序列号,消息提示用序列号
  2184. uid = item['uid']
  2185. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  2186. serial_number = device_info_qs[0]['serial_number']
  2187. device_type = device_info_qs[0]['Type']
  2188. if serial_number and device_type == 101:
  2189. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  2190. else:
  2191. device_name = uid
  2192. if item['bucket__area'] == 'cn':
  2193. sys_msg_text = "温馨提示:尊敬的客户,您%s设备的云存套餐将在%s到期" % (
  2194. device_name, time.strftime("%Y-%m-%d", time.localtime(item['endTime'])))
  2195. else:
  2196. sys_msg_text = 'Dear customer,the cloud storage package for your device %s will expire on %s' % \
  2197. (device_name, time.strftime('%m-%d-%y', time.localtime(item['endTime'])))
  2198. msg_list.append(SysMsgModel(
  2199. userID_id=order['userID_id'],
  2200. addTime=now_time,
  2201. updTime=now_time,
  2202. uid=item['uid'],
  2203. eventType=0,
  2204. msg=sys_msg_text,
  2205. status=0
  2206. ))
  2207. SysMsgModel.objects.bulk_create(msg_list)
  2208. msg_list.clear()
  2209. user_qs = Device_User.objects.filter(userID=order['userID_id'])
  2210. if user_qs.exists():
  2211. user = user_qs.first()
  2212. username = user.username
  2213. data_valid = DataValid()
  2214. if data_valid.email_validate(username):
  2215. S3Email().faEmail(sys_msg_text, username)
  2216. elif data_valid.mobile_validate(username):
  2217. params = u'{"devname":"%s","submittime":"%s"}' % (
  2218. device_name, time.strftime("%Y-%m-%d", time.localtime(item['endTime'])))
  2219. self.send_message(username, params, 'SMS_219748440')
  2220. @staticmethod
  2221. def send_message(phone, params, temp_msg):
  2222. """
  2223. 发送手机消息
  2224. @param phone: 用户名
  2225. @param params: 消息参数
  2226. @param temp_msg: sms码
  2227. """
  2228. sign_ms = '周视'
  2229. ali_sms = AliSmsObject()
  2230. ali_sms.send_code_sms_cloud(phone=phone, params=params, sign_name=sign_ms, temp_msg=temp_msg)
  2231. @staticmethod
  2232. def do_refund(request_dict, response):
  2233. """
  2234. 退款
  2235. @param request_dict: 请求数据
  2236. @request_dict orderID: 订单id
  2237. @request_dict refund_amount: 退款金额
  2238. @param response: 响应
  2239. @return: response
  2240. """
  2241. order_id = request_dict.get('orderID', None) # 商户订单号
  2242. refund_amount = request_dict.get('refund_amount', None) # 退款金额
  2243. if not all([order_id, refund_amount]):
  2244. return response.json(444)
  2245. try:
  2246. order_qs = Order_Model.objects.filter(orderID=order_id) \
  2247. .values('status', 'payType', 'price', 'refunded_amount',
  2248. 'currency', 'paymentID', 'trade_no')
  2249. if not order_qs.exists():
  2250. return response.json(173)
  2251. # 支付状态不为支付成功和退款失败和部分退款
  2252. status = order_qs[0]['status']
  2253. if status != 1 and status != 4 and status != 6:
  2254. return response.json(805)
  2255. refund_amount = float(refund_amount)
  2256. now_time = int(time.time())
  2257. pay_type = order_qs[0]['payType']
  2258. price = order_qs[0]['price'] # 订单金额
  2259. refunded_amount = order_qs[0]['refunded_amount'] # 已退款金额
  2260. currency = order_qs[0]['currency'] # 货币
  2261. # 判断是否符合付款条件
  2262. if refunded_amount == float(price): # 已全额退款
  2263. return response.json(805)
  2264. if refund_amount + refunded_amount > float(price): # 退款金额超出订单价格
  2265. return response.json(805)
  2266. # 部分退款标识
  2267. is_partial_refund = True if (float(price) > refund_amount + refunded_amount) else False
  2268. out_request_no = str(time.strftime('%Y%m%d%H%M%S', time.localtime(now_time))) # 退款请求号
  2269. # 根据支付类型处理退款
  2270. if pay_type == 1: # PayPal
  2271. payment_id = order_qs[0]['paymentID'] # PayPal PAYMENT_ID
  2272. trade_no = order_qs[0]['trade_no']
  2273. sale_id = ''
  2274. paypalrestsdk.configure(PAYPAL_CRD)
  2275. if payment_id:
  2276. payment = paypalrestsdk.Payment.find(payment_id)
  2277. related_resources = payment['transactions'][0]['related_resources']
  2278. if not related_resources:
  2279. return response.json(805)
  2280. sale = related_resources[0]['sale']
  2281. # 没退款过 'state' 不为 'completed' 或 已退款过但 'state' 不为 'partially_refunded'
  2282. if (refunded_amount == 0 and sale['state'] != 'completed') or (
  2283. refunded_amount != 0 and sale['state'] != 'partially_refunded'):
  2284. return response.json(805)
  2285. sale_id = sale['id']
  2286. sale_id = sale_id if sale_id else trade_no
  2287. paypal_sale = paypalrestsdk.Sale.find(sale_id)
  2288. if not paypal_sale or paypal_sale['state'] != 'completed':
  2289. return response.json(805)
  2290. refund = paypal_sale.refund({
  2291. 'amount': {
  2292. 'total': refund_amount,
  2293. 'currency': currency
  2294. }
  2295. })
  2296. refund_success = True if refund.success() else False
  2297. elif pay_type == 2: # 支付宝
  2298. ali_pay_obj = AliPayObject()
  2299. alipay = ali_pay_obj.conf()
  2300. refund_response = alipay.api_alipay_trade_refund(refund_amount=refund_amount, out_trade_no=order_id,
  2301. out_request_no=out_request_no)
  2302. refund_success = True if (refund_response['code'] == '10000') else False
  2303. elif pay_type == 3: # 微信
  2304. wechat_pay_obj = WechatPayObject()
  2305. refund_fee = int(refund_amount * 100) # 退款金额,单位为分,只能为整数
  2306. success = wechat_pay_obj.refund(out_trade_no=order_id, out_refund_no=out_request_no,
  2307. total_fee=refund_fee, refund_fee=refund_fee)
  2308. refund_success = True if success else False
  2309. else: # 不支持退款的支付类型
  2310. return response.json(805)
  2311. # 更新订单状态和已退款金额
  2312. update_dict = {'updTime': now_time}
  2313. if refund_success:
  2314. update_dict['status'] = 6 if is_partial_refund else 5
  2315. update_dict['refunded_amount'] = refunded_amount + refund_amount
  2316. else:
  2317. update_dict['status'] = 4
  2318. order_qs.update(**update_dict)
  2319. return response.json(0)
  2320. except Exception as e:
  2321. logger = logging.getLogger('info')
  2322. logger.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  2323. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))