DetectController.py 33 KB

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