DetectController.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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 os
  15. import time
  16. import apns2
  17. import jpush as jpush
  18. import oss2
  19. from django.http import JsonResponse
  20. from django.views.generic.base import View
  21. from pyfcm import FCMNotification
  22. from AnsjerPush.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, DETECT_PUSH_DOMAIN, JPUSH_CONFIG, \
  23. FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE
  24. from Model.models import Equipment_Info, UidPushModel, SysMsgModel
  25. from Object.ETkObject import ETkObject
  26. from Object.RedisObject import RedisObject
  27. from Object.UidTokenObject import UidTokenObject
  28. from Service.CommonService import CommonService
  29. '''
  30. http://push.dvema.com/notify/push?etk=Y2lTRXhMTjBWS01sWlpURTVJU0ZWTlJ6RXhNVUU9T3o=&n_time=1526845794&channel=1&event_type=704&is_st=0
  31. http://push.dvema.com/deviceShadow/generateUTK?username=debug_user&password=debug_password&uid=VVDHCVBYDKFMJRWA111A
  32. '''
  33. # 移动侦测接口
  34. class NotificationView(View):
  35. def get(self, request, *args, **kwargs):
  36. request.encoding = 'utf-8'
  37. return self.validation(request.GET)
  38. def post(self, request, *args, **kwargs):
  39. request.encoding = 'utf-8'
  40. return self.validation(request.POST)
  41. def validation(self, request_dict):
  42. uidToken = request_dict.get('uidToken', None)
  43. etk = request_dict.get('etk', None)
  44. channel = request_dict.get('channel', '1')
  45. n_time = request_dict.get('n_time', None)
  46. event_type = request_dict.get('event_type', None)
  47. is_st = request_dict.get('is_st', None)
  48. # print("aaa")
  49. # return JsonResponse(0,safe=False)
  50. if not all([channel, n_time]):
  51. return JsonResponse(status=200, data={
  52. 'code': 444,
  53. 'msg': 'param is wrong'})
  54. if etk:
  55. eto = ETkObject(etk)
  56. uid = eto.uid
  57. # uid += channel
  58. if len(uid) != 20:
  59. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  60. else:
  61. utko = UidTokenObject(uidToken)
  62. uid = utko.UID
  63. # uid += channel
  64. redisObj = RedisObject(db=6)
  65. pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  66. ykey = '{uid}_redis_qs'.format(uid=uid)
  67. dkey = '{uid}_{event_type}_redis_qs'.format(uid=uid, event_type=event_type)
  68. if redisObj.get_data(key=pkey):
  69. res_data = {'code': 0, 'msg': 'success!'}
  70. # 1分钟之内不再推送,不存数据库了
  71. return JsonResponse(status=200, data=res_data)
  72. # 第一次进来推送,存库
  73. # 修改redis数据,并设置过期时间为10分钟
  74. # 查数据库,存入redis得到redis_list
  75. # 创建dkey,有效期为detect_interval
  76. # 创建ykey600秒
  77. # 推送,存数据库代码
  78. if not redisObj.get_data(key=dkey):
  79. redis_data = redisObj.get_data(key=ykey)
  80. if redis_data:
  81. print("从缓存查到数据")
  82. redis_list = eval(redis_data)
  83. else:
  84. # 设置推送时间为60秒一次
  85. redisObj.set_data(key=pkey, val=1, expire=60)
  86. print("从数据库查到数据")
  87. # 从数据库查询出来
  88. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  89. values('token_val', 'app_type', 'appBundleId',
  90. 'push_type', 'userID_id', 'lang',
  91. 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group')
  92. # 新建一个list接收数据
  93. redis_list = []
  94. # 把数据库数据追加进redis_list
  95. for qs in uid_push_qs:
  96. redis_list.append(qs)
  97. if redis_list:
  98. detect_interval = redis_list[0]['uid_set__detect_interval']
  99. detect_group = redis_list[0]['uid_set__detect_group']
  100. if detect_group:
  101. detect_group_list = detect_group.split(',')
  102. if event_type in detect_group_list:
  103. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  104. # if redisObj.get_data(key=dkey):
  105. # res_data = {'code': 0, 'msg': 'success!'}
  106. # 把ykey的时间也设置成跟dkey一样
  107. redisObj.set_data(key=ykey, val=str(redis_list), expire=detect_interval)
  108. nickname = redis_list[0]['uid_set__nickname']
  109. now_time = int(time.time())
  110. if not nickname:
  111. nickname = uid
  112. # 判断是否为系统类通知
  113. is_sys_msg = self.is_sys_msg(int(event_type))
  114. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  115. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  116. kwag_args = {
  117. 'uid': uid,
  118. 'channel': channel,
  119. 'event_type': event_type,
  120. 'n_time': n_time,
  121. # 'appBundleId': appBundleId,
  122. # 'token_val': token_val,
  123. # 'msg_title': msg_title,
  124. # 'msg_text': msg_text
  125. }
  126. eq_list = []
  127. sys_msg_list = []
  128. userID_ids = []
  129. for up in redis_list:
  130. push_type = up['push_type']
  131. appBundleId = up['appBundleId']
  132. token_val = up['token_val']
  133. lang = up['lang']
  134. tz = up['tz']
  135. # 发送标题
  136. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  137. # 发送内容
  138. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  139. event_type=event_type)
  140. kwag_args['appBundleId'] = appBundleId
  141. kwag_args['token_val'] = token_val
  142. kwag_args['msg_title'] = msg_title
  143. kwag_args['msg_text'] = msg_text
  144. if push_type == 0: # ios apns
  145. self.do_apns(**kwag_args)
  146. elif push_type == 1: # android gcm
  147. self.do_fcm(**kwag_args)
  148. elif push_type == 2: # android jpush
  149. self.do_jpush(**kwag_args)
  150. userID_id = up["userID_id"]
  151. int_is_st = int(is_st)
  152. if userID_id not in userID_ids:
  153. eq_list.append(Equipment_Info(
  154. userID_id=userID_id,
  155. eventTime=n_time,
  156. eventType=event_type,
  157. devUid=uid,
  158. devNickName=nickname,
  159. Channel=channel,
  160. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  161. is_st=int_is_st,
  162. receiveTime=n_time,
  163. addTime=now_time
  164. ))
  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. userID_ids.append(userID_id)
  176. if is_sys_msg:
  177. SysMsgModel.objects.bulk_create(sys_msg_list)
  178. Equipment_Info.objects.bulk_create(eq_list)
  179. if is_st == '0' or is_st == '2':
  180. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  181. elif is_st == '1':
  182. # Endpoint以杭州为例,其它Region请按实际情况填写。
  183. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  184. # 设置此签名URL在60秒内有效。
  185. url = bucket.sign_url('PUT', obj, 7200)
  186. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  187. return JsonResponse(status=200, data=res_data)
  188. elif is_st == '3':
  189. # 人形检测带动图
  190. # Endpoint以杭州为例,其它Region请按实际情况填写。
  191. img_url_list = []
  192. for i in range(int(is_st)):
  193. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  194. format(uid=uid, channel=channel, filename=n_time, st=i)
  195. # 设置此签名URL在60秒内有效。
  196. url = bucket.sign_url('PUT', obj, 7200)
  197. img_url_list.append(url)
  198. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  199. return JsonResponse(status=200, data=res_data)
  200. # 1分钟之外,dkey 分钟之内,存数据库,不推送
  201. if not redisObj.get_data(key=pkey) and redisObj.get_data(key=dkey):
  202. redis_data = redisObj.get_data(key=ykey)
  203. if redis_data:
  204. print("从缓存查到数据")
  205. redis_list = eval(redis_data)
  206. if redis_list:
  207. nickname = redis_list[0]['uid_set__nickname']
  208. now_time = int(time.time())
  209. if not nickname:
  210. nickname = uid
  211. # 判断是否为系统类通知
  212. is_sys_msg = self.is_sys_msg(int(event_type))
  213. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  214. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  215. kwag_args = {
  216. 'uid': uid,
  217. 'channel': channel,
  218. 'event_type': event_type,
  219. 'n_time': n_time,
  220. # 'appBundleId': appBundleId,
  221. # 'token_val': token_val,
  222. # 'msg_title': msg_title,
  223. # 'msg_text': msg_text
  224. }
  225. eq_list = []
  226. sys_msg_list = []
  227. userID_ids = []
  228. for up in redis_list:
  229. push_type = up['push_type']
  230. appBundleId = up['appBundleId']
  231. token_val = up['token_val']
  232. lang = up['lang']
  233. tz = up['tz']
  234. # 发送标题
  235. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  236. # 发送内容
  237. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)
  238. kwag_args['appBundleId'] = appBundleId
  239. kwag_args['token_val'] = token_val
  240. kwag_args['msg_title'] = msg_title
  241. kwag_args['msg_text'] = msg_text
  242. # if push_type == 0: # ios apns
  243. # self.do_apns(**kwag_args)
  244. # elif push_type == 1: # android gcm
  245. # self.do_fcm(**kwag_args)
  246. # elif push_type == 2: # android jpush
  247. # self.do_jpush(**kwag_args)
  248. userID_id = up["userID_id"]
  249. int_is_st = int(is_st)
  250. if userID_id not in userID_ids:
  251. eq_list.append(Equipment_Info(
  252. userID_id=userID_id,
  253. eventTime=n_time,
  254. eventType=event_type,
  255. devUid=uid,
  256. devNickName=nickname,
  257. Channel=channel,
  258. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  259. is_st=int_is_st,
  260. receiveTime=n_time,
  261. addTime=now_time
  262. ))
  263. if is_sys_msg:
  264. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  265. event_type=event_type, is_sys=1)
  266. sys_msg_list.append(SysMsgModel(
  267. userID_id=userID_id,
  268. msg=sys_msg_text,
  269. addTime=now_time,
  270. updTime=now_time,
  271. uid=uid,
  272. eventType=event_type))
  273. userID_ids.append(userID_id)
  274. if is_sys_msg:
  275. SysMsgModel.objects.bulk_create(sys_msg_list)
  276. Equipment_Info.objects.bulk_create(eq_list)
  277. if is_st == '0' or is_st == '2':
  278. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  279. elif is_st == '1':
  280. # Endpoint以杭州为例,其它Region请按实际情况填写。
  281. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  282. # 设置此签名URL在60秒内有效。
  283. url = bucket.sign_url('PUT', obj, 7200)
  284. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  285. return JsonResponse(status=200, data=res_data)
  286. elif is_st == '3':
  287. # 人形检测带动图
  288. # Endpoint以杭州为例,其它Region请按实际情况填写。
  289. img_url_list = []
  290. for i in range(int(is_st)):
  291. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  292. format(uid=uid, channel=channel, filename=n_time, st=i)
  293. # 设置此签名URL在60秒内有效。
  294. url = bucket.sign_url('PUT', obj, 7200)
  295. img_url_list.append(url)
  296. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  297. return JsonResponse(status=200, data=res_data)
  298. def get_msg_title(self, appBundleId, nickname):
  299. package_title_config = {
  300. 'com.ansjer.customizedd_a': 'DVS',
  301. 'com.ansjer.zccloud_a': 'ZosiSmart',
  302. 'com.ansjer.zccloud_ab': '周视',
  303. 'com.ansjer.adcloud_a': 'ADCloud',
  304. 'com.ansjer.adcloud_ab': 'ADCloud',
  305. 'com.ansjer.accloud_a': 'ACCloud',
  306. 'com.ansjer.loocamccloud_a': 'Loocam',
  307. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  308. 'com.ansjer.customizedb_a': 'COCOONHD',
  309. 'com.ansjer.customizeda_a': 'Guardian365',
  310. 'com.ansjer.customizedc_a': 'PatrolSecure',
  311. }
  312. if appBundleId in package_title_config.keys():
  313. return package_title_config[appBundleId] + '(' + nickname + ')'
  314. else:
  315. return nickname
  316. def is_sys_msg(self, event_type):
  317. event_type_list = [702, 703, 704]
  318. if event_type in event_type_list:
  319. return True
  320. return False
  321. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  322. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  323. etype = int(event_type)
  324. if lang == 'cn':
  325. if etype == 704:
  326. msg_type = '电量过低'
  327. elif etype == 702:
  328. msg_type = '摄像头休眠'
  329. elif etype == 703:
  330. msg_type = '摄像头唤醒'
  331. else:
  332. msg_type = ''
  333. if is_sys:
  334. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  335. else:
  336. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  337. # send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  338. else:
  339. if etype == 704:
  340. msg_type = 'Low battery'
  341. elif etype == 702:
  342. msg_type = 'Camera sleep'
  343. elif etype == 703:
  344. msg_type = 'Camera wake'
  345. else:
  346. msg_type = ''
  347. if is_sys:
  348. send_text = '{msg_type} channel:{channel}'. \
  349. format(msg_type=msg_type, channel=channel)
  350. else:
  351. send_text = '{msg_type} channel:{channel} date:{date}'. \
  352. format(msg_type=msg_type, channel=channel, date=n_date)
  353. return send_text
  354. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
  355. msg_title, msg_text):
  356. app_key = JPUSH_CONFIG[appBundleId]['Key']
  357. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  358. # 此处换成各自的app_key和master_secre
  359. _jpush = jpush.JPush(app_key, master_secret)
  360. push = _jpush.create_push()
  361. # if you set the logging level to "DEBUG",it will show the debug logging.
  362. # _jpush.set_logging("DEBUG")
  363. # push.audience = jpush.all_
  364. push.audience = jpush.registration_id(token_val)
  365. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  366. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  367. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  368. big_text=msg_text, title=msg_title,
  369. extras=push_data)
  370. push.notification = jpush.notification(android=android)
  371. push.platform = jpush.all_
  372. try:
  373. res = push.send()
  374. print(res)
  375. except Exception as e:
  376. print("jpush fail")
  377. print("Exception")
  378. print(repr(e))
  379. return
  380. else:
  381. print("jpush success")
  382. return
  383. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  384. try:
  385. serverKey = FCM_CONFIG[appBundleId]
  386. except Exception as e:
  387. return
  388. push_service = FCMNotification(api_key=serverKey)
  389. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  390. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  391. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  392. message_body=msg_text, data_message=data,
  393. extra_kwargs={
  394. 'default_vibrate_timings': True,
  395. 'default_sound': True,
  396. 'default_light_settings': True
  397. })
  398. print('fcm push ing')
  399. print(result)
  400. return
  401. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  402. msg_text):
  403. try:
  404. cli = apns2.APNSClient(mode=APNS_MODE,
  405. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  406. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  407. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  408. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  409. payload = apns2.Payload(alert=alert, custom=push_data)
  410. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  411. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  412. print(res.status_code)
  413. if res.status_code == 200:
  414. print('apns push success')
  415. return
  416. else:
  417. print('apns push fail')
  418. print(res.reason)
  419. return
  420. except Exception as e:
  421. print(repr(e))
  422. return
  423. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  424. # 移动侦测接口
  425. class PushNotificationView(View):
  426. def get(self, request, *args, **kwargs):
  427. request.encoding = 'utf-8'
  428. # operation = kwargs.get('operation')
  429. return self.validation(request.GET)
  430. def post(self, request, *args, **kwargs):
  431. request.encoding = 'utf-8'
  432. # operation = kwargs.get('operation')
  433. return self.validation(request.POST)
  434. def validation(self, request_dict):
  435. etk = request_dict.get('etk', None)
  436. channel = request_dict.get('channel', '1')
  437. n_time = request_dict.get('n_time', None)
  438. event_type = request_dict.get('event_type', None)
  439. is_st = request_dict.get('is_st', None)
  440. eto = ETkObject(etk)
  441. uid = eto.uid
  442. if len(uid) == 20:
  443. redisObj = RedisObject(db=6)
  444. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  445. pkey = '{uid}_ptl'.format(uid=uid)
  446. ykey = '{uid}_redis_qs'.format(uid=uid)
  447. if redisObj.get_data(key=pkey):
  448. res_data = {'code': 0, 'msg': 'success,!'}
  449. return JsonResponse(status=200, data=res_data)
  450. else:
  451. redisObj.set_data(key=pkey, val=1, expire=60)
  452. ##############
  453. redis_data = redisObj.get_data(key=ykey)
  454. if redis_data:
  455. redis_list = eval(redis_data)
  456. else:
  457. # 设置推送时间为60秒一次
  458. redisObj.set_data(key=pkey, val=1, expire=60)
  459. print("从数据库查到数据")
  460. # 从数据库查询出来
  461. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  462. values('token_val', 'app_type', 'appBundleId',
  463. 'push_type', 'userID_id', 'lang',
  464. 'tz', 'uid_set__nickname')
  465. # 新建一个list接收数据
  466. redis_list = []
  467. # 把数据库数据追加进redis_list
  468. for qs in uid_push_qs:
  469. redis_list.append(qs)
  470. # 修改redis数据,并设置过期时间为10分钟
  471. if redis_list:
  472. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  473. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  474. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  475. self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
  476. if is_st == '0' or is_st == '2':
  477. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  478. elif is_st == '1':
  479. # Endpoint以杭州为例,其它Region请按实际情况填写。
  480. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  481. # 设置此签名URL在60秒内有效。
  482. url = bucket.sign_url('PUT', obj, 7200)
  483. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  484. return JsonResponse(status=200, data=res_data)
  485. elif is_st == '3':
  486. # 人形检测带动图
  487. img_url_list = []
  488. for i in range(int(is_st)):
  489. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  490. format(uid=uid, channel=channel, filename=n_time, st=i)
  491. # 设置此签名URL在60秒内有效。
  492. url = bucket.sign_url('PUT', obj, 7200)
  493. img_url_list.append(url)
  494. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  495. return JsonResponse(status=200, data=res_data)
  496. else:
  497. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  498. else:
  499. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  500. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  501. now_time = int(time.time())
  502. # 设备昵称
  503. userID_ids = []
  504. sys_msg_list = []
  505. is_sys_msg = self.is_sys_msg(int(event_type))
  506. is_st = int(is_st)
  507. eq_list = []
  508. nickname = uaqs[0]['uid_set__nickname']
  509. if not nickname:
  510. nickname = uid
  511. for ua in uaqs:
  512. lang = ua['lang']
  513. tz = ua['tz']
  514. userID_id = ua["userID_id"]
  515. if userID_id not in userID_ids:
  516. eq_list.append(Equipment_Info(
  517. userID_id=userID_id,
  518. eventTime=n_time,
  519. eventType=event_type,
  520. devUid=uid,
  521. devNickName=nickname,
  522. Channel=channel,
  523. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  524. is_st=is_st,
  525. receiveTime=n_time,
  526. addTime=now_time
  527. ))
  528. if is_sys_msg:
  529. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  530. event_type=event_type, is_sys=1)
  531. sys_msg_list.append(SysMsgModel(
  532. userID_id=userID_id,
  533. msg=sys_msg_text,
  534. addTime=now_time,
  535. updTime=now_time,
  536. uid=uid,
  537. eventType=event_type))
  538. if eq_list:
  539. print('eq_list')
  540. Equipment_Info.objects.bulk_create(eq_list)
  541. if is_sys_msg:
  542. print('sys_msg')
  543. SysMsgModel.objects.bulk_create(sys_msg_list)
  544. return True
  545. def is_sys_msg(self, event_type):
  546. event_type_list = [702, 703, 704]
  547. if event_type in event_type_list:
  548. return True
  549. return False
  550. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  551. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  552. etype = int(event_type)
  553. if lang == 'cn':
  554. if etype == 704:
  555. msg_type = '电量过低'
  556. elif etype == 702:
  557. msg_type = '摄像头休眠'
  558. elif etype == 703:
  559. msg_type = '摄像头唤醒'
  560. else:
  561. msg_type = ''
  562. if is_sys:
  563. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  564. else:
  565. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  566. else:
  567. if etype == 704:
  568. msg_type = 'Low battery'
  569. elif etype == 702:
  570. msg_type = 'Camera sleep'
  571. elif etype == 703:
  572. msg_type = 'Camera wake'
  573. else:
  574. msg_type = ''
  575. if is_sys:
  576. send_text = '{msg_type} channel:{channel}'. \
  577. format(msg_type=msg_type, channel=channel)
  578. else:
  579. send_text = '{msg_type} channel:{channel} date:{date}'. \
  580. format(msg_type=msg_type, channel=channel, date=n_date)
  581. return send_text