lodgeit-main / lodgeit /

# -*- coding: utf-8 -*-

    Serveral utilities used by LodgeIt.

    :copyright: 2007-2008 by Christopher Grebs.
    :license: BSD
import re
import time
from os import path
from random import random
from functools import partial

from werkzeug import Request as RequestBase, Response
from werkzeug.contrib.securecookie import SecureCookie

from jinja2 import Environment, FileSystemLoader

from babel import Locale

from lodgeit.lib.highlighting import get_style

    from hashlib import sha1
    from sha import new as sha1

#: constants
_word_only = partial(re.compile(r'[^a-zA-Z0-9]').sub, '')
COOKIE_NAME = u'lodgeit_session'

def generate_paste_hash():
    """Generates a more or less unique-truncated SHA1 hash."""
    while 1:
        digest = sha1('%s|%s' % (random(), time.time())).digest()
        val = _word_only(digest.encode('base64').strip().splitlines()[0])[:20]
        # sanity check.  number only not allowed (though unlikely)
        if not val.isdigit():
            return val

class Request(RequestBase):
    """Subclass of the `Request` object. automatically creates a new
    `user_hash` and sets `first_visit` to `True` if it's a new user.
    It also stores the engine and dbsession on it.
    charset = 'utf-8'

    def __init__(self, environ, urls):
        super(Request, self).__init__(environ)
        self.first_visit = False
        session = SecureCookie.load_cookie(self, COOKIE_NAME,
        user_hash = session.get('user_hash')

        if not user_hash:
            session['user_hash'] = generate_user_hash()
            self.first_visit = True
        self.user_hash = session['user_hash']
        self.session = session

        # language is limited to english until translations are ready
        lang = session.get('locale')
        if lang is None:
            lang = 'en'
            #lang = ( or 'en').split('-')[0]
        self.locale = Locale.parse(lang)
        self.urls = urls

    def set_language(self, lang):
        self.session['locale'] = lang

def render_template(template_name, **context):
    request = local.request
    style, css = get_style(request)
        style = style,
        css = css,
        url = request.get_url,
    return jinja_environment.get_template(template_name).render(context)

def render_to_response(template_name, **context):
    """Render a template to a response. This automatically fetches
    the list of new replies for the layout template. It also
    adds the current request to the context. This is used for the
    welcome message.
    from lodgeit.models import Paste
    request = local.request
    if request.method == 'GET':
        context['new_replies'] = Paste.fetch_replies()
    return Response(render_template(template_name, **context),