コード例 #1
0
    def __init__(
        self,
        raw: str,
        lexer: str = "text",
        filename: Optional[str] = None,
    ) -> None:
        # Start with some basic housekeeping related to size
        if len(raw) > configuration.paste_size:
            raise error.ValidationError(
                f"Text exceeds size limit {configuration.paste_size//1024} (kB)"
            )

        self.pub_date = datetime.datetime.utcnow()
        self.chg_date = datetime.datetime.utcnow()

        self.raw = raw

        self.filename = filename

        self.lexer = lexer

        lexer = pygments.lexers.get_lexer_by_name(lexer)
        formatter = pygments.formatters.HtmlFormatter(  # pylint: disable=no-member
            linenos=True, cssclass="source")

        formatted = pygments.highlight(self.raw, lexer, formatter)

        if len(formatted) >= configuration.paste_size:
            raise error.ValidationError(
                f"Highlighted text exceeds size limit ({configuration.paste_size//1024} kB)"
            )

        self.fmt = formatted
        self.slug = utility.slug_create()
コード例 #2
0
ファイル: api_curl.py プロジェクト: supakeen/pinnwand
    def post(self) -> None:
        if defensive.ratelimit(self.request, area="create"):
            self.set_status(429)
            self.write("Enhance your calm, you have exceeded the ratelimit.")
            return

        lexer = self.get_body_argument("lexer", "text")
        raw = self.get_body_argument("raw", "", strip=False)
        expiry = self.get_body_argument("expiry", "1day")

        self.set_header("Content-Type", "text/plain")

        if lexer not in utility.list_languages():
            log.info(
                "CurlCreate.post: a paste was submitted with an invalid lexer")
            self.set_status(400)
            self.write("Invalid `lexer` supplied.\n")
            return

        # Guard against empty strings
        if not raw or not raw.strip():
            log.info("CurlCreate.post: a paste was submitted without raw")
            self.set_status(400)
            self.write("Invalid `raw` supplied.\n")
            return

        if expiry not in configuration.expiries:
            log.info("CurlCreate.post: a paste was submitted without raw")
            self.set_status(400)
            self.write("Invalid `expiry` supplied.\n")
            return

        paste = database.Paste(utility.slug_create(),
                               configuration.expiries[expiry], "curl")
        file = database.File(paste.slug, raw, lexer)
        paste.files.append(file)

        with database.session() as session:
            session.add(paste)
            session.commit()

            # The removal cookie is set for the specific path of the paste it is
            # related to
            self.set_cookie("removal",
                            str(paste.removal),
                            path=f"/{paste.slug}")

            url_request = self.request.full_url()
            url_paste = urljoin(url_request, f"/{paste.slug}")
            url_removal = urljoin(url_request, f"/remove/{paste.removal}")
            url_raw = urljoin(url_request, f"/raw/{file.slug}")

            self.write(
                f"Paste URL:   {url_paste}\nRaw URL:     {url_raw}\nRemoval URL: {url_removal}\n"
            )
コード例 #3
0
    def __init__(
        self,
        expiry: datetime.timedelta = datetime.timedelta(days=7),
        src: str = None,
    ) -> None:
        # Generate a paste_id and a removal_id
        # Unless someone proves me wrong that I need to check for collisions
        # my famous last words will be that the odds are astronomically small
        self.slug = utility.slug_create()
        self.removal = utility.slug_create(auto_scale=False)

        self.pub_date = datetime.datetime.utcnow()
        self.chg_date = datetime.datetime.utcnow()

        self.src = src

        # The expires date is the pub_date with the delta of the expiry
        if expiry:
            self.exp_date = self.pub_date + expiry
        else:
            self.exp_date = None
コード例 #4
0
    async def post(self) -> None:
        """This is a historical endpoint to create pastes, pastes are marked as
        old-web and will get a warning on top of them to remove any access to
        this route.

        pinnwand has since evolved with an API which should be used and a
        multi-file paste.

        See the 'CreateAction' for the new-style creation of pastes."""

        lexer = self.get_body_argument("lexer")
        raw = self.get_body_argument("code", strip=False)
        expiry = self.get_body_argument("expiry")

        if defensive.ratelimit(self.request, area="create"):
            raise error.RatelimitError()

        if lexer not in utility.list_languages():
            log.info("Paste.post: a paste was submitted with an invalid lexer")
            raise tornado.web.HTTPError(400)

        # Guard against empty strings
        if not raw or not raw.strip():
            return self.redirect(f"/+{lexer}")

        if expiry not in configuration.expiries:
            log.info(
                "Paste.post: a paste was submitted with an invalid expiry")
            raise tornado.web.HTTPError(400)

        paste = database.Paste(
            utility.slug_create(),
            configuration.expiries[expiry],
            "deprecated-web",
        )
        file = database.File(paste.slug, raw, lexer)
        paste.files.append(file)

        with database.session() as session:
            session.add(paste)
            session.commit()

            # The removal cookie is set for the specific path of the paste it is
            # related to
            self.set_cookie("removal",
                            str(paste.removal),
                            path=f"/{paste.slug}")

            # Send the client to the paste
            self.redirect(f"/{paste.slug}")
コード例 #5
0
    async def post(self) -> None:
        if defensive.ratelimit(self.request, area="create"):
            raise error.RatelimitError()

        lexer = self.get_body_argument("lexer")
        raw = self.get_body_argument("code", strip=False)
        expiry = self.get_body_argument("expiry")
        filename = self.get_body_argument("filename", None)

        if not raw or not raw.strip():
            log.info("APINew.post: a paste was submitted without content")
            raise tornado.web.HTTPError(400)

        if lexer not in utility.list_languages():
            log.info(
                "APINew.post: a paste was submitted with an invalid lexer")
            raise tornado.web.HTTPError(400)

        if expiry not in configuration.expiries:
            log.info(
                "APINew.post: a paste was submitted with an invalid expiry")
            raise tornado.web.HTTPError(400)

        paste = database.Paste(
            utility.slug_create(),
            configuration.expiries[expiry],
            "deprecated-api",
        )
        paste.files.append(database.File(paste.slug, raw, lexer, filename))

        with database.session() as session:
            session.add(paste)
            session.commit()

            req_url = self.request.full_url()
            location = paste.slug
            if filename:
                location += "#" + url_escape(filename)
            self.write({
                "paste_id":
                paste.slug,
                "removal_id":
                paste.removal,
                "paste_url":
                urljoin(req_url, f"/{location}"),
                "raw_url":
                urljoin(req_url, f"/raw/{paste.files[0].slug}"),
            })
コード例 #6
0
ファイル: command.py プロジェクト: Bruce1347/pinnwand
def add(lexer: str) -> None:
    """Add a paste to pinnwand's database from stdin."""
    from pinnwand import database
    from pinnwand import utility

    if lexer not in utility.list_languages():
        log.error("add: unknown lexer")
        return

    paste = database.Paste(utility.slug_create(), expiry=timedelta(days=1))
    file = database.File(paste.slug, sys.stdin.read(), lexer=lexer)
    paste.files.append(file)

    with database.session() as session:
        session.add(paste)
        session.commit()

        log.info("add: paste created: %s", paste.slug)