| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254 | 
							- #!/usr/bin/env python3
 
- # -*- coding: utf-8 -*-
 
- """
 
- @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
 
- @AUTHOR: ASJRD018
 
- @NAME: AnsjerFormal
 
- @software: PyCharm
 
- @DATE: 2019/1/14 15:57
 
- @Version: python3.6
 
- @MODIFY DECORD:ansjer dev
 
- @file: DetectController.py
 
- @Contact: chanjunkai@163.com
 
- """
 
- import json
 
- import os
 
- import time
 
- import apns2
 
- import boto3
 
- import botocore
 
- import jpush as jpush
 
- import oss2
 
- from botocore import client
 
- from django.http import JsonResponse
 
- from django.views.generic.base import View
 
- from pyfcm import FCMNotification
 
- from Ansjer.config import DETECT_PUSH_DOMAIN, DETECT_PUSH_DOMAINS, DETECT_PUSH_DOMAIN_JIUAN, DETECT_PUSH_DOMAINS_JIUAN, \
 
-     OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, \
 
-     JPUSH_CONFIG, FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE, SERVER_TYPE
 
- from Ansjer.config import PUSH_REDIS_ADDRESS
 
- from Model.models import Device_Info, VodHlsModel, Equipment_Info, UidSetModel, UidPushModel, CompanyModel, SysMsgModel, \
 
-     AiService
 
- from Object.ETkObject import ETkObject
 
- from Object.RedisObject import RedisObject
 
- from Object.ResponseObject import ResponseObject
 
- from Object.TokenObject import TokenObject
 
- from Object.UidTokenObject import UidTokenObject
 
- from Service.CommonService import CommonService
 
- from Service.EquipmentInfoService import EquipmentInfoService
 
- class DetectControllerViewV2(View):
 
-     def get(self, request, *args, **kwargs):
 
-         request.encoding = 'utf-8'
 
-         operation = kwargs.get('operation')
 
-         # self.ip = CommonService.get_ip_address(request)
 
-         return self.validation(request.GET, operation)
 
-     def post(self, request, *args, **kwargs):
 
-         request.encoding = 'utf-8'
 
-         operation = kwargs.get('operation')
 
-         # self.ip = CommonService.get_ip_address(request)
 
-         return self.validation(request.POST, operation)
 
-     def validation(self, request_dict, operation):
 
-         response = ResponseObject()
 
-         if operation is None:
 
-             return response.json(444, 'error path')
 
-         token = request_dict.get('token', None)
 
-         lang = request_dict.get('lang', None)
 
-         if lang:
 
-             response = ResponseObject(lang)
 
-         tko = TokenObject(token)
 
-         if tko.code == 0:
 
-             userID = tko.userID
 
-             # 修改推送设置
 
-             if operation == 'changeStatus':
 
-                 print("进入changeStatus")
 
-                 return self.do_change_status(userID, request_dict, response)
 
-             # 查询推送信息
 
-             elif operation == 'queryInfo':
 
-                 return self.do_query(request_dict, response, userID)
 
-             # 更新推送延迟
 
-             elif operation == 'updateInterval':
 
-                 return self.do_update_interval(userID, request_dict, response)
 
-             else:
 
-                 return response.json(414)
 
-         else:
 
-             return response.json(tko.code)
 
-     def do_change_status(self, userID, request_dict, response):
 
-         token_val = request_dict.get('token_val', None)
 
-         appBundleId = request_dict.get('appBundleId', None)
 
-         app_type = request_dict.get('app_type', None)
 
-         push_type = request_dict.get('push_type', None)
 
-         status = request_dict.get('status', None)
 
-         m_code = request_dict.get('m_code', None)
 
-         uid = request_dict.get('uid', None)
 
-         # 设备语言
 
-         lang = request_dict.get('lang', 'en')
 
-         tz = request_dict.get('tz', '0')
 
-         company_secrete = request_dict.get('company_secrete', None)
 
-         region = request_dict.get('region', None)  # app必须传:2:国内 1:国外
 
-         electricity_status = request_dict.get('electricity_status', None)
 
-         if not region:
 
-             return response.json(444, 'region')
 
-         region = int(region)
 
-         # 消息提醒功能新增
 
-         # 如果传空上来,就默认为0
 
-         if tz == '':
 
-             tz = 0
 
-         else:
 
-             tz = tz.replace("GMT", "")
 
-         detect_group = request_dict.get('detect_group', None)
 
-         interval = request_dict.get('interval', None)
 
-         if not status and not electricity_status:
 
-             return response.json(444, 'status and electricity_status')
 
-         if not company_secrete:
 
-             return response.json(444, 'company_secrete')
 
-         company = CompanyModel.objects.filter(secret=company_secrete)
 
-         if not company.exists():
 
-             return response.json(444, 'company_secrete')
 
-         # 关闭推送
 
-         if not all([appBundleId, app_type, token_val, uid, m_code]):
 
-             return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
 
-         # 判断推送类型对应key是否存在
 
-         print('push_type:', push_type)
 
-         try:
 
-             if push_type == '0':
 
-                 if appBundleId not in APNS_CONFIG.keys():
 
-                     return response.json(904)
 
-             elif push_type == '1':
 
-                 if appBundleId not in FCM_CONFIG.keys():
 
-                     return response.json(904)
 
-             elif push_type == '2':
 
-                 if appBundleId not in JPUSH_CONFIG.keys():
 
-                     return response.json(904)
 
-             else:
 
-                 return response.json(173)
 
-             # 判断用户是否拥有设备
 
-             device_info_qs = Device_Info.objects.filter(userID_id=userID, UID=uid)
 
-             if not device_info_qs.exists():
 
-                 device_info_qs = Device_Info.objects.filter(userID_id=userID, serial_number=uid)
 
-                 if not device_info_qs.exists():
 
-                     return response.json(14)
 
-             # 更新或创建uid_set数据
 
-             nowTime = int(time.time())
 
-             uid_set_data = {}
 
-             # 设置开关状态,0:关闭,1:开启
 
-             if status:
 
-                 status = int(status)
 
-                 uid_set_data['detect_status'] = status
 
-                 device_info_qs.update(NotificationMode=status)
 
-             # 检测类型
 
-             if detect_group:
 
-                 uid_set_data['detect_group'] = detect_group
 
-             uid_set = UidSetModel.objects.filter(uid=uid).order_by('-updTime')
 
-             if uid_set.exists():
 
-                 interval = uid_set.first().new_detect_interval if not interval else interval
 
-             # 设置消息推送间隔
 
-             if interval:
 
-                 interval = int(interval)
 
-                 uid_set_data['detect_interval'] = interval
 
-                 # 开通了ai服务的设备,通过mqtt通知设备修改消息推送间隔
 
-                 ai_service_qs = AiService.objects.filter(uid=uid, use_status=1, endTime__gte=nowTime)
 
-                 if ai_service_qs.exists():
 
-                     topic_name = 'ansjer/generic/{}'.format(uid)
 
-                     msg = {
 
-                         'commandType': 'AIState',
 
-                         'payload': {
 
-                             'IntervalTime': interval
 
-                         }
 
-                     }
 
-                     CommonService.req_publish_mqtt_msg(uid, topic_name, msg)
 
-                     # req_success = CommonService.req_publish_mqtt_msg(uid, topic_name, msg)
 
-                     # if not req_success:
 
-                     #     return response.json(10044)
 
-             uid_set_qs = UidSetModel.objects.filter(uid=uid)
 
-             if uid_set_qs.exists():
 
-                 uid_set_id = uid_set_qs[0].id
 
-                 uid_set_data['updTime'] = nowTime
 
-                 uid_set_qs.update(**uid_set_data)
 
-             else:
 
-                 uid_set_data['uid'] = uid
 
-                 uid_set_data['addTime'] = nowTime
 
-                 uid_set_data['updTime'] = nowTime
 
-                 uid_set_qs = UidSetModel.objects.create(**uid_set_data)
 
-                 uid_set_id = uid_set_qs.id
 
-             # 初始化UidPushModel推送表
 
-             if electricity_status:
 
-                 uid_push_create_dict = {
 
-                     'uid_set_id': uid_set_id,
 
-                     'userID_id': userID,
 
-                     'appBundleId': appBundleId,
 
-                     'app_type': app_type,
 
-                     'push_type': push_type,
 
-                     'token_val': token_val,
 
-                     'm_code': m_code,
 
-                     'addTime': nowTime,
 
-                     'updTime': nowTime,
 
-                     'lang': lang,
 
-                     'tz': tz
 
-                 }
 
-                 # 绑定设备推送
 
-                 UidPushModel.objects.create(**uid_push_create_dict)
 
-                 return response.json(0)
 
-             if status == 0:
 
-                 # 状态为0的时候删除redis缓存数据
 
-                 self.do_delete_redis(uid)
 
-                 return response.json(0)
 
-             elif status == 1:
 
-                 uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)
 
-                 if uid_push_qs.exists():
 
-                     uid_push_update_dict = {
 
-                         'appBundleId': appBundleId,
 
-                         'app_type': app_type,
 
-                         'push_type': push_type,
 
-                         'token_val': token_val,
 
-                         'updTime': nowTime,
 
-                         'lang': lang,
 
-                         'tz': tz
 
-                     }
 
-                     uid_push_qs.update(**uid_push_update_dict)
 
-                 else:
 
-                     # uid_set_id = uid_set_qs[0].id
 
-                     uid_push_create_dict = {
 
-                         'uid_set_id': uid_set_id,
 
-                         'userID_id': userID,
 
-                         'appBundleId': appBundleId,
 
-                         'app_type': app_type,
 
-                         'push_type': push_type,
 
-                         'token_val': token_val,
 
-                         'm_code': m_code,
 
-                         'addTime': nowTime,
 
-                         'updTime': nowTime,
 
-                         'lang': lang,
 
-                         'tz': tz
 
-                     }
 
-                     # 绑定设备推送
 
-                     UidPushModel.objects.create(**uid_push_create_dict)
 
-                 if interval:
 
-                     self.do_delete_redis(uid, interval)
 
-                 else:
 
-                     self.do_delete_redis(uid)
 
-                 # utko = UidTokenObject()
 
-                 # # right
 
-                 # utko.generate(data={'uid': uid})
 
-                 etkObj = ETkObject(etk='')
 
-                 etk = etkObj.encrypt(uid)
 
-                 if company_secrete == 'MTEyMTNB':
 
-                     url = DETECT_PUSH_DOMAIN
 
-                     urls = DETECT_PUSH_DOMAINS
 
-                 else:
 
-                     url = DETECT_PUSH_DOMAIN_JIUAN
 
-                     urls = DETECT_PUSH_DOMAINS_JIUAN
 
-                 detectUrl = "{DETECT_PUSH_DOMAIN}notifyV2/push?etk={etk}&company_secrete={company_secrete}®ion={region}". \
 
-                     format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN=url, region=region)
 
-                 detectUrls = "{DETECT_PUSH_DOMAIN_V2}notifyV2/push?etk={etk}&company_secrete={company_secrete}®ion={region}". \
 
-                     format(etk=etk, company_secrete=company_secrete, DETECT_PUSH_DOMAIN_V2=urls, region=region)
 
-                 return response.json(0, {'detectUrl': detectUrl, 'detectUrls': detectUrls})
 
-             else:
 
-                 return response.json(173)
 
-         except Exception as e:
 
-             return response.json(500, repr(e))
 
-     def do_delete_redis(self, uid, detect_interval=0):
 
-         keyPattern = '{uid}*'.format(uid=uid)
 
-         redisObj = RedisObject(db=6, SERVER_HOST=PUSH_REDIS_ADDRESS)
 
-         keys = redisObj.get_keys(keyPattern)
 
-         if keys:
 
-             for key in keys:
 
-                 key = key.decode()
 
-                 if detect_interval == 0:
 
-                     redisObj.del_data(key=key)
 
-                 elif key.find('plt') != -1:
 
-                     continue
 
-                 elif key.find('flag') != -1:
 
-                     redisObj.set_data(key=key, val=1, expire=detect_interval)
 
-                 else:
 
-                     redisObj.del_data(key=key)
 
-     def do_query(self, request_dict, response, userID):
 
-         page = int(request_dict.get('page', None))
 
-         line = int(request_dict.get('line', None))
 
-         if not page or not line:
 
-             return response.json(444, 'page,line')
 
-         startTime = request_dict.get('startTime', None)
 
-         endTime = request_dict.get('endTime', None)
 
-         eventType = request_dict.get('eventType', None)
 
-         region = request_dict.get('region', None)
 
-         if not region:
 
-             return response.json(444, 'region')
 
-         region = int(region)
 
-         # now_time = int(time.time())
 
-         # qs = Equipment_Info.objects.filter(userID_id=userID).order_by('-eventTime')
 
-         # qs = qs.filter(eventTime__gt=now_time - 3600 * 168)
 
-         try:
 
-             # 根据时间筛选消息推送
 
-             if startTime and endTime:
 
-                 qs, count = EquipmentInfoService.find_by_start_time_equipment_info(page, line, userID, startTime,
 
-                                                                                    endTime, eventType,
 
-                                                                                    request_dict.get('uids', None))
 
-             else:
 
-                 # 默认查询近七天消息推送
 
-                 qs, count = EquipmentInfoService.get_equipment_info_week_all(page, line, userID, startTime, endTime,
 
-                                                                              eventType,
 
-                                                                              request_dict.get('uids', None))
 
-             # if startTime and endTime:
 
-             #     qs = qs.filter(eventTime__range=(startTime, endTime))
 
-             # if eventType:
 
-             #     if ',' in eventType:  # 兼容AI查询
 
-             #         eventTypeList = eventType.split(',')
 
-             #         eventTypeList = [int(i.strip()) for i in eventTypeList]
 
-             #         qs = qs.filter(eventType__in=eventTypeList)
 
-             #     else:
 
-             #         qs = qs.filter(eventType=eventType)
 
-             uids = request_dict.get('uids', None)
 
-             if uids:
 
-                 uid_list = uids.split(',')
 
-                 # qs = qs.filter(devUid__in=uid_list)
 
-                 dvqs = Device_Info.objects.filter(UID__in=uid_list, userID_id=userID).values('UID', 'Type', 'NickName')
 
-                 uid_type_dict = {}
 
-                 for dv in dvqs:
 
-                     uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
 
-             else:
 
-                 dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
 
-                 uid_type_dict = {}
 
-                 for dv in dvqs:
 
-                     uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
 
-             # print(uid_type_dict)
 
-             if not qs or count == 0 or not qs.exists():
 
-                 return response.json(0, {'datas': [], 'count': 0})
 
-             # qs = qs.values('id', 'devUid', 'devNickName', 'Channel', 'eventType', 'status', 'alarm', 'eventTime',
 
-             #                'receiveTime', 'is_st', 'addTime', 'storage_location', 'borderCoords')
 
-             # count = qs.count()
 
-             # qr = qs[(page - 1) * line:page * line]
 
-             qr = qs
 
-             res = []
 
-             auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
 
-             oss_img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
 
-             aws_s3_guonei = boto3.client(
 
-                 's3',
 
-                 aws_access_key_id=AWS_ACCESS_KEY_ID[0],
 
-                 aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
 
-                 config=botocore.client.Config(signature_version='s3v4'),
 
-                 region_name='cn-northwest-1'
 
-             )
 
-             aws_s3_guowai = boto3.client(
 
-                 's3',
 
-                 aws_access_key_id=AWS_ACCESS_KEY_ID[1],
 
-                 aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
 
-                 config=botocore.client.Config(signature_version='s3v4'),
 
-                 region_name='us-east-1'
 
-             )
 
-             # vod_time_list = []
 
-             # ai消息标识所有组合标签
 
-             ai_all_event_type = EquipmentInfoService.get_all_comb_event_type()
 
-             for p in qr:
 
-                 devUid = p['devUid']
 
-                 eventTime = p['eventTime']
 
-                 channel = p['Channel']
 
-                 storage_location = p['storage_location']
 
-                 if p['is_st'] == 1:
 
-                     thumbspng = '{uid}/{channel}/{time}.jpeg'.format(uid=devUid, channel=p['Channel'], time=eventTime)
 
-                     if storage_location == 1:  # oss
 
-                         response_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
 
-                         p['img'] = response_url
 
-                         p['img_list'] = [response_url]
 
-                     elif region == 2 and storage_location == 2:  # 2:国内,aws
 
-                         response_url = aws_s3_guonei.generate_presigned_url('get_object',
 
-                                                                             Params={'Bucket': 'push', 'Key': thumbspng},
 
-                                                                             ExpiresIn=300)
 
-                         p['img'] = response_url
 
-                         p['img_list'] = [response_url]
 
-                     elif region == 1 and storage_location == 2:  # 1:国外,aws
 
-                         response_url = aws_s3_guowai.generate_presigned_url('get_object',
 
-                                                                             Params={'Bucket': 'foreignpush',
 
-                                                                                     'Key': thumbspng},
 
-                                                                             ExpiresIn=300)
 
-                         p['img'] = response_url
 
-                         p['img_list'] = [response_url]
 
-                 elif p['is_st'] == 2:
 
-                     # 列表装载回放时间戳标记
 
-                     vodqs = VodHlsModel.objects.filter(uid=devUid, channel=channel, time=int(eventTime)) \
 
-                         .values("bucket__bucket", "bucket__endpoint")
 
-                     # print(vodqs)
 
-                     if vodqs.exists():
 
-                         bucket_name = vodqs[0]['bucket__bucket']
 
-                         endpoint = vodqs[0]['bucket__endpoint']
 
-                         bucket = oss2.Bucket(auth, endpoint, bucket_name)
 
-                         ts = '{uid}/vod{channel}/{etime}/ts0.ts'.format(uid=devUid, channel=p['Channel'], etime=eventTime)
 
-                         if storage_location == 1:  # oss
 
-                             thumb0 = bucket.sign_url('GET', ts, 3600,
 
-                                                      params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
 
-                             thumb1 = bucket.sign_url('GET', ts, 3600,
 
-                                                      params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
 
-                             thumb2 = bucket.sign_url('GET', ts, 3600,
 
-                                                      params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
 
-                             # thumb3 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_3000,w_700'})
 
-                             p['img_list'] = [thumb0, thumb1, thumb2]
 
-                         elif region == 2 and storage_location == 2:  # 2:国内,aws
 
-                             thumb = aws_s3_guonei.generate_presigned_url('get_object',
 
-                                                                          Params={'Bucket': 'push', 'Key': ts},
 
-                                                                          ExpiresIn=3600)
 
-                             p['img_list'] = [thumb]
 
-                         elif region == 1 and storage_location == 2:  # 1:国外,aws
 
-                             thumb = aws_s3_guowai.generate_presigned_url('get_object',
 
-                                                                          Params={'Bucket': 'foreignpush', 'Key': ts},
 
-                                                                          ExpiresIn=3600)
 
-                             p['img_list'] = [thumb]
 
-                 elif p['is_st'] == 3 or p['is_st'] == 4:
 
-                     # 列表装载回放时间戳标记
 
-                     p['img_list'] = []
 
-                     for i in range(p['is_st']):
 
-                         thumbspng = '{uid}/{channel}/{time}_{st}.jpeg'.format(uid=devUid, channel=p['Channel'],
 
-                                                                               time=eventTime, st=i)
 
-                         if storage_location == 1:  # oss
 
-                             img = oss_img_bucket.sign_url('GET', thumbspng, 300)
 
-                             p['img_list'].append(img)
 
-                         elif region == 2 and storage_location == 2:  # 2:国内,aws
 
-                             response_url = aws_s3_guonei.generate_presigned_url('get_object',
 
-                                                                                 Params={'Bucket': 'push', 'Key': thumbspng},
 
-                                                                                 ExpiresIn=300)
 
-                             img = response_url
 
-                             p['img_list'].append(img)
 
-                         elif region == 1 and storage_location == 2:  # 1:国外,aws
 
-                             response_url = aws_s3_guowai.generate_presigned_url('get_object',
 
-                                                                                 Params={'Bucket': 'foreignpush',
 
-                                                                                         'Key': thumbspng},
 
-                                                                                 ExpiresIn=300)
 
-                             img = response_url
 
-                             p['img_list'].append(img)
 
-                 if devUid in uid_type_dict.keys():
 
-                     p['uid_type'] = uid_type_dict[devUid]['type']
 
-                     p['devNickName'] = uid_type_dict[devUid]['NickName']
 
-                 else:
 
-                     p['uid_type'] = ''
 
-                 p['borderCoords'] = '' if p['borderCoords'] == '' else json.loads(p['borderCoords'])  # ai消息坐标信息
 
-                 p['ai_event_type_list'] = []
 
-                 if p['eventType'] in ai_all_event_type:  # 如果是ai消息类型,则分解eventType, 如:123 -> [1,2,3]
 
-                     p['ai_event_type_list'] = list(map(int, str(p['eventType'])))
 
-                 res.append(p)
 
-             return response.json(0, {'datas': res, 'count': count})
 
-         except Exception as e:
 
-             return response.json(474)
 
-     def do_update_interval(self, userID, request_dict, response):
 
-         uid = request_dict.get('uid', None)
 
-         interval = request_dict.get('interval', None)
 
-         dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
 
-         if dvqs.exists():
 
-             uid_set_qs = UidSetModel.objects. \
 
-                 filter(uid=uid, uidpushmodel__userID_id=userID)
 
-             # redisObj = RedisObject(db=8)
 
-             # redisObj.del_data(key='uid_qs_' + userID)
 
-             if uid_set_qs.exists():
 
-                 uid_set_qs.update(interval=int(interval))
 
-             else:
 
-                 return response.json(173)
 
-         else:
 
-             return response.json(0)
 
- # 设备调用接口
 
- # 移动侦测接口
 
- class NotificationView(View):
 
-     def get(self, request, *args, **kwargs):
 
-         request.encoding = 'utf-8'
 
-         return self.validation(request.GET)
 
-     def post(self, request, *args, **kwargs):
 
-         request.encoding = 'utf-8'
 
-         return self.validation(request.POST)
 
-     def validation(self, request_dict):
 
-         uidToken = request_dict.get('uidToken', None)
 
-         etk = request_dict.get('etk', None)
 
-         channel = request_dict.get('channel', '1')
 
-         n_time = request_dict.get('n_time', None)
 
-         event_type = request_dict.get('event_type', None)
 
-         is_st = request_dict.get('is_st', None)
 
-         company_secrete = request_dict.get('company_secrete', None)
 
-         region = request_dict.get('region', None)
 
-         if not region:
 
-             return JsonResponse(status=200, data={'code': 404, 'msg': 'region is not exist'})
 
-         region = int(region)
 
-         # print("aaa")
 
-         # return JsonResponse(0,safe=False)
 
-         if not all([channel, n_time]):
 
-             return JsonResponse(status=200, data={
 
-                 'code': 444,
 
-                 'msg': 'param is wrong'})
 
-         if etk:
 
-             eto = ETkObject(etk)
 
-             uid = eto.uid
 
-             if len(uid) != 20 and len(uid) != 14:
 
-                 return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
 
-         else:
 
-             utko = UidTokenObject(uidToken)
 
-             uid = utko.UID
 
-         pkey = '{uid}_{channel}_{event_type}_ptl'.format(uid=uid, event_type=event_type, channel=channel)
 
-         # ykey = 'MUJ887NLR8K8GBM9111A_redis_qs'.format(uid=uid)
 
-         ykey = '{uid}_redis_qs'.format(uid=uid)
 
-         # dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
 
-         is_sys_msg = self.is_sys_msg(int(event_type))
 
-         if is_sys_msg is True:
 
-             dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
 
-         else:
 
-             dkey = '{uid}_{channel}_flag'.format(uid=uid, channel=channel)
 
-         # 判断redisObj.get_data(key=pkey):不为空
 
-         redisObj = RedisObject(db=6)
 
-         have_ykey = redisObj.get_data(key=ykey)  # uid_set 数据库缓存
 
-         have_pkey = redisObj.get_data(key=pkey)  # 一分钟限制key
 
-         have_dkey = redisObj.get_data(key=dkey)  # 推送类型限制
 
-         # 一分钟外,推送开启状态
 
-         detect_med_type = 0  # 0推送旧机制 1存库不推送,2推送存库
 
-         # 暂时注销
 
-         if have_pkey:
 
-             if SERVER_TYPE != "Ansjer.formal_settings":
 
-                 res_data = {'code': 0, 'msg': 'Push once every 10 seconds'}
 
-             else:
 
-                 res_data = {'code': 0, 'msg': 'Push it once a minute'}
 
-             return JsonResponse(status=200, data=res_data)
 
-         # 数据库读取数据
 
-         if have_ykey:
 
-             redis_list = eval(redisObj.get_data(key=ykey))
 
-             print(have_ykey)
 
-             if not redis_list:
 
-                 # 从数据库查询出来
 
-                 uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
 
-                     values('token_val', 'app_type', 'appBundleId', 'm_code',
 
-                            'push_type', 'userID_id', 'userID__NickName',
 
-                            'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval',
 
-                            'uid_set__detect_group',
 
-                            'uid_set__channel')
 
-                 print(uid_push_qs)
 
-                 # 新建一个list接收数据
 
-                 redis_list = []
 
-                 # 把数据库数据追加进redis_list
 
-                 for qs in uid_push_qs:
 
-                     redis_list.append(qs)
 
-                 # 修改redis数据,并设置过期时间为10分钟
 
-                 redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
 
-                 if not redis_list:
 
-                     res_data = {'code': 404, 'msg': 'error !'}
 
-                     return JsonResponse(status=200, data=res_data)
 
-         else:
 
-             # 从数据库查询出来
 
-             uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
 
-                 values('token_val', 'app_type', 'appBundleId', 'm_code',
 
-                        'push_type', 'userID_id', 'userID__NickName',
 
-                        'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
 
-                        'uid_set__channel')
 
-             print(uid_push_qs)
 
-             # 新建一个list接收数据
 
-             redis_list = []
 
-             # 把数据库数据追加进redis_list
 
-             for qs in uid_push_qs:
 
-                 redis_list.append(qs)
 
-             # 修改redis数据,并设置过期时间为10分钟
 
-             redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
 
-             if not redis_list:
 
-                 res_data = {'code': 404, 'msg': 'error !'}
 
-                 return JsonResponse(status=200, data=res_data)
 
-             # 此时应该更新一下redis里面的dkey的有效时间
 
-             # detect_interval = redis_list[0]['uid_set__detect_interval']
 
-             # tmp_channel = redis_list[0]['uid_set__channel']
 
-             # self.do_update_detect_interval(uid, tmp_channel, redisObj, detect_interval)
 
-         if not redis_list:
 
-             print("没有redi_list")
 
-             res_data = {'code': 0, 'msg': 'no redi_list success!'}
 
-             return JsonResponse(status=200, data=res_data)
 
-         # is_sys_msg = self.is_sys_msg(int(event_type))
 
-         nickname = redis_list[0]['uid_set__nickname']
 
-         detect_interval = redis_list[0]['uid_set__detect_interval']
 
-         detect_group = redis_list[0]['uid_set__detect_group']
 
-         now_time = int(time.time())
 
-         if not nickname:
 
-             nickname = uid
 
-         if detect_group is not None:
 
-             if have_dkey:
 
-                 detect_med_type = 1  # 1为存库不推送
 
-             else:
 
-                 detect_med_type = 2  # 为2的话,既推送,又存库
 
-                 # detect_group=0允许全部推送的时候
 
-                 if detect_group == '0' or detect_group == '':
 
-                     redisObj.set_data(key=dkey, val=1, expire=detect_interval)
 
-                 else:
 
-                     detect_group_list = detect_group.split(',')
 
-                     if event_type in detect_group_list:
 
-                         if detect_interval < 60:
 
-                             detect_interval = 60
 
-                         redisObj.set_data(key=dkey, val=1, expire=detect_interval)
 
-                 # 改为1秒
 
-                 # 如果不是正式
 
-                 if SERVER_TYPE != "Ansjer.formal_settings":
 
-                     redisObj.set_data(key=pkey, val=1, expire=10)
 
-                 else:
 
-                     redisObj.set_data(key=pkey, val=1, expire=60)
 
-             # 打印have_ykey
 
-         # return JsonResponse(status=200, data={'pkey': 0, 'have_ykey': have_ykey, 'have_pkey': have_pkey, 'have_ykey': have_dkey})
 
-         # 旧模式并且没有pkey,重新创建一个
 
-         if not detect_group and not have_pkey:
 
-             # 设置推送时间为60秒一次
 
-             # 如果不是正式
 
-             if SERVER_TYPE != "Ansjer.formal_settings":
 
-                 redisObj.set_data(key=pkey, val=1, expire=10)
 
-             else:
 
-                 redisObj.set_data(key=pkey, val=1, expire=60)
 
-         # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
 
-         # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
 
-         aws_s3_guonei = boto3.client(
 
-             's3',
 
-             aws_access_key_id=AWS_ACCESS_KEY_ID[0],
 
-             aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
 
-             config=botocore.client.Config(signature_version='s3v4'),
 
-             region_name='cn-northwest-1'
 
-         )
 
-         aws_s3_guowai = boto3.client(
 
-             's3',
 
-             aws_access_key_id=AWS_ACCESS_KEY_ID[1],
 
-             aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
 
-             config=botocore.client.Config(signature_version='s3v4'),
 
-             region_name='us-east-1'
 
-         )
 
-         kwag_args = {
 
-             'uid': uid,
 
-             'channel': channel,
 
-             'event_type': event_type,
 
-             'n_time': n_time,
 
-             # 'appBundleId': appBundleId,
 
-             # 'token_val': token_val,
 
-             # 'msg_title': msg_title,
 
-             # 'msg_text': msg_text
 
-         }
 
-         eq_list = []
 
-         sys_msg_list = []
 
-         userID_ids = []
 
-         do_apns_code = ''
 
-         do_fcm_code = ''
 
-         do_jpush_code = ''
 
-         for up in redis_list:
 
-             push_type = up['push_type']
 
-             appBundleId = up['appBundleId']
 
-             token_val = up['token_val']
 
-             lang = up['lang']
 
-             tz = up['tz']
 
-             if tz is None or tz == '':
 
-                 tz = 0
 
-             # 发送标题
 
-             msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
 
-             # 发送内容
 
-             msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
 
-                                          event_type=event_type)
 
-             kwag_args['appBundleId'] = appBundleId
 
-             kwag_args['token_val'] = token_val
 
-             kwag_args['msg_title'] = msg_title
 
-             kwag_args['msg_text'] = msg_text
 
-             push_server_status = 0
 
-             # 推送
 
-             if detect_med_type == 2 or detect_med_type == 0:
 
-                 if push_type == 0:  # ios apns
 
-                     print('do_apns')
 
-                     # self.do_apns(**kwag_args)
 
-                     do_apns_code = self.do_apns(**kwag_args)
 
-                     if isinstance(do_apns_code, int):
 
-                         push_server_status = do_apns_code
 
-                     else:
 
-                         push_server_status = 400
 
-                 elif push_type == 1:  # android gcm
 
-                     print('do_fcm')
 
-                     do_fcm_code = self.do_fcm(**kwag_args)
 
-                     push_server_status = 200
 
-                 elif push_type == 2:  # android jpush
 
-                     print('do_jpush')
 
-                     do_jpush_code = self.do_jpush(**kwag_args)
 
-                     push_server_status = do_jpush_code
 
-                     # return JsonResponse(status=200, data={'code': 0, '状态:': self.do_jpush(**kwag_args)})
 
-             if detect_med_type == 1:
 
-                 do_apns_code = '只存库不推送'
 
-                 do_fcm_code = '只存库不推送'
 
-                 do_jpush_code = '只存库不推送'
 
-             # 以下是存库
 
-             userID_id = up["userID_id"]
 
-             int_is_st = int(is_st)
 
-             if userID_id not in userID_ids:
 
-                 eq_list.append(Equipment_Info(
 
-                     userID_id=userID_id,
 
-                     eventTime=n_time,
 
-                     eventType=event_type,
 
-                     devUid=uid,
 
-                     devNickName=nickname,
 
-                     Channel=channel,
 
-                     alarm='Motion \tChannel:{channel}'.format(channel=channel),
 
-                     is_st=int_is_st,
 
-                     receiveTime=n_time,
 
-                     addTime=now_time,
 
-                     storage_location=2
 
-                 ))
 
-                 if is_sys_msg:
 
-                     sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
 
-                                                      event_type=event_type, is_sys=1)
 
-                     sys_msg_list.append(SysMsgModel(
 
-                         userID_id=userID_id,
 
-                         msg=sys_msg_text,
 
-                         addTime=now_time,
 
-                         updTime=now_time,
 
-                         uid=uid,
 
-                         eventType=event_type))
 
-                 userID_ids.append(userID_id)
 
-         if is_sys_msg:
 
-             SysMsgModel.objects.bulk_create(sys_msg_list)
 
-         Equipment_Info.objects.bulk_create(eq_list)
 
-         if is_st == '0' or is_st == '2':
 
-             print("is_st=0or2")
 
-             for up in redis_list:
 
-                 if up['push_type'] == 0:  # ios apns
 
-                     up['do_apns_code'] = do_apns_code
 
-                 elif up['push_type'] == 1:  # android gcm
 
-                     up['do_fcm_code'] = do_fcm_code
 
-                 elif up['push_type'] == 2:  # android jpush
 
-                     up['do_jpush_code'] = do_jpush_code
 
-                 up['test_or_www'] = SERVER_TYPE
 
-                 del up['push_type']
 
-                 del up['userID_id']
 
-                 del up['userID__NickName']
 
-                 del up['lang']
 
-                 del up['tz']
 
-                 del up['uid_set__nickname']
 
-                 del up['uid_set__detect_interval']
 
-                 del up['uid_set__detect_group']
 
-             return JsonResponse(status=200, data={'code': 0, 'msg': 'success 0 or 2', 're_list': redis_list})
 
-         elif is_st == '1':
 
-             print("is_st=1")
 
-             # Endpoint以杭州为例,其它Region请按实际情况填写。
 
-             # obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
 
-             # 设置此签名URL在60秒内有效。
 
-             # url = bucket.sign_url('PUT', obj, 7200)
 
-             thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
 
-             if region == 2:  # 2:国内
 
-                 response_url = aws_s3_guonei.generate_presigned_url(
 
-                     ClientMethod='put_object',
 
-                     Params={
 
-                         'Bucket': 'push',
 
-                         'Key': thumbspng
 
-                     },
 
-                     ExpiresIn=3600
 
-                 )
 
-             else:  # 1:国外
 
-                 response_url = aws_s3_guowai.generate_presigned_url(
 
-                     ClientMethod='put_object',
 
-                     Params={
 
-                         'Bucket': 'foreignpush',
 
-                         'Key': thumbspng
 
-                     },
 
-                     ExpiresIn=3600
 
-                 )
 
-             for up in redis_list:
 
-                 up['do_apns_code'] = do_apns_code
 
-                 up['do_fcm_code'] = do_fcm_code
 
-                 up['do_jpush_code'] = do_jpush_code
 
-                 up['test_or_www'] = SERVER_TYPE
 
-                 del up['push_type']
 
-                 del up['userID_id']
 
-                 del up['userID__NickName']
 
-                 del up['lang']
 
-                 del up['tz']
 
-                 del up['uid_set__nickname']
 
-                 del up['uid_set__detect_interval']
 
-                 del up['uid_set__detect_group']
 
-                 # 不是正式服务器
 
-             # response_url = response_url[:4] + response_url[5:]
 
-             if SERVER_TYPE != "Ansjer.formal_settings":
 
-                 # res_data = {'code': 0, 'img_push': url, 'msg': 'success', 're_list': redis_list}
 
-                 res_data = {'code': 0, 'img_push': response_url, 'msg': 'success', 're_list': redis_list}
 
-             else:
 
-                 # 是正式服务器的时候
 
-                 # res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
 
-                 res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
 
-             return JsonResponse(status=200, data=res_data)
 
-         elif is_st == '3':
 
-             print("is_st=3")
 
-             # 人形检测带动图
 
-             # Endpoint以杭州为例,其它Region请按实际情况填写。
 
-             img_url_list = []
 
-             for i in range(int(is_st)):
 
-                 obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
 
-                     format(uid=uid, channel=channel, filename=n_time, st=i)
 
-                 # 设置此签名URL在60秒内有效。
 
-                 # url = bucket.sign_url('PUT', obj, 7200)
 
-                 thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
 
-                     format(uid=uid, channel=channel, filename=n_time, st=i)
 
-                 if region == 2:  # 2:国内
 
-                     response_url = aws_s3_guonei.generate_presigned_url(
 
-                         ClientMethod='put_object',
 
-                         Params={
 
-                             'Bucket': 'push',
 
-                             'Key': thumbspng
 
-                         },
 
-                         ExpiresIn=3600
 
-                     )
 
-                 else:  # 1:国外
 
-                     response_url = aws_s3_guowai.generate_presigned_url(
 
-                         ClientMethod='put_object',
 
-                         Params={
 
-                             'Bucket': 'foreignpush',
 
-                             'Key': thumbspng
 
-                         },
 
-                         ExpiresIn=3600
 
-                     )
 
-                 # response_url = response_url[:4] + response_url[5:]
 
-                 img_url_list.append(response_url)
 
-                 # img_url_list.append(url)
 
-             for up in redis_list:
 
-                 up['do_apns_code'] = do_apns_code
 
-                 up['do_fcm_code'] = do_fcm_code
 
-                 up['do_jpush_code'] = do_jpush_code
 
-                 up['test_or_www'] = SERVER_TYPE
 
-                 del up['push_type']
 
-                 del up['userID_id']
 
-                 del up['userID__NickName']
 
-                 del up['lang']
 
-                 del up['tz']
 
-                 del up['uid_set__nickname']
 
-                 del up['uid_set__detect_interval']
 
-                 del up['uid_set__detect_group']
 
-             # 不是正式服务器
 
-             if SERVER_TYPE != "Ansjer.formal_settings":
 
-                 res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3', 're_list': redis_list}
 
-             else:
 
-                 # 是正式服务器的时候
 
-                 res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
 
-             return JsonResponse(status=200, data=res_data)
 
-     def get_msg_title(self, appBundleId, nickname):
 
-         package_title_config = {
 
-             'com.ansjer.customizedd_a': 'DVS',
 
-             'com.ansjer.zccloud_a': 'ZosiSmart',
 
-             'com.ansjer.zccloud_ab': '周视',
 
-             'com.ansjer.adcloud_a': 'ADCloud',
 
-             'com.ansjer.adcloud_ab': 'ADCloud',
 
-             'com.ansjer.accloud_a': 'ACCloud',
 
-             'com.ansjer.loocamccloud_a': 'Loocam',
 
-             'com.ansjer.loocamdcloud_a': 'Anlapus',
 
-             'com.ansjer.customizedb_a': 'COCOONHD',
 
-             'com.ansjer.customizeda_a': 'Guardian365',
 
-             'com.ansjer.customizedc_a': 'PatrolSecure',
 
-         }
 
-         if appBundleId in package_title_config.keys():
 
-             return package_title_config[appBundleId] + '(' + nickname + ')'
 
-         else:
 
-             return nickname
 
-     def is_sys_msg(self, event_type):
 
-         event_type_list = [702, 703, 704]
 
-         if event_type in event_type_list:
 
-             return True
 
-         return False
 
-     def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
 
-         n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
 
-         etype = int(event_type)
 
-         if lang == 'cn':
 
-             if etype == 704:
 
-                 msg_type = '电量过低'
 
-             elif etype == 702:
 
-                 msg_type = '摄像头休眠'
 
-             elif etype == 703:
 
-                 msg_type = '摄像头唤醒'
 
-             else:
 
-                 msg_type = ''
 
-             if is_sys:
 
-                 send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
 
-             else:
 
-                 send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
 
-                 # send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
 
-         else:
 
-             if etype == 704:
 
-                 msg_type = 'Low battery'
 
-             elif etype == 702:
 
-                 msg_type = 'Camera sleep'
 
-             elif etype == 703:
 
-                 msg_type = 'Camera wake'
 
-             else:
 
-                 msg_type = ''
 
-             if is_sys:
 
-                 send_text = '{msg_type} channel:{channel}'. \
 
-                     format(msg_type=msg_type, channel=channel)
 
-             else:
 
-                 send_text = '{msg_type} channel:{channel} date:{date}'. \
 
-                     format(msg_type=msg_type, channel=channel, date=n_date)
 
-         return send_text
 
-     def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
 
-                  msg_title, msg_text):
 
-         app_key = JPUSH_CONFIG[appBundleId]['Key']
 
-         master_secret = JPUSH_CONFIG[appBundleId]['Secret']
 
-         # 此处换成各自的app_key和master_secre
 
-         _jpush = jpush.JPush(app_key, master_secret)
 
-         push = _jpush.create_push()
 
-         # if you set the logging level to "DEBUG",it will show the debug logging.
 
-         # _jpush.set_logging("DEBUG")
 
-         # push.audience = jpush.all_
 
-         push.audience = jpush.registration_id(token_val)
 
-         push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
 
-                      "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
 
-         android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
 
-                                 big_text=msg_text, title=msg_title,
 
-                                 extras=push_data)
 
-         push.notification = jpush.notification(android=android)
 
-         push.platform = jpush.all_
 
-         res = push.send()
 
-         print(res)
 
-         return res.status_code
 
-         # try:
 
-         #     res = push.send()
 
-         #     print(res)
 
-         # except Exception as e:
 
-         #     print("jpush fail")
 
-         #     print("Exception")
 
-         #     print(repr(e))
 
-         #     return
 
-         # else:
 
-         #     print("jpush success")
 
-         #     return
 
-     def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
 
-         try:
 
-             serverKey = FCM_CONFIG[appBundleId]
 
-         except Exception as e:
 
-             return 'serverKey abnormal'
 
-         push_service = FCMNotification(api_key=serverKey)
 
-         data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
 
-                 "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
 
-         result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
 
-                                                    message_body=msg_text, data_message=data,
 
-                                                    extra_kwargs={
 
-                                                        'default_vibrate_timings': True,
 
-                                                        'default_sound': True,
 
-                                                        'default_light_settings': True
 
-                                                    })
 
-         print('fcm push ing')
 
-         print(result)
 
-         return result
 
-     def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
 
-                 msg_text):
 
-         try:
 
-             cli = apns2.APNSClient(mode=APNS_MODE,
 
-                                    client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
 
-             push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
 
-                          "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
 
-             alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
 
-             payload = apns2.Payload(alert=alert, custom=push_data)
 
-             # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
 
-             n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
 
-             res = cli.push(n=n, device_token=token_val, topic=appBundleId)
 
-             print(res.status_code)
 
-             #     200, 推送成功。
 
-             #   400, 请求有问题。
 
-             #   403, 证书或Token有问题。
 
-             #   405, 请求方式不正确, 只支持POST请求
 
-             #   410, 设备的Token与证书不一致
 
-             if res.status_code == 200:
 
-                 return res.status_code
 
-             else:
 
-                 print('apns push fail')
 
-                 print(res.reason)
 
-                 return res.status_code
 
-         except (ValueError, ArithmeticError):
 
-             return 'The program has a numeric format exception, one of the arithmetic exceptions'
 
-         except Exception as e:
 
-             print(repr(e))
 
-             return repr(e)
 
-     def do_update_detect_interval(self, uid, channel, redisObject, detect_interval):
 
-         if channel == 0:
 
-             channel = 17
 
-         else:
 
-             channel += 1
 
-         for i in range(1, channel):
 
-             tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=51, channel=i)
 
-             if tmpDKey is not False:
 
-                 llt = redisObject.get_ttl(tmpDKey)
 
-                 if llt > detect_interval:
 
-                     redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
 
-             tmpDKey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=54, channel=i)
 
-             if tmpDKey is not False:
 
-                 llt = redisObject.get_ttl(tmpDKey)
 
-                 if llt > detect_interval:
 
-                     redisObject.set_data(key=tmpDKey, val=1, expire=detect_interval)
 
- # 这个接口没有调用过,不敢动
 
- # http://test.dvema.com/detect/add?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0
 
- # 移动侦测接口
 
- class PushNotificationView(View):
 
-     def get(self, request, *args, **kwargs):
 
-         request.encoding = 'utf-8'
 
-         # operation = kwargs.get('operation')
 
-         return self.validation(request.GET)
 
-     def post(self, request, *args, **kwargs):
 
-         request.encoding = 'utf-8'
 
-         # operation = kwargs.get('operation')
 
-         return self.validation(request.POST)
 
-     def validation(self, request_dict):
 
-         etk = request_dict.get('etk', None)
 
-         channel = request_dict.get('channel', '1')
 
-         n_time = request_dict.get('n_time', None)
 
-         event_type = request_dict.get('event_type', None)
 
-         is_st = request_dict.get('is_st', None)
 
-         region = request_dict.get('region', '2')
 
-         region = int(region)
 
-         eto = ETkObject(etk)
 
-         uid = eto.uid
 
-         if len(uid) == 20:
 
-             redisObj = RedisObject(db=6)
 
-             # pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)
 
-             pkey = '{uid}_ptl'.format(uid=uid)
 
-             ykey = '{uid}_redis_qs'.format(uid=uid)
 
-             if redisObj.get_data(key=pkey):
 
-                 res_data = {'code': 0, 'msg': 'success,!33333333333'}
 
-                 return JsonResponse(status=200, data=res_data)
 
-             else:
 
-                 redisObj.set_data(key=pkey, val=1, expire=60)
 
-             ##############
 
-             redis_data = redisObj.get_data(key=ykey)
 
-             if redis_data:
 
-                 redis_list = eval(redis_data)
 
-             else:
 
-                 # 设置推送时间为60秒一次
 
-                 redisObj.set_data(key=pkey, val=1, expire=60)
 
-                 print("从数据库查到数据")
 
-                 # 从数据库查询出来
 
-                 uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
 
-                     values('token_val', 'app_type', 'appBundleId',
 
-                            'push_type', 'userID_id', 'lang', 'm_code',
 
-                            'tz', 'uid_set__nickname')
 
-                 # 新建一个list接收数据
 
-                 redis_list = []
 
-                 # 把数据库数据追加进redis_list
 
-                 for qs in uid_push_qs:
 
-                     redis_list.append(qs)
 
-                 # 修改redis数据,并设置过期时间为10分钟
 
-             if redis_list:
 
-                 redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
 
-                 # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
 
-                 # bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
 
-                 aws_s3_guonei = boto3.client(
 
-                     's3',
 
-                     aws_access_key_id=AWS_ACCESS_KEY_ID[0],
 
-                     aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
 
-                     config=botocore.client.Config(signature_version='s3v4'),
 
-                     region_name='cn-northwest-1'
 
-                 )
 
-                 aws_s3_guowai = boto3.client(
 
-                     's3',
 
-                     aws_access_key_id=AWS_ACCESS_KEY_ID[1],
 
-                     aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
 
-                     config=botocore.client.Config(signature_version='s3v4'),
 
-                     region_name='us-east-1'
 
-                 )
 
-                 self.do_bulk_create_info(redis_list, n_time, channel, event_type, is_st, uid)
 
-                 if is_st == '0' or is_st == '2':
 
-                     return JsonResponse(status=200, data={'code': 0, 'msg': 'success44444444444444444'})
 
-                 elif is_st == '1':
 
-                     # Endpoint以杭州为例,其它Region请按实际情况填写。
 
-                     # obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
 
-                     # 设置此签名URL在60秒内有效。
 
-                     # url = bucket.sign_url('PUT', obj, 7200)
 
-                     thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
 
-                     if region == 2:  # 2:国内
 
-                         response_url = aws_s3_guonei.generate_presigned_url(
 
-                             ClientMethod='put_object',
 
-                             Params={
 
-                                 'Bucket': 'push',
 
-                                 'Key': thumbspng
 
-                             },
 
-                             ExpiresIn=3600
 
-                         )
 
-                     else:  # 1:国外
 
-                         response_url = aws_s3_guowai.generate_presigned_url(
 
-                             ClientMethod='put_object',
 
-                             Params={
 
-                                 'Bucket': 'foreignpush',
 
-                                 'Key': thumbspng
 
-                             },
 
-                             ExpiresIn=3600
 
-                         )
 
-                     # res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
 
-                     # response_url = response_url[:4] + response_url[5:]
 
-                     res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
 
-                     return JsonResponse(status=200, data=res_data)
 
-                 elif is_st == '3':
 
-                     # 人形检测带动图
 
-                     img_url_list = []
 
-                     for i in range(int(is_st)):
 
-                         # obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
 
-                         #     format(uid=uid, channel=channel, filename=n_time, st=i)
 
-                         # 设置此签名URL在60秒内有效。
 
-                         # url = bucket.sign_url('PUT', obj, 7200)
 
-                         thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
 
-                             format(uid=uid, channel=channel, filename=n_time, st=i)
 
-                         if region == 2:  # 2:国内
 
-                             response_url = aws_s3_guonei.generate_presigned_url(
 
-                                 ClientMethod='put_object',
 
-                                 Params={
 
-                                     'Bucket': 'push',
 
-                                     'Key': thumbspng
 
-                                 },
 
-                                 ExpiresIn=3600
 
-                             )
 
-                         else:  # 1:国外
 
-                             response_url = aws_s3_guowai.generate_presigned_url(
 
-                                 ClientMethod='put_object',
 
-                                 Params={
 
-                                     'Bucket': 'foreignpush',
 
-                                     'Key': thumbspng
 
-                                 },
 
-                                 ExpiresIn=3600
 
-                             )
 
-                         # response_url = response_url[:4] + response_url[5:]
 
-                         img_url_list.append(response_url)
 
-                         # img_url_list.append(url)
 
-                     res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success'}
 
-                     return JsonResponse(status=200, data=res_data)
 
-             else:
 
-                 return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})
 
-         else:
 
-             return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
 
-     def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):
 
-         now_time = int(time.time())
 
-         # 设备昵称
 
-         userID_ids = []
 
-         sys_msg_list = []
 
-         is_sys_msg = self.is_sys_msg(int(event_type))
 
-         is_st = int(is_st)
 
-         eq_list = []
 
-         nickname = uaqs[0]['uid_set__nickname']
 
-         if not nickname:
 
-             nickname = uid
 
-         for ua in uaqs:
 
-             lang = ua['lang']
 
-             tz = ua['tz']
 
-             userID_id = ua["userID_id"]
 
-             if userID_id not in userID_ids:
 
-                 eq_list.append(Equipment_Info(
 
-                     userID_id=userID_id,
 
-                     eventTime=n_time,
 
-                     eventType=event_type,
 
-                     devUid=uid,
 
-                     devNickName=nickname,
 
-                     Channel=channel,
 
-                     alarm='Motion \tChannel:{channel}'.format(channel=channel),
 
-                     is_st=is_st,
 
-                     receiveTime=n_time,
 
-                     addTime=now_time,
 
-                     storage_location=2
 
-                 ))
 
-                 if is_sys_msg:
 
-                     sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
 
-                                                      event_type=event_type, is_sys=1)
 
-                     sys_msg_list.append(SysMsgModel(
 
-                         userID_id=userID_id,
 
-                         msg=sys_msg_text,
 
-                         addTime=now_time,
 
-                         updTime=now_time,
 
-                         uid=uid,
 
-                         eventType=event_type))
 
-         if eq_list:
 
-             print('eq_list')
 
-             Equipment_Info.objects.bulk_create(eq_list)
 
-         if is_sys_msg:
 
-             print('sys_msg')
 
-             SysMsgModel.objects.bulk_create(sys_msg_list)
 
-         return True
 
-     def is_sys_msg(self, event_type):
 
-         event_type_list = [702, 703, 704]
 
-         if event_type in event_type_list:
 
-             return True
 
-         return False
 
-     def get_msg_text(self, channel, n_time, lang, tz, event_type, is_sys=0):
 
-         n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)
 
-         etype = int(event_type)
 
-         if lang == 'cn':
 
-             if etype == 704:
 
-                 msg_type = '电量过低'
 
-             elif etype == 702:
 
-                 msg_type = '摄像头休眠'
 
-             elif etype == 703:
 
-                 msg_type = '摄像头唤醒'
 
-             else:
 
-                 msg_type = ''
 
-             if is_sys:
 
-                 send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
 
-             else:
 
-                 send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
 
-         else:
 
-             if etype == 704:
 
-                 msg_type = 'Low battery'
 
-             elif etype == 702:
 
-                 msg_type = 'Camera sleep'
 
-             elif etype == 703:
 
-                 msg_type = 'Camera wake'
 
-             else:
 
-                 msg_type = ''
 
-             if is_sys:
 
-                 send_text = '{msg_type} channel:{channel}'. \
 
-                     format(msg_type=msg_type, channel=channel)
 
-             else:
 
-                 send_text = '{msg_type} channel:{channel} date:{date}'. \
 
-                     format(msg_type=msg_type, channel=channel, date=n_date)
 
-         return send_text
 
 
  |