DetectController.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  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. if uid_push_qs.exists():
  236. uid_push_update_dict = {
  237. 'appBundleId': appBundleId,
  238. 'app_type': app_type,
  239. 'push_type': push_type,
  240. 'token_val': token_val,
  241. 'updTime': nowTime,
  242. 'lang': lang,
  243. 'tz': tz
  244. }
  245. uid_push_qs.update(**uid_push_update_dict)
  246. else:
  247. # uid_set_id = uid_set_qs[0].id
  248. uid_push_create_dict = {
  249. 'uid_set_id': uid_set_id,
  250. 'userID_id': userID,
  251. 'appBundleId': appBundleId,
  252. 'app_type': app_type,
  253. 'push_type': push_type,
  254. 'token_val': token_val,
  255. 'm_code': m_code,
  256. 'addTime': nowTime,
  257. 'updTime': nowTime,
  258. 'lang': lang,
  259. 'tz': tz
  260. }
  261. # 绑定设备推送
  262. UidPushModel.objects.create(**uid_push_create_dict)
  263. if interval:
  264. self.do_delete_redis(uid, int(interval))
  265. else:
  266. self.do_delete_redis(uid)
  267. # utko = UidTokenObject()
  268. # # right
  269. # utko.generate(data={'uid': uid})
  270. etkObj = ETkObject(etk='')
  271. etk = etkObj.encrypt(uid)
  272. detectUrl = "{DETECT_PUSH_DOMAIN}notify/push?etk={etk}". \
  273. format(etk=etk, DETECT_PUSH_DOMAIN=DETECT_PUSH_DOMAIN)
  274. return response.json(0, {'detectUrl': detectUrl})
  275. else:
  276. return response.json(14)
  277. def do_delete_redis(self, uid, detect_interval=0):
  278. keyPattern = '{uid}*'.format(uid=uid)
  279. redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')
  280. keys = redisObj.get_keys(keyPattern)
  281. if keys:
  282. for key in keys:
  283. key = key.decode()
  284. if detect_interval == 0:
  285. redisObj.del_data(key=key)
  286. elif key.find('plt') != -1:
  287. continue
  288. elif key.find('flag') != -1:
  289. redisObj.set_data(key=key, val=1, expire=detect_interval)
  290. else:
  291. redisObj.del_data(key=key)
  292. def do_update_interval(self, userID, request_dict, response):
  293. uid = request_dict.get('uid', None)
  294. interval = request_dict.get('interval', None)
  295. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  296. if dvqs.exists():
  297. uid_set_qs = UidSetModel.objects. \
  298. filter(uid=uid, uidpushmodel__userID_id=userID)
  299. # redisObj = RedisObject(db=8)
  300. # redisObj.del_data(key='uid_qs_' + userID)
  301. if uid_set_qs.exists():
  302. uid_set_qs.update(interval=int(interval))
  303. else:
  304. return response.json(173)
  305. else:
  306. return response.json(0)
  307. # http://192.168.136.40:8077/notify/push?uidToken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJUTjdNUEUzMjExVUU3NkFQMTExQSJ9.k501567VdnhFpn_ygzGRDat3Kqlz5CsEA9jAC2dDk_g&obj=12341234&n_time=1234561234
  308. # http://test.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  309. # 移动侦测接口
  310. class NotificationView(View):
  311. def get(self, request, *args, **kwargs):
  312. request.encoding = 'utf-8'
  313. # operation = kwargs.get('operation')
  314. return self.validation(request.GET)
  315. def post(self, request, *args, **kwargs):
  316. request.encoding = 'utf-8'
  317. # operation = kwargs.get('operation')
  318. return self.validation(request.POST)
  319. def validation(self, request_dict):
  320. response = ResponseObject()
  321. uidToken = request_dict.get('uidToken', None)
  322. etk = request_dict.get('etk', None)
  323. channel = request_dict.get('channel', '1')
  324. n_time = request_dict.get('n_time', None)
  325. event_type = request_dict.get('event_type', None)
  326. is_st = request_dict.get('is_st', None)
  327. if not all([channel, n_time]):
  328. return JsonResponse(status=200, data={
  329. 'code': 444,
  330. 'msg': 'param is wrong'})
  331. # return response.json(444)
  332. if etk:
  333. eto = ETkObject(etk)
  334. uid = eto.uid
  335. if len(uid) != 20:
  336. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  337. else:
  338. utko = UidTokenObject(uidToken)
  339. uid = utko.UID
  340. # utko = UidTokenObject(uidToken)
  341. # uid = utko.UID
  342. detect_group = UidSetModel.objects.filter(uid=uid). \
  343. values('detect_group')
  344. event_type = detect_group
  345. # 新增 移动侦测
  346. if event_type == '0':
  347. self.detect_group_push(self, request_dict, uid, response, channel, n_time, event_type, is_st)
  348. # 新增 pir侦测
  349. if event_type == '1':
  350. self.detect_group_push(self, request_dict, uid, response, channel, n_time, event_type, is_st)
  351. # 新增 移动侦测和pir侦测
  352. if event_type == '01':
  353. self.detect_group_push(self, request_dict, uid, response, channel, n_time, event_type, is_st)
  354. # 新增 把代码封装以便后面分侦测类型
  355. def detect_group_push(self, request_dict, uid, response, channel, n_time, event_type, is_st):
  356. redisObj = RedisObject(db=6)
  357. pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  358. if redisObj.get_data(key=pkey):
  359. res_data = {'code': 0, 'msg': 'success,!'}
  360. return JsonResponse(status=200, data=res_data)
  361. else:
  362. # 设置推送间隔60秒一次
  363. redisObj.set_data(key=pkey, val=1, expire=60)
  364. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  365. values('token_val', 'app_type', 'appBundleId',
  366. 'push_type', 'userID_id', 'userID__NickName',
  367. 'lang', 'tz', 'uid_set__nickname')
  368. if uid_push_qs.exists():
  369. nickname = uid_push_qs[0]['uid_set__nickname']
  370. if not nickname:
  371. nickname = uid
  372. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  373. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  374. for up in uid_push_qs:
  375. push_type = up['push_type']
  376. # ios apns
  377. print(push_type)
  378. if push_type == 0:
  379. self.do_apns(request_dict, up, response, uid, channel, nickname)
  380. # android gcm
  381. elif push_type == 1:
  382. self.do_fcm(request_dict, up, response, uid, channel, nickname)
  383. # self.do_gmc(request_dict, up, response, uid, channel,nickname)
  384. # android jpush
  385. elif push_type == 2:
  386. self.do_jpush(request_dict, up, response, uid, channel, nickname)
  387. # self.do_save_equipment_info(ua, n_time, channel, event_type, is_st)
  388. # 需求不一样,所以这么做的
  389. self.do_bulk_create_info(uid_push_qs, n_time, channel, event_type, is_st, uid)
  390. if is_st == '0' or is_st == '2':
  391. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  392. elif is_st == '1':
  393. # Endpoint以杭州为例,其它Region请按实际情况填写。
  394. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  395. # 设置此签名URL在60秒内有效。
  396. url = bucket.sign_url('PUT', obj, 7200)
  397. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  398. return JsonResponse(status=200, data=res_data)
  399. elif is_st == '3':
  400. # 人形检测带动图
  401. # Endpoint以杭州为例,其它Region请按实际情况填写。
  402. img_url_list = []
  403. for i in range(int(is_st)):
  404. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  405. format(uid=uid, channel=channel, filename=n_time, st=i)
  406. # 设置此签名URL在60秒内有效。
  407. url = bucket.sign_url('PUT', obj, 7200)
  408. img_url_list.append(url)
  409. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  410. return JsonResponse(status=200, data=res_data)
  411. else:
  412. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  413. def do_jpush(self, request_dict, uaql, response, uid, channel, nickname):
  414. event_type = request_dict.get('event_type', None)
  415. n_time = request_dict.get('n_time', None)
  416. appBundleId = uaql['appBundleId']
  417. token_val = uaql['token_val']
  418. lang = uaql['lang']
  419. tz = uaql['tz']
  420. response = ResponseObject()
  421. app_key = JPUSH_CONFIG[appBundleId]['Key']
  422. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  423. # 此处换成各自的app_key和master_secre
  424. _jpush = jpush.JPush(app_key, master_secret)
  425. push = _jpush.create_push()
  426. # if you set the logging level to "DEBUG",it will show the debug logging.
  427. _jpush.set_logging("DEBUG")
  428. # push.audience = jpush.all_
  429. push.audience = jpush.registration_id(token_val)
  430. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  431. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  432. message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
  433. send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)
  434. android = jpush.android(alert=send_text, priority=1, style=1, alert_type=7,
  435. big_text=send_text, title=message_title,
  436. extras=push_data)
  437. push.notification = jpush.notification(android=android)
  438. push.platform = jpush.all_
  439. try:
  440. res = push.send()
  441. print(res)
  442. except Exception as e:
  443. print("Exception")
  444. print(repr(e))
  445. return response.json(10, repr(e))
  446. else:
  447. return response.json(0)
  448. def get_message_title(self, appBundleId, nickname):
  449. package_title_config = {
  450. 'com.ansjer.customizedd_a': 'DVS',
  451. 'com.ansjer.zccloud_a': 'ZosiSmart',
  452. 'com.ansjer.zccloud_ab': '周视',
  453. 'com.ansjer.adcloud_a': 'ADCloud',
  454. 'com.ansjer.adcloud_ab': 'ADCloud',
  455. 'com.ansjer.accloud_a': 'ACCloud',
  456. 'com.ansjer.loocamccloud_a': 'Loocam',
  457. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  458. 'com.ansjer.customizedb_a': 'COCOONHD',
  459. 'com.ansjer.customizeda_a': 'Guardian365',
  460. 'com.ansjer.customizedc_a': 'PatrolSecure',
  461. }
  462. if appBundleId in package_title_config.keys():
  463. return package_title_config[appBundleId] + '(' + nickname + ')'
  464. else:
  465. return nickname
  466. def get_send_text(self, channel, n_time, lang, tz, event_type):
  467. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  468. msg_type = ''
  469. if int(event_type) == 704:
  470. msg_type = 'battery is too low'
  471. if lang == 'cn':
  472. msg_type = '电池电量过低'
  473. send_text = '{msg_type}channel:{channel} date:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  474. if lang == 'cn':
  475. send_text = '{msg_type}通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  476. return send_text
  477. def do_fcm(self, request_dict, uaql, response, uid, channel, nickname):
  478. n_time = request_dict.get('n_time')
  479. appBundleId = uaql['appBundleId']
  480. token_val = uaql['token_val']
  481. lang = uaql['lang']
  482. tz = uaql['tz']
  483. try:
  484. serverKey = FCM_CONFIG[appBundleId]
  485. except Exception as e:
  486. return response.json(404)
  487. event_type = request_dict.get('event_type', None)
  488. push_service = FCMNotification(api_key=serverKey)
  489. registration_id = token_val
  490. message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
  491. send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)
  492. 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. result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title,
  495. message_body=send_text, data_message=data,
  496. extra_kwargs={
  497. 'default_vibrate_timings': True,
  498. 'default_sound': True,
  499. 'default_light_settings': True
  500. })
  501. response = ResponseObject()
  502. return response.json(0, result)
  503. def do_apns(self, request_dict, uaql, response, uid, channel, nickname):
  504. event_type = request_dict.get('event_type', None)
  505. token_val = uaql['token_val']
  506. lang = uaql['lang']
  507. n_time = request_dict.get('n_time')
  508. appBundleId = uaql['appBundleId']
  509. tz = uaql['tz']
  510. message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)
  511. send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)
  512. try:
  513. print('---')
  514. cli = apns2.APNSClient(mode=APNS_MODE,
  515. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  516. # password=APNS_CONFIG[appBundleId]['password'])
  517. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  518. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  519. # body = json.dumps(push_data)
  520. alert = apns2.PayloadAlert(body=send_text, title=message_title)
  521. payload = apns2.Payload(alert=alert, custom=push_data)
  522. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  523. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  524. # assert res.status_code == 200, res.reason
  525. # assert res.apns_id
  526. print('========')
  527. print(res.status_code)
  528. if res.status_code == 200:
  529. return response.json(0)
  530. else:
  531. return response.json(404, res.reason)
  532. except Exception as e:
  533. print(repr(e))
  534. return response.json(10, repr(e))
  535. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  536. #
  537. qs_list = []
  538. nowTime = int(time.time())
  539. # 设备昵称
  540. userID_ids = []
  541. for dv in uaqs:
  542. userID_id = dv["userID_id"]
  543. if userID_id not in userID_ids:
  544. if dv['uid_set__nickname']:
  545. uid_nickname = dv['uid_set__nickname']
  546. else:
  547. uid_nickname = uid
  548. add_data = {
  549. 'userID_id': dv["userID_id"],
  550. 'eventTime': n_time,
  551. 'eventType': event_type,
  552. 'devUid': uid,
  553. 'devNickName': uid_nickname,
  554. 'Channel': channel,
  555. 'alarm': 'Motion \tChannel:{channel}'.format(channel=channel),
  556. 'is_st': int(is_st),
  557. 'receiveTime': n_time,
  558. 'addTime': nowTime
  559. }
  560. qs_list.append(Equipment_Info(**add_data))
  561. userID_ids.append(userID_id)
  562. if qs_list:
  563. print(1)
  564. Equipment_Info.objects.bulk_create(qs_list)
  565. return True
  566. else:
  567. return False
  568. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  569. # 移动侦测接口
  570. class PushNotificationView(View):
  571. def get(self, request, *args, **kwargs):
  572. request.encoding = 'utf-8'
  573. # operation = kwargs.get('operation')
  574. return self.validation(request.GET)
  575. def post(self, request, *args, **kwargs):
  576. request.encoding = 'utf-8'
  577. # operation = kwargs.get('operation')
  578. return self.validation(request.POST)
  579. def validation(self, request_dict):
  580. etk = request_dict.get('etk', None)
  581. channel = request_dict.get('channel', '1')
  582. n_time = request_dict.get('n_time', None)
  583. event_type = request_dict.get('event_type', None)
  584. is_st = request_dict.get('is_st', None)
  585. eto = ETkObject(etk)
  586. uid = eto.uid
  587. if len(uid) == 20:
  588. redisObj = RedisObject(db=6)
  589. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  590. pkey = '{uid}_ptl'.format(uid=uid)
  591. # 推送时间限制
  592. if redisObj.get_data(key=pkey):
  593. res_data = {'code': 0, 'msg': 'success,!'}
  594. return JsonResponse(status=200, data=res_data)
  595. else:
  596. redisObj.set_data(key=pkey, val=1, expire=60)
  597. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  598. values('token_val', 'app_type', 'appBundleId', 'push_type', 'userID_id', 'userID__NickName', 'lang',
  599. 'tz', 'uid_set__nickname')
  600. if uid_push_qs.exists():
  601. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  602. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  603. self.do_bulk_create_info(uid_push_qs, n_time, channel, event_type, is_st, uid)
  604. if is_st == '0' or is_st == '2':
  605. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  606. elif is_st == '1':
  607. # Endpoint以杭州为例,其它Region请按实际情况填写。
  608. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  609. # 设置此签名URL在60秒内有效。
  610. url = bucket.sign_url('PUT', obj, 7200)
  611. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  612. return JsonResponse(status=200, data=res_data)
  613. elif is_st == '3':
  614. # 人形检测带动图
  615. img_url_list = []
  616. for i in range(int(is_st)):
  617. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  618. format(uid=uid, channel=channel, filename=n_time, st=i)
  619. # 设置此签名URL在60秒内有效。
  620. url = bucket.sign_url('PUT', obj, 7200)
  621. img_url_list.append(url)
  622. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  623. return JsonResponse(status=200, data=res_data)
  624. else:
  625. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  626. else:
  627. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  628. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  629. #
  630. qs_list = []
  631. nowTime = int(time.time())
  632. # 设备昵称
  633. userID_ids = []
  634. for dv in uaqs:
  635. userID_id = dv["userID_id"]
  636. if userID_id not in userID_ids:
  637. if dv['uid_set__nickname']:
  638. uid_nickname = dv['uid_set__nickname']
  639. else:
  640. uid_nickname = uid
  641. add_data = {
  642. 'userID_id': dv["userID_id"],
  643. 'eventTime': n_time,
  644. 'eventType': event_type,
  645. 'devUid': uid,
  646. 'devNickName': uid_nickname,
  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