123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
- @AUTHOR: ASJRD018
- @NAME: AnsjerFormal
- @software: PyCharm
- @DATE: 2018/12/5 9:30
- @Version: python3.6
- @MODIFY DECORD:ansjer dev
- @file: cloudstorage.py
- @Contact: chanjunkai@163.com
- """
- import base64
- import json
- import os
- import time
- import urllib
- from urllib.parse import quote, parse_qs, unquote
- import apns2
- import boto3
- import jpush
- import oss2
- import paypalrestsdk
- import threading
- import calendar
- import datetime
- import logging
- import sys
- from aliyunsdkcore import client
- from aliyunsdksts.request.v20150401 import AssumeRoleRequest
- from boto3.session import Session
- from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
- from django.db import transaction
- from django.views.generic.base import View
- import jwt
- from Object.ETkObject import ETkObject
- from pyfcm import FCMNotification
- from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, OSS_ROLE_ARN, SERVER_DOMAIN, PAYPAL_CRD, \
- SERVER_DOMAIN_SSL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ARN, APNS_MODE, APNS_CONFIG, BASE_DIR, \
- JPUSH_CONFIG, FCM_CONFIG, OAUTH_ACCESS_TOKEN_SECRET
- from Controller.CheckUserData import DataValid
- from Model.models import Device_Info, Order_Model, Store_Meal, VodHlsModel, OssCrdModel, UID_Bucket, StsCrdModel, \
- ExperienceContextModel, Pay_Type, CDKcontextModel, Device_User, SysMassModel, SysMsgModel, UidPushModel, \
- Unused_Uid_Meal, UIDMainUser, UserModel, PromotionRuleModel, VideoPlaybackTimeModel, CloudLogModel, CouponModel, \
- AiStoreMeal, AiService, UidSetModel
- from Object.AWS.S3Email import S3Email
- from Object.AliPayObject import AliPayObject
- from Object.AliSmsObject import AliSmsObject
- from Object.RedisObject import RedisObject
- from Object.ResponseObject import ResponseObject
- from Object.TokenObject import TokenObject
- from Object.UidTokenObject import UidTokenObject
- from Service.CommonService import CommonService
- from Object.m3u8generate import PlaylistGenerator
- from Object.WechatPayObject import WechatPayObject
- from django.db.models import Q, F, Count
- from Controller.PaymentCycle import Paypal
- from decimal import Decimal
- from Ansjer.config import SERVER_TYPE
- from Service.ModelService import ModelService
- # AI服务
- class AiView(View):
- def get(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- operation = kwargs.get('operation')
- return self.validation(request.GET, request, operation)
- def post(self, request, *args, **kwargs):
- request.encoding = 'utf-8'
- operation = kwargs.get('operation')
- return self.validation(request.POST, request, operation)
- def validation(self, request_dict, request, operation):
- response = ResponseObject()
- if operation is None:
- return response.json(444, 'error path')
- elif operation == 'identification': # ai识别
- return self.do_ai_identification(request_dict, response)
- else:
- token = request_dict.get('token', None)
- # 设备主键uid
- tko = TokenObject(token)
- response.lang = tko.lang
- if tko.code != 0:
- return response.json(tko.code)
- userID = tko.userID
- if operation == 'createpayorder': # 创建支付订单
- ip = CommonService.get_ip_address(request)
- return self.do_create_pay_order(request_dict, userID, ip, response)
- elif operation == 'changeaistatus': # 修改云存状态,传送两个url,即getsignsts接口和storeplaylist接口
- return self.do_change_ai_status(userID, request_dict, response)
- elif operation == 'commoditylist': # 修改云存状态,传送两个url,即getsignsts接口和storeplaylist接口
- return self.do_commodity_list(userID, request_dict, response)
- else:
- return response.json(414)
- def do_change_ai_status(self, userID, request_dict, response):
- token_val = request_dict.get('token_val', None)
- appBundleId = request_dict.get('appBundleId', None)
- app_type = request_dict.get('app_type', None)
- push_type = request_dict.get('push_type', None)
- status = request_dict.get('status', None)
- m_code = request_dict.get('m_code', None)
- uid = request_dict.get('uid', None)
- # 设备语言
- lang = request_dict.get('lang', 'en')
- tz = request_dict.get('tz', '0')
- # 消息提醒功能新增
- # 如果传空上来,就默认为0
- if tz == '':
- tz = 0
- else:
- tz = tz.replace("GMT", "")
- detect_group = request_dict.get('detect_group', None)
- interval = request_dict.get('interval', None)
- if not status:
- return response.json(444, 'status')
- # 关闭推送
- if not all([appBundleId, app_type, token_val, uid, m_code]):
- return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
- # 判断推送类型对应key是否存在
- print('push_type:', push_type)
- if push_type == '0':
- if appBundleId not in APNS_CONFIG.keys():
- return response.json(904)
- elif push_type == '1':
- if appBundleId not in FCM_CONFIG.keys():
- return response.json(904)
- elif push_type == '2':
- if appBundleId not in JPUSH_CONFIG.keys():
- return response.json(904)
- else:
- return response.json(173)
- hasAiService = AiService.objects.filter(uid=uid,use_status=1)
- if not hasAiService.exists():
- return response.json(10053)
- nowTime = int(time.time())
- endTime = hasAiService.values('endTime')[0]['endTime']
- if nowTime >endTime:
- return response.json(10054)
- dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
- status = int(status)
- nowTime = int(time.time())
- if dvqs.exists():
- # 修改状态
- # dvqs.update(NotificationMode=status)
- uid_set_qs = UidSetModel.objects.filter(uid=uid)
- # uid配置信息是否存在
- if uid_set_qs.exists():
- uid_set_id = uid_set_qs[0].id
- qs_data = {
- 'detect_status': status,
- 'updTime': nowTime,
- }
- if interval:
- qs_data['detect_interval'] = int(interval)
- if detect_group:
- qs_data['detect_group'] = detect_group
- uid_set_qs.update(**qs_data)
- else:
- qs_data = {
- 'uid': uid,
- 'addTime': nowTime,
- 'updTime': nowTime,
- 'detect_status': status,
- }
- if interval:
- qs_data['detect_interval'] = int(interval)
- if detect_group:
- qs_data['detect_group'] = detect_group
- # 添加设备配置
- uid_set_qs = UidSetModel.objects.create(**qs_data)
- uid_set_id = uid_set_qs.id
- if status == 0:
- hasAiService.update(**qs_data)
- # UidPushModel.objects.filter(uid_set__uid=uid).delete()
- # 状态为0的时候删除redis缓存数据
- # self.do_delete_redis(uid)
- return response.json(0)
- elif status == 1:
- hasAiService.update(**qs_data)
- uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
- if uid_push_qs.exists():
- uid_push_update_dict = {
- 'appBundleId': appBundleId,
- 'app_type': app_type,
- 'push_type': push_type,
- 'token_val': token_val,
- 'updTime': nowTime,
- 'lang': lang,
- 'tz': tz
- }
- uid_push_qs.update(**uid_push_update_dict)
- else:
- # uid_set_id = uid_set_qs[0].id
- uid_push_create_dict = {
- 'uid_set_id': uid_set_id,
- 'userID_id': userID,
- 'appBundleId': appBundleId,
- 'app_type': app_type,
- 'push_type': push_type,
- 'token_val': token_val,
- 'm_code': m_code,
- 'addTime': nowTime,
- 'updTime': nowTime,
- 'lang': lang,
- 'tz': tz
- }
- # 绑定设备推送
- UidPushModel.objects.create(**uid_push_create_dict)
- # if interval:
- # self.do_delete_redis(uid, int(interval))
- # else:
- # self.do_delete_redis(uid)
- # utko = UidTokenObject()
- # # right
- # utko.generate(data={'uid': uid})
- etkObj = ETkObject(etk='')
- etk = etkObj.encrypt(uid)
- #只返回一个接口就行
- # detectUrl = "{DETECT_PUSH_DOMAIN}AiService/push?etk={etk}&endTime={endTime}". \
- # format(etk=etk, DETECT_PUSH_DOMAIN=SERVER_DOMAIN_SSL, endTime=endTime)
- aiIdentificationUrl = "{DETECT_PUSH_DOMAIN}AiService/identification".format(DETECT_PUSH_DOMAIN=SERVER_DOMAIN_SSL)
- return response.json(0, {'aiIdentificationUrl':aiIdentificationUrl, 'endTime':endTime, 'etk':etk})
- else:
- return response.json(14)
- def do_commodity_list(self, userID, request_dict, response): # 查询套餐列表
- uid = request_dict.get('uid', None)
- lang = request_dict.get('lang', 'en')
- nowTime = int(time.time())
- # DVR/NVR设备暂不返回云存套餐列表
- device_info_qs = Device_Info.objects.filter(Q(UID=uid), Q(Type__lte=4) | Q(Type=10001))
- if device_info_qs.exists():
- return response.json(0)
- qs = AiStoreMeal.objects
- qs = qs.filter(is_show=1) #过滤隐藏套餐
- qs = qs.annotate(ai_meal_id=F('id'))
- qs = qs.values("ai_meal_id", "title", "content", "price", "effective_day", "currency",
- "virtual_price", "symbol", "pay_type")
- if qs.exists():
- res = list(qs)
- for key, val in enumerate(res):
- pay_types = Pay_Type.objects.filter(aistoremeal=res[key]['ai_meal_id']).values("id", "payment")
- res[key]['pay_type'] = list(pay_types)
- result = {
- 'meals': res,
- }
- return response.json(0, result)
- else:
- return response.json(0)
- def do_create_pay_order(self, request_dict, userID, ip, response):
- uid = request_dict.get('uid', None)
- channel = request_dict.get('channel', None)
- pay_type = int(request_dict.get('pay_type', 1))
- ai_meal_id = request_dict.get('ai_meal_id', None)
- lang = request_dict.get('lang', 'en')
- if not uid or not channel or not pay_type or not ai_meal_id:
- return response.json(444)
- # dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1).values(
- # 'vodPrimaryUserID',
- # 'vodPrimaryMaster')
- # if not dv_qs.exists():
- # return response.json(12)
- # dvq = Device_Info.objects.filter(UID=uid)
- # dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
- # if dvq.exists():
- # if dvq[0]['vodPrimaryUserID'] != userID:
- # return response.json(10033)
- nowTime = int(time.time())
- smqs = AiStoreMeal.objects.filter(id=ai_meal_id, pay_type=pay_type, is_show=1). \
- values('currency', 'price', 'content', 'effective_day', 'title')
- if not smqs.exists():
- return response.json(173)
- currency = smqs[0]['currency']
- price = smqs[0]['price']
- content = smqs[0]['content']
- day = smqs[0]['effective_day']
- orderID = CommonService.createOrderID()
- price = float(price)
- price = round(price, 2)
- if pay_type == 1:
- #正常扣款
- cal_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
- if lang != 'cn':
- cal_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
- call_sub_url = "{SERVER_DOMAIN_SSL}cloudstorage/dopaypalcallback?orderID={orderID}&lang={lang}". \
- format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, orderID=orderID, lang=lang)
- # call_sub_url = "http://binbin.uicp.vip/cloudstorage/dopaypalcallback?orderID={orderID}".format(
- # SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, orderID=orderID)
- Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
- desc=content, payType=pay_type, payTime=nowTime,
- price=price, currency=currency, addTime=nowTime, updTime=nowTime,
- pay_url='', commodity_code='', commodity_type=1,
- ai_rank_id=ai_meal_id, rank_id=1, order_type=1)
- has = AiService.objects.filter(uid=uid, channel=channel, use_status=1)
- if has.exists():
- use_status = 0
- else:
- use_status = 1
- # return response.json(0)
- AiService.objects.create(orders_id=orderID, uid=uid, channel=channel, detect_status=0,
- endTime=nowTime+(day*86400), addTime=nowTime, updTime=nowTime,
- use_status=use_status, detect_group='1')
- return response.json(0, {"orderID": orderID})
- return response.json(10, 'generate_order_false')
- def do_ai_identification(self, request_dict):
- etk = request_dict.get('etk', None)
- if etk:
- eto = ETkObject(etk)
- uid = eto.uid
- file_post_one = request_dict.get('file_one', None)
- file_post = file_post_one.replace(' ', '+')
- # file_decode = base64.b64decode(file_post)
- file_post_two = request_dict.get('file_two', None)
- file_post_two = file_post_two.replace(' ', '+')
- # file_decode_two = base64.b64decode(file_post_two)
- now_time = int(time.time())
- dir_path = os.path.join(BASE_DIR, 'static/ai/')
- if not os.path.exists(dir_path):
- os.makedirs(dir_path)
- file_path_one = dir_path + 'one' + str(now_time) + '.jpeg'
- file_path_two = dir_path + 'two' + str(now_time) + '.jpeg'
- file_list = ['one', 'two']
- for index in file_list:
- file_path = dir_path + index + str(now_time) + '.jpeg'
- with open(file_path, 'wb') as f:
- # file_byte = file_post.encode('utf-8')
- f.write(file_decode)
- return HttpResponse("seccess")
- file2 = request.FILES.get('file_one', None)
- file3 = request.FILES.get('file_two', None)
- file4 = request.FILES.get('file_three', None)
- print('--------------------------file')
- print(file)
- print('===========================post_file')
- print(file_post)
- post_file_list = [file, file2, file3, file4]
- file_list = []
- for index in range(len(post_file_list)):
- if post_file_list[index]:
- file_list.append(post_file_list[index])
- del post_file_list
- if len(file_list) > 1:
- merge = []
- now_time = int(time.time())
- dir_path = os.path.join(BASE_DIR, 'static/', str(now_time))
- if not os.path.exists(dir_path):
- os.makedirs(dir_path)
- for item in file_list:
- if hasattr(item, 'name'):
- file_path = os.path.join(dir_path, item.name)
- with open(file_path, 'wb') as f:
- for c in item.chunks():
- f.write(c)
- merge.append(file_path)
- image_size = 500 # 每张小图片的大小
- image_colnum = 2 # 合并成一张图后,一行有几个小图
- MergePic.merge_images(dir_path, image_size, image_colnum)
- # return HttpResponse(dir_path + '.jpg')
- photo = open(dir_path + '.jpg', 'rb')
- else:
- photo = file_list[0]
- else:
- return HttpResponse("fail")
|