| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705 | #!/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 osimport timeimport apns2import jpush as jpushimport oss2from django.http import JsonResponsefrom django.views.generic.base import Viewfrom pyfcm import FCMNotificationfrom Object.RedisObject import RedisObjectfrom Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, DETECT_PUSH_DOMAIN, JPUSH_CONFIG, \    FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODEfrom Model.models import Device_Info, VodHlsModel, Equipment_Info, UidSetModel, UidPushModelfrom Object.ETkObject import ETkObjectfrom Object.RedisObject import RedisObjectfrom Object.ResponseObject import ResponseObjectfrom Object.TokenObject import TokenObjectfrom Object.UidTokenObject import UidTokenObjectfrom Service.CommonService import CommonService'''http://test.push.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJUNEFaM0NVS0NFUkg5RlpBMTExQSJ9.GtrXeq5gb2Z9M3mKECxi9eNQbPxqC-6PtgJkOOg6PwI&n_time=1598456451&channel=1&event_type=1&is_st=1http://push.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJUNEFaM0NVS0NFUkg5RlpBMTExQSJ9.GtrXeq5gb2Z9M3mKECxi9eNQbPxqC-6PtgJkOOg6PwI&n_time=1598456451&channel=1&event_type=1&is_st=1http://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=2http://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=60http://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=60detect/changeStatus'''class DetectControllerView(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)        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_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)        qs = Equipment_Info.objects.filter(userID_id=userID).order_by('-eventTime')        if startTime and endTime:            qs = qs.filter(eventTime__range=(startTime, endTime))        if eventType:            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.exists():            return response.json(0, {'datas': [], 'count': 0})        qs = qs.values('id', 'devUid', 'devNickName', 'Channel', 'eventType', 'status', 'alarm', 'eventTime',                       'receiveTime', 'is_st', 'addTime')        count = qs.count()        qr = qs[(page - 1) * line:page * line]        res = []        auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)        img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')        # vod_time_list = []        for p in qr:            devUid = p['devUid']            eventTime = p['eventTime']            channel = p['Channel']            if p['is_st'] == 1:                p['img'] = img_bucket.sign_url('GET', '{uid}/{channel}/{time}.jpeg'.                                               format(uid=devUid, channel=p['Channel'], time=eventTime), 300)                p['img_list'] = [img_bucket.sign_url('GET', '{uid}/{channel}/{time}.jpeg'.                                                     format(uid=devUid, channel=channel, time=eventTime), 300)]            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)                    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 p['is_st'] == 3:                # 列表装载回放时间戳标记                p['img_list'] = []                for i in range(p['is_st']):                    img = img_bucket.sign_url('GET', '{uid}/{channel}/{time}_{st}.jpeg'.                                              format(uid=devUid, channel=p['Channel'], time=eventTime, st=i), 300)                    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'] = ''            res.append(p)        return response.json(0, {'datas': res, 'count': count})    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')        # 消息提醒功能新增        # 如果传空上来,就默认为0        if tz == '':            tz = 0        detect_group = request_dict.get('detect_group', None)        interval = request_dict.get('interval', None)        if not status:            return response.json(444, 'status')        # 关闭推送        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)        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)        dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)        status = int(status)        # 获取用户区域        # ip = self.ip        # ipInfo = CommonService.getIpIpInfo(ip=ip, lang='EN')        # area = ipInfo['country_name']        # if area == 'China':        #     DETECT_PUSH_DOMAIN = 'cn.push.dvema.com'        # else:        #     DETECT_PUSH_DOMAIN = 'en.push.dvema.com'        nowTime = int(time.time())        if dvqs.exists():            # 修改状态            dvqs.update(NotificationMode=status)            uid_set_qs = UidSetModel.objects.filter(uid=uid)            # uid配置信息是否存在            if uid_set_qs.exists():                uid_set_id = uid_set_qs[0].id                qs_data = {                    'detect_status': status,                    'updTime': nowTime,                }                if interval:                    qs_data['detect_interval'] = int(interval)                if detect_group:                    qs_data['detect_group'] = detect_group                print(qs_data)                uid_set_qs.update(**qs_data)            else:                qs_data = {                    'uid': uid,                    'addTime': nowTime,                    'updTime': nowTime,                    'detect_status': status,                }                if interval:                    qs_data['detect_interval'] = int(interval)                if detect_group:                    qs_data['detect_group'] = detect_group                # 添加设备配置                uid_set_qs = UidSetModel.objects.create(**qs_data)                uid_set_id = uid_set_qs.id            if status == 0:                UidPushModel.objects.filter(uid_set__uid=uid).delete()                # 状态为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)                # ykey = '{uid}_redis_qs'.format(uid=uid)                # redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')                # redisObj.del_data(key=ykey)                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, int(interval))                else:                    self.do_delete_redis(uid)                # utko = UidTokenObject()                # # right                # utko.generate(data={'uid': uid})                etkObj = ETkObject(etk='')                etk = etkObj.encrypt(uid)                detectUrl = "{DETECT_PUSH_DOMAIN}notify/push?etk={etk}". \                    format(etk=etk, DETECT_PUSH_DOMAIN=DETECT_PUSH_DOMAIN)                return response.json(0, {'detectUrl': detectUrl})        else:            return response.json(14)    def do_delete_redis(self, uid, detect_interval=0):        keyPattern = '{uid}*'.format(uid=uid)        redisObj = RedisObject(db=6, SERVER_HOST='push.dvema.com')        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_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)# http://192.168.136.40:8077/notify/push?uidToken=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJUTjdNUEUzMjExVUU3NkFQMTExQSJ9.k501567VdnhFpn_ygzGRDat3Kqlz5CsEA9jAC2dDk_g&obj=12341234&n_time=1234561234# http://test.dvema.com/notify/push?uidToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiJQMldOR0pSRDJFSEE1RVU5MTExQSJ9.xOCI5lerk8JOs5OcAzunrKCfCrtuPIZ3AnkMmnd-bPY&n_time=1526845794&channel=1&event_type=51&is_st=0# 移动侦测接口class NotificationView(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):        response = ResponseObject()        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)        if not all([channel, n_time]):            return JsonResponse(status=200, data={                'code': 444,                'msg': 'param is wrong'})            # return response.json(444)        if etk:            eto = ETkObject(etk)            uid = eto.uid            if len(uid) != 20:                return JsonResponse(status=200, data={'code': 404, 'msg': 'data is not exist'})        else:            utko = UidTokenObject(uidToken)            uid = utko.UID        # utko = UidTokenObject(uidToken)        # uid = utko.UID        detect_group = UidSetModel.objects.filter(uid=uid). \            values('detect_group')        event_type = detect_group        # 新增 移动侦测        if event_type == '0':            self.detect_group_push(self, request_dict, uid, response, channel, n_time, event_type, is_st)        # 新增 pir侦测        if event_type == '1':            self.detect_group_push(self, request_dict, uid, response, channel, n_time, event_type, is_st)        # 新增 移动侦测和pir侦测        if event_type == '01':            self.detect_group_push(self, request_dict, uid, response, channel, n_time, event_type, is_st)    # 新增 把代码封装以便后面分侦测类型    def detect_group_push(self, request_dict, uid, response, channel, n_time, event_type, is_st):        redisObj = RedisObject(db=6)        pkey = '{uid}_{channel}_ptl'.format(uid=uid, channel=channel)        if redisObj.get_data(key=pkey):            res_data = {'code': 0, 'msg': 'success,!'}            return JsonResponse(status=200, data=res_data)        else:            # 设置推送间隔60秒一次            redisObj.set_data(key=pkey, val=1, expire=60)        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', 'userID__NickName',                   'lang', 'tz', 'uid_set__nickname')        if uid_push_qs.exists():            nickname = uid_push_qs[0]['uid_set__nickname']            if not nickname:                nickname = uid            auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)            bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')            for up in uid_push_qs:                push_type = up['push_type']                # ios apns                print(push_type)                if push_type == 0:                    self.do_apns(request_dict, up, response, uid, channel, nickname)                # android gcm                elif push_type == 1:                    self.do_fcm(request_dict, up, response, uid, channel, nickname)                # self.do_gmc(request_dict, up, response, uid, channel,nickname)                # android jpush                elif push_type == 2:                    self.do_jpush(request_dict, up, response, uid, channel, nickname)            # self.do_save_equipment_info(ua, n_time, channel, event_type, is_st)            # 需求不一样,所以这么做的            self.do_bulk_create_info(uid_push_qs, n_time, channel, event_type, is_st, uid)            if is_st == '0' or is_st == '2':                return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})            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)                res_data = {'code': 0, 'img_push': url, 'msg': 'success'}                return JsonResponse(status=200, data=res_data)            elif 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)                    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'})    def do_jpush(self, request_dict, uaql, response, uid, channel, nickname):        event_type = request_dict.get('event_type', None)        n_time = request_dict.get('n_time', None)        appBundleId = uaql['appBundleId']        token_val = uaql['token_val']        lang = uaql['lang']        tz = uaql['tz']        response = ResponseObject()        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}        message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)        send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)        android = jpush.android(alert=send_text, priority=1, style=1, alert_type=7,                                big_text=send_text, title=message_title,                                extras=push_data)        push.notification = jpush.notification(android=android)        push.platform = jpush.all_        try:            res = push.send()            print(res)        except Exception as e:            print("Exception")            print(repr(e))            return response.json(10, repr(e))        else:            return response.json(0)    def get_message_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 get_send_text(self, channel, n_time, lang, tz, event_type):        n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz)        msg_type = ''        if int(event_type) == 704:            msg_type = 'battery is too low'            if lang == 'cn':                msg_type = '电池电量过低'        send_text = '{msg_type}channel:{channel} date:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)        if lang == 'cn':            send_text = '{msg_type}通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)        return send_text    def do_fcm(self, request_dict, uaql, response, uid, channel, nickname):        n_time = request_dict.get('n_time')        appBundleId = uaql['appBundleId']        token_val = uaql['token_val']        lang = uaql['lang']        tz = uaql['tz']        try:            serverKey = FCM_CONFIG[appBundleId]        except Exception as e:            return response.json(404)        event_type = request_dict.get('event_type', None)        push_service = FCMNotification(api_key=serverKey)        registration_id = token_val        message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)        send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)        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=registration_id, message_title=message_title,                                                   message_body=send_text, data_message=data,                                                   extra_kwargs={                                                       'default_vibrate_timings': True,                                                       'default_sound': True,                                                       'default_light_settings': True                                                   })        response = ResponseObject()        return response.json(0, result)    def do_apns(self, request_dict, uaql, response, uid, channel, nickname):        event_type = request_dict.get('event_type', None)        token_val = uaql['token_val']        lang = uaql['lang']        n_time = request_dict.get('n_time')        appBundleId = uaql['appBundleId']        tz = uaql['tz']        message_title = self.get_message_title(appBundleId=appBundleId, nickname=nickname)        send_text = self.get_send_text(channel=channel, n_time=n_time, lang=lang, tz=tz, event_type=event_type)        try:            print('---')            cli = apns2.APNSClient(mode=APNS_MODE,                                   client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))            # password=APNS_CONFIG[appBundleId]['password'])            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}            # body = json.dumps(push_data)            alert = apns2.PayloadAlert(body=send_text, title=message_title)            payload = apns2.Payload(alert=alert, custom=push_data)            n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)            res = cli.push(n=n, device_token=token_val, topic=appBundleId)            # assert res.status_code == 200, res.reason            # assert res.apns_id            print('========')            print(res.status_code)            if res.status_code == 200:                return response.json(0)            else:                return response.json(404, res.reason)        except Exception as e:            print(repr(e))            return response.json(10, repr(e))    def do_bulk_create_info(self, uaqs, n_time, channel, event_type, is_st, uid):        #        qs_list = []        nowTime = int(time.time())        # 设备昵称        userID_ids = []        for dv in uaqs:            userID_id = dv["userID_id"]            if userID_id not in userID_ids:                if dv['uid_set__nickname']:                    uid_nickname = dv['uid_set__nickname']                else:                    uid_nickname = uid                add_data = {                    'userID_id': dv["userID_id"],                    'eventTime': n_time,                    'eventType': event_type,                    'devUid': uid,                    'devNickName': uid_nickname,                    'Channel': channel,                    'alarm': 'Motion \tChannel:{channel}'.format(channel=channel),                    'is_st': int(is_st),                    'receiveTime': n_time,                    'addTime': nowTime                }                qs_list.append(Equipment_Info(**add_data))                userID_ids.append(userID_id)        if qs_list:            print(1)            Equipment_Info.objects.bulk_create(qs_list)            return True        else:            return False# 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)        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)            # 推送时间限制            if redisObj.get_data(key=pkey):                res_data = {'code': 0, 'msg': 'success,!'}                return JsonResponse(status=200, data=res_data)            else:                redisObj.set_data(key=pkey, val=1, expire=60)            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', 'userID__NickName', 'lang',                       'tz', 'uid_set__nickname')            if uid_push_qs.exists():                auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)                bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')                self.do_bulk_create_info(uid_push_qs, n_time, channel, event_type, is_st, uid)                if is_st == '0' or is_st == '2':                    return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})                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)                    res_data = {'code': 0, 'img_push': 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)                        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):        #        qs_list = []        nowTime = int(time.time())        # 设备昵称        userID_ids = []        for dv in uaqs:            userID_id = dv["userID_id"]            if userID_id not in userID_ids:                if dv['uid_set__nickname']:                    uid_nickname = dv['uid_set__nickname']                else:                    uid_nickname = uid                add_data = {                    'userID_id': dv["userID_id"],                    'eventTime': n_time,                    'eventType': event_type,                    'devUid': uid,                    'devNickName': uid_nickname,                    'Channel': channel,                    'alarm': 'Motion \tChannel:{channel}'.format(channel=channel),                    'is_st': int(is_st),                    'receiveTime': n_time,                    'addTime': nowTime                }                qs_list.append(Equipment_Info(**add_data))                userID_ids.append(userID_id)        if qs_list:            print(1)            Equipment_Info.objects.bulk_create(qs_list)            return True        else:            return False
 |