DetectControllerV2.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @AUTHOR: ASJRD018
  6. @NAME: AnsjerFormal
  7. @software: PyCharm
  8. @DATE: 2019/1/14 15:57
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: DetectController.py
  12. @Contact: chanjunkai@163.com
  13. """
  14. import os
  15. import time
  16. import apns2
  17. import jpush as jpush
  18. import oss2
  19. from django.http import JsonResponse
  20. from django.views.generic.base import View
  21. from pyfcm import FCMNotification
  22. from Object.RedisObject import RedisObject
  23. from Ansjer.config import DETECT_PUSH_DOMAIN, DETECT_PUSH_DOMAINS, DETECT_PUSH_DOMAIN_JIUAN, DETECT_PUSH_DOMAINS_JIUAN,\
  24. SERVER_DOMAIN, SERVER_DOMAIN_SSL, \
  25. OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, \
  26. JPUSH_CONFIG, FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE, SERVER_TYPE
  27. from Model.models import Device_Info, VodHlsModel, Equipment_Info, UidSetModel, UidPushModel, CompanyModel, SysMsgModel
  28. from Object.ETkObject import ETkObject
  29. from Object.RedisObject import RedisObject
  30. from Object.ResponseObject import ResponseObject
  31. from Object.TokenObject import TokenObject
  32. from Object.UidTokenObject import UidTokenObject
  33. from Service.CommonService import CommonService
  34. from Service.ModelService import ModelService
  35. import boto3
  36. import botocore
  37. from botocore import client
  38. '''
  39. http://test.push.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJUNEFaM0NVS0NFUkg5RlpBMTExQSJ9.GtrXeq5gb2Z9M3mKECxi9eNQbPxqC-6PtgJkOOg6PwI&n_time=1598456451&channel=1&event_type=1&is_st=1
  40. http://push.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJUNEFaM0NVS0NFUkg5RlpBMTExQSJ9.GtrXeq5gb2Z9M3mKECxi9eNQbPxqC-6PtgJkOOg6PwI&n_time=1598456451&channel=1&event_type=1&is_st=1
  41. 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
  42. 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
  43. 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
  44. detect/changeStatus
  45. '''
  46. class DetectControllerViewV2(View):
  47. def get(self, request, *args, **kwargs):
  48. request.encoding = 'utf-8'
  49. operation = kwargs.get('operation')
  50. # self.ip = CommonService.get_ip_address(request)
  51. return self.validation(request.GET, operation)
  52. def post(self, request, *args, **kwargs):
  53. request.encoding = 'utf-8'
  54. operation = kwargs.get('operation')
  55. # self.ip = CommonService.get_ip_address(request)
  56. return self.validation(request.POST, operation)
  57. def validation(self, request_dict, operation):
  58. response = ResponseObject()
  59. if operation is None:
  60. return response.json(444, 'error path')
  61. token = request_dict.get('token', None)
  62. tko = TokenObject(token)
  63. if tko.code == 0:
  64. userID = tko.userID
  65. # 修改推送设置
  66. if operation == 'changeStatus':
  67. print("进入changeStatus")
  68. return self.do_change_status(userID, request_dict, response)
  69. # 查询推送信息
  70. elif operation == 'queryInfo':
  71. return self.do_query(request_dict, response, userID)
  72. # 更新推送延迟
  73. elif operation == 'updateInterval':
  74. return self.do_update_interval(userID, request_dict, response)
  75. else:
  76. return response.json(414)
  77. else:
  78. return response.json(tko.code)
  79. def do_change_status(self, userID, request_dict, response):
  80. token_val = request_dict.get('token_val', None)
  81. appBundleId = request_dict.get('appBundleId', None)
  82. app_type = request_dict.get('app_type', None)
  83. push_type = request_dict.get('push_type', None)
  84. status = request_dict.get('status', None)
  85. m_code = request_dict.get('m_code', None)
  86. uid = request_dict.get('uid', None)
  87. # 设备语言
  88. lang = request_dict.get('lang', 'en')
  89. tz = request_dict.get('tz', '0')
  90. company_secrete = request_dict.get('company_secrete', None)
  91. region = request_dict.get('region', None) # app必须传:2:国内 1:国外
  92. if not region:
  93. return response.json(444, 'region')
  94. region = int(region)
  95. # 消息提醒功能新增
  96. # 如果传空上来,就默认为0
  97. if tz == '':
  98. tz = 0
  99. detect_group = request_dict.get('detect_group', None)
  100. interval = request_dict.get('interval', None)
  101. if not status:
  102. return response.json(444, 'status')
  103. if not company_secrete:
  104. return response.json(444, 'company_secrete')
  105. company = CompanyModel.objects.filter(secret=company_secrete)
  106. if not company.exists():
  107. return response.json(444, 'company_secrete')
  108. # 关闭推送
  109. if not all([appBundleId, app_type, token_val, uid, m_code]):
  110. return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
  111. # 判断推送类型对应key是否存在
  112. print('push_type:', push_type)
  113. if push_type == '0':
  114. if appBundleId not in APNS_CONFIG.keys():
  115. return response.json(904)
  116. elif push_type == '1':
  117. if appBundleId not in FCM_CONFIG.keys():
  118. return response.json(904)
  119. elif push_type == '2':
  120. if appBundleId not in JPUSH_CONFIG.keys():
  121. return response.json(904)
  122. else:
  123. return response.json(173)
  124. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  125. status = int(status)
  126. # 获取用户区域
  127. # ip = self.ip
  128. # ipInfo = CommonService.getIpIpInfo(ip=ip, lang='EN')
  129. # area = ipInfo['country_name']
  130. # if area == 'China':
  131. # DETECT_PUSH_DOMAIN_V2 = 'cn.push.dvema.com'
  132. # else:
  133. # DETECT_PUSH_DOMAIN_V2 = 'en.push.dvema.com'
  134. nowTime = int(time.time())
  135. if dvqs.exists():
  136. # 修改状态
  137. dvqs.update(NotificationMode=status)
  138. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  139. # uid配置信息是否存在
  140. if uid_set_qs.exists():
  141. uid_set_id = uid_set_qs[0].id
  142. qs_data = {
  143. 'detect_status': status,
  144. 'updTime': nowTime,
  145. }
  146. if interval:
  147. qs_data['detect_interval'] = int(interval)
  148. if detect_group:
  149. qs_data['detect_group'] = detect_group
  150. print(qs_data)
  151. uid_set_qs.update(**qs_data)
  152. else:
  153. qs_data = {
  154. 'uid': uid,
  155. 'addTime': nowTime,
  156. 'updTime': nowTime,
  157. 'detect_status': status,
  158. }
  159. if interval:
  160. qs_data['detect_interval'] = int(interval)
  161. if detect_group:
  162. qs_data['detect_group'] = detect_group
  163. # 添加设备配置
  164. uid_set_qs = UidSetModel.objects.create(**qs_data)
  165. uid_set_id = uid_set_qs.id
  166. if status == 0:
  167. UidPushModel.objects.filter(uid_set__uid=uid).delete()
  168. # 状态为0的时候删除redis缓存数据
  169. self.do_delete_redis(uid)
  170. return response.json(0)
  171. elif status == 1:
  172. uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
  173. # ykey = '{uid}_redis_qs'.format(uid=uid)
  174. # redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')
  175. # redisObj.del_data(key=ykey)
  176. if uid_push_qs.exists():
  177. uid_push_update_dict = {
  178. 'appBundleId': appBundleId,
  179. 'app_type': app_type,
  180. 'push_type': push_type,
  181. 'token_val': token_val,
  182. 'updTime': nowTime,
  183. 'lang': lang,
  184. 'tz': tz
  185. }
  186. uid_push_qs.update(**uid_push_update_dict)
  187. else:
  188. # uid_set_id = uid_set_qs[0].id
  189. uid_push_create_dict = {
  190. 'uid_set_id': uid_set_id,
  191. 'userID_id': userID,
  192. 'appBundleId': appBundleId,
  193. 'app_type': app_type,
  194. 'push_type': push_type,
  195. 'token_val': token_val,
  196. 'm_code': m_code,
  197. 'addTime': nowTime,
  198. 'updTime': nowTime,
  199. 'lang': lang,
  200. 'tz': tz
  201. }
  202. # 绑定设备推送
  203. UidPushModel.objects.create(**uid_push_create_dict)
  204. if interval:
  205. self.do_delete_redis(uid, int(interval))
  206. else:
  207. self.do_delete_redis(uid)
  208. # utko = UidTokenObject()
  209. # # right
  210. # utko.generate(data={'uid': uid})
  211. etkObj = ETkObject(etk='')
  212. etk = etkObj.encrypt(uid)
  213. if company_secrete == 'MTEyMTNB':
  214. url = DETECT_PUSH_DOMAIN
  215. urls = DETECT_PUSH_DOMAINS
  216. else:
  217. url = DETECT_PUSH_DOMAIN_JIUAN
  218. urls = DETECT_PUSH_DOMAINS_JIUAN
  219. detectUrl = "{DETECT_PUSH_DOMAIN}notify/push?etk={etk}&company_secrete={company_secrete}&region={region}". \
  220. format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN=url, region=region)
  221. detectUrls = "{DETECT_PUSH_DOMAIN_V2}notify/push?etk={etk}&company_secrete={company_secrete}&region={region}". \
  222. format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN_V2=urls, region=region)
  223. return response.json(0, {'detectUrl': detectUrl, 'detectUrls': detectUrls})
  224. else:
  225. return response.json(14)
  226. def do_delete_redis(self, uid, detect_interval=0):
  227. keyPattern = '{uid}*'.format(uid=uid)
  228. redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')
  229. keys = redisObj.get_keys(keyPattern)
  230. if keys:
  231. for key in keys:
  232. key = key.decode()
  233. if detect_interval == 0:
  234. redisObj.del_data(key=key)
  235. elif key.find('plt') != -1:
  236. continue
  237. elif key.find('flag') != -1:
  238. redisObj.set_data(key=key, val=1, expire=detect_interval)
  239. else:
  240. redisObj.del_data(key=key)
  241. def do_query(self, request_dict, response, userID):
  242. page = int(request_dict.get('page', None))
  243. line = int(request_dict.get('line', None))
  244. if not page or not line:
  245. return response.json(444, 'page,line')
  246. startTime = request_dict.get('startTime', None)
  247. endTime = request_dict.get('endTime', None)
  248. eventType = request_dict.get('eventType', None)
  249. region = request_dict.get('region', None)
  250. if not region:
  251. return response.json(444, 'region')
  252. region = int(region)
  253. qs = Equipment_Info.objects.filter(userID_id=userID).order_by('-eventTime')
  254. if startTime and endTime:
  255. qs = qs.filter(eventTime__range=(startTime, endTime))
  256. if eventType:
  257. qs = qs.filter(eventType=eventType)
  258. uids = request_dict.get('uids', None)
  259. if uids:
  260. uid_list = uids.split(',')
  261. qs = qs.filter(devUid__in=uid_list)
  262. dvqs = Device_Info.objects.filter(UID__in=uid_list, userID_id=userID).values('UID', 'Type', 'NickName')
  263. uid_type_dict = {}
  264. for dv in dvqs:
  265. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  266. else:
  267. dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
  268. uid_type_dict = {}
  269. for dv in dvqs:
  270. uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
  271. # print(uid_type_dict)
  272. if not qs.exists():
  273. return response.json(0, {'datas': [], 'count': 0})
  274. qs = qs.values('id', 'devUid', 'devNickName', 'Channel', 'eventType', 'status', 'alarm', 'eventTime',
  275. 'receiveTime', 'is_st', 'addTime', 'storage_location')
  276. count = qs.count()
  277. qr = qs[(page - 1) * line:page * line]
  278. res = []
  279. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  280. oss_img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  281. aws_s3_guonei = boto3.client(
  282. 's3',
  283. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  284. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  285. config=botocore.client.Config(signature_version='s3v4'),
  286. region_name='cn-northwest-1'
  287. )
  288. aws_s3_guowai = boto3.client(
  289. 's3',
  290. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  291. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  292. config=botocore.client.Config(signature_version='s3v4'),
  293. region_name='us-east-1'
  294. )
  295. # vod_time_list = []
  296. for p in qr:
  297. devUid = p['devUid']
  298. eventTime = p['eventTime']
  299. channel = p['Channel']
  300. storage_location = p['storage_location']
  301. if p['is_st'] == 1:
  302. thumbspng = '{uid}/{channel}/{time}.jpeg'.format(uid=devUid, channel=p['Channel'], time=eventTime)
  303. if storage_location == 1: # oss
  304. response_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  305. p['img'] = response_url
  306. p['img_list'] = [response_url]
  307. elif region == 2 and storage_location == 2: # 2:国内,aws
  308. response_url = aws_s3_guonei.generate_presigned_url('get_object',
  309. Params={'Bucket': 'push', 'Key': thumbspng},
  310. ExpiresIn=300)
  311. p['img'] = response_url
  312. p['img_list'] = [response_url]
  313. elif region == 1 and storage_location == 2: # 1:国外,aws
  314. response_url = aws_s3_guowai.generate_presigned_url('get_object',
  315. Params={'Bucket': 'foreignpush', 'Key': thumbspng},
  316. ExpiresIn=300)
  317. p['img'] = response_url
  318. p['img_list'] = [response_url]
  319. elif p['is_st'] == 2:
  320. # 列表装载回放时间戳标记
  321. vodqs = VodHlsModel.objects.filter(uid=devUid, channel=channel, time=int(eventTime)) \
  322. .values("bucket__bucket", "bucket__endpoint")
  323. # print(vodqs)
  324. if vodqs.exists():
  325. bucket_name = vodqs[0]['bucket__bucket']
  326. endpoint = vodqs[0]['bucket__endpoint']
  327. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  328. ts = '{uid}/vod{channel}/{etime}/ts0.ts'.format(uid=devUid, channel=p['Channel'], etime=eventTime)
  329. if storage_location == 1: # oss
  330. thumb0 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  331. thumb1 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  332. thumb2 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  333. # thumb3 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_3000,w_700'})
  334. p['img_list'] = [thumb0, thumb1, thumb2]
  335. elif region == 2 and storage_location == 2: # 2:国内,aws
  336. thumb = aws_s3_guonei.generate_presigned_url('get_object',
  337. Params={'Bucket': 'push', 'Key': ts},
  338. ExpiresIn=3600)
  339. p['img_list'] = [thumb]
  340. elif region == 1 and storage_location == 2: # 1:国外,aws
  341. thumb = aws_s3_guowai.generate_presigned_url('get_object',
  342. Params={'Bucket': 'foreignpush', 'Key': ts},
  343. ExpiresIn=3600)
  344. p['img_list'] = [thumb]
  345. elif p['is_st'] == 3:
  346. # 列表装载回放时间戳标记
  347. p['img_list'] = []
  348. for i in range(p['is_st']):
  349. thumbspng = '{uid}/{channel}/{time}_{st}.jpeg'.format(uid=devUid, channel=p['Channel'], time=eventTime, st=i)
  350. if storage_location == 1: # oss
  351. img = oss_img_bucket.sign_url('GET', thumbspng, 300)
  352. p['img_list'].append(img)
  353. elif region == 2 and storage_location == 2: # 2:国内,aws
  354. response_url = aws_s3_guonei.generate_presigned_url('get_object',
  355. Params={'Bucket': 'push', 'Key': thumbspng},
  356. ExpiresIn=300)
  357. img = response_url
  358. p['img_list'].append(img)
  359. elif region == 1 and storage_location == 2: # 1:国外,aws
  360. response_url = aws_s3_guowai.generate_presigned_url('get_object',
  361. Params={'Bucket': 'foreignpush', 'Key': thumbspng},
  362. ExpiresIn=300)
  363. img = response_url
  364. p['img_list'].append(img)
  365. if devUid in uid_type_dict.keys():
  366. p['uid_type'] = uid_type_dict[devUid]['type']
  367. p['devNickName'] = uid_type_dict[devUid]['NickName']
  368. else:
  369. p['uid_type'] = ''
  370. res.append(p)
  371. return response.json(0, {'datas': res, 'count': count})
  372. def do_update_interval(self, userID, request_dict, response):
  373. uid = request_dict.get('uid', None)
  374. interval = request_dict.get('interval', None)
  375. dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
  376. if dvqs.exists():
  377. uid_set_qs = UidSetModel.objects. \
  378. filter(uid=uid, uidpushmodel__userID_id=userID)
  379. # redisObj = RedisObject(db=8)
  380. # redisObj.del_data(key='uid_qs_' + userID)
  381. if uid_set_qs.exists():
  382. uid_set_qs.update(interval=int(interval))
  383. else:
  384. return response.json(173)
  385. else:
  386. return response.json(0)
  387. # 设备调用接口
  388. # 移动侦测接口
  389. class NotificationView(View):
  390. def get(self, request, *args, **kwargs):
  391. request.encoding = 'utf-8'
  392. return self.validation(request.GET)
  393. def post(self, request, *args, **kwargs):
  394. request.encoding = 'utf-8'
  395. return self.validation(request.POST)
  396. def validation(self, request_dict):
  397. uidToken = request_dict.get('uidToken', None)
  398. etk = request_dict.get('etk', None)
  399. channel = request_dict.get('channel', '1')
  400. n_time = request_dict.get('n_time', None)
  401. event_type = request_dict.get('event_type', None)
  402. is_st = request_dict.get('is_st', None)
  403. company_secrete = request_dict.get('company_secrete', None)
  404. region = request_dict.get('region', None)
  405. if not region:
  406. return JsonResponse(status=200, data={'code': 404, 'msg': 'region is not exist'})
  407. region = int(region)
  408. # print("aaa")
  409. # return JsonResponse(0,safe=False)
  410. if not all([channel, n_time]):
  411. return JsonResponse(status=200, data={
  412. 'code': 444,
  413. 'msg': 'param is wrong'})
  414. if etk:
  415. eto = ETkObject(etk)
  416. uid = eto.uid
  417. if len(uid) != 20 and len(uid) != 14:
  418. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  419. else:
  420. utko = UidTokenObject(uidToken)
  421. uid = utko.UID
  422. pkey = '{uid}_{channel}_{event_type}_ptl'.format(uid=uid, event_type=event_type, channel=channel)
  423. # ykey = 'MUJ887NLR8K8GBM9111A_redis_qs'.format(uid=uid)
  424. ykey = '{uid}_redis_qs'.format(uid=uid)
  425. # dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
  426. is_sys_msg = self.is_sys_msg(int(event_type))
  427. if is_sys_msg is True:
  428. dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
  429. else:
  430. dkey = '{uid}_{channel}_flag'.format(uid=uid, channel=channel)
  431. # 判断redisObj.get_data(key=pkey):不为空
  432. redisObj = RedisObject(db=6)
  433. have_ykey = redisObj.get_data(key=ykey) # uid_set 数据库缓存
  434. have_pkey = redisObj.get_data(key=pkey) # 一分钟限制key
  435. have_dkey = redisObj.get_data(key=dkey) # 推送类型限制
  436. # 一分钟外,推送开启状态
  437. detect_med_type = 0 # 0推送旧机制 1存库不推送,2推送存库
  438. # 暂时注销
  439. if have_pkey:
  440. if SERVER_TYPE != "Ansjer.formal_settings":
  441. res_data = {'code': 0, 'msg': 'Push once every 10 seconds'}
  442. else:
  443. res_data = {'code': 0, 'msg': 'Push it once a minute'}
  444. return JsonResponse(status=200, data=res_data)
  445. # 数据库读取数据
  446. if have_ykey:
  447. redis_list = eval(redisObj.get_data(key=ykey))
  448. print(have_ykey)
  449. if not redis_list:
  450. # 从数据库查询出来
  451. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  452. values('token_val', 'app_type', 'appBundleId', 'm_code',
  453. 'push_type', 'userID_id', 'userID__NickName',
  454. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  455. 'uid_set__channel')
  456. print(uid_push_qs)
  457. # 新建一个list接收数据
  458. redis_list = []
  459. # 把数据库数据追加进redis_list
  460. for qs in uid_push_qs:
  461. redis_list.append(qs)
  462. # 修改redis数据,并设置过期时间为10分钟
  463. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  464. if not redis_list:
  465. res_data = {'code': 404, 'msg': 'error !'}
  466. return JsonResponse(status=200, data=res_data)
  467. else:
  468. # 从数据库查询出来
  469. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid,uid_set__detect_status=1). \
  470. values('token_val', 'app_type', 'appBundleId','m_code',
  471. 'push_type', 'userID_id', 'userID__NickName',
  472. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  473. 'uid_set__channel')
  474. print(uid_push_qs)
  475. # 新建一个list接收数据
  476. redis_list = []
  477. # 把数据库数据追加进redis_list
  478. for qs in uid_push_qs:
  479. redis_list.append(qs)
  480. # 修改redis数据,并设置过期时间为10分钟
  481. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  482. if not redis_list:
  483. res_data = {'code': 404, 'msg': 'error !'}
  484. return JsonResponse(status=200, data=res_data)
  485. # 此时应该更新一下redis里面的dkey的有效时间
  486. # detect_interval = redis_list[0]['uid_set__detect_interval']
  487. # tmp_channel = redis_list[0]['uid_set__channel']
  488. # self.do_update_detect_interval(uid, tmp_channel, redisObj, detect_interval)
  489. if not redis_list:
  490. print("没有redi_list")
  491. res_data = {'code': 0, 'msg': 'no redi_list success!'}
  492. return JsonResponse(status=200, data=res_data)
  493. # is_sys_msg = self.is_sys_msg(int(event_type))
  494. nickname = redis_list[0]['uid_set__nickname']
  495. detect_interval = redis_list[0]['uid_set__detect_interval']
  496. detect_group = redis_list[0]['uid_set__detect_group']
  497. now_time = int(time.time())
  498. if not nickname:
  499. nickname = uid
  500. if detect_group is not None:
  501. if have_dkey:
  502. detect_med_type = 1 # 1为存库不推送
  503. else:
  504. detect_med_type = 2 # 为2的话,既推送,又存库
  505. # detect_group=0允许全部推送的时候
  506. if detect_group == '0'or detect_group == '':
  507. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  508. else:
  509. detect_group_list = detect_group.split(',')
  510. if event_type in detect_group_list:
  511. if detect_interval < 60:
  512. detect_interval = 60
  513. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  514. # 改为1秒
  515. # 如果不是正式
  516. if SERVER_TYPE!="Ansjer.formal_settings":
  517. redisObj.set_data(key=pkey, val=1, expire=10)
  518. else:
  519. redisObj.set_data(key=pkey, val=1, expire=60)
  520. # 打印have_ykey
  521. # return JsonResponse(status=200, data={'pkey': 0, 'have_ykey': have_ykey, 'have_pkey': have_pkey, 'have_ykey': have_dkey})
  522. # 旧模式并且没有pkey,重新创建一个
  523. if not detect_group and not have_pkey:
  524. # 设置推送时间为60秒一次
  525. # 如果不是正式
  526. if SERVER_TYPE != "Ansjer.formal_settings":
  527. redisObj.set_data(key=pkey, val=1, expire=10)
  528. else:
  529. redisObj.set_data(key=pkey, val=1, expire=60)
  530. # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  531. # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  532. aws_s3_guonei = boto3.client(
  533. 's3',
  534. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  535. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  536. config=botocore.client.Config(signature_version='s3v4'),
  537. region_name='cn-northwest-1'
  538. )
  539. aws_s3_guowai = boto3.client(
  540. 's3',
  541. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  542. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  543. config=botocore.client.Config(signature_version='s3v4'),
  544. region_name='us-east-1'
  545. )
  546. kwag_args = {
  547. 'uid': uid,
  548. 'channel': channel,
  549. 'event_type': event_type,
  550. 'n_time': n_time,
  551. # 'appBundleId': appBundleId,
  552. # 'token_val': token_val,
  553. # 'msg_title': msg_title,
  554. # 'msg_text': msg_text
  555. }
  556. eq_list = []
  557. sys_msg_list = []
  558. userID_ids = []
  559. do_apns_code = ''
  560. do_fcm_code = ''
  561. do_jpush_code = ''
  562. for up in redis_list:
  563. push_type = up['push_type']
  564. appBundleId = up['appBundleId']
  565. token_val = up['token_val']
  566. lang = up['lang']
  567. tz = up['tz']
  568. if tz is None or tz == '':
  569. tz = 0
  570. # 发送标题
  571. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  572. # 发送内容
  573. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  574. event_type=event_type)
  575. kwag_args['appBundleId'] = appBundleId
  576. kwag_args['token_val'] = token_val
  577. kwag_args['msg_title'] = msg_title
  578. kwag_args['msg_text'] = msg_text
  579. push_server_status = 0
  580. #推送
  581. if detect_med_type == 2 or detect_med_type == 0:
  582. if push_type == 0: # ios apns
  583. print('do_apns')
  584. # self.do_apns(**kwag_args)
  585. do_apns_code = self.do_apns(**kwag_args)
  586. if isinstance(do_apns_code, int):
  587. push_server_status = do_apns_code
  588. else:
  589. push_server_status = 400
  590. elif push_type == 1: # android gcm
  591. print('do_fcm')
  592. do_fcm_code = self.do_fcm(**kwag_args)
  593. push_server_status = 200
  594. elif push_type == 2: # android jpush
  595. print('do_jpush')
  596. do_jpush_code = self.do_jpush(**kwag_args)
  597. push_server_status = do_jpush_code
  598. # return JsonResponse(status=200, data={'code': 0, '状态:': self.do_jpush(**kwag_args)})
  599. if detect_med_type == 1:
  600. do_apns_code = '只存库不推送'
  601. do_fcm_code = '只存库不推送'
  602. do_jpush_code = '只存库不推送'
  603. # 以下是存库
  604. userID_id = up["userID_id"]
  605. int_is_st = int(is_st)
  606. if userID_id not in userID_ids:
  607. eq_list.append(Equipment_Info(
  608. userID_id=userID_id,
  609. eventTime=n_time,
  610. eventType=event_type,
  611. devUid=uid,
  612. devNickName=nickname,
  613. Channel=channel,
  614. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  615. is_st=int_is_st,
  616. receiveTime=n_time,
  617. addTime=now_time,
  618. storage_location=2
  619. ))
  620. if is_sys_msg:
  621. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  622. event_type=event_type, is_sys=1)
  623. sys_msg_list.append(SysMsgModel(
  624. userID_id=userID_id,
  625. msg=sys_msg_text,
  626. addTime=now_time,
  627. updTime=now_time,
  628. uid=uid,
  629. eventType=event_type))
  630. userID_ids.append(userID_id)
  631. if is_sys_msg:
  632. SysMsgModel.objects.bulk_create(sys_msg_list)
  633. Equipment_Info.objects.bulk_create(eq_list)
  634. if is_st == '0' or is_st == '2':
  635. print("is_st=0or2")
  636. for up in redis_list:
  637. if up['push_type'] == 0: # ios apns
  638. up['do_apns_code'] = do_apns_code
  639. elif up['push_type'] == 1: # android gcm
  640. up['do_fcm_code'] = do_fcm_code
  641. elif up['push_type'] == 2: # android jpush
  642. up['do_jpush_code'] = do_jpush_code
  643. up['test_or_www'] = SERVER_TYPE
  644. del up['push_type']
  645. del up['userID_id']
  646. del up['userID__NickName']
  647. del up['lang']
  648. del up['tz']
  649. del up['uid_set__nickname']
  650. del up['uid_set__detect_interval']
  651. del up['uid_set__detect_group']
  652. return JsonResponse(status=200, data={'code': 0, 'msg': 'success 0 or 2' ,'re_list':redis_list})
  653. elif is_st == '1':
  654. print("is_st=1")
  655. # Endpoint以杭州为例,其它Region请按实际情况填写。
  656. # obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  657. # 设置此签名URL在60秒内有效。
  658. # url = bucket.sign_url('PUT', obj, 7200)
  659. thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  660. if region == 2: # 2:国内
  661. response_url = aws_s3_guonei.generate_presigned_url(
  662. ClientMethod='put_object',
  663. Params={
  664. 'Bucket': 'push',
  665. 'Key': thumbspng
  666. },
  667. ExpiresIn=3600
  668. )
  669. else: # 1:国外
  670. response_url = aws_s3_guowai.generate_presigned_url(
  671. ClientMethod='put_object',
  672. Params={
  673. 'Bucket': 'foreignpush',
  674. 'Key': thumbspng
  675. },
  676. ExpiresIn=3600
  677. )
  678. for up in redis_list:
  679. up['do_apns_code'] = do_apns_code
  680. up['do_fcm_code'] = do_fcm_code
  681. up['do_jpush_code'] = do_jpush_code
  682. up['test_or_www'] = SERVER_TYPE
  683. del up['push_type']
  684. del up['userID_id']
  685. del up['userID__NickName']
  686. del up['lang']
  687. del up['tz']
  688. del up['uid_set__nickname']
  689. del up['uid_set__detect_interval']
  690. del up['uid_set__detect_group']
  691. # 不是正式服务器
  692. # response_url = response_url[:4] + response_url[5:]
  693. if SERVER_TYPE != "Ansjer.formal_settings":
  694. # res_data = {'code': 0, 'img_push': url, 'msg': 'success', 're_list': redis_list}
  695. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success', 're_list': redis_list}
  696. else:
  697. # 是正式服务器的时候
  698. # res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  699. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
  700. return JsonResponse(status=200, data=res_data)
  701. elif is_st == '3':
  702. print("is_st=3")
  703. # 人形检测带动图
  704. # Endpoint以杭州为例,其它Region请按实际情况填写。
  705. img_url_list = []
  706. for i in range(int(is_st)):
  707. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  708. format(uid=uid, channel=channel, filename=n_time, st=i)
  709. # 设置此签名URL在60秒内有效。
  710. # url = bucket.sign_url('PUT', obj, 7200)
  711. thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  712. format(uid=uid, channel=channel, filename=n_time, st=i)
  713. if region == 2: # 2:国内
  714. response_url = aws_s3_guonei.generate_presigned_url(
  715. ClientMethod='put_object',
  716. Params={
  717. 'Bucket': 'push',
  718. 'Key': thumbspng
  719. },
  720. ExpiresIn=3600
  721. )
  722. else: # 1:国外
  723. response_url = aws_s3_guowai.generate_presigned_url(
  724. ClientMethod='put_object',
  725. Params={
  726. 'Bucket': 'foreignpush',
  727. 'Key': thumbspng
  728. },
  729. ExpiresIn=3600
  730. )
  731. # response_url = response_url[:4] + response_url[5:]
  732. img_url_list.append(response_url)
  733. # img_url_list.append(url)
  734. for up in redis_list:
  735. up['do_apns_code'] = do_apns_code
  736. up['do_fcm_code'] = do_fcm_code
  737. up['do_jpush_code'] = do_jpush_code
  738. up['test_or_www'] = SERVER_TYPE
  739. del up['push_type']
  740. del up['userID_id']
  741. del up['userID__NickName']
  742. del up['lang']
  743. del up['tz']
  744. del up['uid_set__nickname']
  745. del up['uid_set__detect_interval']
  746. del up['uid_set__detect_group']
  747. # 不是正式服务器
  748. if SERVER_TYPE != "Ansjer.formal_settings":
  749. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3', 're_list': redis_list}
  750. else:
  751. # 是正式服务器的时候
  752. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
  753. return JsonResponse(status=200, data=res_data)
  754. def get_msg_title(self, appBundleId, nickname):
  755. package_title_config = {
  756. 'com.ansjer.customizedd_a': 'DVS',
  757. 'com.ansjer.zccloud_a': 'ZosiSmart',
  758. 'com.ansjer.zccloud_ab': '周视',
  759. 'com.ansjer.adcloud_a': 'ADCloud',
  760. 'com.ansjer.adcloud_ab': 'ADCloud',
  761. 'com.ansjer.accloud_a': 'ACCloud',
  762. 'com.ansjer.loocamccloud_a': 'Loocam',
  763. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  764. 'com.ansjer.customizedb_a': 'COCOONHD',
  765. 'com.ansjer.customizeda_a': 'Guardian365',
  766. 'com.ansjer.customizedc_a': 'PatrolSecure',
  767. }
  768. if appBundleId in package_title_config.keys():
  769. return package_title_config[appBundleId] + '(' + nickname + ')'
  770. else:
  771. return nickname
  772. def is_sys_msg(self, event_type):
  773. event_type_list = [702, 703, 704]
  774. if event_type in event_type_list:
  775. return True
  776. return False
  777. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  778. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz,lang=lang)
  779. etype = int(event_type)
  780. if lang == 'cn':
  781. if etype == 704:
  782. msg_type = '电量过低'
  783. elif etype == 702:
  784. msg_type = '摄像头休眠'
  785. elif etype == 703:
  786. msg_type = '摄像头唤醒'
  787. else:
  788. msg_type = ''
  789. if is_sys:
  790. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  791. else:
  792. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  793. # send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  794. else:
  795. if etype == 704:
  796. msg_type = 'Low battery'
  797. elif etype == 702:
  798. msg_type = 'Camera sleep'
  799. elif etype == 703:
  800. msg_type = 'Camera wake'
  801. else:
  802. msg_type = ''
  803. if is_sys:
  804. send_text = '{msg_type} channel:{channel}'. \
  805. format(msg_type=msg_type, channel=channel)
  806. else:
  807. send_text = '{msg_type} channel:{channel} date:{date}'. \
  808. format(msg_type=msg_type, channel=channel, date=n_date)
  809. return send_text
  810. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
  811. msg_title, msg_text):
  812. app_key = JPUSH_CONFIG[appBundleId]['Key']
  813. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  814. # 此处换成各自的app_key和master_secre
  815. _jpush = jpush.JPush(app_key, master_secret)
  816. push = _jpush.create_push()
  817. # if you set the logging level to "DEBUG",it will show the debug logging.
  818. # _jpush.set_logging("DEBUG")
  819. # push.audience = jpush.all_
  820. push.audience = jpush.registration_id(token_val)
  821. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  822. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  823. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  824. big_text=msg_text, title=msg_title,
  825. extras=push_data)
  826. push.notification = jpush.notification(android=android)
  827. push.platform = jpush.all_
  828. res = push.send()
  829. print(res)
  830. return res.status_code
  831. # try:
  832. # res = push.send()
  833. # print(res)
  834. # except Exception as e:
  835. # print("jpush fail")
  836. # print("Exception")
  837. # print(repr(e))
  838. # return
  839. # else:
  840. # print("jpush success")
  841. # return
  842. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  843. try:
  844. serverKey = FCM_CONFIG[appBundleId]
  845. except Exception as e:
  846. return 'serverKey abnormal'
  847. push_service = FCMNotification(api_key=serverKey)
  848. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  849. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  850. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  851. message_body=msg_text, data_message=data,
  852. extra_kwargs={
  853. 'default_vibrate_timings': True,
  854. 'default_sound': True,
  855. 'default_light_settings': True
  856. })
  857. print('fcm push ing')
  858. print(result)
  859. return result
  860. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  861. msg_text):
  862. try:
  863. cli = apns2.APNSClient(mode=APNS_MODE,
  864. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  865. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  866. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  867. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  868. payload = apns2.Payload(alert=alert, custom=push_data)
  869. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  870. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  871. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  872. print(res.status_code)
  873. # 200, 推送成功。
  874. #   400, 请求有问题。
  875. #   403, 证书或Token有问题。
  876. #   405, 请求方式不正确, 只支持POST请求
  877. #   410, 设备的Token与证书不一致
  878. if res.status_code == 200:
  879. return res.status_code
  880. else:
  881. print('apns push fail')
  882. print(res.reason)
  883. return res.status_code
  884. except (ValueError, ArithmeticError):
  885. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  886. except Exception as e:
  887. print(repr(e))
  888. return repr(e)
  889. def do_update_detect_interval(self, uid, channel, redisObject, detect_interval):
  890. if channel == 0:
  891. channel = 17
  892. else:
  893. channel += 1
  894. for i in range(1, channel):
  895. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=51, channel=i)
  896. if tmpDKey is not False:
  897. llt = redisObject.get_ttl(tmpDKey)
  898. if llt > detect_interval:
  899. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  900. tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=54, channel=i)
  901. if tmpDKey is not False:
  902. llt = redisObject.get_ttl(tmpDKey)
  903. if llt > detect_interval:
  904. redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
  905. # 这个接口没有调用过,不敢动
  906. # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
  907. # 移动侦测接口
  908. class PushNotificationView(View):
  909. def get(self, request, *args, **kwargs):
  910. request.encoding = 'utf-8'
  911. # operation = kwargs.get('operation')
  912. return self.validation(request.GET)
  913. def post(self, request, *args, **kwargs):
  914. request.encoding = 'utf-8'
  915. # operation = kwargs.get('operation')
  916. return self.validation(request.POST)
  917. def validation(self, request_dict):
  918. etk = request_dict.get('etk', None)
  919. channel = request_dict.get('channel', '1')
  920. n_time = request_dict.get('n_time', None)
  921. event_type = request_dict.get('event_type', None)
  922. is_st = request_dict.get('is_st', None)
  923. region = request_dict.get('region', '2')
  924. region = int(region)
  925. eto = ETkObject(etk)
  926. uid = eto.uid
  927. if len(uid) == 20:
  928. redisObj = RedisObject(db=6)
  929. # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
  930. pkey = '{uid}_ptl'.format(uid=uid)
  931. ykey = '{uid}_redis_qs'.format(uid=uid)
  932. if redisObj.get_data(key=pkey):
  933. res_data = {'code': 0, 'msg': 'success,!33333333333'}
  934. return JsonResponse(status=200, data=res_data)
  935. else:
  936. redisObj.set_data(key=pkey, val=1, expire=60)
  937. ##############
  938. redis_data = redisObj.get_data(key=ykey)
  939. if redis_data:
  940. redis_list = eval(redis_data)
  941. else:
  942. # 设置推送时间为60秒一次
  943. redisObj.set_data(key=pkey, val=1, expire=60)
  944. print("从数据库查到数据")
  945. # 从数据库查询出来
  946. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  947. values('token_val', 'app_type', 'appBundleId',
  948. 'push_type', 'userID_id', 'lang','m_code',
  949. 'tz', 'uid_set__nickname')
  950. # 新建一个list接收数据
  951. redis_list = []
  952. # 把数据库数据追加进redis_list
  953. for qs in uid_push_qs:
  954. redis_list.append(qs)
  955. # 修改redis数据,并设置过期时间为10分钟
  956. if redis_list:
  957. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  958. # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  959. # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  960. aws_s3_guonei = boto3.client(
  961. 's3',
  962. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  963. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  964. config=botocore.client.Config(signature_version='s3v4'),
  965. region_name='cn-northwest-1'
  966. )
  967. aws_s3_guowai = boto3.client(
  968. 's3',
  969. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  970. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  971. config=botocore.client.Config(signature_version='s3v4'),
  972. region_name='us-east-1'
  973. )
  974. self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
  975. if is_st == '0' or is_st == '2':
  976. return JsonResponse(status=200, data={'code': 0, 'msg': 'success44444444444444444'})
  977. elif is_st == '1':
  978. # Endpoint以杭州为例,其它Region请按实际情况填写。
  979. # obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  980. # 设置此签名URL在60秒内有效。
  981. # url = bucket.sign_url('PUT', obj, 7200)
  982. thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  983. if region == 2: # 2:国内
  984. response_url = aws_s3_guonei.generate_presigned_url(
  985. ClientMethod='put_object',
  986. Params={
  987. 'Bucket': 'push',
  988. 'Key': thumbspng
  989. },
  990. ExpiresIn=3600
  991. )
  992. else: # 1:国外
  993. response_url = aws_s3_guowai.generate_presigned_url(
  994. ClientMethod='put_object',
  995. Params={
  996. 'Bucket': 'foreignpush',
  997. 'Key': thumbspng
  998. },
  999. ExpiresIn=3600
  1000. )
  1001. # res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  1002. # response_url = response_url[:4] + response_url[5:]
  1003. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
  1004. return JsonResponse(status=200, data=res_data)
  1005. elif is_st == '3':
  1006. # 人形检测带动图
  1007. img_url_list = []
  1008. for i in range(int(is_st)):
  1009. # obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  1010. # format(uid=uid, channel=channel, filename=n_time, st=i)
  1011. # 设置此签名URL在60秒内有效。
  1012. # url = bucket.sign_url('PUT', obj, 7200)
  1013. thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  1014. format(uid=uid, channel=channel, filename=n_time, st=i)
  1015. if region == 2: # 2:国内
  1016. response_url = aws_s3_guonei.generate_presigned_url(
  1017. ClientMethod='put_object',
  1018. Params={
  1019. 'Bucket': 'push',
  1020. 'Key': thumbspng
  1021. },
  1022. ExpiresIn=3600
  1023. )
  1024. else: # 1:国外
  1025. response_url = aws_s3_guowai.generate_presigned_url(
  1026. ClientMethod='put_object',
  1027. Params={
  1028. 'Bucket': 'foreignpush',
  1029. 'Key': thumbspng
  1030. },
  1031. ExpiresIn=3600
  1032. )
  1033. # response_url = response_url[:4] + response_url[5:]
  1034. img_url_list.append(response_url)
  1035. # img_url_list.append(url)
  1036. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
  1037. return JsonResponse(status=200, data=res_data)
  1038. else:
  1039. return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
  1040. else:
  1041. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
  1042. def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
  1043. now_time = int(time.time())
  1044. # 设备昵称
  1045. userID_ids = []
  1046. sys_msg_list = []
  1047. is_sys_msg = self.is_sys_msg(int(event_type))
  1048. is_st = int(is_st)
  1049. eq_list = []
  1050. nickname = uaqs[0]['uid_set__nickname']
  1051. if not nickname:
  1052. nickname = uid
  1053. for ua in uaqs:
  1054. lang = ua['lang']
  1055. tz = ua['tz']
  1056. userID_id = ua["userID_id"]
  1057. if userID_id not in userID_ids:
  1058. eq_list.append(Equipment_Info(
  1059. userID_id=userID_id,
  1060. eventTime=n_time,
  1061. eventType=event_type,
  1062. devUid=uid,
  1063. devNickName=nickname,
  1064. Channel=channel,
  1065. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  1066. is_st=is_st,
  1067. receiveTime=n_time,
  1068. addTime=now_time,
  1069. storage_location=2
  1070. ))
  1071. if is_sys_msg:
  1072. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  1073. event_type=event_type, is_sys=1)
  1074. sys_msg_list.append(SysMsgModel(
  1075. userID_id=userID_id,
  1076. msg=sys_msg_text,
  1077. addTime=now_time,
  1078. updTime=now_time,
  1079. uid=uid,
  1080. eventType=event_type))
  1081. if eq_list:
  1082. print('eq_list')
  1083. Equipment_Info.objects.bulk_create(eq_list)
  1084. if is_sys_msg:
  1085. print('sys_msg')
  1086. SysMsgModel.objects.bulk_create(sys_msg_list)
  1087. return True
  1088. def is_sys_msg(self, event_type):
  1089. event_type_list = [702, 703, 704]
  1090. if event_type in event_type_list:
  1091. return True
  1092. return False
  1093. def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
  1094. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
  1095. etype = int(event_type)
  1096. if lang == 'cn':
  1097. if etype == 704:
  1098. msg_type = '电量过低'
  1099. elif etype == 702:
  1100. msg_type = '摄像头休眠'
  1101. elif etype == 703:
  1102. msg_type = '摄像头唤醒'
  1103. else:
  1104. msg_type = ''
  1105. if is_sys:
  1106. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  1107. else:
  1108. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  1109. else:
  1110. if etype == 704:
  1111. msg_type = 'Low battery'
  1112. elif etype == 702:
  1113. msg_type = 'Camera sleep'
  1114. elif etype == 703:
  1115. msg_type = 'Camera wake'
  1116. else:
  1117. msg_type = ''
  1118. if is_sys:
  1119. send_text = '{msg_type} channel:{channel}'. \
  1120. format(msg_type=msg_type, channel=channel)
  1121. else:
  1122. send_text = '{msg_type} channel:{channel} date:{date}'. \
  1123. format(msg_type=msg_type, channel=channel, date=n_date)
  1124. return send_text