CloudStorage.py 149 KB

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