AiController.py 26 KB

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