DetectController.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  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 Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, DETECT_PUSH_DOMAIN, \
  24. JPUSH_CONFIG, FCM_CONFIG, APNS_CONFIG, \
  25. BASE_DIR, APNS_MODE, SERVER_TYPE
  26. from Ansjer.config import PUSH_REDIS_ADDRESS
  27. from Model.models import Device_Info, VodHlsModel, Equipment_Info, UidSetModel, UidPushModel, SysMsgModel
  28. from Object.ETkObject import ETkObject
  29. from Object.RedisObject import RedisObject
  30. from Object.ResponseObject import ResponseObject
  31. from Object.TokenObject import TokenObject
  32. from Object.UidTokenObject import UidTokenObject
  33. from Service.CommonService import CommonService
  34. from Service.EquipmentInfoService import EquipmentInfoService
  35. class DetectControllerView(View):
  36. def get(self, request, *args, **kwargs):
  37. request.encoding = 'utf-8'
  38. operation = kwargs.get('operation')
  39. # self.ip = CommonService.get_ip_address(request)
  40. return self.validation(request.GET, operation)
  41. def post(self, request, *args, **kwargs):
  42. request.encoding = 'utf-8'
  43. operation = kwargs.get('operation')
  44. # self.ip = CommonService.get_ip_address(request)
  45. return self.validation(request.POST, operation)
  46. def validation(self, request_dict, operation):
  47. response = ResponseObject()
  48. if operation is None:
  49. return response.json(444, 'error path')
  50. token = request_dict.get('token', None)
  51. tko = TokenObject(token)
  52. if tko.code == 0:
  53. userID = tko.userID
  54. # 修改推送设置
  55. if operation == 'changeStatus':
  56. print("进入changeStatus")
  57. return self.do_change_status(userID, request_dict, response)
  58. # 查询推送信息
  59. elif operation == 'queryInfo':
  60. return self.do_query(request_dict, response, userID)
  61. # 更新推送延迟
  62. elif operation == 'updateInterval':
  63. return self.do_update_interval(userID, request_dict, response)
  64. else:
  65. return response.json(414)
  66. else:
  67. return response.json(tko.code)
  68. def do_query(self, request_dict, response, userID):
  69. logger = logging.getLogger('info')
  70. logger.info("-----旧APP调用移动侦测查询")
  71. page = int(request_dict.get('page', None))
  72. line = int(request_dict.get('line', None))
  73. if not page or not line:
  74. return response.json(444, 'page,line')
  75. startTime = request_dict.get('startTime', None)
  76. endTime = request_dict.get('endTime', None)
  77. eventType = request_dict.get('eventType', None)
  78. # qs = Equipment_Info.objects.filter(userID_id=userID).order_by('-eventTime')
  79. # if startTime and endTime:
  80. # qs = qs.filter(eventTime__range=(startTime, endTime))
  81. # if eventType:
  82. # qs = qs.filter(eventType=eventType)
  83. if startTime and endTime:
  84. qs, count = EquipmentInfoService.find_by_start_time_equipment_info(page, line, userID, startTime,
  85. endTime, eventType,
  86. request_dict.get('uids', None))
  87. else:
  88. # 默认查询近七天消息推送
  89. qs, count = EquipmentInfoService.get_equipment_info_week_all(page, line, userID, startTime, endTime,
  90. eventType,
  91. request_dict.get('uids', None))
  92. logger.info('<<<|||分表查询结果count:{}'.format(count))
  93. uids = request_dict.get('uids', None)
  94. if uids:
  95. uid_list = uids.split(',')
  96. # qs = qs.filter(devUid__in=uid_list)
  97. dvqs = Device_Info.objects.filter(UID__in=uid_list, userID_id=userID).values('UID', 'Type', 'NickName')
  98. uid_type_dict = {}
  99. for dv in dvqs:
  100. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  101. else:
  102. dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
  103. uid_type_dict = {}
  104. for dv in dvqs:
  105. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  106. # print(uid_type_dict)
  107. if not qs or count == 0 or not qs.exists():
  108. return response.json(0, {'datas': [], 'count': 0})
  109. # if not qs.exists():
  110. # return response.json(0, {'datas': [], 'count': 0})
  111. # qs = qs.values('id', 'devUid', 'devNickName', 'Channel', 'eventType', 'status', 'alarm', 'eventTime',
  112. # 'receiveTime', 'is_st', 'addTime')
  113. # count = qs.count()
  114. # qr = qs[(page - 1) * line:page * line]
  115. qr = qs
  116. res = []
  117. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  118. img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  119. # vod_time_list = []
  120. for p in qr:
  121. devUid = p['devUid']
  122. eventTime = p['eventTime']
  123. channel = p['Channel']
  124. if p['is_st'] == 1:
  125. p['img'] = img_bucket.sign_url('GET', '{uid}/{channel}/{time}.jpeg'.
  126. format(uid=devUid, channel=p['Channel'], time=eventTime), 300)
  127. p['img_list'] = [img_bucket.sign_url('GET', '{uid}/{channel}/{time}.jpeg'.
  128. format(uid=devUid, channel=channel, time=eventTime), 300)]
  129. elif p['is_st'] == 2:
  130. # 列表装载回放时间戳标记
  131. vodqs = VodHlsModel.objects.filter(uid=devUid, channel=channel, time=int(eventTime)) \
  132. .values("bucket__bucket", "bucket__endpoint")
  133. # print(vodqs)
  134. if vodqs.exists():
  135. bucket_name = vodqs[0]['bucket__bucket']
  136. endpoint = vodqs[0]['bucket__endpoint']
  137. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  138. ts = '{uid}/vod{channel}/{etime}/ts0.ts'.format(uid=devUid, channel=p['Channel'], etime=eventTime)
  139. thumb0 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  140. thumb1 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  141. thumb2 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  142. # thumb3 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_3000,w_700'})
  143. p['img_list'] = [thumb0, thumb1, thumb2]
  144. elif p['is_st'] == 3:
  145. # 列表装载回放时间戳标记
  146. p['img_list'] = []
  147. for i in range(p['is_st']):
  148. img = img_bucket.sign_url('GET', '{uid}/{channel}/{time}_{st}.jpeg'.
  149. format(uid=devUid, channel=p['Channel'], time=eventTime, st=i), 300)
  150. p['img_list'].append(img)
  151. if devUid in uid_type_dict.keys():
  152. p['uid_type'] = uid_type_dict[devUid]['type']
  153. p['devNickName'] = uid_type_dict[devUid]['NickName']
  154. else:
  155. p['uid_type'] = ''
  156. res.append(p)
  157. return response.json(0, {'datas': res, 'count': count})
  158. def do_change_status(self, userID, request_dict, response):
  159. token_val = request_dict.get('token_val', None)
  160. appBundleId = request_dict.get('appBundleId', None)
  161. app_type = request_dict.get('app_type', None)
  162. push_type = request_dict.get('push_type', None)
  163. status = request_dict.get('status', None)
  164. m_code = request_dict.get('m_code', None)
  165. uid = request_dict.get('uid', None)
  166. # 设备语言
  167. lang = request_dict.get('lang', 'en')
  168. tz = request_dict.get('tz', '0')
  169. # 消息提醒功能新增
  170. # 如果传空上来,就默认为0
  171. if tz == '':
  172. tz = 0
  173. else:
  174. tz = tz.replace("GMT", "")
  175. detect_group = request_dict.get('detect_group', None)
  176. interval = request_dict.get('interval', None)
  177. if not status:
  178. return response.json(444, 'status')
  179. # 关闭推送
  180. if not all([appBundleId, app_type, token_val, uid, m_code]):
  181. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  182. # 判断推送类型对应key是否存在
  183. print('push_type:', push_type)
  184. if push_type == '0':
  185. if appBundleId not in APNS_CONFIG.keys():
  186. return response.json(904)
  187. elif push_type == '1':
  188. if appBundleId not in FCM_CONFIG.keys():
  189. return response.json(904)
  190. elif push_type == '2':
  191. if appBundleId not in JPUSH_CONFIG.keys():
  192. return response.json(904)
  193. else:
  194. return response.json(173)
  195. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  196. status = int(status)
  197. # 获取用户区域
  198. # ip = self.ip
  199. # ipInfo = CommonService.getIpIpInfo(ip=ip, lang='EN')
  200. # area = ipInfo['country_name']
  201. # if area == 'China':
  202. # DETECT_PUSH_DOMAIN = 'cn.push.dvema.com'
  203. # else:
  204. # DETECT_PUSH_DOMAIN = 'en.push.dvema.com'
  205. nowTime = int(time.time())
  206. if dvqs.exists():
  207. # 修改状态
  208. dvqs.update(NotificationMode=status)
  209. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  210. # uid配置信息是否存在
  211. if uid_set_qs.exists():
  212. uid_set_id = uid_set_qs[0].id
  213. qs_data = {
  214. 'detect_status': status,
  215. 'updTime': nowTime,
  216. }
  217. if interval:
  218. qs_data['detect_interval'] = int(interval)
  219. if detect_group:
  220. qs_data['detect_group'] = detect_group
  221. print(qs_data)
  222. uid_set_qs.update(**qs_data)
  223. else:
  224. qs_data = {
  225. 'uid': uid,
  226. 'addTime': nowTime,
  227. 'updTime': nowTime,
  228. 'detect_status': status,
  229. }
  230. if interval:
  231. qs_data['detect_interval'] = int(interval)
  232. if detect_group:
  233. qs_data['detect_group'] = detect_group
  234. # 添加设备配置
  235. uid_set_qs = UidSetModel.objects.create(**qs_data)
  236. uid_set_id = uid_set_qs.id
  237. if status == 0:
  238. UidPushModel.objects.filter(uid_set__uid=uid).delete()
  239. # 状态为0的时候删除redis缓存数据
  240. self.do_delete_redis(uid)
  241. return response.json(0)
  242. elif status == 1:
  243. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  244. if uid_push_qs.exists():
  245. uid_push_update_dict = {
  246. 'appBundleId': appBundleId,
  247. 'app_type': app_type,
  248. 'push_type': push_type,
  249. 'token_val': token_val,
  250. 'updTime': nowTime,
  251. 'lang': lang,
  252. 'tz': tz
  253. }
  254. uid_push_qs.update(**uid_push_update_dict)
  255. else:
  256. # uid_set_id = uid_set_qs[0].id
  257. uid_push_create_dict = {
  258. 'uid_set_id': uid_set_id,
  259. 'userID_id': userID,
  260. 'appBundleId': appBundleId,
  261. 'app_type': app_type,
  262. 'push_type': push_type,
  263. 'token_val': token_val,
  264. 'm_code': m_code,
  265. 'addTime': nowTime,
  266. 'updTime': nowTime,
  267. 'lang': lang,
  268. 'tz': tz
  269. }
  270. # 绑定设备推送
  271. UidPushModel.objects.create(**uid_push_create_dict)
  272. if interval:
  273. self.do_delete_redis(uid, int(interval))
  274. else:
  275. self.do_delete_redis(uid)
  276. # utko = UidTokenObject()
  277. # # right
  278. # utko.generate(data={'uid': uid})
  279. etkObj = ETkObject(etk='')
  280. etk = etkObj.encrypt(uid)
  281. detectUrl = "{DETECT_PUSH_DOMAIN}notify/push?etk={etk}". \
  282. format(etk=etk, DETECT_PUSH_DOMAIN=DETECT_PUSH_DOMAIN)
  283. return response.json(0, {'detectUrl': detectUrl})
  284. else:
  285. return response.json(14)
  286. def do_delete_redis(self, uid, detect_interval=0):
  287. keyPattern = '{uid}*'.format(uid=uid)
  288. redisObj = RedisObject(db=6, SERVER_HOST=PUSH_REDIS_ADDRESS)
  289. keys = redisObj.get_keys(keyPattern)
  290. if keys:
  291. for key in keys:
  292. key = key.decode()
  293. if detect_interval == 0:
  294. redisObj.del_data(key=key)
  295. elif key.find('plt') != -1:
  296. continue
  297. elif key.find('flag') != -1:
  298. redisObj.set_data(key=key, val=1, expire=detect_interval)
  299. else:
  300. redisObj.del_data(key=key)
  301. def do_update_interval(self, userID, request_dict, response):
  302. uid = request_dict.get('uid', None)
  303. interval = request_dict.get('interval', None)
  304. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  305. if dvqs.exists():
  306. uid_set_qs = UidSetModel.objects. \
  307. filter(uid=uid, uidpushmodel__userID_id=userID)
  308. # redisObj = RedisObject(db=8)
  309. # redisObj.del_data(key='uid_qs_' + userID)
  310. if uid_set_qs.exists():
  311. uid_set_qs.update(interval=int(interval))
  312. else:
  313. return response.json(173)
  314. else:
  315. return response.json(0)
  316. '''
  317. http://push.dvema.com/notify/push?etk=Y2lTRXhMTjBWS01sWlpURTVJU0ZWTlJ6RXhNVUU9T3o=&n_time=1526845794&channel=1&event_type=704&is_st=0
  318. http://push.dvema.com/deviceShadow/generateUTK?username=debug_user&password=debug_password&uid=VVDHCVBYDKFMJRWA111A
  319. '''
  320. # 移动侦测接口
  321. class NotificationView(View):
  322. def get(self, request, *args, **kwargs):
  323. request.encoding = 'utf-8'
  324. return self.validation(request.GET)
  325. def post(self, request, *args, **kwargs):
  326. request.encoding = 'utf-8'
  327. return self.validation(request.POST)
  328. def validation(self, request_dict):
  329. uidToken = request_dict.get('uidToken', None)
  330. etk = request_dict.get('etk', None)
  331. channel = request_dict.get('channel', '1')
  332. n_time = request_dict.get('n_time', None)
  333. event_type = request_dict.get('event_type', None)
  334. is_st = request_dict.get('is_st', None)
  335. # print("aaa")
  336. # return JsonResponse(0,safe=False)
  337. if not all([channel, n_time]):
  338. return JsonResponse(status=200, data={
  339. 'code': 444,
  340. 'msg': 'param is wrong'})
  341. if etk:
  342. eto = ETkObject(etk)
  343. uid = eto.uid
  344. if len(uid) != 20:
  345. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  346. else:
  347. utko = UidTokenObject(uidToken)
  348. uid = utko.UID
  349. pkey = '{uid}_{channel}_{event_type}_ptl'.format(uid=uid, event_type=event_type, channel=channel)
  350. # ykey = 'MUJ887NLR8K8GBM9111A_redis_qs'.format(uid=uid)
  351. ykey = '{uid}_redis_qs'.format(uid=uid)
  352. # dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
  353. is_sys_msg = self.is_sys_msg(int(event_type))
  354. if is_sys_msg is True:
  355. dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
  356. else:
  357. dkey = '{uid}_{channel}_flag'.format(uid=uid, channel=channel)
  358. # 判断redisObj.get_data(key=pkey):不为空
  359. redisObj = RedisObject(db=6)
  360. have_ykey = redisObj.get_data(key=ykey) # uid_set 数据库缓存
  361. have_pkey = redisObj.get_data(key=pkey) # 一分钟限制key
  362. have_dkey = redisObj.get_data(key=dkey) # 推送类型限制
  363. # 一分钟外,推送开启状态
  364. detect_med_type = 0 # 0推送旧机制 1存库不推送,2推送存库
  365. # 暂时注销
  366. if have_pkey:
  367. if SERVER_TYPE != "Ansjer.formal_settings":
  368. res_data = {'code': 0, 'msg': 'Push once every 10 seconds'}
  369. else:
  370. res_data = {'code': 0, 'msg': 'Push it once a minute'}
  371. return JsonResponse(status=200, data=res_data)
  372. # 数据库读取数据
  373. if have_ykey:
  374. redis_list = eval(redisObj.get_data(key=ykey))
  375. print(have_ykey)
  376. else:
  377. # 从数据库查询出来
  378. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  379. values('token_val', 'app_type', 'appBundleId', 'm_code',
  380. 'push_type', 'userID_id', 'userID__NickName',
  381. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  382. 'uid_set__channel')
  383. print(uid_push_qs)
  384. # 新建一个list接收数据
  385. redis_list = []
  386. # 把数据库数据追加进redis_list
  387. for qs in uid_push_qs:
  388. redis_list.append(qs)
  389. # 修改redis数据,并设置过期时间为10分钟
  390. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  391. if not redis_list:
  392. res_data = {'code': 404, 'msg': 'error !'}
  393. return JsonResponse(status=200, data=res_data)
  394. # 此时应该更新一下redis里面的dkey的有效时间
  395. # detect_interval = redis_list[0]['uid_set__detect_interval']
  396. # tmp_channel = redis_list[0]['uid_set__channel']
  397. # self.do_update_detect_interval(uid, tmp_channel, redisObj, detect_interval)
  398. if not redis_list:
  399. print("没有redi_list")
  400. res_data = {'code': 0, 'msg': 'no redi_list success!'}
  401. return JsonResponse(status=200, data=res_data)
  402. # is_sys_msg = self.is_sys_msg(int(event_type))
  403. nickname = redis_list[0]['uid_set__nickname']
  404. detect_interval = redis_list[0]['uid_set__detect_interval']
  405. detect_group = redis_list[0]['uid_set__detect_group']
  406. now_time = int(time.time())
  407. if not nickname:
  408. nickname = uid
  409. if detect_group is not None:
  410. if have_dkey:
  411. detect_med_type = 1 # 1为存库不推送
  412. else:
  413. detect_med_type = 2 # 为2的话,既推送,又存库
  414. # detect_group=0允许全部推送的时候
  415. if detect_group == '0' or detect_group == '':
  416. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  417. else:
  418. detect_group_list = detect_group.split(',')
  419. if event_type in detect_group_list:
  420. if detect_interval < 60:
  421. detect_interval = 60
  422. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  423. # 改为1秒
  424. # 如果不是正式
  425. if SERVER_TYPE != "Ansjer.formal_settings":
  426. redisObj.set_data(key=pkey, val=1, expire=10)
  427. else:
  428. redisObj.set_data(key=pkey, val=1, expire=60)
  429. # 打印have_ykey
  430. # return JsonResponse(status=200, data={'pkey': 0, 'have_ykey': have_ykey, 'have_pkey': have_pkey, 'have_ykey': have_dkey})
  431. # 旧模式并且没有pkey,重新创建一个
  432. if not detect_group and not have_pkey:
  433. # 设置推送时间为60秒一次
  434. # 如果不是正式
  435. if SERVER_TYPE != "Ansjer.formal_settings":
  436. redisObj.set_data(key=pkey, val=1, expire=10)
  437. else:
  438. redisObj.set_data(key=pkey, val=1, expire=60)
  439. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  440. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  441. kwag_args = {
  442. 'uid': uid,
  443. 'channel': channel,
  444. 'event_type': event_type,
  445. 'n_time': n_time,
  446. # 'appBundleId': appBundleId,
  447. # 'token_val': token_val,
  448. # 'msg_title': msg_title,
  449. # 'msg_text': msg_text
  450. }
  451. eq_list = []
  452. sys_msg_list = []
  453. userID_ids = []
  454. do_apns_code = ''
  455. do_fcm_code = ''
  456. do_jpush_code = ''
  457. for up in redis_list:
  458. push_type = up['push_type']
  459. appBundleId = up['appBundleId']
  460. token_val = up['token_val']
  461. lang = up['lang']
  462. tz = up['tz']
  463. if tz is None or tz == '':
  464. tz = 0
  465. # 发送标题
  466. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  467. # 发送内容
  468. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  469. event_type=event_type)
  470. kwag_args['appBundleId'] = appBundleId
  471. kwag_args['token_val'] = token_val
  472. kwag_args['msg_title'] = msg_title
  473. kwag_args['msg_text'] = msg_text
  474. push_server_status = 0
  475. # 推送
  476. if detect_med_type == 2 or detect_med_type == 0:
  477. if push_type == 0: # ios apns
  478. print('do_apns')
  479. # self.do_apns(**kwag_args)
  480. do_apns_code = self.do_apns(**kwag_args)
  481. if isinstance(do_apns_code, int):
  482. push_server_status = do_apns_code
  483. else:
  484. push_server_status = 400
  485. elif push_type == 1: # android gcm
  486. print('do_fcm')
  487. do_fcm_code = self.do_fcm(**kwag_args)
  488. push_server_status = 200
  489. elif push_type == 2: # android jpush
  490. print('do_jpush')
  491. do_jpush_code = self.do_jpush(**kwag_args)
  492. push_server_status = do_jpush_code
  493. # return JsonResponse(status=200, data={'code': 0, '状态:': self.do_jpush(**kwag_args)})
  494. if detect_med_type == 1:
  495. do_apns_code = '只存库不推送'
  496. do_fcm_code = '只存库不推送'
  497. do_jpush_code = '只存库不推送'
  498. # 以下是存库
  499. userID_id = up["userID_id"]
  500. int_is_st = int(is_st)
  501. if userID_id not in userID_ids:
  502. eq_list.append(Equipment_Info(
  503. userID_id=userID_id,
  504. eventTime=n_time,
  505. eventType=event_type,
  506. devUid=uid,
  507. devNickName=nickname,
  508. Channel=channel,
  509. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  510. is_st=int_is_st,
  511. receiveTime=n_time,
  512. addTime=now_time,
  513. storage_location=1
  514. ))
  515. if is_sys_msg:
  516. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  517. event_type=event_type, is_sys=1)
  518. sys_msg_list.append(SysMsgModel(
  519. userID_id=userID_id,
  520. msg=sys_msg_text,
  521. addTime=now_time,
  522. updTime=now_time,
  523. uid=uid,
  524. eventType=event_type))
  525. userID_ids.append(userID_id)
  526. if is_sys_msg:
  527. SysMsgModel.objects.bulk_create(sys_msg_list)
  528. Equipment_Info.objects.bulk_create(eq_list)
  529. if is_st == '0' or is_st == '2':
  530. print("is_st=0or2")
  531. for up in redis_list:
  532. if up['push_type'] == 0: # ios apns
  533. up['do_apns_code'] = do_apns_code
  534. elif up['push_type'] == 1: # android gcm
  535. up['do_fcm_code'] = do_fcm_code
  536. elif up['push_type'] == 2: # android jpush
  537. up['do_jpush_code'] = do_jpush_code
  538. up['test_or_www'] = SERVER_TYPE
  539. del up['push_type']
  540. del up['userID_id']
  541. del up['userID__NickName']
  542. del up['lang']
  543. del up['tz']
  544. del up['uid_set__nickname']
  545. del up['uid_set__detect_interval']
  546. del up['uid_set__detect_group']
  547. return JsonResponse(status=200, data={'code': 0, 'msg': 'success 0 or 2', 're_list': redis_list})
  548. elif is_st == '1':
  549. print("is_st=1")
  550. # Endpoint以杭州为例,其它Region请按实际情况填写。
  551. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  552. # 设置此签名URL在60秒内有效。
  553. url = bucket.sign_url('PUT', obj, 7200)
  554. for up in redis_list:
  555. up['do_apns_code'] = do_apns_code
  556. up['do_fcm_code'] = do_fcm_code
  557. up['do_jpush_code'] = do_jpush_code
  558. up['test_or_www'] = SERVER_TYPE
  559. del up['push_type']
  560. del up['userID_id']
  561. del up['userID__NickName']
  562. del up['lang']
  563. del up['tz']
  564. del up['uid_set__nickname']
  565. del up['uid_set__detect_interval']
  566. del up['uid_set__detect_group']
  567. # 不是正式服务器
  568. if SERVER_TYPE != "Ansjer.formal_settings":
  569. res_data = {'code': 0, 'img_push': url, 'msg': 'success', 're_list': redis_list}
  570. else:
  571. # 是正式服务器的时候
  572. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  573. return JsonResponse(status=200, data=res_data)
  574. elif is_st == '3':
  575. print("is_st=3")
  576. # 人形检测带动图
  577. # Endpoint以杭州为例,其它Region请按实际情况填写。
  578. img_url_list = []
  579. for i in range(int(is_st)):
  580. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  581. format(uid=uid, channel=channel, filename=n_time, st=i)
  582. # 设置此签名URL在60秒内有效。
  583. url = bucket.sign_url('PUT', obj, 7200)
  584. img_url_list.append(url)
  585. for up in redis_list:
  586. up['do_apns_code'] = do_apns_code
  587. up['do_fcm_code'] = do_fcm_code
  588. up['do_jpush_code'] = do_jpush_code
  589. up['test_or_www'] = SERVER_TYPE
  590. del up['push_type']
  591. del up['userID_id']
  592. del up['userID__NickName']
  593. del up['lang']
  594. del up['tz']
  595. del up['uid_set__nickname']
  596. del up['uid_set__detect_interval']
  597. del up['uid_set__detect_group']
  598. # 不是正式服务器
  599. if SERVER_TYPE != "Ansjer.formal_settings":
  600. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3', 're_list': redis_list}
  601. else:
  602. # 是正式服务器的时候
  603. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
  604. return JsonResponse(status=200, data=res_data)
  605. def get_msg_title(self, appBundleId, nickname):
  606. package_title_config = {
  607. 'com.ansjer.customizedd_a': 'DVS',
  608. 'com.ansjer.zccloud_a': 'ZosiSmart',
  609. 'com.ansjer.zccloud_ab': '周视',
  610. 'com.ansjer.adcloud_a': 'ADCloud',
  611. 'com.ansjer.adcloud_ab': 'ADCloud',
  612. 'com.ansjer.accloud_a': 'ACCloud',
  613. 'com.ansjer.loocamccloud_a': 'Loocam',
  614. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  615. 'com.ansjer.customizedb_a': 'COCOONHD',
  616. 'com.ansjer.customizeda_a': 'Guardian365',
  617. 'com.ansjer.customizedc_a': 'PatrolSecure',
  618. }
  619. if appBundleId in package_title_config.keys():
  620. return package_title_config[appBundleId] + '(' + nickname + ')'
  621. else:
  622. return nickname
  623. def is_sys_msg(self, event_type):
  624. event_type_list = [702, 703, 704]
  625. if event_type in event_type_list:
  626. return True
  627. return False
  628. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  629. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  630. etype = int(event_type)
  631. if lang == 'cn':
  632. if etype == 704:
  633. msg_type = '电量过低'
  634. elif etype == 702:
  635. msg_type = '摄像头休眠'
  636. elif etype == 703:
  637. msg_type = '摄像头唤醒'
  638. else:
  639. msg_type = ''
  640. if is_sys:
  641. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  642. else:
  643. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  644. # send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  645. else:
  646. if etype == 704:
  647. msg_type = 'Low battery'
  648. elif etype == 702:
  649. msg_type = 'Camera sleep'
  650. elif etype == 703:
  651. msg_type = 'Camera wake'
  652. else:
  653. msg_type = ''
  654. if is_sys:
  655. send_text = '{msg_type} channel:{channel}'. \
  656. format(msg_type=msg_type, channel=channel)
  657. else:
  658. send_text = '{msg_type} channel:{channel} date:{date}'. \
  659. format(msg_type=msg_type, channel=channel, date=n_date)
  660. return send_text
  661. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
  662. msg_title, msg_text):
  663. app_key = JPUSH_CONFIG[appBundleId]['Key']
  664. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  665. # 此处换成各自的app_key和master_secre
  666. _jpush = jpush.JPush(app_key, master_secret)
  667. push = _jpush.create_push()
  668. # if you set the logging level to "DEBUG",it will show the debug logging.
  669. # _jpush.set_logging("DEBUG")
  670. # push.audience = jpush.all_
  671. push.audience = jpush.registration_id(token_val)
  672. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  673. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  674. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  675. big_text=msg_text, title=msg_title,
  676. extras=push_data)
  677. push.notification = jpush.notification(android=android)
  678. push.platform = jpush.all_
  679. res = push.send()
  680. print(res)
  681. return res.status_code
  682. # try:
  683. # res = push.send()
  684. # print(res)
  685. # except Exception as e:
  686. # print("jpush fail")
  687. # print("Exception")
  688. # print(repr(e))
  689. # return
  690. # else:
  691. # print("jpush success")
  692. # return
  693. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  694. try:
  695. serverKey = FCM_CONFIG[appBundleId]
  696. except Exception as e:
  697. return 'serverKey abnormal'
  698. push_service = FCMNotification(api_key=serverKey)
  699. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  700. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  701. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  702. message_body=msg_text, data_message=data,
  703. extra_kwargs={
  704. 'default_vibrate_timings': True,
  705. 'default_sound': True,
  706. 'default_light_settings': True
  707. })
  708. print('fcm push ing')
  709. print(result)
  710. return result
  711. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  712. msg_text):
  713. try:
  714. cli = apns2.APNSClient(mode=APNS_MODE,
  715. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  716. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  717. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  718. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  719. payload = apns2.Payload(alert=alert, custom=push_data)
  720. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  721. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  722. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  723. print(res.status_code)
  724. # 200, 推送成功。
  725. #   400, 请求有问题。
  726. #   403, 证书或Token有问题。
  727. #   405, 请求方式不正确, 只支持POST请求
  728. #   410, 设备的Token与证书不一致
  729. if res.status_code == 200:
  730. return res.status_code
  731. else:
  732. print('apns push fail')
  733. print(res.reason)
  734. return res.status_code
  735. except (ValueError, ArithmeticError):
  736. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  737. except Exception as e:
  738. print(repr(e))
  739. return repr(e)
  740. def do_update_detect_interval(self, uid, channel, redisObject, detect_interval):
  741. if channel == 0:
  742. channel = 17
  743. else:
  744. channel += 1
  745. for i in range(1, channel):
  746. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=51, channel=i)
  747. if tmpDKey is not False:
  748. llt = redisObject.get_ttl(tmpDKey)
  749. if llt > detect_interval:
  750. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  751. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=54, channel=i)
  752. if tmpDKey is not False:
  753. llt = redisObject.get_ttl(tmpDKey)
  754. if llt > detect_interval:
  755. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  756. # 新增 把代码封装以便后面分侦测类型
  757. def detect_group_push(self, request_dict, uid, response, channel, n_time, event_type, is_st):
  758. redisObj = RedisObject(db=6)
  759. pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  760. if redisObj.get_data(key=pkey):
  761. res_data = {'code': 0, 'msg': 'success,!'}
  762. return JsonResponse(status=200, data=res_data)
  763. else:
  764. # 设置推送间隔60秒一次
  765. redisObj.set_data(key=pkey, val=1, expire=60)
  766. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  767. values('token_val', 'app_type', 'appBundleId',
  768. 'push_type', 'userID_id', 'userID__NickName',
  769. 'lang', 'tz', 'uid_set__nickname')
  770. if uid_push_qs.exists():
  771. nickname = uid_push_qs[0]['uid_set__nickname']
  772. if not nickname:
  773. nickname = uid
  774. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  775. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  776. for up in uid_push_qs:
  777. push_type = up['push_type']
  778. # ios apns
  779. print(push_type)
  780. if push_type == 0:
  781. self.do_apns(request_dict, up, response, uid, channel, nickname)
  782. # android gcm
  783. elif push_type == 1:
  784. self.do_fcm(request_dict, up, response, uid, channel, nickname)
  785. # self.do_gmc(request_dict, up, response, uid, channel,nickname)
  786. # android jpush
  787. elif push_type == 2:
  788. self.do_jpush(request_dict, up, response, uid, channel, nickname)
  789. # self.do_save_equipment_info(ua, n_time, channel, event_type, is_st)
  790. # 需求不一样,所以这么做的
  791. self.do_bulk_create_info(uid_push_qs, n_time, channel, event_type, is_st, uid)
  792. if is_st == '0' or is_st == '2':
  793. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  794. elif is_st == '1':
  795. # Endpoint以杭州为例,其它Region请按实际情况填写。
  796. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  797. # 设置此签名URL在60秒内有效。
  798. url = bucket.sign_url('PUT', obj, 7200)
  799. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  800. return JsonResponse(status=200, data=res_data)
  801. elif is_st == '3':
  802. # 人形检测带动图
  803. # Endpoint以杭州为例,其它Region请按实际情况填写。
  804. img_url_list = []
  805. for i in range(int(is_st)):
  806. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  807. format(uid=uid, channel=channel, filename=n_time, st=i)
  808. # 设置此签名URL在60秒内有效。
  809. url = bucket.sign_url('PUT', obj, 7200)
  810. img_url_list.append(url)
  811. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  812. return JsonResponse(status=200, data=res_data)
  813. else:
  814. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  815. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  816. #
  817. qs_list = []
  818. nowTime = int(time.time())
  819. # 设备昵称
  820. userID_ids = []
  821. for dv in uaqs:
  822. userID_id = dv["userID_id"]
  823. if userID_id not in userID_ids:
  824. if dv['uid_set__nickname']:
  825. uid_nickname = dv['uid_set__nickname']
  826. else:
  827. uid_nickname = uid
  828. add_data = {
  829. 'userID_id': dv["userID_id"],
  830. 'eventTime': n_time,
  831. 'eventType': event_type,
  832. 'devUid': uid,
  833. 'devNickName': uid_nickname,
  834. 'Channel': channel,
  835. 'alarm': 'Motion \tChannel:{channel}'.format(channel=channel),
  836. 'is_st': int(is_st),
  837. 'receiveTime': n_time,
  838. 'addTime': nowTime
  839. }
  840. qs_list.append(Equipment_Info(**add_data))
  841. userID_ids.append(userID_id)
  842. if qs_list:
  843. print(1)
  844. Equipment_Info.objects.bulk_create(qs_list)
  845. return True
  846. else:
  847. return False
  848. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  849. # 移动侦测接口
  850. class PushNotificationView(View):
  851. def get(self, request, *args, **kwargs):
  852. request.encoding = 'utf-8'
  853. # operation = kwargs.get('operation')
  854. return self.validation(request.GET)
  855. def post(self, request, *args, **kwargs):
  856. request.encoding = 'utf-8'
  857. # operation = kwargs.get('operation')
  858. return self.validation(request.POST)
  859. def validation(self, request_dict):
  860. etk = request_dict.get('etk', None)
  861. channel = request_dict.get('channel', '1')
  862. n_time = request_dict.get('n_time', None)
  863. event_type = request_dict.get('event_type', None)
  864. is_st = request_dict.get('is_st', None)
  865. eto = ETkObject(etk)
  866. uid = eto.uid
  867. if len(uid) == 20:
  868. redisObj = RedisObject(db=6)
  869. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  870. pkey = '{uid}_ptl'.format(uid=uid)
  871. ykey = '{uid}_redis_qs'.format(uid=uid)
  872. if redisObj.get_data(key=pkey):
  873. res_data = {'code': 0, 'msg': 'success,!33333333333'}
  874. return JsonResponse(status=200, data=res_data)
  875. else:
  876. redisObj.set_data(key=pkey, val=1, expire=60)
  877. ##############
  878. redis_data = redisObj.get_data(key=ykey)
  879. if redis_data:
  880. redis_list = eval(redis_data)
  881. else:
  882. # 设置推送时间为60秒一次
  883. redisObj.set_data(key=pkey, val=1, expire=60)
  884. print("从数据库查到数据")
  885. # 从数据库查询出来
  886. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  887. values('token_val', 'app_type', 'appBundleId',
  888. 'push_type', 'userID_id', 'lang', 'm_code',
  889. 'tz', 'uid_set__nickname')
  890. # 新建一个list接收数据
  891. redis_list = []
  892. # 把数据库数据追加进redis_list
  893. for qs in uid_push_qs:
  894. redis_list.append(qs)
  895. # 修改redis数据,并设置过期时间为10分钟
  896. if redis_list:
  897. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  898. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  899. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  900. self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
  901. if is_st == '0' or is_st == '2':
  902. return JsonResponse(status=200, data={'code': 0, 'msg': 'success44444444444444444'})
  903. elif is_st == '1':
  904. # Endpoint以杭州为例,其它Region请按实际情况填写。
  905. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  906. # 设置此签名URL在60秒内有效。
  907. url = bucket.sign_url('PUT', obj, 7200)
  908. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  909. return JsonResponse(status=200, data=res_data)
  910. elif is_st == '3':
  911. # 人形检测带动图
  912. img_url_list = []
  913. for i in range(int(is_st)):
  914. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  915. format(uid=uid, channel=channel, filename=n_time, st=i)
  916. # 设置此签名URL在60秒内有效。
  917. url = bucket.sign_url('PUT', obj, 7200)
  918. img_url_list.append(url)
  919. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  920. return JsonResponse(status=200, data=res_data)
  921. else:
  922. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  923. else:
  924. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  925. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  926. now_time = int(time.time())
  927. # 设备昵称
  928. userID_ids = []
  929. sys_msg_list = []
  930. is_sys_msg = self.is_sys_msg(int(event_type))
  931. is_st = int(is_st)
  932. eq_list = []
  933. nickname = uaqs[0]['uid_set__nickname']
  934. if not nickname:
  935. nickname = uid
  936. for ua in uaqs:
  937. lang = ua['lang']
  938. tz = ua['tz']
  939. userID_id = ua["userID_id"]
  940. if userID_id not in userID_ids:
  941. eq_list.append(Equipment_Info(
  942. userID_id=userID_id,
  943. eventTime=n_time,
  944. eventType=event_type,
  945. devUid=uid,
  946. devNickName=nickname,
  947. Channel=channel,
  948. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  949. is_st=is_st,
  950. receiveTime=n_time,
  951. addTime=now_time,
  952. storage_location=1
  953. ))
  954. if is_sys_msg:
  955. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  956. event_type=event_type, is_sys=1)
  957. sys_msg_list.append(SysMsgModel(
  958. userID_id=userID_id,
  959. msg=sys_msg_text,
  960. addTime=now_time,
  961. updTime=now_time,
  962. uid=uid,
  963. eventType=event_type))
  964. if eq_list:
  965. print('eq_list')
  966. Equipment_Info.objects.bulk_create(eq_list)
  967. if is_sys_msg:
  968. print('sys_msg')
  969. SysMsgModel.objects.bulk_create(sys_msg_list)
  970. return True
  971. def is_sys_msg(self, event_type):
  972. event_type_list = [702, 703, 704]
  973. if event_type in event_type_list:
  974. return True
  975. return False
  976. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  977. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  978. etype = int(event_type)
  979. if lang == 'cn':
  980. if etype == 704:
  981. msg_type = '电量过低'
  982. elif etype == 702:
  983. msg_type = '摄像头休眠'
  984. elif etype == 703:
  985. msg_type = '摄像头唤醒'
  986. else:
  987. msg_type = ''
  988. if is_sys:
  989. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  990. else:
  991. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  992. else:
  993. if etype == 704:
  994. msg_type = 'Low battery'
  995. elif etype == 702:
  996. msg_type = 'Camera sleep'
  997. elif etype == 703:
  998. msg_type = 'Camera wake'
  999. else:
  1000. msg_type = ''
  1001. if is_sys:
  1002. send_text = '{msg_type} channel:{channel}'. \
  1003. format(msg_type=msg_type, channel=channel)
  1004. else:
  1005. send_text = '{msg_type} channel:{channel} date:{date}'. \
  1006. format(msg_type=msg_type, channel=channel, date=n_date)
  1007. return send_text