class MailboxInfo(RadarDocument):
    """
    General metadata about a mailbox.
    """
    type = TextField(default=MAILBOXINFO_TYPE)
    version = TextField(default="0.0.1")
    title = TextField()
    
    def __init__(self, **values):
        Document.__init__(self, id=MAILBOXINFO_ID, **values)
    
    @classmethod
    def get(cls, mailbox):
        return MailboxInfo.load(mailbox, MAILBOXINFO_ID)

    user_updatable = ('title', ) class Subscription(DowncastDoc):
    """
    Represents a subscription to a particular
    source of messages by a mailbox.
    """
    type = TextField(default=SUBSCRIPTION_TYPE)
    subscription_type = TextField()
    title = TextField()
    status = TextField()
    last_update = DateTimeField()

    # helpful view constants
    by_type = '_design/mailbox/_view/subscriptions_by_type'

    # status constants
    STATUS_OK        = 'ok'
    STATUS_ERROR     = 'error'
    STATUS_UNCHANGED = 'unchanged'
    
    SUBTYPE_PLUGIN = 'radar.mailbox.subscription_subtype'
    SUBTYPE_FIELD = 'subscription_type'

    user_updatable = ('title', )

    def reset(self):
        """
        called to reset any subscription state associated with this
        subscription.
        """
        self.last_update = None
        self.status = None class Message(DowncastDoc):
    """
    A message in a mailbox.
    """
    
    type = TextField(default=MESSAGE_TYPE)
    message_type = TextField()
    fingerprint = TextField()
    timestamp = DateTimeField()
    source = DictField(SourceInfo)

    # helpful view constants
    by_timestamp = '_design/mailbox/_view/messages_by_timestamp'
    by_subscription = '_design/mailbox/_view/messages_by_subscription'
    
    SUBTYPE_PLUGIN = 'radar.mailbox.mailbox_subtype'
    SUBTYPE_FIELD = 'message_type' class MailboxInfo(RadarDocument):
    """
    General metadata about a mailbox.
    """
    type = TextField(default=MAILBOXINFO_TYPE)
    version = TextField(default="0.0.1")
    title = TextField()
    
    def __init__(self, **values):
        Document.__init__(self, id=MAILBOXINFO_ID, **values)
    
    @classmethod
    def get(cls, mailbox):
        return MailboxInfo.load(mailbox, MAILBOXINFO_ID)

    user_updatable = ('title', ) PERM_CREATE = 'radar:perm:create' PERM_READ   = 'radar:perm:read' PERM_UPDATE = 'radar:perm:update' PERM_DELETE = 'radar:perm:delete' PERM_CREATE_MAILBOX = 'radar:perm:create:mailbox' class TemplateContext(dict):
    def __init__(self, request, ctx):
        self.update(ctx)
        self.request = request
        for proc in plugins.get(TEMPLATE_CONTEXT_PROCESSORS):
            proc(request, self) def render_to_response(template_name, template_context):
    ctx = template_context.request.context
    return HttpResponse(ctx.get_template(template_name).render(template_context)) ENTRY_POINT = 'radarpost_plugins'
def get(slot):
def _get(slot):
def register(thing, slot):
def plugin(slot):
    def dd(thing):
def _search(): def plugin(slot):
    """
    decorator to declare a plugin
    """
    def dd(thing):
        register(thing, slot)
        return thing
    return dd
from operator import attrgetter
from urllib import quote_plus
from webob import Response as HttpResponse
from radarpost.mailbox import MailboxInfo, Subscription, Message, MailboxInfo
from radarpost.user import PERM_CREATE, PERM_READ, PERM_UPDATE, PERM_DELETE
from radarpost.user import PERM_CREATE_MAILBOX
from radarpost.web.context import TemplateContext, render_to_response
from radarpost import plugins
from radarpost.plugins import plugin

######################################
#
# view helpers
#
######################################

def handle_unauth(request):
    if request.context.user.is_anonymous():
        # redirect to login with any additional info
        login_url = request.context.url_for('login', next=request.url)
        login_url = request.relative_url(login_url)
        res = HttpResponse(status=301)
        res.location = login_url
        return res
    else: 
        # logged in, but current user does not have permission
        # show message indicating unauthorized.
        return render_to_response('radar/unauthorized.html',
                                  TemplateContext(request, {}))

def unauth_handler(request, *args, **kw):
    return HttpResponse(status=401)

def login_required(controller_action):
    def wrapped_action(request, *args, **kw):
        if request.context.user is None or request.context.user.is_anonymous():
            return unauth_handler(request, *args, **kw)
        else:
            return controller_action(*args, **kw)
    wrapped_action.__name__ = controller_action.__name__
    return wrapped_action

#####################################
#
# views
#
######################################

def login(request):
    ctx = {}
    next_page = request.params.get('next')
    if next_page:
        ctx = {'next': next_page}
    return render_to_response('radar/login.html', 
                              TemplateContext(request, ctx))

def logout(request):
    request.context.set_session_user(None)
    return render_to_response('radar/logout.html', TemplateContext(request, {}))

def signup(request):
    if request.method == 'GET':
        return render_to_response('radar/signup.html', TemplateContext(request, {}))
        
def front_page(request):
    return render_to_response('radar/front_page.html', 
                              TemplateContext(request, {}))

def list_mailboxes(request):
    ctx = request.context
    mailboxes = []
    for mb in ctx.iter_mailboxes():
        if not ctx.user.has_perm(PERM_READ, mb): 
            continue

        slug = ctx.get_mailbox_slug(mb.name)
        info = MailboxInfo.get(mb)
        mailboxes.append({
            'slug': slug,
            'title': info.title or 'Untitled',
            'db': mb
        })
    return render_to_response('radar/list_mailboxes.html', 
                              TemplateContext(request, {'mailboxes': mailboxes}))

    
def create_mailbox(request):
    if request.method != 'GET':
        res = HttpResponse(status=405)
        res.allow = ['GET']
        return res
    
    ctx = request.context
    if not ctx.user.has_perm(PERM_CREATE_MAILBOX):
        return handle_unauth(request)
        
    return render_to_response('radar/create_mailbox.html', 
                              TemplateContext(request, {}))

def view_mailbox_latest(request, mailbox_slug):
    ctx = request.context
    mb = ctx.get_mailbox(mailbox_slug)
    if mb is None:
        return HttpResponse(status=404)


    if not ctx.user.has_perm(PERM_READ, mb):