Пример #1
0
def get_account():
    token = request.headers.get('Authorization', '')[len('Bearer '):]
    if not database.token(access=token) or database.token(access=token)[0]['expired'] < datetime.now():
        return '', 403
    user_id = database.token(access=token)[0]['user_id']

    return json.dumps({
        'login': database.user[user_id]['login'],
        'name': database.user[user_id]['name'],
        'email': database.user[user_id]['email'],
        'phone': database.user[user_id]['phone']
    }, indent=4), 200, {
        'Content-Type': 'application/json;charset=UTF-8'
    }
Пример #2
0
def delete_cart_item(id):
    token = request.headers.get('Authorization', '')[len('Bearer '):]
    if not database.token(access=token) or database.token(access=token)[0]['expired'] < datetime.now():
        return '', 403
    user_id = database.token(access=token)[0]['user_id']

    try:
        id = int(id)
        if id not in database.item or database.cart[id]['user_id'] != user_id:
            raise Exception()
    except:
        return '', 404

    database.cart.delete(database.cart[id])
    database.cart.commit()
    return '', 200
Пример #3
0
def starter():
    from database import token
    import json
    from multiprocessing import Process, Queue, Manager
    token = token()
    manager = Manager()
    flags = manager.dict()
    with open('prefs.jpg', 'r') as f:
        m = f.read()
        if len(m) > 1:
            k = json.loads(m)
            for i in k:
                flags[i] = k[i]
    message_queue = Queue()
    input_queue = Queue()
    main_proc = Process(target=main_hull, args=(flags, input_queue, message_queue, token,))
    handlers = []
    for i in range(5):
        handlers.append(Process(target=handler_hull, args=(input_queue, message_queue, token, flags,)))
    sender_proc = Process(target=sender, args=(message_queue, token,))
    main_proc.start()
    for i in handlers:
        i.start()
    sender_proc.start()
    main_proc.join()
    for i in handlers:
        i.join()
    sender_proc.join()
Пример #4
0
def add_to_cart():
    token = request.headers.get('Authorization', '')[len('Bearer '):]
    if not database.token(access=token) or database.token(access=token)[0]['expired'] < datetime.now():
        return '', 403
    user_id = database.token(access=token)[0]['user_id']

    try:
        item_id = int(request.form['item_id'])
        count = int(request.form['count'])
        if item_id not in database.item:
            raise Exception()
    except:
        return '', 400

    id = database.cart.insert(user_id=user_id, item_id=item_id, count=count)
    database.cart.commit()
    return json.dumps({'id': id}), 201, {
        'Content-Type': 'application/json;charset=UTF-8'
    }
Пример #5
0
def get_cart():
    token = request.headers.get('Authorization', '')[len('Bearer '):]
    if not database.token(access=token) or database.token(access=token)[0]['expired'] < datetime.now():
        return '', 403
    user_id = database.token(access=token)[0]['user_id']

    try:
        per_page = int(request.args.get('per_page', 9))

        page = int(request.args.get('page', 0))
        if page < 0 or page > len(database.item) // per_page:
            raise Exception()
    except:
        return '', 400

    items = []
    for i, cart_item in enumerate(database.cart(user_id=user_id)):
        if i < per_page * page:
            continue
        if i >= per_page * (page + 1):
            break
        items.append({
            'id': cart_item['__id__'],
            'item': json.dumps({
                'name': database.item[cart_item['item_id']]['name'],
                'price': database.item[cart_item['item_id']]['price']
            }),
            'count': cart_item['count']
        })
    return json.dumps({
        'cart_items': items,
        'per_page': per_page,
        'page': page,
        'page_count': math.ceil(len(database.cart(user_id=user_id)) / per_page)
    }, indent=4), 200, {
        'Content-Type': 'application/json;charset=UTF-8'
    }
Пример #6
0
def token():
    try:
        client_id = request.form['client_id']
        client_secret = request.form['client_secret']
        grant_type = request.form['grant_type']
    except KeyError:
        return json.dumps({'error': 'invalid_request'}), 400, {
            'Content-Type': 'application/json;charset=UTF-8'
        }

    try:
        client_id = int(client_id)
    except:
        client_id = None
    if client_id not in database.client or database.client[client_id]['client_secret'] != client_secret:
        return json.dumps({'error': 'invalid_client'}), 400, {
            'Content-Type': 'application/json;charset=UTF-8'
        }

    if grant_type == 'authorization_code':
        try:
            code = request.form['code']
        except KeyError:
            return json.dumps({'error': 'invalid_request'}), 400, {
                'Content-Type': 'application/json;charset=UTF-8'
            }
        if not database.auth_code(code=code) or database.auth_code(code=code)[0]['expired'] < datetime.now():
            return json.dumps({'error': 'invalid_grant'}), 400, {
                'Content-Type': 'application/json;charset=UTF-8'
            }
        user_id = database.auth_code(code=code)[0]['user_id']
        database.auth_code.delete(database.auth_code(code=code))
        database.auth_code.commit()
    elif grant_type == 'refresh_token':
        try:
            refresh_token = request.form['refresh_token']
        except KeyError:
            return json.dumps({'error': 'invalid_request'}), 400, {
                'Content-Type': 'application/json;charset=UTF-8'
            }
        if not database.token(refresh=refresh_token):
            return json.dumps({'error': 'invalid_grant'}), 400, {
                'Content-Type': 'application/json;charset=UTF-8'
            }
        user_id = database.token(refresh=refresh_token)[0]['user_id']
        database.token.delete(database.token(refresh=refresh_token))
        database.token.commit()
    else:
        return json.dumps({'error': 'unsupported_grant_type'}), 400, {
            'Content-Type': 'application/json;charset=UTF-8'
        }

    access_token = sha256(str(uuid4()).encode('UTF-8')).hexdigest()
    expired = datetime.now() + timedelta(hours=1)
    refresh_token = sha256(str(uuid4()).encode('UTF-8')).hexdigest()
    database.token.insert(user_id=user_id, access=access_token, expired=expired, refresh=refresh_token)
    database.token.commit()

    return json.dumps({
        'access_token': access_token,
        'token_type': 'bearer',
        'expired': 3600,
        'refresh_token': refresh_token
    }), 200, {
        'Content-Type': 'application/json;charset=UTF-8',
        'Cache-Control': 'no-store',
        'Pragma': 'no-cache'
    }
Пример #7
0
def handle_dialog(res, req):
    vk_session = vk_api.VkApi(token=token())
    uid = req['session']['user_id']
    if req['session']['new']:
        flags[uid] = {
            'translate': False,
            'voices': False,
            'lang_translate': 'en'
        }
        res['response']['text'] = 'Привет! Отправь боту голосовое или введи одну из команд:\n\n' \
                  'автоперевод включить/выключить - присылать ответ голосовым сообщением\n' \
                  'перевод вкл/выкл - переводить ли на другой язык (по умолчанию - английский)\n' \
                  'перевод английский - переводить на английский\n\n' \
                  'Tips and tricks:\n\n' \
                  '+ Можно сокращать некоторые запросы (кроме названий языков): авто вкл (автоперевод)\n' \
                  '+ Хотя в примере показан лишь английский, бот позволяет распознавать, переводить и' \
                  ' озвучивать 103 языка.'
        return

    text = req['request']['original_utterance']
    message = text
    settings = False
    if 'нач' in text or 'start' in text:
        settings = True
    elif 'авто' in text and (' на ' in text or 'вкл' in text
                             or 'выкл' in text):
        if 'вкл' in text:
            flags[uid]['voices'] = True
            settings = True
        elif 'выкл' in text:
            flags[uid]['voices'] = False
            settings = True
    elif 'перевод' in text and (' на ' in text or 'вкл' in text
                                or 'выкл' in text):
        if ' на ' in text:
            for i in text.split():
                d = get_translation(i, 'en')
                if d in langlist:
                    flags[uid]['lang_translate'] = langlist[d]
                    settings = True
        if 'вкл' in text:
            flags[uid]['translate'] = True
            settings = True
        elif 'выкл' in text:
            flags[uid]['translate'] = False
            settings = True
    else:
        message = req['request']['original_utterance']
        if flags[uid]['translate']:
            message = get_translation(message, flags[uid]['lang_translate'])
            logging.info(message)
        if flags[uid]['voices']:
            logging.info('voices!')
            audio_url = vk_session.method(
                'docs.getMessagesUploadServer', {
                    'type': 'audio_message',
                    'peer_id': peer_id(),
                    'group_id': group_id()
                })['upload_url']
            logging.info(audio_url)
            meow = synthesis(message, detect(message))
            if meow != 0:
                res['response']['text'] = 'Извините, но сейчас доступны следующие языки:\n' \
                                          'Английский, голландский, датский, испанский, итальянский, корейский, немецкий, ' \
                                          'польский, португальский, русский, словацкий, турецкий, украинский, французский, ' \
                                          'шведский, японский.'

            else:
                files = [('file', ('output.mp3', open('output.mp3', 'rb')))]
                url2 = requests.post(audio_url, files=files).text
                os.remove('output.mp3')
                logging.info('meow!')
                RESPONSE = json.loads(url2)['file']
                RESPONSE_2 = vk_session.method('docs.save', {'file': RESPONSE})
                logging.info('RESPONSE_2: %r', RESPONSE_2)
                _id = RESPONSE_2['audio_message']['id']
                owner_id = RESPONSE_2['audio_message']['owner_id']
                document = 'doc%s_%s' % (str(owner_id), str(_id))
            return
        else:
            res['response']['text'] = message
            logging.info('message: %s' % message)
            return

    if settings:
        if flags[uid]['translate']:
            one = 'включен'
        else:
            one = 'выключен'
        if flags[uid]['voices']:
            two = 'включен'
        else:
            two = 'выключен'
        message += '\n\nПеревод: %s\nАвтоперевод: %s\nЯзык перевода: %s' % (
            one, two, flags[uid]['lang_translate'])
    res['response']['text'] = message.strip()
    logging.info('message: %s' % res['response']['text'])
    return