AiController.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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
  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. else:
  105. return response.json(414)
  106. def do_change_ai_status(self, userID, request_dict, response):
  107. token_val = request_dict.get('token_val', None)
  108. appBundleId = request_dict.get('appBundleId', None)
  109. app_type = request_dict.get('app_type', None)
  110. push_type = request_dict.get('push_type', None)
  111. status = request_dict.get('status', None)
  112. m_code = request_dict.get('m_code', None)
  113. uid = request_dict.get('uid', None)
  114. # 设备语言
  115. lang = request_dict.get('lang', 'en')
  116. tz = request_dict.get('tz', '0')
  117. # 消息提醒功能新增
  118. # 如果传空上来,就默认为0
  119. if tz == '':
  120. tz = 0
  121. else:
  122. tz = tz.replace("GMT", "")
  123. detect_group = request_dict.get('detect_group', None)
  124. interval = request_dict.get('interval', None)
  125. if not status:
  126. return response.json(444, 'status')
  127. # 关闭推送
  128. if not all([appBundleId, app_type, token_val, uid, m_code]):
  129. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  130. # 判断推送类型对应key是否存在
  131. print('push_type:', push_type)
  132. if push_type == '0':
  133. if appBundleId not in APNS_CONFIG.keys():
  134. return response.json(904)
  135. elif push_type == '1':
  136. if appBundleId not in FCM_CONFIG.keys():
  137. return response.json(904)
  138. elif push_type == '2':
  139. if appBundleId not in JPUSH_CONFIG.keys():
  140. return response.json(904)
  141. else:
  142. return response.json(173)
  143. hasAiService = AiService.objects.filter(uid=uid,use_status=1)
  144. if not hasAiService.exists():
  145. return response.json(10053)
  146. nowTime = int(time.time())
  147. endTime = hasAiService.values('endTime')[0]['endTime']
  148. if nowTime >endTime:
  149. return response.json(10054)
  150. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  151. status = int(status)
  152. nowTime = int(time.time())
  153. if dvqs.exists():
  154. # 修改状态
  155. # dvqs.update(NotificationMode=status)
  156. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  157. # uid配置信息是否存在
  158. if uid_set_qs.exists():
  159. uid_set_id = uid_set_qs[0].id
  160. qs_data = {
  161. 'updTime': nowTime,
  162. }
  163. if interval:
  164. qs_data['detect_interval'] = int(interval)
  165. if detect_group:
  166. qs_data['detect_group'] = detect_group
  167. uid_set_qs.update(**qs_data)
  168. else:
  169. qs_data = {
  170. 'uid': uid,
  171. 'addTime': nowTime,
  172. 'updTime': nowTime,
  173. }
  174. if interval:
  175. qs_data['detect_interval'] = int(interval)
  176. if detect_group:
  177. qs_data['detect_group'] = detect_group
  178. # 添加设备配置
  179. uid_set_qs = UidSetModel.objects.create(**qs_data)
  180. uid_set_id = uid_set_qs.id
  181. topic_name = 'AiServer/{}'.format(uid)
  182. if status == 0:
  183. hasAiService.update(**qs_data)
  184. # UidPushModel.objects.filter(uid_set__uid=uid).delete()
  185. # 状态为0的时候删除redis缓存数据
  186. # self.do_delete_redis(uid)
  187. # mqtt通知设备关闭AI识别功能
  188. msg = {'AiStatus': 'inactive'},
  189. req_success = self.requestPublishMqtt(uid, topic_name, msg)
  190. if not req_success:
  191. return response.json(10044)
  192. return response.json(0)
  193. elif status == 1:
  194. hasAiService.update(**qs_data)
  195. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  196. if uid_push_qs.exists():
  197. uid_push_update_dict = {
  198. 'appBundleId': appBundleId,
  199. 'app_type': app_type,
  200. 'push_type': push_type,
  201. 'token_val': token_val,
  202. 'updTime': nowTime,
  203. 'lang': lang,
  204. 'tz': tz
  205. }
  206. uid_push_qs.update(**uid_push_update_dict)
  207. else:
  208. # uid_set_id = uid_set_qs[0].id
  209. uid_push_create_dict = {
  210. 'uid_set_id': uid_set_id,
  211. 'userID_id': userID,
  212. 'appBundleId': appBundleId,
  213. 'app_type': app_type,
  214. 'push_type': push_type,
  215. 'token_val': token_val,
  216. 'm_code': m_code,
  217. 'addTime': nowTime,
  218. 'updTime': nowTime,
  219. 'lang': lang,
  220. 'tz': tz
  221. }
  222. # 绑定设备推送
  223. UidPushModel.objects.create(**uid_push_create_dict)
  224. # if interval:
  225. # self.do_delete_redis(uid, int(interval))
  226. # else:
  227. # self.do_delete_redis(uid)
  228. # utko = UidTokenObject()
  229. # # right
  230. # utko.generate(data={'uid': uid})
  231. etkObj = ETkObject(etk='')
  232. etk = etkObj.encrypt(uid)
  233. #只返回一个接口就行
  234. # detectUrl = "{DETECT_PUSH_DOMAIN}AiService/push?etk={etk}&endTime={endTime}". \
  235. # format(etk=etk, DETECT_PUSH_DOMAIN=SERVER_DOMAIN_SSL, endTime=endTime)
  236. aiIdentificationUrl = "{DETECT_PUSH_DOMAIN}AiService/identification".format(DETECT_PUSH_DOMAIN=SERVER_DOMAIN_SSL)
  237. # mqtt通知设备开启AI识别功能
  238. msg = {
  239. 'AiStatus': 'active',
  240. 'etk': etk,
  241. 'endTime': endTime,
  242. 'aiIdentificationUrl': aiIdentificationUrl,
  243. },
  244. req_success = self.requestPublishMqtt(uid, topic_name, msg)
  245. if not req_success:
  246. return response.json(10044)
  247. return response.json(0, {'aiIdentificationUrl': aiIdentificationUrl, 'endTime': endTime, 'etk': etk})
  248. else:
  249. return response.json(14)
  250. def getAiStatus(self, userID, request_dict, response):
  251. uid = request_dict.get('uid', None)
  252. if not uid:
  253. return response.json(444)
  254. try:
  255. ai_server_qs = AiService.objects.filter(uid=uid).values('detect_status', 'detect_group')
  256. if not ai_server_qs.exists():
  257. return response,json(173)
  258. res = {
  259. 'detect_status': ai_server_qs[0]['detect_status'],
  260. 'detect_group': ai_server_qs[0]['detect_group'],
  261. }
  262. return response.json(0, {'data': res})
  263. except Exception as e:
  264. return response.json(500, repr(e))
  265. def requestPublishMqtt(self, thing_name, topic_name, msg):
  266. # 通用发布MQTT主题通知
  267. if not all([msg, thing_name, topic_name]):
  268. return False
  269. try:
  270. # 获取数据组织将要请求的url
  271. iot = iotdeviceInfoModel.objects.filter(
  272. thing_name__icontains=thing_name).values(
  273. 'endpoint', 'token_iot_number')
  274. if not iot.exists():
  275. return False
  276. endpoint = iot[0]['endpoint']
  277. Token = iot[0]['token_iot_number']
  278. # api doc: https://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/http.html
  279. # url: https://IoT_data_endpoint/topics/url_encoded_topic_name?qos=1
  280. # post请求url发布MQTT消息
  281. url = 'https://{}/topics/{}'.format(endpoint, topic_name)
  282. authorizer_name = 'Ansjer_Iot_Auth'
  283. signature = CommonService.rsa_sign(Token) # Token签名
  284. headers = {
  285. 'x-amz-customauthorizer-name': authorizer_name,
  286. 'Token': Token,
  287. 'x-amz-customauthorizer-signature': signature}
  288. r = requests.post(url=url, headers=headers, json=msg, timeout=2)
  289. if r.status_code == 200:
  290. res = r.json()
  291. if res['message'] == 'OK':
  292. return True
  293. return False
  294. else:
  295. return False
  296. except Exception as e:
  297. return False
  298. def do_commodity_list(self, userID, request_dict, response): # 查询套餐列表
  299. uid = request_dict.get('uid', None)
  300. lang = request_dict.get('lang', 'en')
  301. nowTime = int(time.time())
  302. # DVR/NVR设备暂不返回云存套餐列表
  303. device_info_qs = Device_Info.objects.filter(Q(UID=uid), Q(Type__lte=4) | Q(Type=10001))
  304. if device_info_qs.exists():
  305. return response.json(0)
  306. qs = AiStoreMeal.objects
  307. qs = qs.filter(is_show=1) #过滤隐藏套餐
  308. qs = qs.annotate(ai_meal_id=F('id'))
  309. qs = qs.values("ai_meal_id", "title", "content", "price", "effective_day", "currency",
  310. "virtual_price", "symbol", "pay_type")
  311. if qs.exists():
  312. res = list(qs)
  313. for key, val in enumerate(res):
  314. pay_types = Pay_Type.objects.filter(aistoremeal=res[key]['ai_meal_id']).values("id", "payment")
  315. res[key]['pay_type'] = list(pay_types)
  316. result = {
  317. 'meals': res,
  318. }
  319. return response.json(0, result)
  320. else:
  321. return response.json(0)
  322. def do_create_pay_order(self, request_dict, userID, ip, response):
  323. uid = request_dict.get('uid', None)
  324. channel = request_dict.get('channel', None)
  325. pay_type = int(request_dict.get('pay_type', 1))
  326. ai_meal_id = request_dict.get('ai_meal_id', None)
  327. lang = request_dict.get('lang', 'en')
  328. if not uid or not channel or not pay_type or not ai_meal_id:
  329. return response.json(444)
  330. # dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1).values(
  331. # 'vodPrimaryUserID',
  332. # 'vodPrimaryMaster')
  333. # if not dv_qs.exists():
  334. # return response.json(12)
  335. # dvq = Device_Info.objects.filter(UID=uid)
  336. # dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  337. # if dvq.exists():
  338. # if dvq[0]['vodPrimaryUserID'] != userID:
  339. # return response.json(10033)
  340. nowTime = int(time.time())
  341. smqs = AiStoreMeal.objects.filter(id=ai_meal_id, pay_type=pay_type, is_show=1). \
  342. values('currency', 'price', 'content', 'effective_day', 'title')
  343. if not smqs.exists():
  344. return response.json(173)
  345. currency = smqs[0]['currency']
  346. price = smqs[0]['price']
  347. content = smqs[0]['content']
  348. day = smqs[0]['effective_day']
  349. orderID = CommonService.createOrderID()
  350. price = float(price)
  351. price = round(price, 2)
  352. if pay_type == 1:
  353. #正常扣款
  354. cal_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  355. if lang != 'cn':
  356. cal_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  357. call_sub_url = "{SERVER_DOMAIN_SSL}cloudstorage/dopaypalcallback?orderID={orderID}&lang={lang}". \
  358. format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, orderID=orderID, lang=lang)
  359. # call_sub_url = "http://binbin.uicp.vip/cloudstorage/dopaypalcallback?orderID={orderID}".format(
  360. # SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, orderID=orderID)
  361. Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
  362. desc=content, payType=pay_type, payTime=nowTime,
  363. price=price, currency=currency, addTime=nowTime, updTime=nowTime,
  364. pay_url='', commodity_code='', commodity_type=1,
  365. ai_rank_id=ai_meal_id, rank_id=1, order_type=1)
  366. has = AiService.objects.filter(uid=uid, channel=channel, use_status=1)
  367. if has.exists():
  368. use_status = 0
  369. else:
  370. use_status = 1
  371. # return response.json(0)
  372. AiService.objects.create(orders_id=orderID, uid=uid, channel=channel, detect_status=1,
  373. endTime=nowTime+(day*86400), addTime=nowTime, updTime=nowTime,
  374. use_status=use_status, detect_group='1')
  375. return response.json(0, {"orderID": orderID})
  376. return response.json(10, 'generate_order_false')
  377. def do_ai_identification(self, request_dict,response):
  378. etk = request_dict.get('etk', None)
  379. now_time = int(time.time())
  380. logger = logging.getLogger('info')
  381. logger.info('-----------into----ai--api')
  382. logger.info("etk={etk}".format(etk=etk))
  383. if not etk:
  384. return response.json(444)
  385. try:
  386. # 解密uid及判断长度
  387. eto = ETkObject(etk)
  388. uid = eto.uid
  389. logger.info("uid={uid}".format(uid=uid))
  390. if len(uid) != 20 and len(uid) != 14:
  391. return response.json(444)
  392. ##通过uid查出endTime是否过期,并且ai开关是否打开
  393. AiServiceQuery = AiService.objects.filter(uid=uid, detect_status=1, use_status=1, endTime__gt=now_time).\
  394. values('detect_group')
  395. if not AiServiceQuery.exists():
  396. logger.info('none-----aiService')
  397. return response.json(173)
  398. detect_group = AiServiceQuery[0]['detect_group']
  399. #{}??
  400. #
  401. file_post_one = request_dict.get('fileOne', None)
  402. file_post_two = request_dict.get('fileTwo', None)
  403. file_post_three = request_dict.get('fileThree', None)
  404. file_post_one = file_post_one.replace(' ', '+')
  405. file_post_two = file_post_two.replace(' ', '+')
  406. file_post_three = file_post_three.replace(' ', '+')
  407. file_post_one = base64.b64decode(file_post_one)
  408. file_post_two = base64.b64decode(file_post_two)
  409. file_post_three = base64.b64decode(file_post_three)
  410. file_list = [file_post_one, file_post_two, file_post_three]
  411. del file_post_one, file_post_two, file_post_three
  412. dir_path = os.path.join(BASE_DIR, 'static/ai/' + uid + '/' + str(now_time))
  413. if not os.path.exists(dir_path):
  414. os.makedirs(dir_path)
  415. file_path_list = []
  416. i = 1
  417. for index in file_list:
  418. file_path = dir_path + '/' + str(i) + '.jpg'
  419. file_path_list.append(file_path)
  420. with open(file_path, 'wb') as f:
  421. f.write(index)
  422. f.close()
  423. i += 1
  424. image_size = 500 # 每张小图片的大小
  425. image_colnum = 1 # 合并成一张图后,一行有几个小图
  426. MergePic.merge_images(dir_path, image_size, image_colnum)
  427. photo = open(dir_path + '.jpg', 'rb') #打开合成图
  428. cover = dir_path + '/' + str(i-1) + '.jpg'
  429. desc = dir_path + '.jpg'
  430. logger.info('----------------cover')
  431. logger.info(cover)
  432. logger.info(desc)
  433. # photo = open(r'E:\test---------------\test\snipaste20220121_215952.jpg', 'rb')
  434. #识别合成图片
  435. maxLabels = 50
  436. minConfidence = 96
  437. client = boto3.client(
  438. 'rekognition',
  439. aws_access_key_id='AKIA2E67UIMD6JD6TN3J',
  440. aws_secret_access_key='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',
  441. region_name='us-east-1')
  442. # doc:
  443. rekognition_res = client.detect_labels(
  444. Image={'Bytes': photo.read()},
  445. MaxLabels=maxLabels,
  446. MinConfidence=minConfidence)
  447. if rekognition_res['ResponseMetadata']['HTTPStatusCode'] != 200:
  448. return response.json(173)
  449. labels =rekognition_res['Labels']
  450. label_name = []
  451. logger.info('--------识别到的标签-------')
  452. logger.info(labels)
  453. for label in labels:
  454. label_name.append(label['Name'])
  455. for Parents in label['Parents']:
  456. label_name.append(Parents['Name'])
  457. labels = self.checkLabels(detect_group, label_name) #检查标签是否符合用户选择的识别类型
  458. if len(labels['label_list']) == 0:
  459. logger.info('没有识别到任何标签-----------------')
  460. return response.json(10055)
  461. event_type = ','.join(labels['label_type'])
  462. label_list = ','.join(labels['label_list'])
  463. logger.info(event_type)
  464. logger.info(label_list)
  465. #存储消息以及推送
  466. channel = request_dict.get('channel', '1')
  467. n_time = now_time
  468. is_st = 1 #单图
  469. # 查询推送数据
  470. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid). \
  471. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id',
  472. 'userID__NickName',
  473. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval',
  474. 'uid_set__detect_group',
  475. 'uid_set__channel')
  476. if not uid_push_qs.exists():
  477. return response.json(173)
  478. uid_push_list = []
  479. for qs in uid_push_qs:
  480. uid_push_list.append(qs)
  481. nickname = uid_push_list[0]['uid_set__nickname']
  482. if not nickname:
  483. nickname = uid
  484. eq_list = []
  485. userID_ids = []
  486. for up in uid_push_list:
  487. push_type = up['push_type']
  488. appBundleId = up['appBundleId']
  489. token_val = up['token_val']
  490. lang = up['lang']
  491. tz = up['tz']
  492. if tz is None or tz == '':
  493. tz = 0
  494. # 推送标题
  495. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  496. # 推送内容
  497. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz, label_list=label_list)
  498. kwargs = {
  499. 'uid': uid,
  500. 'channel': channel,
  501. 'event_type': event_type,
  502. 'n_time': n_time,
  503. 'appBundleId': appBundleId,
  504. 'token_val': token_val,
  505. 'msg_title': msg_title,
  506. 'msg_text': msg_text,
  507. }
  508. # 推送消息
  509. if push_type == 0: # ios apns
  510. logger.info('into-------apns')
  511. res = self.do_apns(**kwargs)
  512. logger.info(res)
  513. # elif push_type == 1: # android gcm
  514. # self.do_fcm(**kwargs)
  515. elif push_type == 2: # android jpush
  516. logger.info('into-------jpush')
  517. res = self.do_jpush(**kwargs)
  518. logger.info(res)
  519. # 以下是存库
  520. userID_id = up["userID_id"]
  521. if userID_id not in userID_ids:
  522. now_time = int(time.time())
  523. eq_list.append(Ai_Push_Info(
  524. userID_id=userID_id,
  525. eventTime=n_time,
  526. eventType=event_type,
  527. devUid=uid,
  528. devNickName=nickname,
  529. Channel=channel,
  530. alarm='检查到{labels} \tChannel:{channel}'.format(labels=','.join(labels['label_list']), channel=channel),
  531. is_st=is_st,
  532. receiveTime=n_time,
  533. addTime=now_time,
  534. storage_location=2
  535. ))
  536. userID_ids.append(userID_id)
  537. Ai_Push_Info.objects.bulk_create(eq_list)
  538. #上传缩略图到s3
  539. upload_cover_path = "{uid}/{channel}/cover{n_time}.jpg".format(uid=uid, channel=channel, n_time=n_time) #封面图
  540. upload_desc_path = "{uid}/{channel}/desc{n_time}.jpg".format(uid=uid, channel=channel, n_time=n_time) #详情内容图
  541. c_res = self.upload_s3(cover, upload_cover_path)
  542. d_res = self.upload_s3(desc, upload_desc_path)
  543. if c_res and d_res:
  544. logger.info('upload-----S3----success')
  545. return JsonResponse(status=200, data='success', safe=False)
  546. return JsonResponse(status=500, data='fail', safe=False)
  547. except Exception as e:
  548. print(e)
  549. return response.json(500, repr(e))
  550. ## 检查是否有符合条件的标签
  551. def checkLabels(self, user_detect_group, labels):
  552. labels_type = {
  553. '1': ['Person', 'Human'], #人
  554. '2': ['Dog', 'Pet', 'Canine', 'Animal'], #动物
  555. '3': ['Car', '', 'Vehicle', 'Transportation', 'Automobile'] #车
  556. }
  557. user_detect_list = user_detect_group.split(',')
  558. user_labels_type = {}
  559. for user_detect in user_detect_list:
  560. if user_detect in labels_type.keys():
  561. user_labels_type[user_detect] = labels_type[user_detect]
  562. label_list = []
  563. for k, labels_type in user_labels_type.items():
  564. for label in labels_type:
  565. if label in labels:
  566. label_list.append(label)
  567. user_labels_list = list(user_labels_type.keys())
  568. user_labels_list.sort()
  569. return {'label_type': user_labels_list, 'label_list': label_list}
  570. def upload_s3(self, file_path, upload_path):
  571. try:
  572. aws_key = "AKIA2MMWBR4DSFG67DTG" #【你的 aws_access_key】
  573. aws_secret = "aI9gxcAKPmiGgPy9axrtFKzjYGbvpuytEX4xWweL" # 【你的 aws_secret_key】
  574. session = Session(aws_access_key_id=aws_key,
  575. aws_secret_access_key=aws_secret,
  576. region_name="cn-northwest-1")
  577. s3 = session.resource("s3")
  578. # client = session.client("s3")
  579. bucket = "aipush" # 【你 bucket 的名字】 # 首先需要保.证 s3 上已经存在该存储桶,否则报错
  580. upload_data = open(file_path, "rb")
  581. # upload_key = "test"
  582. s3.Bucket(bucket).put_object(Key=upload_path, Body=upload_data)
  583. return True
  584. except Exception as e:
  585. print(repr(e))
  586. return False
  587. def get_msg_title(self, appBundleId, nickname):
  588. package_title_config = {
  589. 'com.ansjer.customizedd_a': 'DVS',
  590. 'com.ansjer.zccloud_a': 'ZosiSmart',
  591. 'com.ansjer.zccloud_ab': '周视',
  592. 'com.ansjer.adcloud_a': 'ADCloud',
  593. 'com.ansjer.adcloud_ab': 'ADCloud',
  594. 'com.ansjer.accloud_a': 'ACCloud',
  595. 'com.ansjer.loocamccloud_a': 'Loocam',
  596. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  597. 'com.ansjer.customizedb_a': 'COCOONHD',
  598. 'com.ansjer.customizeda_a': 'Guardian365',
  599. 'com.ansjer.customizedc_a': 'PatrolSecure',
  600. }
  601. if appBundleId in package_title_config.keys():
  602. return package_title_config[appBundleId] + '(' + nickname + ')'
  603. else:
  604. return nickname
  605. def get_msg_text(self, channel, n_time, lang, tz, label_list):
  606. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz,lang=lang)
  607. if lang == 'cn':
  608. msg = '摄像头AI识别到了{}'.format(label_list)
  609. send_text = '{msg} 通道:{channel} 日期:{date}'.format(msg=msg, channel=channel, date=n_date)
  610. else:
  611. msg = 'Camera AI recognizes{}'.format(label_list)
  612. send_text = '{msg} channel:{channel} date:{date}'.format(msg=msg, channel=channel, date=n_date)
  613. return send_text
  614. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  615. app_key = JPUSH_CONFIG[appBundleId]['Key']
  616. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  617. # 此处换成各自的app_key和master_secre
  618. _jpush = jpush.JPush(app_key, master_secret)
  619. push = _jpush.create_push()
  620. push.audience = jpush.registration_id(token_val)
  621. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  622. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  623. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  624. big_text=msg_text, title=msg_title,
  625. extras=push_data)
  626. push.notification = jpush.notification(android=android)
  627. push.platform = jpush.all_
  628. res = push.send()
  629. print(res)
  630. return res.status_code
  631. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  632. try:
  633. serverKey = FCM_CONFIG[appBundleId]
  634. except Exception as e:
  635. return 'serverKey abnormal'
  636. push_service = FCMNotification(api_key=serverKey)
  637. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  638. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  639. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  640. message_body=msg_text, data_message=data,
  641. extra_kwargs={
  642. 'default_vibrate_timings': True,
  643. 'default_sound': True,
  644. 'default_light_settings': True
  645. })
  646. print('fcm push ing')
  647. print(result)
  648. return result
  649. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  650. logger = logging.getLogger('info')
  651. logger.info("进来do_apns函数了")
  652. logger.info(token_val)
  653. logger.info(APNS_MODE)
  654. logger.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  655. try:
  656. cli = apns2.APNSClient(mode=APNS_MODE, client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  657. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  658. "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
  659. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  660. payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
  661. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  662. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  663. if res.status_code == 200:
  664. return res.status_code
  665. else:
  666. logger.info('apns push fail')
  667. logger.info(res.reason)
  668. return res.status_code
  669. except (ValueError, ArithmeticError):
  670. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  671. except Exception as e:
  672. print(repr(e))
  673. logger.info(repr(e))
  674. return repr(e)
  675. def queryInfo(self, userID, request_dict, response):
  676. page = int(request_dict.get('page', None))
  677. line = int(request_dict.get('line', None))
  678. if not page or not line:
  679. return response.json(444, 'page,line')
  680. startTime = request_dict.get('startTime', None)
  681. endTime = request_dict.get('endTime', None)
  682. eventType = request_dict.get('eventType', None)
  683. now_time = int(time.time())
  684. seven_days_ago = now_time - 7 * 24 * 3600 # 查询7天内的数据
  685. qs = Ai_Push_Info.objects.filter(userID_id=userID, eventTime__gt=seven_days_ago).order_by('-eventTime')
  686. if startTime and endTime:
  687. qs = qs.filter(eventTime__range=(startTime, endTime))
  688. # if eventType:
  689. # qs = qs.filter(eventType__contains=eventType)
  690. uids = request_dict.get('uids', None)
  691. if uids:
  692. uid_list = uids.split(',')
  693. qs = qs.filter(devUid__in=uid_list)
  694. dvqs = Device_Info.objects.filter(UID__in=uid_list, userID_id=userID).values('UID', 'Type', 'NickName')
  695. uid_type_dict = {}
  696. for dv in dvqs:
  697. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  698. else:
  699. dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
  700. uid_type_dict = {}
  701. for dv in dvqs:
  702. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  703. if not qs.exists():
  704. return response.json(0, {'datas': [], 'count': 0})
  705. count = qs.count()
  706. qs = qs.values('id', 'devUid', 'devNickName', 'Channel', 'eventType', 'status', 'alarm', 'eventTime',
  707. 'receiveTime', 'is_st', 'addTime', 'storage_location')
  708. qs = qs[(page - 1) * line:page * line]
  709. res = []
  710. aws_s3_client = boto3.client(
  711. 's3',
  712. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  713. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  714. config=botocore.client.Config(signature_version='s3v4'),
  715. region_name='cn-northwest-1'
  716. )
  717. for p in qs:
  718. p['eventType'] = int(p['eventType'][0])
  719. devUid = p['devUid']
  720. eventTime = p['eventTime']
  721. channel = p['Channel']
  722. storage_location = p['storage_location']
  723. if p['is_st'] == 1:
  724. s3_img_cover = '{uid}/{channel}/cover{time}.jpg'.format(uid=devUid, channel=channel, time=eventTime)
  725. s3_img_desc = '{uid}/{channel}/desc{time}.jpg'.format(uid=devUid, channel=channel, time=eventTime)
  726. response_url_cover = aws_s3_client.generate_presigned_url('get_object',
  727. ExpiresIn=300,
  728. Params={
  729. 'Bucket': 'aipush', 'Key': s3_img_cover
  730. },
  731. )
  732. response_url_desc = aws_s3_client.generate_presigned_url('get_object',
  733. ExpiresIn=300,
  734. Params={
  735. 'Bucket': 'aipush', 'Key': s3_img_desc
  736. },
  737. )
  738. p['img'] = response_url_cover
  739. p['img_list'] = [response_url_desc]
  740. elif p['is_st'] == 2:
  741. pass
  742. if devUid in uid_type_dict.keys():
  743. p['uid_type'] = uid_type_dict[devUid]['type']
  744. p['devNickName'] = uid_type_dict[devUid]['NickName']
  745. else:
  746. p['uid_type'] = ''
  747. res.append(p)
  748. return response.json(0, {'datas': res, 'count': count})