Beispiel #1
0
def delete_token_to_facebook(brick_id):
    try:
        log_id = request.args.get('log_id', None)

        if request.method == 'DELETE':
            user_inform = get_facebook_account()
            user_id = user_inform.get('fb_id')

            result = mongo3.db.facebook.update_one({'id': brick_id},
                                                   {'$set': {'page_id': '', 'access_token': ''}},
                                                   upsert=False)
            if result.matched_count:
                return {
                    'success': True,
                    'facebook': get_facebook_account(),
                    'data': {
                        'matched_count': result.matched_count,
                        'modified_count': result.modified_count,
                        'published': publish(brick_id, log_id=log_id, user_id=user_id)
                    }
                }
        return {
            'success': False,
            'action': 'ERR0002',
            'msg': '세트가 존재하지 않습니다.'
        }
    except:
        pass
Beispiel #2
0
def save_log_new_to_server():
    req_json = request.get_json()
    if 'log_id' not in req_json:
        raise RuntimeError('로그 ID 값이 존재하지 않습니다.')

    if 'start' not in req_json:
        raise RuntimeError('시작 시간이 존재하지 않습니다.')

    if 'end' not in req_json:
        raise RuntimeError('종료 시간이 존재하지 않습니다.')

    if 'task_code' not in req_json and 'api_code' not in req_json:
        raise RuntimeError('Task 코드나 API 코드 중 하나는 존재해야합니다.')

    application = req_json.get('application', False)
    if application and application == 'telegram':
        if req_json.get('task_code', False):
            if req_json['task_code'] in ('editMessageCaption',
                                         'editMessageText'):
                req_json['task_code'] = 'editMessageReplyMarkup'

    if req_json.get('user_id') is None or str(
            req_json.get('user_id')).strip() == '':
        req_json['user_id'] = get_facebook_account().get('fb_id', 'No_ID')

    req_json['user-agent'] = request.headers.get('User-Agent', None)

    mongo3.db.log_new.insert_one(req_json)

    return {'success': True}
Beispiel #3
0
def get_users_connected_platforms():
    if request.method == 'GET':
        if 'fb_id' in session:
            rslt_data = {
                'success': True,
                'facebook': get_facebook_account(),
                'data': {

                }
            }

            result = mongo3.db.facebook.find({
                'user_id': session['fb_id']
            }, {
                'name': True,
                'page_id': True
            })

            if result:
                rslt_data['data']['registered_page_list'] = result

            return rslt_data
        else:
            return {
                'success': False,
                'action': 'ERR0001',
                'msg': '로그인 상태가 아니에요'
            }
Beispiel #4
0
def get_brick():
    try:
        user_inform = get_facebook_account()
        if 'fb_id' in session:
            try:
                return {
                    'success':
                    True,
                    'facebook':
                    user_inform,
                    'data':
                    loads(
                        dumps(
                            mongo3.db.facebook.find(
                                {'user_id': session['fb_id']}, {
                                    "access_token": False,
                                    "verify_token": False,
                                    "persistent_menu": False,
                                    "bricks": False,
                                    "telegram": False,
                                    "settings": False
                                })))
                }
            except Exception as ex:
                return {
                    'success': False,
                    'action': 'ERR0002',
                    'msg': '에러가 발생했어요.\n잠시 뒤에 시도해주세요.\n에러 내용: %s' % str(ex)
                }
        return {'success': False, 'action': 'ERR0001', 'msg': '로그인 상태가 아니에요.'}
    except:
        pass
Beispiel #5
0
def get_brick_list():
    try:
        user_inform = get_facebook_account()
        data = loads(
            dumps(mongo3.db.brick.find({}).sort([('seq', pymongo.ASCENDING)])))
        for idx, value in enumerate(data):
            if value['id'] == 'mailerforset':
                del (data[idx])

        return {'success': True, 'facebook': user_inform, 'data': data}
    except:
        pass
Beispiel #6
0
def get_users_connected_platforms_by_id(brick_id):
    if request.method == 'GET':
        if 'fb_id' in session:
            rslt_data = {
                'success': True,
                'facebook': get_facebook_account(),
                'data': {
                }
            }
            result = mongo3.db.facebook.find({
                'user_id': session['fb_id']
            }, {
                'id': True,
                'name': True,
                'page_id': True,
            })

            tg_result = mongo3.db.facebook.find_one({
                'user_id': session['fb_id'],
                'id': brick_id
            }, {
                'telegram.token': True
            })

            if result:
                rslt_data['data']['registered_page_list'] = result

            if 'telegram' in tg_result:
                if 'token' in tg_result['telegram']:
                    token = tg_result['telegram']['token']
                    if token is not None and token.strip() != '':
                        res = requests.get('https://api.telegram.org/bot%s/getMe' % token)
                        rslt_data['data']['telegram'] = res.json().get('result', {})

            return rslt_data

        else:
            return {
                'success': False,
                'action': 'ERR0001',
                'msg': '로그인 상태가 아니에요.'
            }
Beispiel #7
0
def save_log_on_server(req_json):
    logger.info(req_json)
    if 'log_id' not in req_json:
        raise RuntimeError('로그 ID 값이 존재하지 않습니다.')

    if 'start' not in req_json:
        raise RuntimeError('시작 시간이 존재하지 않습니다.')

    if 'end' not in req_json:
        raise RuntimeError('종료 시간이 존재하지 않습니다.')

    if 'task_code' not in req_json and 'api_code' not in req_json:
        raise RuntimeError('Task 코드나 API 코드 중 하나는 존재해야합니다.')

    if req_json.get('user_id') is None or str(req_json.get('user_id')).strip() == '':
        req_json['user_id'] = get_facebook_account().get('fb_id')

    result = mongo3.db.log.insert_one(req_json)

    logger.info(result)
    return {
        'success': True
    }
Beispiel #8
0
def save_log_to_server():
    req_json = request.get_json()
    if 'log_id' not in req_json:
        raise RuntimeError('로그 ID 값이 존재하지 않습니다.')

    if 'start' not in req_json:
        raise RuntimeError('시작 시간이 존재하지 않습니다.')

    if 'end' not in req_json:
        raise RuntimeError('종료 시간이 존재하지 않습니다.')

    if 'task_code' not in req_json and 'api_code' not in req_json:
        raise RuntimeError('Task 코드나 API 코드 중 하나는 존재해야합니다.')

    if req_json.get('user_id') is None or str(
            req_json.get('user_id')).strip() == '':
        req_json['user_id'] = get_facebook_account().get('fb_id', 'No_ID')

    req_json['user-agent'] = request.headers.get('User-Agent', None)

    mongo3.db.log.insert_one(req_json)

    return {'success': True}
Beispiel #9
0
def set_token_to_telegram(brick_id, telegram_token):
    if request.method == 'PUT':
        count_token = mongo3.db.facebook.find({'telegram.token': telegram_token}).count()

        if count_token:
            return {
                'success': False,
                'action': 'ERR0002',
                'msg': '이미 등록된 토큰입니다.\n해당 토큰의 사용해제 후 사용해주세요.'
            }

        result = mongo3.db.facebook.update_one({'id': brick_id}, {'$set': {'telegram.token': telegram_token}},
                                               upsert=False)

        if result.matched_count:
            requests.get(
                url='https://www.chatbrick.io/webhooks/api/telegram/register/?token=%s&brick_id=%s' % (
                    telegram_token, brick_id))

            bot_name = mongo3.db.telegram_token.find_one({'token': telegram_token})

            if bot_name is None:
                res = requests.get('https://api.telegram.org/bot%s/getMe' % telegram_token).json()

                if res.get('result', False):
                    res = res.get('result')
                    res['token'] = telegram_token
                    bot_name = res
                    mongo3.db.telegram_token.insert_one(res)

            return {
                'success': True,
                'facebook': get_facebook_account(),
                'data': {
                    'matched_count': result.matched_count,
                    'modified_count': result.modified_count,
                    'telegram': {
                        'ok': True,
                        'result': True,
                        'description': "Webhook was set"
                    },
                    'bot': bot_name,
                    'published': True
                }
            }
        else:
            return {
                'success': False,
                'action': 'ERR0002',
                'msg': '텔레그램 봇 등록 실패했어요.'
            }
    elif request.method == 'DELETE':
        result = mongo3.db.facebook.update_one({'id': brick_id}, {'$set': {'telegram.token': ''}},
                                               upsert=False)
        if result.matched_count:
            requests.get(
                url='https://www.chatbrick.io/webhooks/api/telegram/delete/?token=%s&brick_id=%s' % (
                    telegram_token, brick_id))
            return {
                'success': True,
                'facebook': get_facebook_account(),
                'data': {
                    'matched_count': result.matched_count,
                    'modified_count': result.modified_count,
                    'telegram': {
                        'ok': True,
                        'result': True,
                        'description': "Webhook was set"
                    },
                    'published': True
                }
            }
    return {
        'success': False,
        'action': 'ERR0002',
        'msg': '세트가 존재하지 않아요.'
    }
Beispiel #10
0
def brick_login():
    try:
        if request.method == 'POST':
            if request.form.get('test', False):
                session['fb_id'] = 'test'
                session['fb_profile'] = ''
                session['fb_name'] = ''
                session['fb_access_token'] = ''
                return {
                    'success': True,
                    'facebook': get_facebook_account(),
                    'is_test': True
                }

            fb_access_token = request.form.get('fb_access_token', False)
            data = {
                'client_id': '134243977372890',
                'client_secret': '37f41797e0e6c53677f185817d08589f',
                'short_access_token': fb_access_token,
                'redirect_url': 'https://www.chatbrick.io'
            }

            res = requests.get(
                'https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id={client_id}&client_secret={client_secret}&fb_exchange_token={short_access_token}'.format(
                    **data))

            fb_long_lived_access_token = res.json()['access_token']
            data['long_access_token'] = fb_long_lived_access_token

            profile_res = requests.get(
                'https://graph.facebook.com/v2.12/me?fields=id,name&access_token=%s' % fb_long_lived_access_token
            )

            fb_id = profile_res.json()['id']
            fb_name = profile_res.json()['name']

            profile_image_res = requests.get(
                'https://graph.facebook.com/v2.12/%s/picture?access_token=%s&redirect=false' % (
                    fb_id, fb_long_lived_access_token),
                headers={
                    'Content-Type': 'application/json'
                }
            )

            code_res = requests.get(
                'https://graph.facebook.com/oauth/client_code?access_token={long_access_token}&client_secret={client_secret}&redirect_uri={redirect_url}&client_id={client_id}'.format(
                    **data))

            fb_code = code_res.json()['code']
            fb_profile = profile_image_res.json()['data']['url']

            if fb_id:
                session['fb_id'] = fb_id
                session['fb_profile'] = fb_profile
                session['fb_name'] = fb_name
                session['fb_access_token'] = fb_long_lived_access_token

                return {
                    'success': True,
                    'facebook': get_facebook_account(),
                    'code': fb_code
                }
        elif request.method == 'DELETE':
            if 'fb_id' in session:
                session.clear()
            return {
                'success': True
            }
        elif request.method == 'GET':
            if 'fb_id' in session:
                return {
                    'success': True,
                    'facebook': get_facebook_account(),
                }

            return {
                'success': False,
                'action': 'ERR0001',
                'msg': '로그인 상태가 아니에요.'
            }
        elif request.method == 'PUT':
            fb_access_token = request.form.get('fb_client_access_token', False)
            session['fb_client_access_token'] = fb_access_token
            return {
                'success': True,
                'facebook': get_facebook_account(),
            }

        return {
            'success': False,
            'action': 'ERR0001',
            'msg': '로그인 실패했어요.'
        }
    except Exception as ex:
        return {
            'success': False,
            'action': 'ERR0002',
            'msg': '에러가 발생했어요.\n에러 사유: %s' % str(ex)
        }