DetectController.py 32 KB

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