DetectControllerV2.py 43 KB

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