DetectControllerV2.py 56 KB

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