DetectControllerV2.py 55 KB

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