DetectController.py 34 KB

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