Ejemplo n.º 1
0
Archivo: misc.py Proyecto: aitjcize/bb8
def redirect_track_url(bot_id, platform_user_ident):
    """Handler for tracking URL

    This handler allow us to track 'web_url' button clicks by embedding the
    tracking info in the url parameters and sending to GA.
    """
    url = request.args.get('url', None)
    if not url:
        raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                       CustomError.ERR_WRONG_PARAM,
                       'No URL specified')

    path = request.args.get('path', None)
    if not path:
        raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                       CustomError.ERR_WRONG_PARAM,
                       'No path specified')

    try:
        ret = Bot.query(Bot.ga_id).filter_by(id=bot_id).one()
    except Exception:
        raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                       CustomError.ERR_WRONG_PARAM,
                       'Internal Error')

    g.ga_id = ret[0]
    track(TrackingInfo.Pageview(platform_user_ident, '/Redirect/%s' % path))

    return redirect(url)
Ejemplo n.º 2
0
Archivo: bots.py Proyecto: aitjcize/bb8
def get_account_bot_by_id(bot_id):
    bot = Bot.get_by(id=bot_id, account_id=g.account.id, single=True)
    if bot is None:
        raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                       CustomError.ERR_NOT_FOUND,
                       'bot_id: %d not found' % bot_id)
    return bot
Ejemplo n.º 3
0
def update_broadcast(broadcast_id):
    """Update a broadcast."""
    broadcast = get_account_broadcast_by_id(broadcast_id)
    try:
        broadcast_json = request.json
        broadcast_json['account_id'] = g.account.id
        parse_broadcast(broadcast_json, broadcast.id)
    except BroadcastUnmodifiableError:
        raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                       CustomError.ERR_WRONG_PARAM, 'Broadcast not modifiable')
    except Exception as e:
        logger.exception(e)
        raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                       CustomError.ERR_WRONG_PARAM,
                       'Broadcast update request failed')
    DatabaseManager.commit()
    return jsonify(message='ok')
Ejemplo n.º 4
0
def social_register():
    data = request.json
    try:
        jsonschema.validate(data, SOCIAL_REGISTER_SCHEMA)
    except Exception:
        raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                       CustomError.ERR_FORM_VALIDATION,
                       'schema validation fail')
Ejemplo n.º 5
0
def get_account_platform_by_id(platform_id):
    platform = Platform.get_by(id=platform_id,
                               account_id=g.account.id,
                               single=True)
    if platform is None:
        raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                       CustomError.ERR_NOT_FOUND,
                       'platform_id: %d not found' % platform_id)
    return platform
Ejemplo n.º 6
0
Archivo: bots.py Proyecto: aitjcize/bb8
def get_bot_def_revision(bot_id, version):
    """Get bot_def JSON object given a version."""
    unused_bot = get_account_bot_by_id(bot_id)
    bot_def = BotDef.get_by(bot_id=bot_id, version=version, single=True)
    if bot_def is None:
        raise AppError(
            HTTPStatus.STATUS_CLIENT_ERROR, CustomError.ERR_NOT_FOUND,
            'bot_def for bot_id %d, version %d not found' % (bot_id, version))
    return jsonify(bot_def.to_json(['bot_json']))
Ejemplo n.º 7
0
def delete_broadcast(broadcast_id):
    """Delete a broadcast."""
    broadcast = get_account_broadcast_by_id(broadcast_id)
    if broadcast.status == BroadcastStatusEnum.SENT:
        raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                       CustomError.ERR_WRONG_PARAM, 'Broadcast not deletable')
    broadcast.delete()
    DatabaseManager.commit()
    return jsonify(message='ok')
Ejemplo n.º 8
0
Archivo: misc.py Proyecto: aitjcize/bb8
def image_convert_url():
    """Image convert service."""
    # TODO(aitjcize): cache converted image to S3
    try:
        url = base64.b64decode(request.args['url'])
        size = [int(x) for x in request.args['size'].split('x')]
    except Exception:
        raise AppError(HTTPStatus.STATUS_BAD_REQUEST,
                       CustomError.ERR_WRONG_PARAM,
                       'invalid request argument')

    try:
        h = urllib2.urlopen(url, timeout=5)
    except Exception:
        raise AppError(HTTPStatus.STATUS_BAD_REQUEST,
                       CustomError.ERR_INVALID_URL,
                       'invalid image url')

    buf = StringIO()
    buf.write(h.read())

    img = Image.open(buf)
    buf = StringIO()

    if img.mode != 'RGB':
        img = img.convert('RGB')

    # Resize not required
    if img.width < size[0] and img.height < size[1]:
        img.save(buf, 'JPEG', quality=95)
    else:
        if img.width >= img.height:
            ratio = float(size[0]) / img.width
        else:
            ratio = float(size[1]) / img.height

        img = img.resize((int(img.width * ratio), int(img.height * ratio)),
                         Image.LANCZOS)
        img.save(buf, 'JPEG', quality=95)

    response = make_response(buf.getvalue())
    response.headers['content-type'] = 'image/jpeg'

    return response
Ejemplo n.º 9
0
Archivo: misc.py Proyecto: aitjcize/bb8
def cache_image():
    """Cache the image and return the cached URL."""
    gs_client = storage.Client(project=config.GCP_PROJECT)
    bucket = gs_client.get_bucket('cached-pictures')
    url = request.args['url']
    host = urlparse.urlparse(url).netloc

    if not url:
        raise AppError(HTTPStatus.STATUS_BAD_REQUEST,
                       CustomError.ERR_WRONG_PARAM,
                       'invalid request argument')

    if host not in ALLOWED_HOSTS:
        return redirect(url)

    ext = url.split('.')[-1]
    if ext not in ['jpg', 'jpeg', 'png', 'gif']:
        raise AppError(HTTPStatus.STATUS_BAD_REQUEST,
                       CustomError.ERR_WRONG_PARAM,
                       'invalid request argument')

    url_hash = hashlib.sha1(url).hexdigest()
    hash_name = '%s.%s' % (url_hash, ext)

    blob = bucket.get_blob(hash_name)
    if blob:
        return redirect(blob.media_link)

    response = requests.get(url, stream=True)

    # If the request failed, ignore and just redirect user to it.
    if response.status_code != 200:
        return redirect(url)

    with tempfile.NamedTemporaryFile(delete=False) as fio:
        shutil.copyfileobj(response.raw, fio)

    blob = storage.blob.Blob(hash_name, bucket)
    blob.upload_from_filename(fio.name)
    os.unlink(fio.name)

    return redirect(blob.public_url)
Ejemplo n.º 10
0
def login():
    data = request.json
    account = Account.get_by(email=data['email'], single=True)
    if not account or not account.verify_passwd(data['passwd']):
        raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                       CustomError.ERR_WRONG_PASSWD,
                       'Invalid combination of email and password')

    ret = account.to_json()
    ret[Key.AUTH_TOKEN] = account.auth_token
    return jsonify(ret)
Ejemplo n.º 11
0
    def decorated(*args, **kwargs):
        if Key.X_COMPOSEAI_AUTH not in request.headers:
            raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                           CustomError.ERR_UNAUTHENTICATED,
                           'Not loggined')

        auth_header = request.headers[Key.X_COMPOSEAI_AUTH]
        parts = auth_header.split()
        if parts[0] != 'Bearer':
            raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                           CustomError.ERR_UNAUTHENTICATED,
                           'Invalid auth token')

        try:
            token = parts[1]
            g.account = Account.from_auth_token(token)
        except RuntimeError:
            raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                           CustomError.ERR_UNAUTHENTICATED,
                           'The token %s is invalid' % token)
        return func(*args, **kwargs)
Ejemplo n.º 12
0
def email_register():
    data = request.json
    try:
        jsonschema.validate(data, REGISTER_SCHEMA)
        pytz.timezone(data['timezone'])
    except Exception:
        raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                       CustomError.ERR_FORM_VALIDATION,
                       'schema validation fail')

    account = Account.get_by(email=data['email'], single=True)
    if not account:
        account = Account(email=data['email']).set_passwd(data['passwd']).add()
        DatabaseManager.commit()
    else:
        raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                       CustomError.ERR_USER_EXISTED,
                       'email %s is already taken' % data['email'])

    ret = account.to_json()
    ret[Key.AUTH_TOKEN] = account.auth_token
    return jsonify(ret)
Ejemplo n.º 13
0
def create_broadcast():
    """Create a new broadcast."""
    try:
        broadcast_json = request.json
        broadcast_json['account_id'] = g.account.id
        broadcast = parse_broadcast(broadcast_json)
    except Exception as e:
        logger.exception(e)
        raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                       CustomError.ERR_WRONG_PARAM,
                       'Broadcast create request failed')
    DatabaseManager.commit()
    return jsonify(broadcast.to_json())
Ejemplo n.º 14
0
def create_platform():
    """Create a new platform."""
    try:
        platform_json = request.json
        platform_json['account_id'] = g.account.id
        platform = parse_platform(platform_json)
    except Exception as e:
        logger.exception(e)
        raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                       CustomError.ERR_WRONG_PARAM,
                       'Platform definition parsing failed')
    DatabaseManager.commit()
    return jsonify(platform.to_json(['config']))
Ejemplo n.º 15
0
Archivo: bots.py Proyecto: aitjcize/bb8
def deploy_bot(bot_id):
    bot = get_account_bot_by_id(bot_id)
    try:
        parse_bot(bot.staging, bot.id)
    except Exception as e:
        logger.exception(e)
        raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                       CustomError.ERR_WRONG_PARAM,
                       'Bot definition parsing failed')
    bot_def = BotDef.add_version(bot.id, bot.staging)
    bot.staging = None  # Clear staging area
    DatabaseManager.commit()
    return jsonify(version=bot_def.version)
Ejemplo n.º 16
0
Archivo: bots.py Proyecto: aitjcize/bb8
def create_bot():
    """Create a new bot."""
    data = request.json
    try:
        jsonschema.validate(data, BOT_CREATE_SCHEMA)
    except Exception:
        raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                       CustomError.ERR_FORM_VALIDATION,
                       'schema validation fail')

    bot = Bot(**data).add()
    g.account.bots.append(bot)
    DatabaseManager.commit()
    return jsonify(bot.to_json(bot.detail_fields))
Ejemplo n.º 17
0
Archivo: bots.py Proyecto: aitjcize/bb8
def update_bot(bot_id):
    """Modify a bot staging area."""
    bot = get_account_bot_by_id(bot_id)
    try:
        validate_bot_schema(request.json)
    except Exception as e:
        logger.exception(e)
        raise AppError(HTTPStatus.STATUS_CLIENT_ERROR,
                       CustomError.ERR_WRONG_PARAM,
                       'Bot definition parsing failed')

    bot.name = request.json['bot']['name']
    bot.description = request.json['bot']['description']
    bot.staging = request.json
    DatabaseManager.commit()
    return jsonify(message='ok')