DetectControllerV2.py 55 KB

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