예제 #1
0
def embed_snippet(request, snippetid):
    """
        Get a javascript code for pasting snippet anywhere on the web.

        Processes GET and POST requests.

        Snippet id is specified as url path (part between the host name and params), i.e.:
            GET xsnippet.org/1/embed will return js code for pasting snippet on your page
    """
    snippet = Snippet.get_by_id(int(snippetid))

    if snippet is not None:
        languagehl = Snippet.languages[snippet.language]
        if languagehl:
            lexer = get_lexer_by_name(languagehl, stripall=True)
        else:
            lexer = guess_lexer(snippet.content)

        formatter = HtmlFormatter(linenos="table")
        snippet.content = highlight(snippet.content, lexer, formatter)

        html = """
          <link rel="stylesheet" href="http://www.xsnippet.org/static/pygments/styles/colorful.css">
          <link rel="stylesheet" href="http://www.xsnippet.org/static/styles/embed.css">
          {0}
        """.format(
            snippet.content
        )

        js = "document.write('{0}');".format(r"\n".join(html.splitlines()))
        return create_response({"Content-Type": "text/html; charset=utf-8"}, js)
    else:
        return webapp2.abort(404, "Snippet with id {0} not found".format(snippetid))
예제 #2
0
def recent_snippet(request, page=1, limit=FETCH_LIMIT):
    """
        Return the list of recently posted snippets.

        Processes GET and POST requests.
    """
    limit = int(limit)
    if limit > FETCH_LIMIT:
        limit = FETCH_LIMIT

    query = Snippet.all()
    query.order("-date")
    snippets = query.fetch(limit)

    try:
        p = Paginator(snippets, FETCH_PER_PAGE)
        elems, pages = p[int(page)]
    except (ValueError, AssertionError):
        if snippets:
            return webapp2.abort(404, "Invalid page number: {0}".format(page))
        else:
            elems = []
            pages = []

    return render_to_response("list.html", snippets=elems, pages=pages, url=u"/recent/")
예제 #3
0
def png_snippet(request, snippetid):
    """
        Show image (png) with highlighted code of snippet.

        Processes GET and POST requests.

        Snippet id is specified as url path (part between the host name and params), i.e.:
            GET xsnippet.org/1/png will return image for snippet with id 1
    """
    snippet = Snippet.get_by_id(int(snippetid))

    if snippet is not None:
        # pygments highlighting
        languagehl = Snippet.languages[snippet.language]

        if languagehl:
            lexer = get_lexer_by_name(languagehl, stripall=True)
        else:
            lexer = guess_lexer(snippet.content)

        formatter = ImageFormatter(font_name="Ubuntu Mono")
        png = highlight(snippet.content, lexer, formatter)

        return create_response({"Content-Type": "image/png"}, png)
    else:
        return webapp2.abort(404, "Snippet with id {0} not found".format(snippetid))
예제 #4
0
def show_snippet(request, snippetid):
    """
        Show the highlighted code of snippet and additional information

        Processes GET and POST requests.

        Snippet id is specified as url path (part between the host name and params), i.e.:
            GET xsnippet.org/1 will return page for snippet with id 1
    """

    snippet = Snippet.get_by_id(int(snippetid))

    if snippet is not None:
        # pygments highlighting
        languagehl = Snippet.languages.get(snippet.language, "text")

        if languagehl:
            lexer = get_lexer_by_name(languagehl, stripall=True)
        else:
            lexer = guess_lexer(snippet.content)

        formatter = HtmlFormatter(linenos="table")
        snippet.content = highlight(snippet.content, lexer, formatter)
        return render_to_response("show.html", snippet=snippet)
    else:
        return webapp2.abort(404, "Snippet with id {0} not found".format(snippetid))
예제 #5
0
def sitemap(request):
    """
        Generate sitemap.xml.

        Processes GET and POST requests.
    """
    keys = Snippet.all(keys_only=True).order("-date")
    jinja = jinja2.get_jinja2(app=webapp2.get_app())
    return create_response({"Content-Type": "text/xml; charset=utf-8"}, jinja.render_template("sitemap.xml", keys=keys))
예제 #6
0
파일: emails.py 프로젝트: steder/snippets
 def post(self):
     user = user_from_email(self.request.get('email'))
     d = date_for_retrieval()
     all_snippets = Snippet.all().filter("date =", d).fetch(500)
     all_users = User.all().fetch(500)
     following = compute_following(user, all_users)
     logging.info(all_snippets)
     body = '\n\n\n'.join([self.__snippet_to_text(s) for s in all_snippets if s.user.email in following])
     if body:
         self.__send_mail(user.email, 'https://snippetless.appspot.com\n\n' + body)
     else:
         logging.info(user.email + ' not following anybody.')
예제 #7
0
def raw_snippet(request, snippetid):
    """
        Get a raw text representation of snippet content

        Processes GET and POST requests.

        Snippet id is specified as url path (part between the host name and params), i.e.:
            GET xsnippet.org/1/raw will return text content of snippet with id 1
    """
    snippet = Snippet.get_by_id(int(snippetid))

    if snippet is not None:
        return create_response({"Content-Type": "text/plain; charset=utf-8"}, snippet.content)
    else:
        return webapp2.abort(404, "Snippet with id {0} not found".format(snippetid))
예제 #8
0
def search_snippet(request, querystr="", page=1, limit=FETCH_LIMIT):
    """
        Return the list of snippets that meet the given requirements (author, language, etc)

        Processes GET and POST requests.

        Requirements are specified in search request, i.e. a query:
            author:James Black,tags:coolstuff,language:C++
        will return a list of all code snippets written by James Black
        in C++ and tagged as 'coolstuff' (all conditions should be fulfiled)

        NOTE: the delimeter is a ',' character

        List of snippet properties consits of:
            language
            author
            tags
            title
    """
    limit = int(limit)
    if limit > FETCH_LIMIT:
        limit = FETCH_LIMIT

    if request.get("search"):
        querystr = urllib.unquote(request.get("search"))
    else:
        querystr = urllib.unquote(querystr).decode("utf-8")

    pattern = ur"(author|language|tags|title):([^,]+),?"
    conditions = re.findall(pattern, querystr)

    query = Snippet.all()
    for key, value in conditions:
        query.filter("{0} =".format(key), value)
    query.order("-date")
    snippets = query.fetch(limit)

    try:
        p = Paginator(snippets, FETCH_PER_PAGE)
        elems, pages = p[int(page)]
    except (ValueError, AssertionError):
        if snippets:
            return webapp2.abort(404, "Invalid page number: {0}".format(page))
        else:
            elems = []
            pages = []

    return render_to_response("list.html", snippets=elems, pages=pages, url=u"/search/{0}/".format(querystr))
예제 #9
0
파일: emails.py 프로젝트: tef/snippets
    def post(self):
        user = user_from_email(self.request.get('email'))
        d = date_for_retrieval()
        all_snippets = Snippet.all().filter("digest_date =", d).filter("replaced =", False).fetch(500)
        logging.info(all_snippets)

        def snippet_to_text(snippet):
            divider = '-' * 30
            return '%s\n%s\n%s' % (snippet.user.pretty_name(), divider, snippet.text)

        body = '\n\n\n'.join(snippet_to_text(s) for s in all_snippets)

        if body:
            self.__send_mail(user.email, body)
        else:
            logging.info(user.email + 'not following anybody.')
예제 #10
0
def download_snippet(request, snippetid):
    """
        Download snippet content as a file

        Processes GET and POST requests.

        Snippet id is specified as url path (part between the host name and params), i.e.:
            GET xsnippet.org/1/download will return content of snippet with id 1 as a file
    """
    snippet = Snippet.get_by_id(int(snippetid))

    if snippet is not None:
        filename = snippetid
        extension = snippet.extensions[snippet.language] if snippet.language in snippet.extensions else ".txt"
        attachment = 'attachment; filename="{0}{1}"'.format(filename, extension)

        return create_response(
            {"Content-Type": "text/plain; charset=utf-8", "Content-Disposition": attachment}, snippet.content
        )
    else:
        return webapp2.abort(404, "Snippet with id {0} not found".format(snippetid))
예제 #11
0
def list_snippet(request, key, value, page=1, limit=FETCH_LIMIT):

    limit = int(limit)
    if limit > FETCH_LIMIT:
        limit = FETCH_LIMIT

    value = urllib.unquote(value).decode("utf-8")

    query = Snippet.all()
    query.filter("{0} =".format(key), value)
    query.order("-date")
    snippets = query.fetch(int(limit))

    try:
        p = Paginator(snippets, FETCH_PER_PAGE)
        elems, pages = p[int(page)]
    except (ValueError, AssertionError):
        if snippets:
            return webapp2.abort(404, "Invalid page number: {0}".format(page))
        else:
            elems = []
            pages = []

    return render_to_response("list.html", snippets=elems, pages=pages, url=u"/{0}/{1}/".format(key, value))
예제 #12
0
def new_snippet(request):
    """
        Create a new snippet entry

        Creates a snippet entry given the information (content, language, etc)
        and saves it into the datastore. Each snippet entry gets assigned a unique
        identifier which is used to retrieve it later.

        Processes GET and POST requests.

        Params:
            author   --- an author of snippet
            title    --- a title of snippet
            language --- a language of snippet
            content  --- a text of snippet
            tags     --- a list of strings separated by commas

        Redirect:
            When a snippet is put into the datastore user gets redirected
            to the page showing the highlighted content of the snippet.
    """
    snippet = Snippet()

    # anti-spam protection
    if request.get("email"):
        return webapp2.redirect("/")

    snippet.author = request.get("author")
    if not snippet.author:
        snippet.author = "Anonymous"

    snippet.title = request.get("title")
    if not snippet.title:
        snippet.title = "Untitled"

    snippet.language = request.get("language")
    if not snippet.language or not snippet.language in Snippet.languages:
        snippet.language = "Text"

    tags = request.get("tags")
    if tags:
        snippet.tags = [tag.lstrip() for tag in tags.split(",")]
    else:
        snippet.tags = []

    filedata = request.get("file")
    if filedata:
        snippet.content = filedata.decode("utf-8")

        # get the name of uploaded file from request body
        body = urllib.unquote(request.body)
        info = re.search('filename="(.+)"', body)
        basename = os.path.basename(info.groups(0)[0])
        filename, extension = os.path.splitext(basename)

        if snippet.title == "Untitled":
            snippet.title = basename
        snippet.language = Snippet.extensions_reverse.get(extension, "Text")
    else:
        snippet.content = request.get("content")

    if snippet.content:
        snippet.put()
        return webapp2.redirect("/" + str(snippet.key().id()))
    else:
        return webapp2.redirect("/")