DetectControllerV2.py 56 KB

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