DetectControllerV2.py 56 KB

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