AiController.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @software: PyCharm
  6. @Version: python3.6
  7. @MODIFY DECORD:ansjer dev
  8. """
  9. import base64
  10. import json
  11. import os
  12. import time
  13. import glob
  14. import urllib
  15. from urllib.parse import quote, parse_qs, unquote
  16. import apns2
  17. import boto3
  18. import jpush
  19. import oss2
  20. import paypalrestsdk
  21. import threading
  22. import calendar
  23. import datetime
  24. import logging
  25. import sys
  26. import requests
  27. from aliyunsdkcore import client
  28. from aliyunsdksts.request.v20150401 import AssumeRoleRequest
  29. from boto3.session import Session
  30. from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
  31. from django.db import transaction
  32. from django.views.generic.base import View
  33. import jwt
  34. from Object.ETkObject import ETkObject
  35. from pyfcm import FCMNotification
  36. from AnsjerPush.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, OSS_ROLE_ARN, SERVER_DOMAIN, PAYPAL_CRD, \
  37. SERVER_DOMAIN_SSL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_ARN, APNS_MODE, APNS_CONFIG, BASE_DIR, \
  38. JPUSH_CONFIG, FCM_CONFIG, OAUTH_ACCESS_TOKEN_SECRET
  39. from Model.models import UidPushModel, AiService, Equipment_Info
  40. from Object.RedisObject import RedisObject
  41. from Object.ResponseObject import ResponseObject
  42. from Object.TokenObject import TokenObject
  43. from Object.UidTokenObject import UidTokenObject
  44. from Object.utils import LocalDateTimeUtil
  45. from Service.CommonService import CommonService
  46. from django.db.models import Q, F, Count
  47. from decimal import Decimal
  48. from AnsjerPush.config import SERVER_TYPE
  49. from Service.EquipmentInfoService import EquipmentInfoService
  50. from Service.ModelService import ModelService
  51. from Object import MergePic
  52. import boto3
  53. import botocore
  54. from botocore import client
  55. # AI服务
  56. class AiView(View):
  57. def get(self, request, *args, **kwargs):
  58. request.encoding = 'utf-8'
  59. operation = kwargs.get('operation')
  60. return self.validation(request.GET, request, operation)
  61. def post(self, request, *args, **kwargs):
  62. request.encoding = 'utf-8'
  63. operation = kwargs.get('operation')
  64. return self.validation(request.POST, request, operation)
  65. def validation(self, request_dict, request, operation):
  66. response = ResponseObject()
  67. if operation is None:
  68. return response.json(444, 'error path')
  69. elif operation == 'identification': # ai识别
  70. return self.do_ai_identification(request.POST, response)
  71. elif operation == 'doPayPalCallBack': # paypal支付回调
  72. return self.do_pay_by_paypal_callback(request_dict, response)
  73. elif operation == 'doAlipayCallBack': # 支付宝支付回调
  74. return self.do_alipay_callback(request_dict, response)
  75. elif operation == 'doWechatCallBack': # 微信支付回调
  76. return self.do_wechat_callback(request, response)
  77. else:
  78. token = request_dict.get('token', None)
  79. # 设备主键uid
  80. tko = TokenObject(token)
  81. response.lang = tko.lang
  82. if tko.code != 0:
  83. return response.json(tko.code)
  84. userID = tko.userID
  85. if operation == 'identification': # ai识别
  86. return self.do_ai_identification(request_dict, response)
  87. else:
  88. return response.json(414)
  89. def do_ai_identification(self, request_dict,response):
  90. etk = request_dict.get('etk', None)
  91. n_time = request_dict.get('n_time', None)
  92. channel = request_dict.get('channel', '1')
  93. receiveTime = int(time.time())
  94. logger = logging.getLogger('info')
  95. logger.info('-----------into----ai--api')
  96. logger.info("etk={etk}".format(etk=etk))
  97. if not etk:
  98. return response.json(444)
  99. try:
  100. # 解密uid及判断长度
  101. eto = ETkObject(etk)
  102. uid = eto.uid
  103. logger.info("uid={uid}".format(uid=uid))
  104. if len(uid) != 20 and len(uid) != 14:
  105. return response.json(444)
  106. ##通过uid查出endTime是否过期,并且ai开关是否打开
  107. AiServiceQuery = AiService.objects.filter(uid=uid, detect_status=1, use_status=1, endTime__gt=receiveTime).\
  108. values('detect_group')
  109. if not AiServiceQuery.exists():
  110. logger.info('none-----aiService')
  111. return response.json(173)
  112. detect_group = AiServiceQuery[0]['detect_group']
  113. #{}??
  114. #
  115. file_post_one = request_dict.get('fileOne', None)
  116. file_post_two = request_dict.get('fileTwo', None)
  117. file_post_three = request_dict.get('fileThree', None)
  118. file_post_four = request_dict.get('fileFour', None)
  119. file_list = [file_post_one, file_post_two, file_post_three, file_post_four]
  120. del file_post_one, file_post_two, file_post_three, file_post_four
  121. if not all(file_list):
  122. for k, val in enumerate(file_list):
  123. if not val:
  124. return response.json(444,'缺少第{k}张图'.format(k=k+1))
  125. dir_path = os.path.join(BASE_DIR, 'static/ai/' + uid + '/' + str(n_time))
  126. if not os.path.exists(dir_path):
  127. os.makedirs(dir_path)
  128. file_path_list = []
  129. for i, val in enumerate(file_list):
  130. val = val.replace(' ', '+')
  131. val = base64.b64decode(val)
  132. file_path = "{dir_path}/{n_time}_{i}.jpg".format(dir_path=dir_path, n_time=n_time, i=i)
  133. file_path_list.append(file_path)
  134. with open(file_path, 'wb') as f:
  135. f.write(val)
  136. f.close()
  137. image_size = 0 # 每张小图片的大小,等于0是按原图大小进行合并
  138. image_colnum = 1 # 合并成一张图后,一行有几个小图
  139. image_size = MergePic.merge_images(dir_path, image_size, image_colnum)
  140. photo = open(dir_path + '.jpg', 'rb') #打开合成图
  141. # photo = open(r'E:\test---------------\test\snipaste20220121_215952.jpg', 'rb')
  142. #识别合成图片
  143. maxLabels = 50 #最大标签
  144. minConfidence = 95 #置信度
  145. ai_start_time = int(time.time())
  146. client = boto3.client(
  147. 'rekognition',
  148. aws_access_key_id='AKIA2E67UIMD6JD6TN3J',
  149. aws_secret_access_key='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',
  150. region_name='us-east-1')
  151. # doc:
  152. rekognition_res = client.detect_labels(
  153. Image={'Bytes': photo.read()},
  154. MaxLabels=maxLabels,
  155. MinConfidence=minConfidence)
  156. if rekognition_res['ResponseMetadata']['HTTPStatusCode'] != 200:
  157. return response.json(173)
  158. # rekognition_res = '{"Labels":[{"Name":"Person","Confidence":99.55254364013672,"Instances":[{"BoundingBox":{"Width":0.07776174694299698,"Height":0.13592061400413513,"Left":0.38370513916015625,"Top":0.09075711667537689},"Confidence":99.55254364013672},{"BoundingBox":{"Width":0.10947742313146591,"Height":0.12066027522087097,"Left":0.2790755331516266,"Top":0.10242735594511032},"Confidence":99.54237365722656},{"BoundingBox":{"Width":0.2935298979282379,"Height":0.09244367480278015,"Left":0.6143953204154968,"Top":0.9052517414093018},"Confidence":98.82627868652344},{"BoundingBox":{"Width":0.35492533445358276,"Height":0.21574528515338898,"Left":0.3411630690097809,"Top":0.27151572704315186},"Confidence":96.74708557128906},{"BoundingBox":{"Width":0.39604419469833374,"Height":0.09648437798023224,"Left":0.060247838497161865,"Top":0.9000436663627625},"Confidence":95.03588104248047},{"BoundingBox":{"Width":0.1105344295501709,"Height":0.1257047802209854,"Left":0.0025259912945330143,"Top":0.8314586877822876},"Confidence":92.17312622070312},{"BoundingBox":{"Width":0.13166509568691254,"Height":0.12054375559091568,"Left":0.10105808824300766,"Top":0.8364697694778442},"Confidence":89.71287536621094},{"BoundingBox":{"Width":0.22752150893211365,"Height":0.09563954919576645,"Left":0.7430258989334106,"Top":0.8961490392684937},"Confidence":85.34542083740234},{"BoundingBox":{"Width":0.1297324150800705,"Height":0.096779465675354,"Left":0.4607183039188385,"Top":0.9025260806083679},"Confidence":83.4525375366211}],"Parents":[]},{"Name":"Human","Confidence":99.55254364013672,"Instances":[],"Parents":[]},{"Name":"Husky","Confidence":98.64888763427734,"Instances":[],"Parents":[{"Name":"Dog"},{"Name":"Pet"},{"Name":"Canine"},{"Name":"Animal"},{"Name":"Mammal"}]},{"Name":"Dog","Confidence":98.64888763427734,"Instances":[{"BoundingBox":{"Width":0.2157023847103119,"Height":0.2352331429719925,"Left":0.26413947343826294,"Top":0.5162186622619629},"Confidence":94.06558990478516},{"BoundingBox":{"Width":0.23323440551757812,"Height":0.2026243358850479,"Left":0.4748744070529938,"Top":0.5457579493522644},"Confidence":92.4560546875},{"BoundingBox":{"Width":0.31273096799850464,"Height":0.23413777351379395,"Left":0.6696768999099731,"Top":0.5142407417297363},"Confidence":91.39192199707031},{"BoundingBox":{"Width":0.27037277817726135,"Height":0.21958686411380768,"Left":0.053227268159389496,"Top":0.5305629968643188},"Confidence":90.0697250366211}],"Parents":[{"Name":"Pet"},{"Name":"Canine"},{"Name":"Animal"},{"Name":"Mammal"}]},{"Name":"Canine","Confidence":98.64888763427734,"Instances":[],"Parents":[{"Name":"Mammal"},{"Name":"Animal"}]},{"Name":"Pet","Confidence":98.64888763427734,"Instances":[],"Parents":[{"Name":"Animal"}]},{"Name":"Mammal","Confidence":98.64888763427734,"Instances":[],"Parents":[{"Name":"Animal"}]},{"Name":"Animal","Confidence":98.64888763427734,"Instances":[],"Parents":[]},{"Name":"Car","Confidence":96.32373809814453,"Instances":[{"BoundingBox":{"Width":0.5476366281509399,"Height":0.10842914879322052,"Left":0.38325461745262146,"Top":0.11447073519229889},"Confidence":96.32373809814453}],"Parents":[{"Name":"Vehicle"},{"Name":"Transportation"}]},{"Name":"Transportation","Confidence":96.32373809814453,"Instances":[],"Parents":[]},{"Name":"Vehicle","Confidence":96.32373809814453,"Instances":[],"Parents":[{"Name":"Transportation"}]},{"Name":"Automobile","Confidence":96.32373809814453,"Instances":[],"Parents":[{"Name":"Vehicle"},{"Name":"Transportation"}]},{"Name":"Clothing","Confidence":86.02703857421875,"Instances":[],"Parents":[]},{"Name":"Apparel","Confidence":86.02703857421875,"Instances":[],"Parents":[]},{"Name":"Puppy","Confidence":85.16007232666016,"Instances":[],"Parents":[{"Name":"Dog"},{"Name":"Pet"},{"Name":"Canine"},{"Name":"Animal"},{"Name":"Mammal"}]},{"Name":"Wheel","Confidence":74.5079116821289,"Instances":[{"BoundingBox":{"Width":0.0818198174238205,"Height":0.052956655621528625,"Left":0.4488227367401123,"Top":0.17395207285881042},"Confidence":74.5079116821289},{"BoundingBox":{"Width":0.09288611263036728,"Height":0.050751496106386185,"Left":0.7844013571739197,"Top":0.17587198317050934},"Confidence":51.4537353515625}],"Parents":[{"Name":"Machine"}]},{"Name":"Machine","Confidence":74.5079116821289,"Instances":[],"Parents":[]}],"LabelModelVersion":"2.0","ResponseMetadata":{"RequestId":"1088325e-996b-4982-9afb-bd95df6d6fb3","HTTPStatusCode":200,"HTTPHeaders":{"x-amzn-requestid":"1088325e-996b-4982-9afb-bd95df6d6fb3","content-type":"application/x-amz-json-1.1","content-length":"4291","date":"Tue, 15 Mar 2022 06:44:17 GMT"},"RetryAttempts":0}}'
  159. # rekognition_res = json.loads(rekognition_res)
  160. ai_end_time = int(time.time())
  161. labels = self.labelsCoords(detect_group, rekognition_res, image_size, n_time) #检查标签是否符合用户选择的识别类型
  162. # return response.json(0,labels)
  163. if len(labels['label_list']) == 0:
  164. # 需要删除图片
  165. # photo.close()
  166. # self.del_path(os.path.join(BASE_DIR, 'static/ai/' + uid))
  167. logger.info('没有识别到任何标签-----------------')
  168. return response.json(10055)
  169. eventType = labels['eventType']
  170. label_str = ','.join(labels['label_list'])
  171. new_bounding_box_dict = labels['new_bounding_box_dict']
  172. logger.info(eventType)
  173. logger.info(label_str)
  174. # 上传缩略图到s3
  175. for i, val in enumerate(file_path_list):
  176. upload_path = "{uid}/{channel}/{n_time}_{i}.jpeg".format(uid=uid, channel=channel,
  177. n_time=n_time,i=i) # 封面图
  178. thread_task = threading.Thread(target=self.upload_s3, args=(val, upload_path))
  179. thread_task.start()
  180. #存储消息以及推送
  181. is_st = 4 #ai多图
  182. # 查询推送数据
  183. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid). \
  184. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id',
  185. 'userID__NickName',
  186. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval',
  187. 'uid_set__detect_group',
  188. 'uid_set__channel')
  189. if not uid_push_qs.exists():
  190. return response.json(173)
  191. uid_push_list = []
  192. for qs in uid_push_qs:
  193. uid_push_list.append(qs)
  194. nickname = uid_push_list[0]['uid_set__nickname']
  195. if not nickname:
  196. nickname = uid
  197. eq_list = []
  198. userID_ids = []
  199. apns_start_time = 0
  200. apns_end_time = 0
  201. local_date_time = ''
  202. for up in uid_push_list:
  203. push_type = up['push_type']
  204. appBundleId = up['appBundleId']
  205. token_val = up['token_val']
  206. lang = up['lang']
  207. tz = up['tz']
  208. if tz is None or tz == '':
  209. tz = 0
  210. local_date_time = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang='cn')
  211. local_date_time = local_date_time[0:10]
  212. # 以下是存库
  213. userID_id = up["userID_id"]
  214. if userID_id not in userID_ids:
  215. now_time = int(time.time())
  216. eq_list.append(EquipmentInfoService.get_equipment_info_obj(
  217. local_date_time,
  218. device_user_id=userID_id,
  219. event_time=n_time,
  220. event_type=eventType,
  221. device_uid=uid,
  222. device_nick_name=nickname,
  223. channel=channel,
  224. alarm='检查到{labels} \tChannel:{channel}'.format(labels=label_str,channel=channel),
  225. is_st=is_st,
  226. receive_time=receiveTime,
  227. add_time=now_time,
  228. storage_location=2,
  229. border_coords=json.dumps(new_bounding_box_dict)
  230. ))
  231. userID_ids.append(userID_id)
  232. # 推送标题
  233. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  234. # 推送内容
  235. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz, label_list=label_str)
  236. kwargs = {
  237. 'uid': uid,
  238. 'channel': channel,
  239. 'event_type': eventType,
  240. 'n_time': n_time,
  241. 'appBundleId': appBundleId,
  242. 'token_val': token_val,
  243. 'msg_title': msg_title,
  244. 'msg_text': msg_text,
  245. }
  246. try:
  247. # 推送消息
  248. if push_type == 0: # ios apns
  249. res = self.do_apns(**kwargs)
  250. elif push_type == 1: # android gcm
  251. self.do_fcm(**kwargs)
  252. elif push_type == 2: # android jpush
  253. self.do_jpush(**kwargs)
  254. # if push_type == 1: # android gcm
  255. # logger.info('into-------gcm')
  256. # apns_start_time = int(time.time())
  257. # res = self.do_fcm(**kwargs)
  258. # apns_end_time = int(time.time())
  259. except Exception as e:
  260. logger.info("errLine={errLine}, errMsg={errMsg}".format(errLine=e.__traceback__.tb_lineno,errMsg=repr(e)))
  261. continue
  262. # 需要删除图片
  263. photo.close()
  264. self.del_path(dir_path)
  265. self.del_path(dir_path + '.jpg')
  266. # 分表批量存储
  267. if eq_list and len(eq_list) > 0:
  268. week = LocalDateTimeUtil.date_to_week(local_date_time)
  269. EquipmentInfoService.equipment_info_bulk_create(week, eq_list)
  270. return response.json(0)
  271. except Exception as e:
  272. print(e)
  273. data = {
  274. 'errLine':e.__traceback__.tb_lineno,
  275. 'errMsg':repr(e)
  276. }
  277. return response.json(48, data)
  278. def del_path(self, path):
  279. if not os.path.exists(path):
  280. return
  281. if os.path.isfile(path):
  282. os.remove(path)
  283. else:
  284. items = os.listdir(path)
  285. for f in items:
  286. c_path = os.path.join(path, f)
  287. if os.path.isdir(c_path):
  288. self.del_path(c_path)
  289. else:
  290. os.remove(c_path)
  291. os.rmdir(path)
  292. ## 检查是否有符合条件的标签,并且返回标签坐标位置信息
  293. def labelsCoords(self, user_detect_group, rekognition_res, image_size, n_time):
  294. logger = logging.getLogger('info')
  295. labels = rekognition_res['Labels']
  296. label_name = []
  297. logger.info('--------识别到的标签-------')
  298. logger.info(labels)
  299. all_labels_type = {
  300. '1': ['Person', 'Human'], # 人
  301. '2': ['Dog', 'Pet', 'Canine', 'Animal', 'Puppy', 'Cat'], # 动物
  302. '3': ['Car', 'Vehicle', 'Transportation', 'Automobile'] # 车
  303. }
  304. #找出识别的所有标签
  305. for label in labels:
  306. label_name.append(label['Name'])
  307. for Parents in label['Parents']:
  308. label_name.append(Parents['Name'])
  309. logger.info('标签名------')
  310. logger.info(label_name)
  311. #删除用户没有选择的ai识别类型, 并且得出最终识别结果
  312. user_detect_list = user_detect_group.split(',')
  313. user_detect_list = [i.strip() for i in user_detect_list]
  314. conform_label_list = []
  315. conform_user_d_group = set()
  316. for key, label_type_val in all_labels_type.items():
  317. if key in user_detect_list:
  318. for label in label_type_val:
  319. if label in label_name:
  320. conform_user_d_group.add(key)
  321. conform_label_list.append(label)
  322. #找出标签边框线位置信息
  323. boundingBoxList = []
  324. for label in labels:
  325. if label['Name'] in conform_label_list:
  326. for boundingBox in label['Instances']:
  327. boundingBoxList.append(boundingBox['BoundingBox'])
  328. #找出边框位置信息对应的单图位置并重新计算位置比
  329. merge_image_height = image_size['height']
  330. # merge_image_width = image_size['width']
  331. single_height = merge_image_height//image_size['num']
  332. new_bounding_box_dict = {}
  333. new_bounding_box_dict['file_0'] = []
  334. new_bounding_box_dict['file_1'] = []
  335. new_bounding_box_dict['file_2'] = []
  336. new_bounding_box_dict['file_3'] = []
  337. for k, val in enumerate(boundingBoxList):
  338. boundingBoxTop = merge_image_height * val['Top']
  339. #找出当前边框属于哪张图片范围
  340. boxDict = {}
  341. for i in range(image_size['num']):
  342. min = i*single_height #第n张图
  343. max = (i+1)*single_height
  344. if boundingBoxTop >= min and boundingBoxTop <= max:
  345. # print("属于第{i}张图".format(i=i+1))
  346. boxDict['Width'] = val['Width']
  347. boxDict['Height'] = merge_image_height*val['Height']/single_height
  348. boxDict['Top'] = ((merge_image_height*val['Top'])-(i*single_height))/single_height #减去前i张图片的高度
  349. boxDict['Left'] = val['Left']
  350. new_bounding_box_dict["file_{i}".format(i=i)].append(boxDict)
  351. # exit(new_bounding_box_list)
  352. conform_user_d_group = list(conform_user_d_group)
  353. if len(conform_user_d_group) > 1:
  354. eventType = 123 #组合类型
  355. else:
  356. eventType = conform_user_d_group[0]
  357. return {'eventType': eventType, 'label_list': conform_label_list,
  358. 'new_bounding_box_dict':new_bounding_box_dict}
  359. def upload_s3(self, file_path, upload_path):
  360. try:
  361. aws_key = AWS_ACCESS_KEY_ID[0] #【你的 aws_access_key】
  362. aws_secret = AWS_SECRET_ACCESS_KEY[0] # 【你的 aws_secret_key】
  363. session = Session(aws_access_key_id=aws_key,
  364. aws_secret_access_key=aws_secret,
  365. region_name="cn-northwest-1")
  366. s3 = session.resource("s3")
  367. # client = session.client("s3")
  368. bucket = "push" # 【你 bucket 的名字】 # 首先需要保.证 s3 上已经存在该存储桶,否则报错
  369. upload_data = open(file_path, "rb")
  370. # upload_key = "test"
  371. s3.Bucket(bucket).put_object(Key=upload_path, Body=upload_data)
  372. return True
  373. except Exception as e:
  374. print(repr(e))
  375. return False
  376. def get_msg_title(self, appBundleId, nickname):
  377. package_title_config = {
  378. 'com.ansjer.customizedd_a': 'DVS',
  379. 'com.ansjer.zccloud_a': 'ZosiSmart',
  380. 'com.ansjer.zccloud_ab': '周视',
  381. 'com.ansjer.adcloud_a': 'ADCloud',
  382. 'com.ansjer.adcloud_ab': 'ADCloud',
  383. 'com.ansjer.accloud_a': 'ACCloud',
  384. 'com.ansjer.loocamccloud_a': 'Loocam',
  385. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  386. 'com.ansjer.customizedb_a': 'COCOONHD',
  387. 'com.ansjer.customizeda_a': 'Guardian365',
  388. 'com.ansjer.customizedc_a': 'PatrolSecure',
  389. }
  390. if appBundleId in package_title_config.keys():
  391. return package_title_config[appBundleId] + '(' + nickname + ')'
  392. else:
  393. return nickname
  394. def get_msg_text(self, channel, n_time, lang, tz, label_list):
  395. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz,lang=lang)
  396. if lang == 'cn':
  397. msg = '摄像头AI识别到了{}'.format(label_list)
  398. send_text = '{msg} 通道:{channel} 日期:{date}'.format(msg=msg, channel=channel, date=n_date)
  399. else:
  400. msg = 'Camera AI recognizes{}'.format(label_list)
  401. send_text = '{msg} channel:{channel} date:{date}'.format(msg=msg, channel=channel, date=n_date)
  402. return send_text
  403. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  404. app_key = JPUSH_CONFIG[appBundleId]['Key']
  405. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  406. # 此处换成各自的app_key和master_secre
  407. _jpush = jpush.JPush(app_key, master_secret)
  408. push = _jpush.create_push()
  409. push.audience = jpush.registration_id(token_val)
  410. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  411. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  412. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  413. big_text=msg_text, title=msg_title,
  414. extras=push_data)
  415. push.notification = jpush.notification(android=android)
  416. push.platform = jpush.all_
  417. res = push.send()
  418. print(res)
  419. return res.status_code
  420. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  421. try:
  422. serverKey = FCM_CONFIG[appBundleId]
  423. push_service = FCMNotification(api_key=serverKey)
  424. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  425. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  426. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  427. message_body=msg_text, data_message=data,
  428. extra_kwargs={
  429. 'default_vibrate_timings': True,
  430. 'default_sound': True,
  431. 'default_light_settings': True
  432. })
  433. print('fcm push ing')
  434. print(result)
  435. return result
  436. except Exception as e:
  437. return 'serverKey abnormal'
  438. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  439. logger = logging.getLogger('info')
  440. logger.info("进来do_apns函数了")
  441. logger.info(token_val)
  442. logger.info(APNS_MODE)
  443. logger.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  444. try:
  445. cli = apns2.APNSClient(mode=APNS_MODE, client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  446. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  447. "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
  448. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  449. payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
  450. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  451. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  452. if res.status_code == 200:
  453. return res.status_code
  454. else:
  455. logger.info('apns push fail')
  456. logger.info(res.reason)
  457. return res.status_code
  458. except (ValueError, ArithmeticError):
  459. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  460. except Exception as e:
  461. print(repr(e))
  462. logger.info(repr(e))
  463. return repr(e)