Ejemplo n.º 1
0
def put(**kwargs):
    if 'namespace' in kwargs:
        kwargs = _namespace_kwargs(kwargs)

    stream, filename = request_content()
    if not stream:
        return StatusResponse("no post content", 400)

    cur = model.get_digest(stream)
    try:
        return PasteResponse(next(cur), "already exists", filename)
    except StopIteration:
        pass

    if filename:
        kwargs['mimetype'], _ = guess_type(filename)

    # FIXME: such query; wow
    invalidate(**kwargs)
    result = model.put(stream, **kwargs)
    if result['n']:
        paste = next(model.get_meta(**kwargs))
        return PasteResponse(paste, "updated")

    return StatusResponse("not found", 404)
Ejemplo n.º 2
0
def url(label=None):
    stream, _ = request_content()
    if not stream:
        return StatusResponse("no post content", 400)

    args = {}

    if label:
        label, _ = label
        if len(label) == 1:
            return StatusResponse("invalid label", 400)
        args['label'] = label

    stream = BytesIO(stream.read().decode('utf-8').split()[0].encode('utf-8'))

    cur = model.get_digest(stream)

    try:
        url = next(cur)
        status = "already exists"
    except StopIteration:
        url = model.insert(stream, redirect=1, **args)
        status = "created"

    return PasteResponse(url, status)
Ejemplo n.º 3
0
def put(**kwargs):
    if 'namespace' in kwargs:
        kwargs = _namespace_kwargs(kwargs)

    stream, filename = request_content()
    if not stream:
        return StatusResponse("no post content", 400)

    cur = model.get_digest(stream)
    try:
        return PasteResponse(next(cur), "already exists", filename)
    except StopIteration:
        pass

    if filename:
        kwargs['mimetype'], _ = guess_type(filename)

    # this entirely replaces paste headers, which might not be expected behavior
    headers = dict(allowed_headers(request.headers))

    # FIXME: such query; wow
    invalidate(**kwargs)
    result = model.put(stream, headers=headers, **kwargs)
    if result['n']:
        paste = next(model.get_meta(**kwargs))
        return PasteResponse(paste, "updated")

    return StatusResponse("not found", 404)
Ejemplo n.º 4
0
def post(label=None, namespace=None):
    stream, filename = request_content()
    if not stream:
        return StatusResponse("no post content", 400)

    cur = model.get_digest(stream)

    args = {}
    if filename:
        args['mimetype'], _ = guess_type(filename)

    for key, value in request_keys('private', 'sunset'):
        try:
            if key == 'sunset':
                args[key] = parse_sunset(value)
            else:
                args[key] = int(value)
        except (ValueError, OverflowError):
            return StatusResponse({
                "invalid request params": {key: value}
            }, 400)

    if label:
        label, _ = label
        if len(label) == 1:
            return StatusResponse("invalid label", 400)
        args['label'] = label
    if namespace:
        host = get_host_name(request)
        if not _auth_namespace(host):
            return StatusResponse("invalid auth", 403)
        label, _ = namespace
        args.update(dict(
            label=label,
            namespace=host
        ))

    headers = dict(allowed_headers(request.headers))
    args['headers'] = headers

    try:
        paste = next(cur)
        uuid = None
        status = "already exists"
    except StopIteration:
        try:
            paste = model.insert(stream, **args)
        except errors.DuplicateKeyError:
            return StatusResponse("label already exists.", 409)
        invalidate(**paste)
        uuid = str(UUID(hex=paste['_id']))
        status = "created"

    return PasteResponse(paste, status, filename, uuid)
Ejemplo n.º 5
0
def highlight_css(style="default"):
    try:
        css = HtmlFormatter(style=style).get_style_defs('body')
    except ClassNotFound:
        return StatusResponse("not found", 404)

    return BaseResponse(css, mimetype='text/css')
Ejemplo n.º 6
0
def create_app(config_filename='config.yaml'):

    app = App(__name__, static_url_path='/static', static_folder=xdg_static_folder())
    app.url_map.converters.update(dict(
        sid=SIDConverter,
        sha1=SHA1Converter,
        label=LabelConverter,
        namespace=NamespaceConverter,
        handler=HandlerConverter
    ))

    load_config(app, config_filename)
    init_db(app)
    init_cache(app)
    init_template(app)
    init_logging(app)

    app.after_request(cors)

    app.register_blueprint(paste)
    app.register_blueprint(namespace)

    # error handlers
    app.register_error_handler(StopIteration, lambda _: StatusResponse("not found", 404))

    app.url_map.update()
    #print('\n'.join(repr(i) for i in app.url_map._rules))

    return app
Ejemplo n.º 7
0
def get(sid=None, sha1=None, label=None, namespace=None, lexer=None, handler=None, formatter=None):
    cur, name, path = _get_paste(model.get_content, sid, sha1, label, namespace)

    if not cur or not cur.count():
        return StatusResponse("not found", 404)

    paste = next(cur)
    if paste.get('sunset'):
        request.max_age = parse_sunset(**paste) - datetime.utcnow()
        if request.max_age < timedelta():
            uuid = UUID(hex=paste['_id'])
            paste = invalidate(uuid=uuid)
            model.delete(uuid=uuid)
            return PasteResponse(paste, "expired", code=410)
        else:
            request.max_age = request.max_age.seconds

    content = model._get(paste.get('content'))

    if paste.get('redirect'):
        content = content.decode('utf-8')
        return redirect(content, content)

    mimetype, _ = guess_type(name)
    if not mimetype:
        mimetype = paste.get('mimetype', 'text/plain')

    if lexer is not None:
        return highlight(content, lexer, formatter)
    if handler is not None:
        return _handler.get(handler, content, mimetype, path=path)

    return BaseResponse(content, mimetype=mimetype)
Ejemplo n.º 8
0
def post(namespace):
    try:
        namespace = model.create(namespace)
    except DuplicateKeyError:
        return StatusResponse('duplicate', code=409)

    return NamespaceResponse(namespace, 'created', code=201)
Ejemplo n.º 9
0
def report(sid=None, sha1=None, label=None, namespace=None):
    cur, name, path = _get_paste(model.get_meta, sid, sha1, label, namespace)

    if not cur or not cur.count():
        return StatusResponse("not found", 404)

    paste = next(cur)
    return PasteResponse(paste, "found")
Ejemplo n.º 10
0
def delete(**kwargs):
    if 'namespace' in kwargs:
        kwargs = _namespace_kwargs(kwargs)

    paste = invalidate(**kwargs)
    result = model.delete(**kwargs)
    if result['n']:
        return PasteResponse(paste, "deleted")
    return StatusResponse("not found", 404)
Ejemplo n.º 11
0
def _namespace_kwargs(kwargs):
    host = get_host_name(request)
    if not _auth_namespace(host):
        return StatusResponse("invalid auth", 403)
    label, _ = kwargs['namespace']
    return dict(
        label=label,
        namespace=host,
    )
Ejemplo n.º 12
0
def get(namespace):
    cur = model.get(namespace)

    try:
        namespace = next(cur)
    except StopIteration:
        return StatusResponse('not found', code=404)

    return NamespaceResponse(namespace, 'exists', code=200)
Ejemplo n.º 13
0
def url():
    stream, _ = request_content()
    if not stream:
        return StatusResponse("no post content", 400)

    stream = BytesIO(stream.read().decode('utf-8').split()[0].encode('utf-8'))

    cur = model.get_digest(stream)
    if not cur.count():
        url = model.insert(stream, redirect=1)
        status = "created"
    else:
        url = next(cur)
        status = "already exists"

    return PasteResponse(url, status)
Ejemplo n.º 14
0
def get(handler, content, mimetype, **kwargs):
    h = handlers.get(handler)
    if not h:
        return StatusResponse({"invalid handler": handler}, 400)
    return h(content, mimetype, **kwargs)
Ejemplo n.º 15
0
 def decorated_function(*args, **kwargs):
     auth_key = current_app.config.get("AUTH_KEY")
     if auth_key is not None and request.headers.get(
             "x-auth-key") != auth_key:
         return StatusResponse(401)
     return f(*args, **kwargs)