AiController.py 45 KB

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