DetectController.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  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 Object.RedisObject import RedisObject
  23. from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, DETECT_PUSH_DOMAIN, JPUSH_CONFIG, \
  24. FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE
  25. from Model.models import Device_Info, VodHlsModel, Equipment_Info, UidSetModel, UidPushModel
  26. from Object.ETkObject import ETkObject
  27. from Object.RedisObject import RedisObject
  28. from Object.ResponseObject import ResponseObject
  29. from Object.TokenObject import TokenObject
  30. from Object.UidTokenObject import UidTokenObject
  31. from Service.CommonService import CommonService
  32. '''
  33. http://test.push.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJUNEFaM0NVS0NFUkg5RlpBMTExQSJ9.GtrXeq5gb2Z9M3mKECxi9eNQbPxqC-6PtgJkOOg6PwI&n_time=1598456451&channel=1&event_type=1&is_st=1
  34. http://push.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJUNEFaM0NVS0NFUkg5RlpBMTExQSJ9.GtrXeq5gb2Z9M3mKECxi9eNQbPxqC-6PtgJkOOg6PwI&n_time=1598456451&channel=1&event_type=1&is_st=1
  35. http://www.dvema.com/detect/changeStatus?push_type=2&token_val=1a0018970a332cca935&appBundleId=com.ansjer.zccloud_ab&tz=+08.00&uid=HLK7EJ2VYLNHHUMG111A&status=1&m_code=AN02000025070000001207.zccloud_ab&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiMTMxMTk2NTc3MTMiLCJsYW5nIjoiZW4iLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJ1c2VySUQiOiIxNTQ0ODM4MjMyOTczMTM4MDAxMzgwMDAiLCJleHAiOjE1ODQxNDc0NjN9.NjK91B26jZDtdmq8tW-8hXNQPqqDfo9Zwf_Jg6Uf7co&lang=cn&app_type=2
  36. http://127.0.0.1:8077/detect/changeStatus?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTg0MzUxODk2MjgyMTM4MDAxMzgwMDAiLCJsYW5nIjoiZW4iLCJ1c2VyIjoiMTM2ODAzMTc1OTYiLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJleHAiOjE1ODcyNjEzODN9.H87931EDg6PGZK63EAsvY1FRJov9qo_S70mBKvpZeQM&push_type=2&token_val=token_val&appBundleId=appBundleId&tz=0&uid=158440619973313800138000&status=1&m_code&lang=cn&app_type=0&start_status=1&interval=60&eventType=60
  37. http://192.168.136.140:8077/detect/changeStatus?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTg0MzUxODk2MjgyMTM4MDAxMzgwMDAiLCJsYW5nIjoiZW4iLCJ1c2VyIjoiMTM2ODAzMTc1OTYiLCJtX2NvZGUiOiIxMjM0MTMyNDMyMTQiLCJleHAiOjE1ODcyNjEzODN9.H87931EDg6PGZK63EAsvY1FRJov9qo_S70mBKvpZeQM&push_type=2&token_val=token_val&appBundleId=appBundleId&tz=0&uid=158440619973313800138000&status=1&m_code&lang=cn&app_type=0&start_status=1&interval=60&eventType=60
  38. detect/changeStatus
  39. '''
  40. class DetectControllerView(View):
  41. def get(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.GET, operation)
  46. def post(self, request, *args, **kwargs):
  47. request.encoding = 'utf-8'
  48. operation = kwargs.get('operation')
  49. # self.ip = CommonService.get_ip_address(request)
  50. return self.validation(request.POST, operation)
  51. def validation(self, request_dict, operation):
  52. response = ResponseObject()
  53. if operation is None:
  54. return response.json(444, 'error path')
  55. token = request_dict.get('token', None)
  56. tko = TokenObject(token)
  57. if tko.code == 0:
  58. userID = tko.userID
  59. # 修改推送设置
  60. if operation == 'changeStatus':
  61. print("进入changeStatus")
  62. return self.do_change_status(userID, request_dict, response)
  63. # 查询推送信息
  64. elif operation == 'queryInfo':
  65. return self.do_query(request_dict, response, userID)
  66. # 更新推送延迟
  67. elif operation == 'updateInterval':
  68. return self.do_update_interval(userID, request_dict, response)
  69. else:
  70. return response.json(414)
  71. else:
  72. return response.json(tko.code)
  73. def do_query(self, request_dict, response, userID):
  74. page = int(request_dict.get('page', None))
  75. line = int(request_dict.get('line', None))
  76. if not page or not line:
  77. return response.json(444, 'page,line')
  78. startTime = request_dict.get('startTime', None)
  79. endTime = request_dict.get('endTime', None)
  80. eventType = request_dict.get('eventType', None)
  81. qs = Equipment_Info.objects.filter(userID_id=userID).order_by('-eventTime')
  82. if startTime and endTime:
  83. qs = qs.filter(eventTime__range=(startTime, endTime))
  84. if eventType:
  85. qs = qs.filter(eventType=eventType)
  86. uids = request_dict.get('uids', None)
  87. if uids:
  88. uid_list = uids.split(',')
  89. qs = qs.filter(devUid__in=uid_list)
  90. dvqs = Device_Info.objects.filter(UID__in=uid_list, userID_id=userID).values('UID', 'Type', 'NickName')
  91. uid_type_dict = {}
  92. for dv in dvqs:
  93. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  94. else:
  95. dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
  96. uid_type_dict = {}
  97. for dv in dvqs:
  98. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  99. # print(uid_type_dict)
  100. if not qs.exists():
  101. return response.json(0, {'datas': [], 'count': 0})
  102. qs = qs.values('id', 'devUid', 'devNickName', 'Channel', 'eventType', 'status', 'alarm', 'eventTime',
  103. 'receiveTime', 'is_st', 'addTime')
  104. count = qs.count()
  105. qr = qs[(page - 1) * line:page * line]
  106. res = []
  107. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  108. img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  109. # vod_time_list = []
  110. for p in qr:
  111. devUid = p['devUid']
  112. eventTime = p['eventTime']
  113. channel = p['Channel']
  114. if p['is_st'] == 1:
  115. p['img'] = img_bucket.sign_url('GET', '{uid}/{channel}/{time}.jpeg'.
  116. format(uid=devUid, channel=p['Channel'], time=eventTime), 300)
  117. p['img_list'] = [img_bucket.sign_url('GET', '{uid}/{channel}/{time}.jpeg'.
  118. format(uid=devUid, channel=channel, time=eventTime), 300)]
  119. elif p['is_st'] == 2:
  120. # 列表装载回放时间戳标记
  121. vodqs = VodHlsModel.objects.filter(uid=devUid, channel=channel, time=int(eventTime)) \
  122. .values("bucket__bucket", "bucket__endpoint")
  123. # print(vodqs)
  124. if vodqs.exists():
  125. bucket_name = vodqs[0]['bucket__bucket']
  126. endpoint = vodqs[0]['bucket__endpoint']
  127. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  128. ts = '{uid}/vod{channel}/{etime}/ts0.ts'.format(uid=devUid, channel=p['Channel'], etime=eventTime)
  129. thumb0 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  130. thumb1 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  131. thumb2 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  132. # thumb3 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_3000,w_700'})
  133. p['img_list'] = [thumb0, thumb1, thumb2]
  134. elif p['is_st'] == 3:
  135. # 列表装载回放时间戳标记
  136. p['img_list'] = []
  137. for i in range(p['is_st']):
  138. img = img_bucket.sign_url('GET', '{uid}/{channel}/{time}_{st}.jpeg'.
  139. format(uid=devUid, channel=p['Channel'], time=eventTime, st=i), 300)
  140. p['img_list'].append(img)
  141. if devUid in uid_type_dict.keys():
  142. p['uid_type'] = uid_type_dict[devUid]['type']
  143. p['devNickName'] = uid_type_dict[devUid]['NickName']
  144. else:
  145. p['uid_type'] = ''
  146. res.append(p)
  147. return response.json(0, {'datas': res, 'count': count})
  148. def do_change_status(self, userID, request_dict, response):
  149. token_val = request_dict.get('token_val', None)
  150. appBundleId = request_dict.get('appBundleId', None)
  151. app_type = request_dict.get('app_type', None)
  152. push_type = request_dict.get('push_type', None)
  153. status = request_dict.get('status', None)
  154. m_code = request_dict.get('m_code', None)
  155. uid = request_dict.get('uid', None)
  156. # 设备语言
  157. lang = request_dict.get('lang', 'en')
  158. tz = request_dict.get('tz', '0')
  159. # 消息提醒功能新增
  160. # 如果传空上来,就默认为0
  161. if tz=='':
  162. tz=0
  163. detect_group = request_dict.get('detect_group', None)
  164. interval = request_dict.get('interval', None)
  165. if not status:
  166. return response.json(444, 'status')
  167. # 关闭推送
  168. if not all([appBundleId, app_type, token_val, uid, m_code]):
  169. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  170. # 判断推送类型对应key是否存在
  171. print('push_type:', push_type)
  172. if push_type == '0':
  173. if appBundleId not in APNS_CONFIG.keys():
  174. return response.json(904)
  175. elif push_type == '1':
  176. if appBundleId not in FCM_CONFIG.keys():
  177. return response.json(904)
  178. elif push_type == '2':
  179. if appBundleId not in JPUSH_CONFIG.keys():
  180. return response.json(904)
  181. else:
  182. return response.json(173)
  183. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  184. status = int(status)
  185. # 获取用户区域
  186. # ip = self.ip
  187. # ipInfo = CommonService.getIpIpInfo(ip=ip, lang='EN')
  188. # area = ipInfo['country_name']
  189. # if area == 'China':
  190. # DETECT_PUSH_DOMAIN = 'cn.push.dvema.com'
  191. # else:
  192. # DETECT_PUSH_DOMAIN = 'en.push.dvema.com'
  193. nowTime = int(time.time())
  194. if dvqs.exists():
  195. # 修改状态
  196. dvqs.update(NotificationMode=status)
  197. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  198. # uid配置信息是否存在
  199. if uid_set_qs.exists():
  200. uid_set_id = uid_set_qs[0].id
  201. qs_data = {
  202. 'detect_status': status,
  203. 'updTime': nowTime,
  204. }
  205. if interval:
  206. qs_data['detect_interval'] = int(interval)
  207. if detect_group:
  208. qs_data['detect_group'] = detect_group
  209. print(qs_data)
  210. uid_set_qs.update(**qs_data)
  211. else:
  212. qs_data = {
  213. 'uid': uid,
  214. 'addTime': nowTime,
  215. 'updTime': nowTime,
  216. 'detect_status': status,
  217. }
  218. if interval:
  219. qs_data['detect_interval'] = int(interval)
  220. if detect_group:
  221. qs_data['detect_group'] = detect_group
  222. # 添加设备配置
  223. uid_set_qs = UidSetModel.objects.create(**qs_data)
  224. uid_set_id = uid_set_qs.id
  225. if status == 0:
  226. UidPushModel.objects.filter(uid_set__uid=uid).delete()
  227. # 状态为0的时候删除redis缓存数据
  228. self.do_delete_redis(uid)
  229. return response.json(0)
  230. elif status == 1:
  231. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  232. # ykey = '{uid}_redis_qs'.format(uid=uid)
  233. # redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')
  234. # redisObj.del_data(key=ykey)
  235. self.do_delete_redis(uid)
  236. if uid_push_qs.exists():
  237. uid_push_update_dict = {
  238. 'appBundleId': appBundleId,
  239. 'app_type': app_type,
  240. 'push_type': push_type,
  241. 'token_val': token_val,
  242. 'updTime': nowTime,
  243. 'lang': lang,
  244. 'tz': tz
  245. }
  246. uid_push_qs.update(**uid_push_update_dict)
  247. else:
  248. # uid_set_id = uid_set_qs[0].id
  249. uid_push_create_dict = {
  250. 'uid_set_id': uid_set_id,
  251. 'userID_id': userID,
  252. 'appBundleId': appBundleId,
  253. 'app_type': app_type,
  254. 'push_type': push_type,
  255. 'token_val': token_val,
  256. 'm_code': m_code,
  257. 'addTime': nowTime,
  258. 'updTime': nowTime,
  259. 'lang': lang,
  260. 'tz': tz
  261. }
  262. # 绑定设备推送
  263. UidPushModel.objects.create(**uid_push_create_dict)
  264. # utko = UidTokenObject()
  265. # # right
  266. # utko.generate(data={'uid': uid})
  267. etkObj = ETkObject(etk='')
  268. etk = etkObj.encrypt(uid)
  269. detectUrl = "{DETECT_PUSH_DOMAIN}notify/push?etk={etk}". \
  270. format(etk=etk, DETECT_PUSH_DOMAIN=DETECT_PUSH_DOMAIN)
  271. return response.json(0, {'detectUrl': detectUrl})
  272. else:
  273. return response.json(14)
  274. def do_delete_redis(self, uid):
  275. keyPattern = '{uid}*'.format(uid=uid)
  276. redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')
  277. keys = redisObj.get_keys(keyPattern)
  278. if keys:
  279. for key in keys:
  280. redisObj.del_data(key=key.decode())
  281. def do_update_interval(self, userID, request_dict, response):
  282. uid = request_dict.get('uid', None)
  283. interval = request_dict.get('interval', None)
  284. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  285. if dvqs.exists():
  286. uid_set_qs = UidSetModel.objects. \
  287. filter(uid=uid, uidpushmodel__userID_id=userID)
  288. # redisObj = RedisObject(db=8)
  289. # redisObj.del_data(key='uid_qs_' + userID)
  290. if uid_set_qs.exists():
  291. uid_set_qs.update(interval=int(interval))
  292. else:
  293. return response.json(173)
  294. else:
  295. return response.json(0)
  296. # http://192.168.136.40:8077/notify/push?uidToken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJUTjdNUEUzMjExVUU3NkFQMTExQSJ9.k501567VdnhFpn_ygzGRDat3Kqlz5CsEA9jAC2dDk_g&obj=12341234&n_time=1234561234
  297. # http://test.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  298. # 移动侦测接口
  299. class NotificationView(View):
  300. def get(self, request, *args, **kwargs):
  301. request.encoding = 'utf-8'
  302. # operation = kwargs.get('operation')
  303. return self.validation(request.GET)
  304. def post(self, request, *args, **kwargs):
  305. request.encoding = 'utf-8'
  306. # operation = kwargs.get('operation')
  307. return self.validation(request.POST)
  308. def validation(self, request_dict):
  309. response = ResponseObject()
  310. uidToken = request_dict.get('uidToken', None)
  311. etk = request_dict.get('etk', None)
  312. channel = request_dict.get('channel', '1')
  313. n_time = request_dict.get('n_time', None)
  314. event_type = request_dict.get('event_type', None)
  315. is_st = request_dict.get('is_st', None)
  316. if not all([channel, n_time]):
  317. return JsonResponse(status=200, data={
  318. 'code': 444,
  319. 'msg': 'param is wrong'})
  320. # return response.json(444)
  321. if etk:
  322. eto = ETkObject(etk)
  323. uid = eto.uid
  324. if len(uid) != 20:
  325. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  326. else:
  327. utko = UidTokenObject(uidToken)
  328. uid = utko.UID
  329. # utko = UidTokenObject(uidToken)
  330. # uid = utko.UID
  331. detect_group = UidSetModel.objects.filter(uid=uid). \
  332. values('detect_group')
  333. event_type = detect_group
  334. # 新增 移动侦测
  335. if event_type == '0':
  336. self.detect_group_push(self, request_dict, uid, response, channel, n_time, event_type, is_st)
  337. # 新增 pir侦测
  338. if event_type == '1':
  339. self.detect_group_push(self, request_dict, uid, response, channel, n_time, event_type, is_st)
  340. # 新增 移动侦测和pir侦测
  341. if event_type == '01':
  342. self.detect_group_push(self, request_dict, uid, response, channel, n_time, event_type, is_st)
  343. # 新增 把代码封装以便后面分侦测类型
  344. def detect_group_push(self, request_dict, uid, response, channel, n_time, event_type, is_st):
  345. redisObj = RedisObject(db=6)
  346. pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  347. if redisObj.get_data(key=pkey):
  348. res_data = {'code': 0, 'msg': 'success,!'}
  349. return JsonResponse(status=200, data=res_data)
  350. else:
  351. # 设置推送间隔60秒一次
  352. redisObj.set_data(key=pkey, val=1, expire=60)
  353. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  354. values('token_val', 'app_type', 'appBundleId',
  355. 'push_type', 'userID_id', 'userID__NickName',
  356. 'lang', 'tz', 'uid_set__nickname')
  357. if uid_push_qs.exists():
  358. nickname = uid_push_qs[0]['uid_set__nickname']
  359. if not nickname:
  360. nickname = uid
  361. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  362. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  363. for up in uid_push_qs:
  364. push_type = up['push_type']
  365. # ios apns
  366. print(push_type)
  367. if push_type == 0:
  368. self.do_apns(request_dict, up, response, uid, channel, nickname)
  369. # android gcm
  370. elif push_type == 1:
  371. self.do_fcm(request_dict, up, response, uid, channel, nickname)
  372. # self.do_gmc(request_dict, up, response, uid, channel,nickname)
  373. # android jpush
  374. elif push_type == 2:
  375. self.do_jpush(request_dict, up, response, uid, channel, nickname)
  376. # self.do_save_equipment_info(ua, n_time, channel, event_type, is_st)
  377. # 需求不一样,所以这么做的
  378. self.do_bulk_create_info(uid_push_qs, n_time, channel, event_type, is_st, uid)
  379. if is_st == '0' or is_st == '2':
  380. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  381. elif is_st == '1':
  382. # Endpoint以杭州为例,其它Region请按实际情况填写。
  383. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  384. # 设置此签名URL在60秒内有效。
  385. url = bucket.sign_url('PUT', obj, 7200)
  386. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  387. return JsonResponse(status=200, data=res_data)
  388. elif is_st == '3':
  389. # 人形检测带动图
  390. # Endpoint以杭州为例,其它Region请按实际情况填写。
  391. img_url_list = []
  392. for i in range(int(is_st)):
  393. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  394. format(uid=uid, channel=channel, filename=n_time, st=i)
  395. # 设置此签名URL在60秒内有效。
  396. url = bucket.sign_url('PUT', obj, 7200)
  397. img_url_list.append(url)
  398. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  399. return JsonResponse(status=200, data=res_data)
  400. else:
  401. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  402. def do_jpush(self, request_dict, uaql, response, uid, channel, nickname):
  403. event_type = request_dict.get('event_type', None)
  404. n_time = request_dict.get('n_time', None)
  405. appBundleId = uaql['appBundleId']
  406. token_val = uaql['token_val']
  407. lang = uaql['lang']
  408. tz = uaql['tz']
  409. response = ResponseObject()
  410. app_key = JPUSH_CONFIG[appBundleId]['Key']
  411. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  412. # 此处换成各自的app_key和master_secre
  413. _jpush = jpush.JPush(app_key, master_secret)
  414. push = _jpush.create_push()
  415. # if you set the logging level to "DEBUG",it will show the debug logging.
  416. _jpush.set_logging("DEBUG")
  417. # push.audience = jpush.all_
  418. push.audience = jpush.registration_id(token_val)
  419. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  420. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  421. message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
  422. send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)
  423. android = jpush.android(alert=send_text, priority=1, style=1, alert_type=7,
  424. big_text=send_text, title=message_title,
  425. extras=push_data)
  426. push.notification = jpush.notification(android=android)
  427. push.platform = jpush.all_
  428. try:
  429. res = push.send()
  430. print(res)
  431. except Exception as e:
  432. print("Exception")
  433. print(repr(e))
  434. return response.json(10, repr(e))
  435. else:
  436. return response.json(0)
  437. def get_message_title(self, appBundleId, nickname):
  438. package_title_config = {
  439. 'com.ansjer.customizedd_a': 'DVS',
  440. 'com.ansjer.zccloud_a': 'ZosiSmart',
  441. 'com.ansjer.zccloud_ab': '周视',
  442. 'com.ansjer.adcloud_a': 'ADCloud',
  443. 'com.ansjer.adcloud_ab': 'ADCloud',
  444. 'com.ansjer.accloud_a': 'ACCloud',
  445. 'com.ansjer.loocamccloud_a': 'Loocam',
  446. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  447. 'com.ansjer.customizedb_a': 'COCOONHD',
  448. 'com.ansjer.customizeda_a': 'Guardian365',
  449. 'com.ansjer.customizedc_a': 'PatrolSecure',
  450. }
  451. if appBundleId in package_title_config.keys():
  452. return package_title_config[appBundleId] + '(' + nickname + ')'
  453. else:
  454. return nickname
  455. def get_send_text(self, channel, n_time, lang, tz, event_type):
  456. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  457. msg_type = ''
  458. if int(event_type) == 704:
  459. msg_type = 'battery is too low'
  460. if lang == 'cn':
  461. msg_type = '电池电量过低'
  462. send_text = '{msg_type}channel:{channel} date:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  463. if lang == 'cn':
  464. send_text = '{msg_type}通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  465. return send_text
  466. def do_fcm(self, request_dict, uaql, response, uid, channel, nickname):
  467. n_time = request_dict.get('n_time')
  468. appBundleId = uaql['appBundleId']
  469. token_val = uaql['token_val']
  470. lang = uaql['lang']
  471. tz = uaql['tz']
  472. try:
  473. serverKey = FCM_CONFIG[appBundleId]
  474. except Exception as e:
  475. return response.json(404)
  476. event_type = request_dict.get('event_type', None)
  477. push_service = FCMNotification(api_key=serverKey)
  478. registration_id = token_val
  479. message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
  480. send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)
  481. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  482. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  483. result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title,
  484. message_body=send_text, data_message=data,
  485. extra_kwargs={
  486. 'default_vibrate_timings': True,
  487. 'default_sound': True,
  488. 'default_light_settings': True
  489. })
  490. response = ResponseObject()
  491. return response.json(0, result)
  492. def do_apns(self, request_dict, uaql, response, uid, channel, nickname):
  493. event_type = request_dict.get('event_type', None)
  494. token_val = uaql['token_val']
  495. lang = uaql['lang']
  496. n_time = request_dict.get('n_time')
  497. appBundleId = uaql['appBundleId']
  498. tz = uaql['tz']
  499. message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
  500. send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)
  501. try:
  502. print('---')
  503. cli = apns2.APNSClient(mode=APNS_MODE,
  504. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  505. # password=APNS_CONFIG[appBundleId]['password'])
  506. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  507. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  508. # body = json.dumps(push_data)
  509. alert = apns2.PayloadAlert(body=send_text, title=message_title)
  510. payload = apns2.Payload(alert=alert, custom=push_data)
  511. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  512. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  513. # assert res.status_code == 200, res.reason
  514. # assert res.apns_id
  515. print('========')
  516. print(res.status_code)
  517. if res.status_code == 200:
  518. return response.json(0)
  519. else:
  520. return response.json(404, res.reason)
  521. except Exception as e:
  522. print(repr(e))
  523. return response.json(10, repr(e))
  524. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  525. #
  526. qs_list = []
  527. nowTime = int(time.time())
  528. # 设备昵称
  529. userID_ids = []
  530. for dv in uaqs:
  531. userID_id = dv["userID_id"]
  532. if userID_id not in userID_ids:
  533. if dv['uid_set__nickname']:
  534. uid_nickname = dv['uid_set__nickname']
  535. else:
  536. uid_nickname = uid
  537. add_data = {
  538. 'userID_id': dv["userID_id"],
  539. 'eventTime': n_time,
  540. 'eventType': event_type,
  541. 'devUid': uid,
  542. 'devNickName': uid_nickname,
  543. 'Channel': channel,
  544. 'alarm': 'Motion \tChannel:{channel}'.format(channel=channel),
  545. 'is_st': int(is_st),
  546. 'receiveTime': n_time,
  547. 'addTime': nowTime
  548. }
  549. qs_list.append(Equipment_Info(**add_data))
  550. userID_ids.append(userID_id)
  551. if qs_list:
  552. print(1)
  553. Equipment_Info.objects.bulk_create(qs_list)
  554. return True
  555. else:
  556. return False
  557. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  558. # 移动侦测接口
  559. class PushNotificationView(View):
  560. def get(self, request, *args, **kwargs):
  561. request.encoding = 'utf-8'
  562. # operation = kwargs.get('operation')
  563. return self.validation(request.GET)
  564. def post(self, request, *args, **kwargs):
  565. request.encoding = 'utf-8'
  566. # operation = kwargs.get('operation')
  567. return self.validation(request.POST)
  568. def validation(self, request_dict):
  569. etk = request_dict.get('etk', None)
  570. channel = request_dict.get('channel', '1')
  571. n_time = request_dict.get('n_time', None)
  572. event_type = request_dict.get('event_type', None)
  573. is_st = request_dict.get('is_st', None)
  574. eto = ETkObject(etk)
  575. uid = eto.uid
  576. if len(uid) == 20:
  577. redisObj = RedisObject(db=6)
  578. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  579. pkey = '{uid}_ptl'.format(uid=uid)
  580. # 推送时间限制
  581. if redisObj.get_data(key=pkey):
  582. res_data = {'code': 0, 'msg': 'success,!'}
  583. return JsonResponse(status=200, data=res_data)
  584. else:
  585. redisObj.set_data(key=pkey, val=1, expire=60)
  586. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  587. values('token_val', 'app_type', 'appBundleId', 'push_type', 'userID_id', 'userID__NickName', 'lang',
  588. 'tz', 'uid_set__nickname')
  589. if uid_push_qs.exists():
  590. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  591. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  592. self.do_bulk_create_info(uid_push_qs, n_time, channel, event_type, is_st, uid)
  593. if is_st == '0' or is_st == '2':
  594. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  595. elif is_st == '1':
  596. # Endpoint以杭州为例,其它Region请按实际情况填写。
  597. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  598. # 设置此签名URL在60秒内有效。
  599. url = bucket.sign_url('PUT', obj, 7200)
  600. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  601. return JsonResponse(status=200, data=res_data)
  602. elif is_st == '3':
  603. # 人形检测带动图
  604. img_url_list = []
  605. for i in range(int(is_st)):
  606. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  607. format(uid=uid, channel=channel, filename=n_time, st=i)
  608. # 设置此签名URL在60秒内有效。
  609. url = bucket.sign_url('PUT', obj, 7200)
  610. img_url_list.append(url)
  611. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  612. return JsonResponse(status=200, data=res_data)
  613. else:
  614. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  615. else:
  616. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  617. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  618. #
  619. qs_list = []
  620. nowTime = int(time.time())
  621. # 设备昵称
  622. userID_ids = []
  623. for dv in uaqs:
  624. userID_id = dv["userID_id"]
  625. if userID_id not in userID_ids:
  626. if dv['uid_set__nickname']:
  627. uid_nickname = dv['uid_set__nickname']
  628. else:
  629. uid_nickname = uid
  630. add_data = {
  631. 'userID_id': dv["userID_id"],
  632. 'eventTime': n_time,
  633. 'eventType': event_type,
  634. 'devUid': uid,
  635. 'devNickName': uid_nickname,
  636. 'Channel': channel,
  637. 'alarm': 'Motion \tChannel:{channel}'.format(channel=channel),
  638. 'is_st': int(is_st),
  639. 'receiveTime': n_time,
  640. 'addTime': nowTime
  641. }
  642. qs_list.append(Equipment_Info(**add_data))
  643. userID_ids.append(userID_id)
  644. if qs_list:
  645. print(1)
  646. Equipment_Info.objects.bulk_create(qs_list)
  647. return True
  648. else:
  649. return False