AiController.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  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. import requests
  31. from aliyunsdkcore import client
  32. from aliyunsdksts.request.v20150401 import AssumeRoleRequest
  33. from boto3.session import Session
  34. from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
  35. from django.db import transaction
  36. from django.views.generic.base import View
  37. import jwt
  38. from Object.ETkObject import ETkObject
  39. from pyfcm import FCMNotification
  40. from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, OSS_ROLE_ARN, SERVER_DOMAIN, PAYPAL_CRD, \
  41. SERVER_DOMAIN_SSL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ARN, APNS_MODE, APNS_CONFIG, BASE_DIR, \
  42. JPUSH_CONFIG, FCM_CONFIG, OAUTH_ACCESS_TOKEN_SECRET
  43. from Controller.CheckUserData import DataValid
  44. from Model.models import Device_Info, Order_Model, Store_Meal, VodHlsModel, OssCrdModel, UID_Bucket, StsCrdModel, \
  45. ExperienceContextModel, Pay_Type, CDKcontextModel, Device_User, SysMassModel, SysMsgModel, UidPushModel, \
  46. Unused_Uid_Meal, UIDMainUser, UserModel, PromotionRuleModel, VideoPlaybackTimeModel, CloudLogModel, CouponModel, \
  47. AiStoreMeal, AiService, UidSetModel, Ai_Push_Info, iotdeviceInfoModel, AiProcessTime
  48. from Object.AWS.S3Email import S3Email
  49. from Object.AliPayObject import AliPayObject
  50. from Object.AliSmsObject import AliSmsObject
  51. from Object.RedisObject import RedisObject
  52. from Object.ResponseObject import ResponseObject
  53. from Object.TokenObject import TokenObject
  54. from Object.UidTokenObject import UidTokenObject
  55. from Service.CommonService import CommonService
  56. from Object.m3u8generate import PlaylistGenerator
  57. from Object.WechatPayObject import WechatPayObject
  58. from django.db.models import Q, F, Count
  59. from Controller.PaymentCycle import Paypal
  60. from decimal import Decimal
  61. from Ansjer.config import SERVER_TYPE
  62. from Service.ModelService import ModelService
  63. from Object import MergePic
  64. import boto3
  65. import botocore
  66. from botocore import client
  67. # AI服务
  68. class AiView(View):
  69. def get(self, request, *args, **kwargs):
  70. request.encoding = 'utf-8'
  71. operation = kwargs.get('operation')
  72. return self.validation(request.GET, request, operation)
  73. def post(self, request, *args, **kwargs):
  74. request.encoding = 'utf-8'
  75. operation = kwargs.get('operation')
  76. return self.validation(request.POST, request, operation)
  77. def validation(self, request_dict, request, operation):
  78. response = ResponseObject()
  79. if operation is None:
  80. return response.json(444, 'error path')
  81. elif operation == 'identification': # ai识别
  82. return self.do_ai_identification(request.POST, response)
  83. else:
  84. token = request_dict.get('token', None)
  85. # 设备主键uid
  86. tko = TokenObject(token)
  87. response.lang = tko.lang
  88. if tko.code != 0:
  89. return response.json(tko.code)
  90. userID = tko.userID
  91. if operation == 'createpayorder': # 创建支付订单
  92. ip = CommonService.get_ip_address(request)
  93. return self.do_create_pay_order(request_dict, userID, ip, response)
  94. elif operation == 'changeaistatus': # 修改AI开关状态
  95. return self.do_change_ai_status(userID, request_dict, response)
  96. elif operation == 'getAiStatus': # 获取AI开关状态
  97. return self.getAiStatus(userID, request_dict, response)
  98. elif operation == 'commoditylist': # 修改云存状态,传送两个url,即getsignsts接口和storeplaylist接口
  99. return self.do_commodity_list(userID, request_dict, response)
  100. elif operation == 'identification': # ai识别
  101. return self.do_ai_identification(request_dict, response)
  102. elif operation == 'queryInfo': # 查询消息列表
  103. return self.queryInfo(userID, request_dict, response)
  104. elif operation == 'readInfo': # 消息已读
  105. return self.readInfo(userID, request_dict, response)
  106. elif operation == 'deleteInfo': # 删除消息
  107. return self.deleteInfo(userID, request_dict, response)
  108. elif operation == 'queryorderlist': # 查询订单
  109. return self.do_querylist(userID, request_dict, response)
  110. elif operation == 'updateJpushTime': # 查询订单
  111. return self.update_jpush_time(userID, request_dict, response)
  112. else:
  113. return response.json(414)
  114. def do_change_ai_status(self, userID, request_dict, response):
  115. token_val = request_dict.get('token_val', None)
  116. appBundleId = request_dict.get('appBundleId', None)
  117. app_type = request_dict.get('app_type', None)
  118. push_type = request_dict.get('push_type', None)
  119. status = request_dict.get('status', None)
  120. m_code = request_dict.get('m_code', None)
  121. uid = request_dict.get('uid', None)
  122. # 设备语言
  123. lang = request_dict.get('lang', 'en')
  124. tz = request_dict.get('tz', '0')
  125. # 消息提醒功能新增
  126. # 如果传空上来,就默认为0
  127. if tz == '':
  128. tz = 0
  129. else:
  130. tz = tz.replace("GMT", "")
  131. detect_group = request_dict.get('detect_group', None)
  132. interval = request_dict.get('interval', None)
  133. if not status:
  134. return response.json(444, 'status')
  135. # 关闭推送
  136. if not all([appBundleId, app_type, token_val, uid, m_code]):
  137. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  138. # 判断推送类型对应key是否存在
  139. print('push_type:', push_type)
  140. if push_type == '0':
  141. if appBundleId not in APNS_CONFIG.keys():
  142. return response.json(904)
  143. elif push_type == '1':
  144. if appBundleId not in FCM_CONFIG.keys():
  145. return response.json(904)
  146. elif push_type == '2':
  147. if appBundleId not in JPUSH_CONFIG.keys():
  148. return response.json(904)
  149. else:
  150. return response.json(173)
  151. hasAiService = AiService.objects.filter(uid=uid,use_status=1)
  152. if not hasAiService.exists():
  153. return response.json(10053)
  154. nowTime = int(time.time())
  155. endTime = hasAiService.values('endTime')[0]['endTime']
  156. if nowTime >endTime:
  157. return response.json(10054)
  158. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  159. status = int(status)
  160. nowTime = int(time.time())
  161. if dvqs.exists():
  162. # 修改状态
  163. # dvqs.update(NotificationMode=status)
  164. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  165. # uid配置信息是否存在
  166. if uid_set_qs.exists():
  167. uid_set_id = uid_set_qs[0].id
  168. qs_data = {
  169. 'updTime': nowTime,
  170. }
  171. if interval:
  172. qs_data['detect_interval'] = int(interval)
  173. if detect_group:
  174. qs_data['detect_group'] = detect_group
  175. uid_set_qs.update(**qs_data)
  176. else:
  177. qs_data = {
  178. 'uid': uid,
  179. 'addTime': nowTime,
  180. 'updTime': nowTime,
  181. }
  182. if interval:
  183. qs_data['detect_interval'] = int(interval)
  184. if detect_group:
  185. qs_data['detect_group'] = detect_group
  186. # 添加设备配置
  187. uid_set_qs = UidSetModel.objects.create(**qs_data)
  188. uid_set_id = uid_set_qs.id
  189. topic_name = 'AiServer/{}'.format(uid)
  190. if status == 0:
  191. hasAiService.update(**qs_data)
  192. # UidPushModel.objects.filter(uid_set__uid=uid).delete()
  193. # 状态为0的时候删除redis缓存数据
  194. # self.do_delete_redis(uid)
  195. # mqtt通知设备关闭AI识别功能
  196. msg = {'AiStatus': 'inactive'},
  197. req_success = self.requestPublishMqtt(uid, topic_name, msg)
  198. if not req_success:
  199. return response.json(10044)
  200. return response.json(0)
  201. elif status == 1:
  202. hasAiService.update(**qs_data)
  203. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  204. if uid_push_qs.exists():
  205. uid_push_update_dict = {
  206. 'appBundleId': appBundleId,
  207. 'app_type': app_type,
  208. 'push_type': push_type,
  209. 'token_val': token_val,
  210. 'updTime': nowTime,
  211. 'lang': lang,
  212. 'tz': tz
  213. }
  214. uid_push_qs.update(**uid_push_update_dict)
  215. else:
  216. # uid_set_id = uid_set_qs[0].id
  217. uid_push_create_dict = {
  218. 'uid_set_id': uid_set_id,
  219. 'userID_id': userID,
  220. 'appBundleId': appBundleId,
  221. 'app_type': app_type,
  222. 'push_type': push_type,
  223. 'token_val': token_val,
  224. 'm_code': m_code,
  225. 'addTime': nowTime,
  226. 'updTime': nowTime,
  227. 'lang': lang,
  228. 'tz': tz
  229. }
  230. # 绑定设备推送
  231. UidPushModel.objects.create(**uid_push_create_dict)
  232. # if interval:
  233. # self.do_delete_redis(uid, int(interval))
  234. # else:
  235. # self.do_delete_redis(uid)
  236. # utko = UidTokenObject()
  237. # # right
  238. # utko.generate(data={'uid': uid})
  239. etkObj = ETkObject(etk='')
  240. etk = etkObj.encrypt(uid)
  241. #只返回一个接口就行
  242. # detectUrl = "{DETECT_PUSH_DOMAIN}AiService/push?etk={etk}&endTime={endTime}". \
  243. # format(etk=etk, DETECT_PUSH_DOMAIN=SERVER_DOMAIN_SSL, endTime=endTime)
  244. aiIdentificationUrl = "{DETECT_PUSH_DOMAIN}AiService/identification".format(DETECT_PUSH_DOMAIN=SERVER_DOMAIN_SSL)
  245. # mqtt通知设备开启AI识别功能
  246. msg = {
  247. 'AiStatus': 'active',
  248. 'etk': etk,
  249. 'endTime': endTime,
  250. 'aiIdentificationUrl': aiIdentificationUrl,
  251. },
  252. req_success = self.requestPublishMqtt(uid, topic_name, msg)
  253. if not req_success:
  254. return response.json(10044)
  255. return response.json(0, {'aiIdentificationUrl': aiIdentificationUrl, 'endTime': endTime, 'etk': etk})
  256. else:
  257. return response.json(14)
  258. def getAiStatus(self, userID, request_dict, response):
  259. uid = request_dict.get('uid', None)
  260. if not uid:
  261. return response.json(444)
  262. try:
  263. ai_server_qs = AiService.objects.filter(uid=uid).values('detect_status', 'detect_group')
  264. if not ai_server_qs.exists():
  265. return response,json(173)
  266. res = {
  267. 'detect_status': ai_server_qs[0]['detect_status'],
  268. 'detect_group': ai_server_qs[0]['detect_group'],
  269. }
  270. return response.json(0, {'data': res})
  271. except Exception as e:
  272. return response.json(500, repr(e))
  273. def requestPublishMqtt(self, thing_name, topic_name, msg):
  274. # 通用发布MQTT主题通知
  275. if not all([msg, thing_name, topic_name]):
  276. return False
  277. try:
  278. # 获取数据组织将要请求的url
  279. iot = iotdeviceInfoModel.objects.filter(
  280. thing_name__icontains=thing_name).values(
  281. 'endpoint', 'token_iot_number')
  282. if not iot.exists():
  283. return False
  284. endpoint = iot[0]['endpoint']
  285. Token = iot[0]['token_iot_number']
  286. # api doc: https://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/http.html
  287. # url: https://IoT_data_endpoint/topics/url_encoded_topic_name?qos=1
  288. # post请求url发布MQTT消息
  289. url = 'https://{}/topics/{}'.format(endpoint, topic_name)
  290. authorizer_name = 'Ansjer_Iot_Auth'
  291. signature = CommonService.rsa_sign(Token) # Token签名
  292. headers = {
  293. 'x-amz-customauthorizer-name': authorizer_name,
  294. 'Token': Token,
  295. 'x-amz-customauthorizer-signature': signature}
  296. r = requests.post(url=url, headers=headers, json=msg, timeout=2)
  297. if r.status_code == 200:
  298. res = r.json()
  299. if res['message'] == 'OK':
  300. return True
  301. return False
  302. else:
  303. return False
  304. except Exception as e:
  305. return False
  306. def do_commodity_list(self, userID, request_dict, response): # 查询套餐列表
  307. uid = request_dict.get('uid', None)
  308. lang = request_dict.get('lang', 'en')
  309. nowTime = int(time.time())
  310. # DVR/NVR设备暂不返回云存套餐列表
  311. device_info_qs = Device_Info.objects.filter(Q(UID=uid), Q(Type__lte=4) | Q(Type=10001))
  312. if device_info_qs.exists():
  313. return response.json(0)
  314. qs = AiStoreMeal.objects
  315. qs = qs.filter(is_show=1) #过滤隐藏套餐
  316. qs = qs.annotate(ai_meal_id=F('id'))
  317. qs = qs.values("ai_meal_id", "title", "content", "price", "effective_day", "currency",
  318. "virtual_price", "symbol", "pay_type")
  319. if qs.exists():
  320. res = list(qs)
  321. for key, val in enumerate(res):
  322. pay_types = Pay_Type.objects.filter(aistoremeal=res[key]['ai_meal_id']).values("id", "payment")
  323. res[key]['pay_type'] = list(pay_types)
  324. result = {
  325. 'meals': res,
  326. }
  327. return response.json(0, result)
  328. else:
  329. return response.json(0)
  330. def do_querylist(self, userID, request_dict, response):
  331. page = request_dict.get('page', None)
  332. line = request_dict.get('line', None)
  333. uid = request_dict.get('uid', None)
  334. lang = request_dict.get('lang', 'en')
  335. if not page or not line:
  336. return response.json(444, 'page,line')
  337. page = int(page)
  338. line = int(line)
  339. omqs = Order_Model.objects.filter(userID_id=userID, status=1, order_type=1)
  340. # 筛选指定设备id的订单
  341. if uid:
  342. omqs.filter(UID=uid)
  343. if not omqs.exists():
  344. return response.json(173)
  345. # return response.json(10, '订单不存在')
  346. count = omqs.count()
  347. omqs = omqs.annotate(rank__title=F('ai_rank__title'), rank__content=F('ai_rank__content'),
  348. rank__day=F('ai_rank__effective_day'), rank__price=F('ai_rank__price'),
  349. rank__expire=F('ai_rank__effective_day'), rank__id=F('ai_rank_id'), rank__currency=F('ai_rank__currency'))
  350. order_ql = omqs[(page - 1) * line:page * line].values("orderID", "UID", "channel", "desc", "price", "currency",
  351. "addTime",
  352. "updTime", "paypal", "rank__day", "payType",
  353. "rank__price", "status",
  354. "rank__content", "rank__title", "rank__currency",
  355. "rank__expire", "ai_rank_id")
  356. order_list = list(order_ql)
  357. data = []
  358. nowTime = int(time.time())
  359. # 这里需要进行优化
  360. uid_list = []
  361. for od in order_list:
  362. uid_list.append(od['UID'])
  363. didqs = Device_Info.objects.filter(userID_id=userID, UID__in=uid_list).values('id', 'UID', 'Type')
  364. for d in order_list:
  365. if d['status'] == 0:
  366. if d['addTime'] + 3600 < nowTime:
  367. d['status'] = 3
  368. for did in didqs:
  369. if d['UID'] == did['UID']:
  370. d['did'] = did['id']
  371. d['Type'] = did['Type']
  372. data.append(d)
  373. # d['rank__lang__content'] = '月' if lang == 'cn' else 'month'
  374. return response.json(0, {'data': data, 'count': count})
  375. def do_create_pay_order(self, request_dict, userID, ip, response):
  376. uid = request_dict.get('uid', None)
  377. channel = request_dict.get('channel', None)
  378. pay_type = int(request_dict.get('pay_type', 1))
  379. ai_meal_id = request_dict.get('ai_meal_id', None)
  380. lang = request_dict.get('lang', 'en')
  381. if not uid or not channel or not pay_type or not ai_meal_id:
  382. return response.json(444)
  383. # dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1).values(
  384. # 'vodPrimaryUserID',
  385. # 'vodPrimaryMaster')
  386. # if not dv_qs.exists():
  387. # return response.json(12)
  388. # dvq = Device_Info.objects.filter(UID=uid)
  389. # dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  390. # if dvq.exists():
  391. # if dvq[0]['vodPrimaryUserID'] != userID:
  392. # return response.json(10033)
  393. nowTime = int(time.time())
  394. smqs = AiStoreMeal.objects.filter(id=ai_meal_id, pay_type=pay_type, is_show=1). \
  395. values('currency', 'price', 'content', 'effective_day', 'title')
  396. if not smqs.exists():
  397. return response.json(173)
  398. currency = smqs[0]['currency']
  399. price = smqs[0]['price']
  400. content = smqs[0]['content']
  401. day = smqs[0]['effective_day']
  402. orderID = CommonService.createOrderID()
  403. price = float(price)
  404. price = round(price, 2)
  405. if pay_type == 1:
  406. #正常扣款
  407. cal_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  408. if lang != 'cn':
  409. cal_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  410. call_sub_url = "{SERVER_DOMAIN_SSL}cloudstorage/dopaypalcallback?orderID={orderID}&lang={lang}". \
  411. format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, orderID=orderID, lang=lang)
  412. # call_sub_url = "http://binbin.uicp.vip/cloudstorage/dopaypalcallback?orderID={orderID}".format(
  413. # SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, orderID=orderID)
  414. Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
  415. desc=content, payType=pay_type, payTime=nowTime,
  416. price=price, currency=currency, addTime=nowTime, updTime=nowTime,
  417. pay_url='', commodity_code='', commodity_type=1,
  418. ai_rank_id=ai_meal_id, rank_id=1, order_type=1, status=1)
  419. has = AiService.objects.filter(uid=uid, channel=channel, use_status=1)
  420. if has.exists():
  421. use_status = 0
  422. else:
  423. use_status = 1
  424. # return response.json(0)
  425. AiService.objects.create(orders_id=orderID, uid=uid, channel=channel, detect_status=1,
  426. endTime=nowTime+(day*86400), addTime=nowTime, updTime=nowTime,
  427. use_status=use_status, detect_group='1')
  428. return response.json(0, {"orderID": orderID})
  429. return response.json(10, 'generate_order_false')
  430. def update_jpush_time(self,userID, request_dict, response):
  431. logger = logging.getLogger('info')
  432. msg_id = request_dict.get('msg_id', None)
  433. apns_push_time = request_dict.get('apns_push_time', None)
  434. logger.info("----init--apns----push_time={apns_push_time}".format(apns_push_time=apns_push_time))
  435. apns_push_time = int(apns_push_time)
  436. logger.info("---msg--id={msg_id}".format(msg_id=msg_id))
  437. logger.info("---apns----push_time={apns_push_time}".format(apns_push_time=apns_push_time))
  438. AiProcessTime.objects.filter(msg_id=msg_id).update(appPushTime=apns_push_time)
  439. return response.json(0)
  440. def do_ai_identification(self, request_dict,response):
  441. etk = request_dict.get('etk', None)
  442. n_time = request_dict.get('n_time', None)
  443. receiveTime = int(time.time())
  444. logger = logging.getLogger('info')
  445. logger.info('-----------into----ai--api')
  446. logger.info("etk={etk}".format(etk=etk))
  447. if not etk:
  448. return response.json(444)
  449. try:
  450. # 解密uid及判断长度
  451. eto = ETkObject(etk)
  452. uid = eto.uid
  453. logger.info("uid={uid}".format(uid=uid))
  454. if len(uid) != 20 and len(uid) != 14:
  455. return response.json(444)
  456. ##通过uid查出endTime是否过期,并且ai开关是否打开
  457. AiServiceQuery = AiService.objects.filter(uid=uid, detect_status=1, use_status=1, endTime__gt=receiveTime).\
  458. values('detect_group')
  459. if not AiServiceQuery.exists():
  460. logger.info('none-----aiService')
  461. return response.json(173)
  462. detect_group = AiServiceQuery[0]['detect_group']
  463. #{}??
  464. #
  465. file_post_one = request_dict.get('fileOne', None)
  466. file_post_two = request_dict.get('fileTwo', None)
  467. file_post_three = request_dict.get('fileThree', None)
  468. file_post_one = file_post_one.replace(' ', '+')
  469. file_post_two = file_post_two.replace(' ', '+')
  470. file_post_three = file_post_three.replace(' ', '+')
  471. file_post_one = base64.b64decode(file_post_one)
  472. file_post_two = base64.b64decode(file_post_two)
  473. file_post_three = base64.b64decode(file_post_three)
  474. file_list = [file_post_one, file_post_two, file_post_three]
  475. del file_post_one, file_post_two, file_post_three
  476. dir_path = os.path.join(BASE_DIR, 'static/ai/' + uid + '/' + str(receiveTime))
  477. if not os.path.exists(dir_path):
  478. os.makedirs(dir_path)
  479. file_path_list = []
  480. i = 1
  481. for index in file_list:
  482. file_path = dir_path + '/' + str(i) + '.jpg'
  483. file_path_list.append(file_path)
  484. with open(file_path, 'wb') as f:
  485. f.write(index)
  486. f.close()
  487. i += 1
  488. image_size = 500 # 每张小图片的大小
  489. image_colnum = 1 # 合并成一张图后,一行有几个小图
  490. MergePic.merge_images(dir_path, image_size, image_colnum)
  491. photo = open(dir_path + '.jpg', 'rb') #打开合成图
  492. cover = dir_path + '/' + str(i-1) + '.jpg'
  493. desc = dir_path + '.jpg'
  494. logger.info('----------------cover')
  495. logger.info(cover)
  496. logger.info(desc)
  497. # photo = open(r'E:\test---------------\test\snipaste20220121_215952.jpg', 'rb')
  498. #识别合成图片
  499. maxLabels = 50
  500. minConfidence = 96
  501. ai_start_time = int(time.time())
  502. client = boto3.client(
  503. 'rekognition',
  504. aws_access_key_id='AKIA2E67UIMD6JD6TN3J',
  505. aws_secret_access_key='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',
  506. region_name='us-east-1')
  507. # doc:
  508. rekognition_res = client.detect_labels(
  509. Image={'Bytes': photo.read()},
  510. MaxLabels=maxLabels,
  511. MinConfidence=minConfidence)
  512. if rekognition_res['ResponseMetadata']['HTTPStatusCode'] != 200:
  513. return response.json(173)
  514. ai_end_time = int(time.time())
  515. labels =rekognition_res['Labels']
  516. label_name = []
  517. logger.info('--------识别到的标签-------')
  518. logger.info(labels)
  519. for label in labels:
  520. label_name.append(label['Name'])
  521. for Parents in label['Parents']:
  522. label_name.append(Parents['Name'])
  523. labels = self.checkLabels(detect_group, label_name) #检查标签是否符合用户选择的识别类型
  524. if len(labels['label_list']) == 0:
  525. logger.info('没有识别到任何标签-----------------')
  526. return response.json(10055)
  527. event_type = ','.join(labels['label_type'])
  528. label_list = ','.join(labels['label_list'])
  529. logger.info(event_type)
  530. logger.info(label_list)
  531. #存储消息以及推送
  532. channel = request_dict.get('channel', '1')
  533. is_st = 1 #单图
  534. # 查询推送数据
  535. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid). \
  536. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id',
  537. 'userID__NickName',
  538. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval',
  539. 'uid_set__detect_group',
  540. 'uid_set__channel')
  541. if not uid_push_qs.exists():
  542. return response.json(173)
  543. uid_push_list = []
  544. for qs in uid_push_qs:
  545. uid_push_list.append(qs)
  546. nickname = uid_push_list[0]['uid_set__nickname']
  547. if not nickname:
  548. nickname = uid
  549. eq_list = []
  550. userID_ids = []
  551. apns_start_time = 0
  552. apns_end_time = 0
  553. msg_id = CommonService.createOrderID()
  554. for up in uid_push_list:
  555. push_type = up['push_type']
  556. appBundleId = up['appBundleId']
  557. token_val = up['token_val']
  558. lang = up['lang']
  559. tz = up['tz']
  560. if tz is None or tz == '':
  561. tz = 0
  562. # 推送标题
  563. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  564. # 推送内容
  565. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz, label_list=label_list)
  566. kwargs = {
  567. 'uid': uid,
  568. 'channel': channel,
  569. 'event_type': event_type,
  570. 'n_time': n_time,
  571. 'appBundleId': appBundleId,
  572. 'token_val': token_val,
  573. 'msg_title': msg_title,
  574. 'msg_text': msg_text,
  575. 'msg_id' : msg_id,
  576. }
  577. # 推送消息
  578. if push_type == 0: # ios apns
  579. logger.info('into-------apns')
  580. apns_start_time = int(time.time())
  581. res = self.do_apns(**kwargs)
  582. apns_end_time = int(time.time())
  583. logger.info(res)
  584. # elif push_type == 1: # android gcm
  585. # self.do_fcm(**kwargs)
  586. elif push_type == 2: # android jpush
  587. logger.info('into-------jpush')
  588. jpush_start_time = int(time.time())
  589. res = self.do_jpush(**kwargs)
  590. jpush_end_time = int(time.time())
  591. logger.info(res)
  592. # 以下是存库
  593. userID_id = up["userID_id"]
  594. if userID_id not in userID_ids:
  595. now_time = int(time.time())
  596. eq_list.append(Ai_Push_Info(
  597. userID_id=userID_id,
  598. eventTime=n_time,
  599. eventType=event_type,
  600. devUid=uid,
  601. devNickName=nickname,
  602. Channel=channel,
  603. alarm='检查到{labels} \tChannel:{channel}'.format(labels=','.join(labels['label_list']), channel=channel),
  604. is_st=is_st,
  605. receiveTime=receiveTime,
  606. addTime=now_time,
  607. storage_location=2
  608. ))
  609. userID_ids.append(userID_id)
  610. Ai_Push_Info.objects.bulk_create(eq_list)
  611. #上传缩略图到s3
  612. cover_start_time = int(time.time())
  613. upload_cover_path = "{uid}/{channel}/cover{n_time}.jpg".format(uid=uid, channel=channel, n_time=n_time) #封面图
  614. upload_desc_path = "{uid}/{channel}/desc{n_time}.jpg".format(uid=uid, channel=channel, n_time=n_time) #详情内容图
  615. c_res = self.upload_s3(cover, upload_cover_path)
  616. d_res = self.upload_s3(desc, upload_desc_path)
  617. if c_res and d_res:
  618. logger.info('upload-----S3----success')
  619. count_time = int(time.time()) - receiveTime
  620. AiProcessTime.objects.create(detectTime=n_time, receiveTime=receiveTime, aiTime=ai_start_time,
  621. aiEndTime=ai_end_time, pushTime=apns_start_time,
  622. pushEndTime=apns_end_time, serverCountTime=count_time, msg_id=msg_id)
  623. return JsonResponse(status=200, data='success', safe=False)
  624. return JsonResponse(status=500, data='fail', safe=False)
  625. except Exception as e:
  626. print(e)
  627. return response.json(500, repr(e))
  628. ## 检查是否有符合条件的标签
  629. def checkLabels(self, user_detect_group, labels):
  630. labels_type = {
  631. '1': ['Person', 'Human'], #人
  632. '2': ['Dog', 'Pet', 'Canine', 'Animal'], #动物
  633. '3': ['Car', '', 'Vehicle', 'Transportation', 'Automobile'] #车
  634. }
  635. user_detect_list = user_detect_group.split(',')
  636. user_labels_type = {}
  637. for user_detect in user_detect_list:
  638. if user_detect in labels_type.keys():
  639. user_labels_type[user_detect] = labels_type[user_detect]
  640. label_list = []
  641. for k, labels_type in user_labels_type.items():
  642. for label in labels_type:
  643. if label in labels:
  644. label_list.append(label)
  645. user_labels_list = list(user_labels_type.keys())
  646. user_labels_list.sort()
  647. return {'label_type': user_labels_list, 'label_list': label_list}
  648. def upload_s3(self, file_path, upload_path):
  649. try:
  650. aws_key = "AKIA2MMWBR4DSFG67DTG" #【你的 aws_access_key】
  651. aws_secret = "aI9gxcAKPmiGgPy9axrtFKzjYGbvpuytEX4xWweL" # 【你的 aws_secret_key】
  652. session = Session(aws_access_key_id=aws_key,
  653. aws_secret_access_key=aws_secret,
  654. region_name="cn-northwest-1")
  655. s3 = session.resource("s3")
  656. # client = session.client("s3")
  657. bucket = "aipush" # 【你 bucket 的名字】 # 首先需要保.证 s3 上已经存在该存储桶,否则报错
  658. upload_data = open(file_path, "rb")
  659. # upload_key = "test"
  660. s3.Bucket(bucket).put_object(Key=upload_path, Body=upload_data)
  661. return True
  662. except Exception as e:
  663. print(repr(e))
  664. return False
  665. def get_msg_title(self, appBundleId, nickname):
  666. package_title_config = {
  667. 'com.ansjer.customizedd_a': 'DVS',
  668. 'com.ansjer.zccloud_a': 'ZosiSmart',
  669. 'com.ansjer.zccloud_ab': '周视',
  670. 'com.ansjer.adcloud_a': 'ADCloud',
  671. 'com.ansjer.adcloud_ab': 'ADCloud',
  672. 'com.ansjer.accloud_a': 'ACCloud',
  673. 'com.ansjer.loocamccloud_a': 'Loocam',
  674. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  675. 'com.ansjer.customizedb_a': 'COCOONHD',
  676. 'com.ansjer.customizeda_a': 'Guardian365',
  677. 'com.ansjer.customizedc_a': 'PatrolSecure',
  678. }
  679. if appBundleId in package_title_config.keys():
  680. return package_title_config[appBundleId] + '(' + nickname + ')'
  681. else:
  682. return nickname
  683. def get_msg_text(self, channel, n_time, lang, tz, label_list):
  684. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz,lang=lang)
  685. if lang == 'cn':
  686. msg = '摄像头AI识别到了{}'.format(label_list)
  687. send_text = '{msg} 通道:{channel} 日期:{date}'.format(msg=msg, channel=channel, date=n_date)
  688. else:
  689. msg = 'Camera AI recognizes{}'.format(label_list)
  690. send_text = '{msg} channel:{channel} date:{date}'.format(msg=msg, channel=channel, date=n_date)
  691. return send_text
  692. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text, msg_id=0):
  693. app_key = JPUSH_CONFIG[appBundleId]['Key']
  694. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  695. # 此处换成各自的app_key和master_secre
  696. _jpush = jpush.JPush(app_key, master_secret)
  697. push = _jpush.create_push()
  698. push.audience = jpush.registration_id(token_val)
  699. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  700. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  701. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  702. big_text=msg_text, title=msg_title,
  703. extras=push_data)
  704. push.notification = jpush.notification(android=android)
  705. push.platform = jpush.all_
  706. res = push.send()
  707. print(res)
  708. return res.status_code
  709. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text, msg_id=0):
  710. try:
  711. serverKey = FCM_CONFIG[appBundleId]
  712. except Exception as e:
  713. return 'serverKey abnormal'
  714. push_service = FCMNotification(api_key=serverKey)
  715. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  716. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  717. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  718. message_body=msg_text, data_message=data,
  719. extra_kwargs={
  720. 'default_vibrate_timings': True,
  721. 'default_sound': True,
  722. 'default_light_settings': True
  723. })
  724. print('fcm push ing')
  725. print(result)
  726. return result
  727. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text, msg_id=0):
  728. logger = logging.getLogger('info')
  729. logger.info("进来do_apns函数了")
  730. logger.info(token_val)
  731. logger.info(APNS_MODE)
  732. logger.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  733. try:
  734. cli = apns2.APNSClient(mode=APNS_MODE, client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  735. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  736. "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel, "msg_id": msg_id}
  737. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  738. payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
  739. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  740. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  741. if res.status_code == 200:
  742. return res.status_code
  743. else:
  744. logger.info('apns push fail')
  745. logger.info(res.reason)
  746. return res.status_code
  747. except (ValueError, ArithmeticError):
  748. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  749. except Exception as e:
  750. print(repr(e))
  751. logger.info(repr(e))
  752. return repr(e)
  753. def queryInfo(self, userID, request_dict, response):
  754. page = int(request_dict.get('page', None))
  755. line = int(request_dict.get('line', None))
  756. if not page or not line:
  757. return response.json(444, 'page,line')
  758. startTime = request_dict.get('startTime', None)
  759. endTime = request_dict.get('endTime', None)
  760. eventType = request_dict.get('eventType', None)
  761. now_time = int(time.time())
  762. seven_days_ago = now_time - 7 * 24 * 3600 # 查询7天内的数据
  763. qs = Ai_Push_Info.objects.filter(userID_id=userID, eventTime__gt=seven_days_ago).order_by('-eventTime')
  764. if startTime and endTime:
  765. qs = qs.filter(eventTime__range=(startTime, endTime))
  766. # if eventType:
  767. # qs = qs.filter(eventType__contains=eventType)
  768. uids = request_dict.get('uids', None)
  769. if uids:
  770. uid_list = uids.split(',')
  771. qs = qs.filter(devUid__in=uid_list)
  772. dvqs = Device_Info.objects.filter(UID__in=uid_list, userID_id=userID).values('UID', 'Type', 'NickName')
  773. uid_type_dict = {}
  774. for dv in dvqs:
  775. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  776. else:
  777. dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
  778. uid_type_dict = {}
  779. for dv in dvqs:
  780. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  781. if not qs.exists():
  782. return response.json(0, {'datas': [], 'count': 0})
  783. count = qs.count()
  784. qs = qs.values('id', 'devUid', 'devNickName', 'Channel', 'eventType', 'status', 'alarm', 'eventTime',
  785. 'receiveTime', 'is_st', 'addTime', 'storage_location')
  786. qs = qs[(page - 1) * line:page * line]
  787. res = []
  788. aws_s3_client = boto3.client(
  789. 's3',
  790. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  791. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  792. config=botocore.client.Config(signature_version='s3v4'),
  793. region_name='cn-northwest-1'
  794. )
  795. for p in qs:
  796. p['eventType'] = int(p['eventType'][0])
  797. devUid = p['devUid']
  798. eventTime = p['eventTime']
  799. channel = p['Channel']
  800. storage_location = p['storage_location']
  801. if p['is_st'] == 1:
  802. s3_img_cover = '{uid}/{channel}/cover{time}.jpg'.format(uid=devUid, channel=channel, time=eventTime)
  803. s3_img_desc = '{uid}/{channel}/desc{time}.jpg'.format(uid=devUid, channel=channel, time=eventTime)
  804. response_url_cover = aws_s3_client.generate_presigned_url('get_object',
  805. ExpiresIn=300,
  806. Params={
  807. 'Bucket': 'aipush', 'Key': s3_img_cover
  808. },
  809. )
  810. response_url_desc = aws_s3_client.generate_presigned_url('get_object',
  811. ExpiresIn=300,
  812. Params={
  813. 'Bucket': 'aipush', 'Key': s3_img_desc
  814. },
  815. )
  816. p['img'] = response_url_cover
  817. p['img_list'] = [response_url_desc]
  818. elif p['is_st'] == 2:
  819. pass
  820. if devUid in uid_type_dict.keys():
  821. p['uid_type'] = uid_type_dict[devUid]['type']
  822. p['devNickName'] = uid_type_dict[devUid]['NickName']
  823. else:
  824. p['uid_type'] = ''
  825. res.append(p)
  826. return response.json(0, {'datas': res, 'count': count})
  827. def readInfo(self, userID, request_dict, response):
  828. is_update_all = request_dict.get('is_update_all', 0)
  829. try:
  830. if int(is_update_all) == 1: # 全部已读
  831. is_update = Ai_Push_Info.objects.filter(userID_id=userID).update(status=1)
  832. return response.json(0, {'update_count': is_update})
  833. else:
  834. id_list = request_dict.get('id_list', None)
  835. if not id_list:
  836. request_dict.getlist('id_list[]', None) # 获取IOS数组传参
  837. logger = logging.getLogger('info')
  838. logger.info('已读ai消息id_list:{}'.format(id_list))
  839. if not id_list:
  840. return response.json(444)
  841. id_list = eval(id_list) # 字符串转列表
  842. param_flag = CommonService.get_param_flag(data=id_list)
  843. if not param_flag:
  844. return response.json(444)
  845. count = 0
  846. for id in id_list:
  847. ai_push_qs = Ai_Push_Info.objects.filter(id=int(id))
  848. if ai_push_qs.exists():
  849. own_dev = ModelService.check_own_device(userID, ai_push_qs[0].devUid)
  850. if own_dev:
  851. count += 1
  852. ai_push_qs.update(status=1)
  853. return response.json(0, {'update_success': count})
  854. except Exception as e:
  855. print(e)
  856. return response.json(500, repr(e))
  857. def deleteInfo(self, userID, request_dict, response):
  858. id_list = request_dict.get('id_list', None)
  859. if not id_list:
  860. request_dict.getlist('id_list[]', None) # 获取IOS数组传参
  861. logger = logging.getLogger('info')
  862. logger.info('删除ai消息id_list:{}'.format(id_list))
  863. if not id_list:
  864. return response.json(444)
  865. try:
  866. id_list = eval(id_list) # 字符串转列表
  867. param_flag = CommonService.get_param_flag(data=id_list)
  868. if not param_flag:
  869. return response.json(444)
  870. for id in id_list:
  871. ai_push_qs = Ai_Push_Info.objects.filter(id=id)
  872. if ai_push_qs.exists():
  873. own_dev = ModelService.check_own_device(userID, ai_push_qs[0].devUid)
  874. if own_dev:
  875. ai_push_qs.delete()
  876. return response.json(0)
  877. except Exception as e:
  878. print(e)
  879. return response.json(500, repr(e))