AiController.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @AUTHOR: ASJRD018
  6. @NAME: AnsjerFormal
  7. @software: PyCharm
  8. @DATE: 2018/12/5 9:30
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: cloudstorage.py
  12. @Contact: chanjunkai@163.com
  13. """
  14. import base64
  15. import json
  16. import os
  17. import time
  18. import urllib
  19. from urllib.parse import quote, parse_qs, unquote
  20. import apns2
  21. import boto3
  22. import jpush
  23. import oss2
  24. import paypalrestsdk
  25. import threading
  26. import calendar
  27. import datetime
  28. import logging
  29. import sys
  30. from aliyunsdkcore import client
  31. from aliyunsdksts.request.v20150401 import AssumeRoleRequest
  32. from boto3.session import Session
  33. from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
  34. from django.db import transaction
  35. from django.views.generic.base import View
  36. import jwt
  37. from Object.ETkObject import ETkObject
  38. from pyfcm import FCMNotification
  39. from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, OSS_ROLE_ARN, SERVER_DOMAIN, PAYPAL_CRD, \
  40. SERVER_DOMAIN_SSL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ARN, APNS_MODE, APNS_CONFIG, BASE_DIR, \
  41. JPUSH_CONFIG, FCM_CONFIG, OAUTH_ACCESS_TOKEN_SECRET
  42. from Controller.CheckUserData import DataValid
  43. from Model.models import Device_Info, Order_Model, Store_Meal, VodHlsModel, OssCrdModel, UID_Bucket, StsCrdModel, \
  44. ExperienceContextModel, Pay_Type, CDKcontextModel, Device_User, SysMassModel, SysMsgModel, UidPushModel, \
  45. Unused_Uid_Meal, UIDMainUser, UserModel, PromotionRuleModel, VideoPlaybackTimeModel, CloudLogModel, CouponModel, \
  46. AiStoreMeal, AiService, UidSetModel
  47. from Object.AWS.S3Email import S3Email
  48. from Object.AliPayObject import AliPayObject
  49. from Object.AliSmsObject import AliSmsObject
  50. from Object.RedisObject import RedisObject
  51. from Object.ResponseObject import ResponseObject
  52. from Object.TokenObject import TokenObject
  53. from Object.UidTokenObject import UidTokenObject
  54. from Service.CommonService import CommonService
  55. from Object.m3u8generate import PlaylistGenerator
  56. from Object.WechatPayObject import WechatPayObject
  57. from django.db.models import Q, F, Count
  58. from Controller.PaymentCycle import Paypal
  59. from decimal import Decimal
  60. from Ansjer.config import SERVER_TYPE
  61. from Service.ModelService import ModelService
  62. # AI服务
  63. class AiView(View):
  64. def get(self, request, *args, **kwargs):
  65. request.encoding = 'utf-8'
  66. operation = kwargs.get('operation')
  67. return self.validation(request.GET, request, operation)
  68. def post(self, request, *args, **kwargs):
  69. request.encoding = 'utf-8'
  70. operation = kwargs.get('operation')
  71. return self.validation(request.POST, request, operation)
  72. def validation(self, request_dict, request, operation):
  73. response = ResponseObject()
  74. if operation is None:
  75. return response.json(444, 'error path')
  76. elif operation == 'identification': # ai识别
  77. return self.do_ai_identification(request_dict, response)
  78. else:
  79. token = request_dict.get('token', None)
  80. # 设备主键uid
  81. tko = TokenObject(token)
  82. response.lang = tko.lang
  83. if tko.code != 0:
  84. return response.json(tko.code)
  85. userID = tko.userID
  86. if operation == 'createpayorder': # 创建支付订单
  87. ip = CommonService.get_ip_address(request)
  88. return self.do_create_pay_order(request_dict, userID, ip, response)
  89. elif operation == 'changeaistatus': # 修改云存状态,传送两个url,即getsignsts接口和storeplaylist接口
  90. return self.do_change_ai_status(userID, request_dict, response)
  91. elif operation == 'commoditylist': # 修改云存状态,传送两个url,即getsignsts接口和storeplaylist接口
  92. return self.do_commodity_list(userID, request_dict, response)
  93. else:
  94. return response.json(414)
  95. def do_change_ai_status(self, userID, request_dict, response):
  96. token_val = request_dict.get('token_val', None)
  97. appBundleId = request_dict.get('appBundleId', None)
  98. app_type = request_dict.get('app_type', None)
  99. push_type = request_dict.get('push_type', None)
  100. status = request_dict.get('status', None)
  101. m_code = request_dict.get('m_code', None)
  102. uid = request_dict.get('uid', None)
  103. # 设备语言
  104. lang = request_dict.get('lang', 'en')
  105. tz = request_dict.get('tz', '0')
  106. # 消息提醒功能新增
  107. # 如果传空上来,就默认为0
  108. if tz == '':
  109. tz = 0
  110. else:
  111. tz = tz.replace("GMT", "")
  112. detect_group = request_dict.get('detect_group', None)
  113. interval = request_dict.get('interval', None)
  114. if not status:
  115. return response.json(444, 'status')
  116. # 关闭推送
  117. if not all([appBundleId, app_type, token_val, uid, m_code]):
  118. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  119. # 判断推送类型对应key是否存在
  120. print('push_type:', push_type)
  121. if push_type == '0':
  122. if appBundleId not in APNS_CONFIG.keys():
  123. return response.json(904)
  124. elif push_type == '1':
  125. if appBundleId not in FCM_CONFIG.keys():
  126. return response.json(904)
  127. elif push_type == '2':
  128. if appBundleId not in JPUSH_CONFIG.keys():
  129. return response.json(904)
  130. else:
  131. return response.json(173)
  132. hasAiService = AiService.objects.filter(uid=uid,use_status=1)
  133. if not hasAiService.exists():
  134. return response.json(10053)
  135. nowTime = int(time.time())
  136. endTime = hasAiService.values('endTime')[0]['endTime']
  137. if nowTime >endTime:
  138. return response.json(10054)
  139. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  140. status = int(status)
  141. nowTime = int(time.time())
  142. if dvqs.exists():
  143. # 修改状态
  144. # dvqs.update(NotificationMode=status)
  145. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  146. # uid配置信息是否存在
  147. if uid_set_qs.exists():
  148. uid_set_id = uid_set_qs[0].id
  149. qs_data = {
  150. 'detect_status': status,
  151. 'updTime': nowTime,
  152. }
  153. if interval:
  154. qs_data['detect_interval'] = int(interval)
  155. if detect_group:
  156. qs_data['detect_group'] = detect_group
  157. uid_set_qs.update(**qs_data)
  158. else:
  159. qs_data = {
  160. 'uid': uid,
  161. 'addTime': nowTime,
  162. 'updTime': nowTime,
  163. 'detect_status': status,
  164. }
  165. if interval:
  166. qs_data['detect_interval'] = int(interval)
  167. if detect_group:
  168. qs_data['detect_group'] = detect_group
  169. # 添加设备配置
  170. uid_set_qs = UidSetModel.objects.create(**qs_data)
  171. uid_set_id = uid_set_qs.id
  172. if status == 0:
  173. hasAiService.update(**qs_data)
  174. # UidPushModel.objects.filter(uid_set__uid=uid).delete()
  175. # 状态为0的时候删除redis缓存数据
  176. # self.do_delete_redis(uid)
  177. return response.json(0)
  178. elif status == 1:
  179. hasAiService.update(**qs_data)
  180. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  181. if uid_push_qs.exists():
  182. uid_push_update_dict = {
  183. 'appBundleId': appBundleId,
  184. 'app_type': app_type,
  185. 'push_type': push_type,
  186. 'token_val': token_val,
  187. 'updTime': nowTime,
  188. 'lang': lang,
  189. 'tz': tz
  190. }
  191. uid_push_qs.update(**uid_push_update_dict)
  192. else:
  193. # uid_set_id = uid_set_qs[0].id
  194. uid_push_create_dict = {
  195. 'uid_set_id': uid_set_id,
  196. 'userID_id': userID,
  197. 'appBundleId': appBundleId,
  198. 'app_type': app_type,
  199. 'push_type': push_type,
  200. 'token_val': token_val,
  201. 'm_code': m_code,
  202. 'addTime': nowTime,
  203. 'updTime': nowTime,
  204. 'lang': lang,
  205. 'tz': tz
  206. }
  207. # 绑定设备推送
  208. UidPushModel.objects.create(**uid_push_create_dict)
  209. # if interval:
  210. # self.do_delete_redis(uid, int(interval))
  211. # else:
  212. # self.do_delete_redis(uid)
  213. # utko = UidTokenObject()
  214. # # right
  215. # utko.generate(data={'uid': uid})
  216. etkObj = ETkObject(etk='')
  217. etk = etkObj.encrypt(uid)
  218. #只返回一个接口就行
  219. # detectUrl = "{DETECT_PUSH_DOMAIN}AiService/push?etk={etk}&endTime={endTime}". \
  220. # format(etk=etk, DETECT_PUSH_DOMAIN=SERVER_DOMAIN_SSL, endTime=endTime)
  221. aiIdentificationUrl = "{DETECT_PUSH_DOMAIN}AiService/identification".format(DETECT_PUSH_DOMAIN=SERVER_DOMAIN_SSL)
  222. return response.json(0, {'aiIdentificationUrl':aiIdentificationUrl, 'endTime':endTime, 'etk':etk})
  223. else:
  224. return response.json(14)
  225. def do_commodity_list(self, userID, request_dict, response): # 查询套餐列表
  226. uid = request_dict.get('uid', None)
  227. lang = request_dict.get('lang', 'en')
  228. nowTime = int(time.time())
  229. # DVR/NVR设备暂不返回云存套餐列表
  230. device_info_qs = Device_Info.objects.filter(Q(UID=uid), Q(Type__lte=4) | Q(Type=10001))
  231. if device_info_qs.exists():
  232. return response.json(0)
  233. qs = AiStoreMeal.objects
  234. qs = qs.filter(is_show=1) #过滤隐藏套餐
  235. qs = qs.annotate(ai_meal_id=F('id'))
  236. qs = qs.values("ai_meal_id", "title", "content", "price", "effective_day", "currency",
  237. "virtual_price", "symbol", "pay_type")
  238. if qs.exists():
  239. res = list(qs)
  240. for key, val in enumerate(res):
  241. pay_types = Pay_Type.objects.filter(aistoremeal=res[key]['ai_meal_id']).values("id", "payment")
  242. res[key]['pay_type'] = list(pay_types)
  243. result = {
  244. 'meals': res,
  245. }
  246. return response.json(0, result)
  247. else:
  248. return response.json(0)
  249. def do_create_pay_order(self, request_dict, userID, ip, response):
  250. uid = request_dict.get('uid', None)
  251. channel = request_dict.get('channel', None)
  252. pay_type = int(request_dict.get('pay_type', 1))
  253. ai_meal_id = request_dict.get('ai_meal_id', None)
  254. lang = request_dict.get('lang', 'en')
  255. if not uid or not channel or not pay_type or not ai_meal_id:
  256. return response.json(444)
  257. # dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1).values(
  258. # 'vodPrimaryUserID',
  259. # 'vodPrimaryMaster')
  260. # if not dv_qs.exists():
  261. # return response.json(12)
  262. # dvq = Device_Info.objects.filter(UID=uid)
  263. # dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  264. # if dvq.exists():
  265. # if dvq[0]['vodPrimaryUserID'] != userID:
  266. # return response.json(10033)
  267. nowTime = int(time.time())
  268. smqs = AiStoreMeal.objects.filter(id=ai_meal_id, pay_type=pay_type, is_show=1). \
  269. values('currency', 'price', 'content', 'effective_day', 'title')
  270. if not smqs.exists():
  271. return response.json(173)
  272. currency = smqs[0]['currency']
  273. price = smqs[0]['price']
  274. content = smqs[0]['content']
  275. day = smqs[0]['effective_day']
  276. orderID = CommonService.createOrderID()
  277. price = float(price)
  278. price = round(price, 2)
  279. if pay_type == 1:
  280. #正常扣款
  281. cal_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  282. if lang != 'cn':
  283. cal_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  284. call_sub_url = "{SERVER_DOMAIN_SSL}cloudstorage/dopaypalcallback?orderID={orderID}&lang={lang}". \
  285. format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, orderID=orderID, lang=lang)
  286. # call_sub_url = "http://binbin.uicp.vip/cloudstorage/dopaypalcallback?orderID={orderID}".format(
  287. # SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, orderID=orderID)
  288. Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
  289. desc=content, payType=pay_type, payTime=nowTime,
  290. price=price, currency=currency, addTime=nowTime, updTime=nowTime,
  291. pay_url='', commodity_code='', commodity_type=1,
  292. ai_rank_id=ai_meal_id, rank_id=1, order_type=1)
  293. has = AiService.objects.filter(uid=uid, channel=channel, use_status=1)
  294. if has.exists():
  295. use_status = 0
  296. else:
  297. use_status = 1
  298. # return response.json(0)
  299. AiService.objects.create(orders_id=orderID, uid=uid, channel=channel, detect_status=0,
  300. endTime=nowTime+(day*86400), addTime=nowTime, updTime=nowTime,
  301. use_status=use_status, detect_group='1')
  302. return response.json(0, {"orderID": orderID})
  303. return response.json(10, 'generate_order_false')
  304. def do_ai_identification(self, request_dict):
  305. etk = request_dict.get('etk', None)
  306. if etk:
  307. eto = ETkObject(etk)
  308. uid = eto.uid
  309. file_post_one = request_dict.get('file_one', None)
  310. file_post = file_post_one.replace(' ', '+')
  311. # file_decode = base64.b64decode(file_post)
  312. file_post_two = request_dict.get('file_two', None)
  313. file_post_two = file_post_two.replace(' ', '+')
  314. # file_decode_two = base64.b64decode(file_post_two)
  315. now_time = int(time.time())
  316. dir_path = os.path.join(BASE_DIR, 'static/ai/')
  317. if not os.path.exists(dir_path):
  318. os.makedirs(dir_path)
  319. file_path_one = dir_path + 'one' + str(now_time) + '.jpeg'
  320. file_path_two = dir_path + 'two' + str(now_time) + '.jpeg'
  321. file_list = ['one', 'two']
  322. for index in file_list:
  323. file_path = dir_path + index + str(now_time) + '.jpeg'
  324. with open(file_path, 'wb') as f:
  325. # file_byte = file_post.encode('utf-8')
  326. f.write(file_decode)
  327. return HttpResponse("seccess")
  328. file2 = request.FILES.get('file_one', None)
  329. file3 = request.FILES.get('file_two', None)
  330. file4 = request.FILES.get('file_three', None)
  331. print('--------------------------file')
  332. print(file)
  333. print('===========================post_file')
  334. print(file_post)
  335. post_file_list = [file, file2, file3, file4]
  336. file_list = []
  337. for index in range(len(post_file_list)):
  338. if post_file_list[index]:
  339. file_list.append(post_file_list[index])
  340. del post_file_list
  341. if len(file_list) > 1:
  342. merge = []
  343. now_time = int(time.time())
  344. dir_path = os.path.join(BASE_DIR, 'static/', str(now_time))
  345. if not os.path.exists(dir_path):
  346. os.makedirs(dir_path)
  347. for item in file_list:
  348. if hasattr(item, 'name'):
  349. file_path = os.path.join(dir_path, item.name)
  350. with open(file_path, 'wb') as f:
  351. for c in item.chunks():
  352. f.write(c)
  353. merge.append(file_path)
  354. image_size = 500 # 每张小图片的大小
  355. image_colnum = 2 # 合并成一张图后,一行有几个小图
  356. MergePic.merge_images(dir_path, image_size, image_colnum)
  357. # return HttpResponse(dir_path + '.jpg')
  358. photo = open(dir_path + '.jpg', 'rb')
  359. else:
  360. photo = file_list[0]
  361. else:
  362. return HttpResponse("fail")