DetectController.py 37 KB

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