DetectControllerV2.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  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: 2019/1/14 15:57
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: DetectController.py
  12. @Contact: chanjunkai@163.com
  13. """
  14. import logging
  15. import os
  16. import time
  17. import apns2
  18. import jpush as jpush
  19. import oss2
  20. from django.http import JsonResponse
  21. from django.views.generic.base import View
  22. from pyfcm import FCMNotification
  23. from AnsjerPush.config import SERVER_TYPE
  24. from AnsjerPush.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, DETECT_PUSH_DOMAIN, JPUSH_CONFIG, FCM_CONFIG, \
  25. APNS_CONFIG, BASE_DIR, APNS_MODE
  26. from Model.models import Equipment_Info, UidPushModel, SysMsgModel
  27. from Object.ETkObject import ETkObject
  28. from Object.LogUtil import LogUtil
  29. from Object.RedisObject import RedisObject
  30. from Object.UidTokenObject import UidTokenObject
  31. from Service.CommonService import CommonService
  32. import boto3
  33. from AnsjerPush.config import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
  34. import botocore
  35. from botocore import client
  36. '''
  37. http://push.dvema.com/notify/push?etk=Y2lTRXhMTjBWS01sWlpURTVJU0ZWTlJ6RXhNVUU9T3o=&n_time=1526845794&channel=1&event_type=704&is_st=0
  38. http://push.dvema.com/deviceShadow/generateUTK?username=debug_user&password=debug_password&uid=VVDHCVBYDKFMJRWA111A
  39. '''
  40. # 移动侦测接口
  41. class NotificationView(View):
  42. def get(self, request, *args, **kwargs):
  43. request.encoding = 'utf-8'
  44. return self.validation(request.GET)
  45. def post(self, request, *args, **kwargs):
  46. request.encoding = 'utf-8'
  47. return self.validation(request.POST)
  48. def validation(self, request_dict):
  49. logger = logging.getLogger('info')
  50. logger.info("进来推送接口了")
  51. logger.info(request_dict)
  52. logger.info('使用配置: {}'.format(SERVER_TYPE))
  53. uidToken = request_dict.get('uidToken', None)
  54. etk = request_dict.get('etk', None)
  55. channel = request_dict.get('channel', '1')
  56. n_time = request_dict.get('n_time', None)
  57. event_type = request_dict.get('event_type', None)
  58. is_st = request_dict.get('is_st', None)
  59. company_secrete = request_dict.get('company_secrete', None)
  60. region = request_dict.get('region', None)
  61. if not all([channel, n_time]):
  62. return JsonResponse(status=200, data={
  63. 'code': 444,
  64. 'msg': 'param is wrong'})
  65. if not region or not is_st:
  66. return JsonResponse(status=200, data={'code': 404, 'msg': 'no region or is_st'})
  67. try:
  68. is_st = int(is_st)
  69. region = int(region)
  70. # 调试
  71. if etk:
  72. eto = ETkObject(etk)
  73. uid = eto.uid
  74. if len(uid) != 20 and len(uid) != 14:
  75. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong uid'})
  76. else:
  77. utko = UidTokenObject(uidToken)
  78. uid = utko.UID
  79. logger.info('调用推送接口的uid:{}'.format(uid))
  80. pkey = '{uid}_{channel}_{event_type}_ptl'.format(uid=uid, event_type=event_type, channel=channel)
  81. ykey = '{uid}_redis_qs'.format(uid=uid)
  82. is_sys_msg = self.is_sys_msg(int(event_type))
  83. if is_sys_msg:
  84. dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
  85. else:
  86. dkey = '{uid}_{channel}_flag'.format(uid=uid, channel=channel)
  87. redisObj = RedisObject(db=6)
  88. have_ykey = redisObj.get_data(key=ykey) # uid_set 数据库缓存
  89. have_pkey = redisObj.get_data(key=pkey) # 一分钟限制key
  90. have_dkey = redisObj.get_data(key=dkey) # 推送消息时间间隔
  91. logger.info('ykey:{}, pkey: {}, dkey: {},'.format(have_ykey, have_pkey, have_dkey))
  92. # 一分钟内不推送
  93. if have_pkey:
  94. return JsonResponse(status=200, data={'code': 0, 'msg': 'Push again in one minute'})
  95. redisObj.set_data(key=pkey, val=1, expire=60)
  96. # 查询推送数据
  97. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  98. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
  99. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  100. 'uid_set__channel')
  101. if not uid_push_qs.exists():
  102. logger.info('uid_push 数据不存在')
  103. return JsonResponse(status=200, data={'code': 176, 'msg': 'no uid_push data'})
  104. redis_list = []
  105. for qs in uid_push_qs:
  106. redis_list.append(qs)
  107. # 修改redis数据,并设置过期时间为10分钟
  108. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  109. nickname = redis_list[0]['uid_set__nickname']
  110. detect_interval = redis_list[0]['uid_set__detect_interval']
  111. detect_group = redis_list[0]['uid_set__detect_group']
  112. if not nickname:
  113. nickname = uid
  114. if not have_dkey:
  115. # 设置推送消息的时间间隔
  116. if detect_group == '0' or detect_group == '':
  117. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  118. else:
  119. detect_group_list = detect_group.split(',')
  120. if event_type in detect_group_list:
  121. if detect_interval < 60:
  122. detect_interval = 60
  123. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  124. if is_st == 1 or is_st == 3: # 使用aws s3
  125. aws_s3_client = s3_client(region=region)
  126. kwag_args = {
  127. 'uid': uid,
  128. 'channel': channel,
  129. 'event_type': event_type,
  130. 'n_time': n_time,
  131. }
  132. eq_list = []
  133. sys_msg_list = []
  134. userID_ids = []
  135. do_apns_code = ''
  136. do_fcm_code = ''
  137. do_jpush_code = ''
  138. for up in redis_list:
  139. push_type = up['push_type']
  140. appBundleId = up['appBundleId']
  141. token_val = up['token_val']
  142. lang = up['lang']
  143. tz = up['tz']
  144. if tz is None or tz == '':
  145. tz = 0
  146. # 发送标题
  147. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  148. # 发送内容
  149. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  150. event_type=event_type)
  151. kwag_args['appBundleId'] = appBundleId
  152. kwag_args['token_val'] = token_val
  153. kwag_args['msg_title'] = msg_title
  154. kwag_args['msg_text'] = msg_text
  155. logger.info('推送要的数据: {}'.format(kwag_args))
  156. # 推送消息
  157. if not have_dkey:
  158. if push_type == 0: # ios apns
  159. do_apns_code = self.do_apns(**kwag_args)
  160. elif push_type == 1: # android gcm
  161. do_fcm_code = self.do_fcm(**kwag_args)
  162. elif push_type == 2: # android jpush
  163. do_jpush_code = self.do_jpush(**kwag_args)
  164. # 以下是存库
  165. userID_id = up["userID_id"]
  166. if userID_id not in userID_ids:
  167. now_time = int(time.time())
  168. if is_sys_msg:
  169. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  170. event_type=event_type, is_sys=1)
  171. sys_msg_list.append(SysMsgModel(
  172. userID_id=userID_id,
  173. msg=sys_msg_text,
  174. addTime=now_time,
  175. updTime=now_time,
  176. uid=uid,
  177. eventType=event_type))
  178. else:
  179. eq_list.append(Equipment_Info(
  180. userID_id=userID_id,
  181. eventTime=n_time,
  182. eventType=event_type,
  183. devUid=uid,
  184. devNickName=nickname,
  185. Channel=channel,
  186. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  187. is_st=is_st,
  188. receiveTime=n_time,
  189. addTime=now_time,
  190. storage_location=2
  191. ))
  192. userID_ids.append(userID_id)
  193. if is_sys_msg:
  194. SysMsgModel.objects.bulk_create(sys_msg_list)
  195. else:
  196. Equipment_Info.objects.bulk_create(eq_list)
  197. if is_st == 0 or is_st == 2:
  198. for up in redis_list:
  199. if up['push_type'] == 0: # ios apns
  200. up['do_apns_code'] = do_apns_code
  201. elif up['push_type'] == 1: # android gcm
  202. up['do_fcm_code'] = do_fcm_code
  203. elif up['push_type'] == 2: # android jpush
  204. up['do_jpush_code'] = do_jpush_code
  205. up['test_or_www'] = SERVER_TYPE
  206. del up['push_type']
  207. del up['userID_id']
  208. del up['userID__NickName']
  209. del up['lang']
  210. del up['tz']
  211. del up['uid_set__nickname']
  212. del up['uid_set__detect_interval']
  213. del up['uid_set__detect_group']
  214. return JsonResponse(status=200, data={'code': 0, 'msg': 'success 0 or 2', 're_list': redis_list})
  215. elif is_st == 1:
  216. thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  217. Params = {'Key': thumbspng}
  218. if region == 2: # 2:国内
  219. Params['Bucket'] = 'push'
  220. else: # 1:国外
  221. Params['Bucket'] = 'foreignpush'
  222. response_url = generate_s3_url(aws_s3_client, Params)
  223. for up in redis_list:
  224. up['do_apns_code'] = do_apns_code
  225. up['do_fcm_code'] = do_fcm_code
  226. up['do_jpush_code'] = do_jpush_code
  227. up['test_or_www'] = SERVER_TYPE
  228. del up['push_type']
  229. del up['userID_id']
  230. del up['userID__NickName']
  231. del up['lang']
  232. del up['tz']
  233. del up['uid_set__nickname']
  234. del up['uid_set__detect_interval']
  235. del up['uid_set__detect_group']
  236. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
  237. return JsonResponse(status=200, data=res_data)
  238. elif is_st == 3:
  239. img_url_list = []
  240. if region == 2: # 2:国内
  241. Params = {'Bucket': 'push'}
  242. else: # 1:国外
  243. Params = {'Bucket': 'foreignpush'}
  244. for i in range(is_st):
  245. thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  246. format(uid=uid, channel=channel, filename=n_time, st=i)
  247. Params['key'] = thumbspng
  248. response_url = generate_s3_url(aws_s3_client, Params)
  249. img_url_list.append(response_url)
  250. for up in redis_list:
  251. up['do_apns_code'] = do_apns_code
  252. up['do_fcm_code'] = do_fcm_code
  253. up['do_jpush_code'] = do_jpush_code
  254. up['test_or_www'] = SERVER_TYPE
  255. del up['push_type']
  256. del up['userID_id']
  257. del up['userID__NickName']
  258. del up['lang']
  259. del up['tz']
  260. del up['uid_set__nickname']
  261. del up['uid_set__detect_interval']
  262. del up['uid_set__detect_group']
  263. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
  264. return JsonResponse(status=200, data=res_data)
  265. except Exception as e:
  266. logger.info('移动侦测接口异常: {}'.format(e))
  267. return JsonResponse(status=500)
  268. def get_msg_title(self, appBundleId, nickname):
  269. package_title_config = {
  270. 'com.ansjer.customizedd_a': 'DVS',
  271. 'com.ansjer.zccloud_a': 'ZosiSmart',
  272. 'com.ansjer.zccloud_ab': '周视',
  273. 'com.ansjer.adcloud_a': 'ADCloud',
  274. 'com.ansjer.adcloud_ab': 'ADCloud',
  275. 'com.ansjer.accloud_a': 'ACCloud',
  276. 'com.ansjer.loocamccloud_a': 'Loocam',
  277. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  278. 'com.ansjer.customizedb_a': 'COCOONHD',
  279. 'com.ansjer.customizeda_a': 'Guardian365',
  280. 'com.ansjer.customizedc_a': 'PatrolSecure',
  281. }
  282. if appBundleId in package_title_config.keys():
  283. return package_title_config[appBundleId] + '(' + nickname + ')'
  284. else:
  285. return nickname
  286. def is_sys_msg(self, event_type):
  287. event_type_list = [702, 703, 704]
  288. if event_type in event_type_list:
  289. return True
  290. return False
  291. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  292. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz,lang=lang)
  293. etype = int(event_type)
  294. if lang == 'cn':
  295. if etype == 704:
  296. msg_type = '电量过低'
  297. elif etype == 702:
  298. msg_type = '摄像头休眠'
  299. elif etype == 703:
  300. msg_type = '摄像头唤醒'
  301. else:
  302. msg_type = ''
  303. if is_sys:
  304. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  305. else:
  306. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  307. # send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  308. else:
  309. if etype == 704:
  310. msg_type = 'Low battery'
  311. elif etype == 702:
  312. msg_type = 'Camera sleep'
  313. elif etype == 703:
  314. msg_type = 'Camera wake'
  315. else:
  316. msg_type = ''
  317. if is_sys:
  318. send_text = '{msg_type} channel:{channel}'. \
  319. format(msg_type=msg_type, channel=channel)
  320. else:
  321. send_text = '{msg_type} channel:{channel} date:{date}'. \
  322. format(msg_type=msg_type, channel=channel, date=n_date)
  323. return send_text
  324. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
  325. msg_title, msg_text):
  326. app_key = JPUSH_CONFIG[appBundleId]['Key']
  327. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  328. # 此处换成各自的app_key和master_secre
  329. _jpush = jpush.JPush(app_key, master_secret)
  330. push = _jpush.create_push()
  331. # if you set the logging level to "DEBUG",it will show the debug logging.
  332. # _jpush.set_logging("DEBUG")
  333. # push.audience = jpush.all_
  334. push.audience = jpush.registration_id(token_val)
  335. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  336. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  337. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  338. big_text=msg_text, title=msg_title,
  339. extras=push_data)
  340. push.notification = jpush.notification(android=android)
  341. push.platform = jpush.all_
  342. res = push.send()
  343. print(res)
  344. return res.status_code
  345. # try:
  346. # res = push.send()
  347. # print(res)
  348. # except Exception as e:
  349. # print("jpush fail")
  350. # print("Exception")
  351. # print(repr(e))
  352. # return
  353. # else:
  354. # print("jpush success")
  355. # return
  356. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  357. try:
  358. serverKey = FCM_CONFIG[appBundleId]
  359. except Exception as e:
  360. return 'serverKey abnormal'
  361. push_service = FCMNotification(api_key=serverKey)
  362. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  363. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  364. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  365. message_body=msg_text, data_message=data,
  366. extra_kwargs={
  367. 'default_vibrate_timings': True,
  368. 'default_sound': True,
  369. 'default_light_settings': True
  370. })
  371. print('fcm push ing')
  372. print(result)
  373. return result
  374. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  375. msg_text):
  376. logger = logging.getLogger('info')
  377. logger.info("进来do_apns函数了")
  378. logger.info(token_val)
  379. logger.info(APNS_MODE)
  380. logger.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  381. try:
  382. cli = apns2.APNSClient(mode=APNS_MODE,
  383. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  384. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  385. "received_at": n_time, "sound": "default", "uid": uid, "zpush": "1", "channel": channel}
  386. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  387. payload = apns2.Payload(alert=alert, custom=push_data)
  388. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  389. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  390. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  391. print(res.status_code)
  392. logger.info("推送状态:")
  393. logger.info(res.status_code)
  394. # 200, 推送成功。
  395. #   400, 请求有问题。
  396. #   403, 证书或Token有问题。
  397. #   405, 请求方式不正确, 只支持POST请求
  398. #   410, 设备的Token与证书不一致
  399. if res.status_code == 200:
  400. return res.status_code
  401. else:
  402. print('apns push fail')
  403. print(res.reason)
  404. logger.info('apns push fail')
  405. logger.info(res.reason)
  406. return res.status_code
  407. except (ValueError, ArithmeticError):
  408. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  409. except Exception as e:
  410. print(repr(e))
  411. logger.info(repr(e))
  412. return repr(e)
  413. def do_update_detect_interval(self, uid, channel, redisObject, detect_interval):
  414. if channel == 0:
  415. channel = 17
  416. else:
  417. channel += 1
  418. for i in range(1, channel):
  419. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=51, channel=i)
  420. if tmpDKey is not False:
  421. llt = redisObject.get_ttl(tmpDKey)
  422. if llt > detect_interval:
  423. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  424. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=54, channel=i)
  425. if tmpDKey is not False:
  426. llt = redisObject.get_ttl(tmpDKey)
  427. if llt > detect_interval:
  428. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  429. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  430. # 移动侦测接口
  431. class PushNotificationView(View):
  432. def get(self, request, *args, **kwargs):
  433. request.encoding = 'utf-8'
  434. # operation = kwargs.get('operation')
  435. return self.validation(request.GET)
  436. def post(self, request, *args, **kwargs):
  437. request.encoding = 'utf-8'
  438. # operation = kwargs.get('operation')
  439. return self.validation(request.POST)
  440. def validation(self, request_dict):
  441. etk = request_dict.get('etk', None)
  442. channel = request_dict.get('channel', '1')
  443. n_time = request_dict.get('n_time', None)
  444. event_type = request_dict.get('event_type', None)
  445. is_st = request_dict.get('is_st', None)
  446. region = request_dict.get('region', '2')
  447. region = int(region)
  448. eto = ETkObject(etk)
  449. uid = eto.uid
  450. if len(uid) == 20:
  451. redisObj = RedisObject(db=6)
  452. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  453. pkey = '{uid}_ptl'.format(uid=uid)
  454. ykey = '{uid}_redis_qs'.format(uid=uid)
  455. if redisObj.get_data(key=pkey):
  456. res_data = {'code': 0, 'msg': 'success,!33333333333'}
  457. return JsonResponse(status=200, data=res_data)
  458. else:
  459. redisObj.set_data(key=pkey, val=1, expire=60)
  460. ##############
  461. redis_data = redisObj.get_data(key=ykey)
  462. if redis_data:
  463. redis_list = eval(redis_data)
  464. else:
  465. # 设置推送时间为60秒一次
  466. redisObj.set_data(key=pkey, val=1, expire=60)
  467. print("从数据库查到数据")
  468. # 从数据库查询出来
  469. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  470. values('token_val', 'app_type', 'appBundleId',
  471. 'push_type', 'userID_id', 'lang','m_code',
  472. 'tz', 'uid_set__nickname')
  473. # 新建一个list接收数据
  474. redis_list = []
  475. # 把数据库数据追加进redis_list
  476. for qs in uid_push_qs:
  477. redis_list.append(qs)
  478. # 修改redis数据,并设置过期时间为10分钟
  479. if redis_list:
  480. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  481. # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  482. # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  483. aws_s3_guonei = boto3.client(
  484. 's3',
  485. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  486. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  487. config=botocore.client.Config(signature_version='s3v4'),
  488. region_name='cn-northwest-1'
  489. )
  490. aws_s3_guowai = boto3.client(
  491. 's3',
  492. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  493. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  494. config=botocore.client.Config(signature_version='s3v4'),
  495. region_name='us-east-1'
  496. )
  497. self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
  498. if is_st == '0' or is_st == '2':
  499. return JsonResponse(status=200, data={'code': 0, 'msg': 'success44444444444444444'})
  500. elif is_st == '1':
  501. # Endpoint以杭州为例,其它Region请按实际情况填写。
  502. # obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  503. # 设置此签名URL在60秒内有效。
  504. # url = bucket.sign_url('PUT', obj, 7200)
  505. thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  506. if region == 2: # 2:国内
  507. response_url = aws_s3_guonei.generate_presigned_url(
  508. ClientMethod='put_object',
  509. Params={
  510. 'Bucket': 'push',
  511. 'Key': thumbspng
  512. },
  513. ExpiresIn=3600
  514. )
  515. else: # 1:国外
  516. response_url = aws_s3_guowai.generate_presigned_url(
  517. ClientMethod='put_object',
  518. Params={
  519. 'Bucket': 'foreignpush',
  520. 'Key': thumbspng
  521. },
  522. ExpiresIn=3600
  523. )
  524. # res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  525. # response_url = response_url[:4] + response_url[5:]
  526. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
  527. return JsonResponse(status=200, data=res_data)
  528. elif is_st == '3':
  529. # 人形检测带动图
  530. img_url_list = []
  531. for i in range(int(is_st)):
  532. # obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  533. # format(uid=uid, channel=channel, filename=n_time, st=i)
  534. # 设置此签名URL在60秒内有效。
  535. # url = bucket.sign_url('PUT', obj, 7200)
  536. thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  537. format(uid=uid, channel=channel, filename=n_time, st=i)
  538. if region == 2: # 2:国内
  539. response_url = aws_s3_guonei.generate_presigned_url(
  540. ClientMethod='put_object',
  541. Params={
  542. 'Bucket': 'push',
  543. 'Key': thumbspng
  544. },
  545. ExpiresIn=3600
  546. )
  547. else: # 1:国外
  548. response_url = aws_s3_guowai.generate_presigned_url(
  549. ClientMethod='put_object',
  550. Params={
  551. 'Bucket': 'foreignpush',
  552. 'Key': thumbspng
  553. },
  554. ExpiresIn=3600
  555. )
  556. # response_url = response_url[:4] + response_url[5:]
  557. img_url_list.append(response_url)
  558. # img_url_list.append(url)
  559. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  560. return JsonResponse(status=200, data=res_data)
  561. else:
  562. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  563. else:
  564. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  565. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  566. now_time = int(time.time())
  567. # 设备昵称
  568. userID_ids = []
  569. sys_msg_list = []
  570. is_sys_msg = self.is_sys_msg(int(event_type))
  571. is_st = int(is_st)
  572. eq_list = []
  573. nickname = uaqs[0]['uid_set__nickname']
  574. if not nickname:
  575. nickname = uid
  576. for ua in uaqs:
  577. lang = ua['lang']
  578. tz = ua['tz']
  579. userID_id = ua["userID_id"]
  580. if userID_id not in userID_ids:
  581. if is_sys_msg:
  582. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  583. event_type=event_type, is_sys=1)
  584. sys_msg_list.append(SysMsgModel(
  585. userID_id=userID_id,
  586. msg=sys_msg_text,
  587. addTime=now_time,
  588. updTime=now_time,
  589. uid=uid,
  590. eventType=event_type))
  591. else:
  592. eq_list.append(Equipment_Info(
  593. userID_id=userID_id,
  594. eventTime=n_time,
  595. eventType=event_type,
  596. devUid=uid,
  597. devNickName=nickname,
  598. Channel=channel,
  599. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  600. is_st=is_st,
  601. receiveTime=n_time,
  602. addTime=now_time,
  603. storage_location=2
  604. ))
  605. if eq_list:
  606. print('eq_list')
  607. Equipment_Info.objects.bulk_create(eq_list)
  608. if is_sys_msg:
  609. print('sys_msg')
  610. SysMsgModel.objects.bulk_create(sys_msg_list)
  611. return True
  612. def is_sys_msg(self, event_type):
  613. event_type_list = [702, 703, 704]
  614. if event_type in event_type_list:
  615. return True
  616. return False
  617. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  618. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  619. etype = int(event_type)
  620. if lang == 'cn':
  621. if etype == 704:
  622. msg_type = '电量过低'
  623. elif etype == 702:
  624. msg_type = '摄像头休眠'
  625. elif etype == 703:
  626. msg_type = '摄像头唤醒'
  627. else:
  628. msg_type = ''
  629. if is_sys:
  630. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  631. else:
  632. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  633. else:
  634. if etype == 704:
  635. msg_type = 'Low battery'
  636. elif etype == 702:
  637. msg_type = 'Camera sleep'
  638. elif etype == 703:
  639. msg_type = 'Camera wake'
  640. else:
  641. msg_type = ''
  642. if is_sys:
  643. send_text = '{msg_type} channel:{channel}'. \
  644. format(msg_type=msg_type, channel=channel)
  645. else:
  646. send_text = '{msg_type} channel:{channel} date:{date}'. \
  647. format(msg_type=msg_type, channel=channel, date=n_date)
  648. return send_text
  649. # 移动侦测接口
  650. class PWnotificationView(View):
  651. def get(self, request, *args, **kwargs):
  652. request.encoding = 'utf-8'
  653. return self.validation(request.GET)
  654. def post(self, request, *args, **kwargs):
  655. request.encoding = 'utf-8'
  656. return self.validation(request.POST)
  657. def validation(self, request_dict):
  658. uid = request_dict.get('uid', None)
  659. channel = request_dict.get('channel', None)
  660. electricity = request_dict.get('electricity', None)
  661. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  662. values('token_val', 'app_type', 'appBundleId', 'm_code',
  663. 'push_type', 'userID_id', 'userID__NickName',
  664. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  665. 'uid_set__channel')
  666. print(uid_push_qs)
  667. # 新建一个list接收数据
  668. redis_list = []
  669. # 把数据库数据追加进redis_list
  670. for qs in uid_push_qs:
  671. redis_list.append(qs)
  672. if not redis_list:
  673. print("没有redi_list")
  674. res_data = {'code': 0, 'msg': 'no redi_list success!'}
  675. return JsonResponse(status=200, data=res_data)
  676. nickname = redis_list[0]['uid_set__nickname']
  677. if not nickname:
  678. nickname = uid
  679. now_time = int(time.time())
  680. channel = channel
  681. event_type = 704
  682. sys_msg_list = []
  683. userID_ids = []
  684. kwag_args = {
  685. 'uid': uid,
  686. 'channel': channel,
  687. 'event_type': event_type,
  688. 'n_time': now_time,
  689. # 'appBundleId': appBundleId,
  690. # 'token_val': token_val,
  691. # 'msg_title': msg_title,
  692. # 'msg_text': msg_text
  693. }
  694. for up in redis_list:
  695. push_type = up['push_type']
  696. appBundleId = up['appBundleId']
  697. token_val = up['token_val']
  698. lang = up['lang']
  699. tz = up['tz']
  700. if tz is None or tz == '':
  701. tz = 0
  702. # 发送标题
  703. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  704. # 发送内容
  705. msg_text = self.get_msg_text(channel=channel, n_time=now_time, lang=lang, tz=tz,
  706. event_type=event_type, electricity= electricity)
  707. kwag_args['appBundleId'] = appBundleId
  708. kwag_args['token_val'] = token_val
  709. kwag_args['msg_title'] = msg_title
  710. kwag_args['msg_text'] = msg_text
  711. if push_type == 0: # ios apns
  712. do_apns_code = self.do_apns(**kwag_args)
  713. elif push_type == 1: # android gcm
  714. print('do_fcm')
  715. do_fcm_code = self.do_fcm(**kwag_args)
  716. elif push_type == 2: # android jpush
  717. print('do_jpush')
  718. do_jpush_code = self.do_jpush(**kwag_args)
  719. # 以下是存库
  720. userID_id = up["userID_id"]
  721. if userID_id not in userID_ids:
  722. sys_msg_text = self.get_msg_text(channel=channel, n_time=now_time, lang=lang, tz=tz,
  723. event_type=event_type, is_sys=1, electricity= electricity)
  724. sys_msg_list.append(SysMsgModel(
  725. userID_id=userID_id,
  726. msg=sys_msg_text,
  727. addTime=now_time,
  728. updTime=now_time,
  729. uid=uid,
  730. eventType=event_type))
  731. userID_ids.append(userID_id)
  732. SysMsgModel.objects.bulk_create(sys_msg_list)
  733. return JsonResponse(status=200, data={'code': 0})
  734. def get_msg_title(self, appBundleId, nickname):
  735. package_title_config = {
  736. 'com.ansjer.customizedd_a': 'DVS',
  737. 'com.ansjer.zccloud_a': 'ZosiSmart',
  738. 'com.ansjer.zccloud_ab': '周视',
  739. 'com.ansjer.adcloud_a': 'ADCloud',
  740. 'com.ansjer.adcloud_ab': 'ADCloud',
  741. 'com.ansjer.accloud_a': 'ACCloud',
  742. 'com.ansjer.loocamccloud_a': 'Loocam',
  743. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  744. 'com.ansjer.customizedb_a': 'COCOONHD',
  745. 'com.ansjer.customizeda_a': 'Guardian365',
  746. 'com.ansjer.customizedc_a': 'PatrolSecure',
  747. }
  748. if appBundleId in package_title_config.keys():
  749. return package_title_config[appBundleId] + '(' + nickname + ')'
  750. else:
  751. return nickname
  752. def is_sys_msg(self, event_type):
  753. event_type_list = [702, 703, 704]
  754. if event_type in event_type_list:
  755. return True
  756. return False
  757. def get_msg_text(self, channel, n_time, lang, tz, event_type, electricity, is_sys=0):
  758. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz,lang=lang)
  759. etype = int(event_type)
  760. if lang == 'cn':
  761. if etype == 704:
  762. msg_type = '电量已剩:'+electricity+'%'
  763. elif etype == 702:
  764. msg_type = '摄像头休眠'
  765. elif etype == 703:
  766. msg_type = '摄像头唤醒'
  767. else:
  768. msg_type = ''
  769. if is_sys:
  770. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  771. else:
  772. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  773. # send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  774. else:
  775. if etype == 704:
  776. msg_type = 'Battery is left: '+electricity+'%'
  777. elif etype == 702:
  778. msg_type = 'Camera sleep'
  779. elif etype == 703:
  780. msg_type = 'Camera wake'
  781. else:
  782. msg_type = ''
  783. if is_sys:
  784. send_text = '{msg_type} channel:{channel}'. \
  785. format(msg_type=msg_type, channel=channel)
  786. else:
  787. send_text = '{msg_type} channel:{channel} date:{date}'. \
  788. format(msg_type=msg_type, channel=channel, date=n_date)
  789. return send_text
  790. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
  791. msg_title, msg_text):
  792. app_key = JPUSH_CONFIG[appBundleId]['Key']
  793. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  794. # 此处换成各自的app_key和master_secre
  795. _jpush = jpush.JPush(app_key, master_secret)
  796. push = _jpush.create_push()
  797. # if you set the logging level to "DEBUG",it will show the debug logging.
  798. # _jpush.set_logging("DEBUG")
  799. # push.audience = jpush.all_
  800. push.audience = jpush.registration_id(token_val)
  801. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  802. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  803. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  804. big_text=msg_text, title=msg_title,
  805. extras=push_data)
  806. push.notification = jpush.notification(android=android)
  807. push.platform = jpush.all_
  808. res = push.send()
  809. print(res)
  810. return res.status_code
  811. # try:
  812. # res = push.send()
  813. # print(res)
  814. # except Exception as e:
  815. # print("jpush fail")
  816. # print("Exception")
  817. # print(repr(e))
  818. # return
  819. # else:
  820. # print("jpush success")
  821. # return
  822. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  823. try:
  824. serverKey = FCM_CONFIG[appBundleId]
  825. except Exception as e:
  826. return 'serverKey abnormal'
  827. push_service = FCMNotification(api_key=serverKey)
  828. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  829. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  830. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  831. message_body=msg_text, data_message=data,
  832. extra_kwargs={
  833. 'default_vibrate_timings': True,
  834. 'default_sound': True,
  835. 'default_light_settings': True
  836. })
  837. print('fcm push ing')
  838. print(result)
  839. return result
  840. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  841. msg_text):
  842. logger = logging.getLogger('info')
  843. logger.info("进来do_apns函数了")
  844. logger.info(token_val)
  845. logger.info(APNS_MODE)
  846. logger.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  847. try:
  848. cli = apns2.APNSClient(mode=APNS_MODE,
  849. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  850. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  851. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  852. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  853. payload = apns2.Payload(alert=alert, custom=push_data)
  854. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  855. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  856. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  857. print(res.status_code)
  858. logger.info("推送状态:")
  859. logger.info(res.status_code)
  860. # 200, 推送成功。
  861. #   400, 请求有问题。
  862. #   403, 证书或Token有问题。
  863. #   405, 请求方式不正确, 只支持POST请求
  864. #   410, 设备的Token与证书不一致
  865. if res.status_code == 200:
  866. return res.status_code
  867. else:
  868. print('apns push fail')
  869. print(res.reason)
  870. logger.info('apns push fail')
  871. logger.info(res.reason)
  872. return res.status_code
  873. except (ValueError, ArithmeticError):
  874. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  875. except Exception as e:
  876. print(repr(e))
  877. logger.info(repr(e))
  878. return repr(e)
  879. def do_update_detect_interval(self, uid, channel, redisObject, detect_interval):
  880. if channel == 0:
  881. channel = 17
  882. else:
  883. channel += 1
  884. for i in range(1, channel):
  885. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=51, channel=i)
  886. if tmpDKey is not False:
  887. llt = redisObject.get_ttl(tmpDKey)
  888. if llt > detect_interval:
  889. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  890. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=54, channel=i)
  891. if tmpDKey is not False:
  892. llt = redisObject.get_ttl(tmpDKey)
  893. if llt > detect_interval:
  894. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  895. def s3_client(region):
  896. if region == 2: # 国内
  897. aws_s3_client = boto3.client(
  898. 's3',
  899. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  900. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  901. config=botocore.client.Config(signature_version='s3v4'),
  902. region_name='cn-northwest-1'
  903. )
  904. else: # 国外
  905. aws_s3_client = boto3.client(
  906. 's3',
  907. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  908. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  909. config=botocore.client.Config(signature_version='s3v4'),
  910. region_name='us-east-1'
  911. )
  912. return aws_s3_client
  913. def generate_s3_url(aws_s3_client, Params):
  914. response_url = aws_s3_client.generate_presigned_url(
  915. ClientMethod='put_object',
  916. Params=Params,
  917. ExpiresIn=3600
  918. )
  919. return response_url