DetectController.py 32 KB

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