CloudStorage.py 142 KB

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