DetectController.py 42 KB

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