Mango / handlers.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

import hashlib
import urllib2

from django.core.cache import cache
from django.core.mail import EmailMultiAlternatives
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.template import Context, loader

import mango.settings
from mango.decorators import baseurl
from mango.main import Index
from mango.utils import akismet_request, logger, text_response
if mango.settings.SUBSCRIPTIONS:
    from mango.models import Subscription

@baseurl
def flush_cache(request):
    Index().uncache()
    return text_response('Top-level cache flushed.')

@baseurl
def moderate(request, action):
    if not mango.settings.DISQUS:
        return text_response('Invalid DISQUS settings.', 500)

    if request.GET.get('api_key') != hashlib.sha1(mango.settings.DISQUS_API_KEY).hexdigest():
        return text_response('Invalid API key.', 400)

    post_id = request.GET.get('post_id')
    thread_id = request.GET.get('thread_id')

    if thread_id:
        if not mango.settings.FORUM:
            return text_response('Invalid DISQUS settings.', 500)

        for thread in mango.settings.DISQUS.get_thread_list(mango.settings.FORUM, limit=9999):
            if thread.id == thread_id:
                break
        else:
            return text_response('Invalid thread id.', 400)

    if action == 'close':
        mango.settings.DISQUS.update_thread(mango.settings.FORUM, thread, allow_comments=False)
        message = 'Thread closed.'

    elif action == 'approve':
        comment = mango.settings.DISQUS.moderate_post(post_id, 'approve')
        message = 'Comment approved.'
        comment.thread.url = request.GET.get('url', comment.thread.url)

        cache_key = 'mango:disqus:%s' % comment.thread.id
        cache.delete(cache_key)
        logger.debug('Cache key invalidated: %s' % cache_key)

        if mango.settings.SUBSCRIPTIONS and comment.thread.url: # notify subscribers
            subject = u'New comment on "%s"' % comment.thread.title
            text_template = loader.get_template('email/subscriber.dtext')
            html_template = loader.get_template('email/subscriber.dhtml')
            for sub in Subscription.objects.filter(url=comment.thread.url):
                context = Context({'comment': comment, 'subscription_id': sub.id})
                msg = EmailMultiAlternatives(subject, text_template.render(context),
                        to=[u'%s <%s>' % (sub.subscriber_name, sub.subscriber_email)])
                msg.attach_alternative(html_template.render(context), 'text/html')
                msg.send(fail_silently=False)
    else:
        comment = mango.settings.DISQUS.moderate_post(post_id, 'kill')
        message = 'Comment deleted.'

        if not mango.settings.COMMENTS_REQUIRE_APPROVAL:
            cache_key = 'mango:disqus:%s' % comment.thread.id
            cache.delete(cache_key)
            logger.debug('Cache key invalidated: %s' % cache_key)

        if action == 'spam':
            mango.settings.DISQUS.moderate_post(post_id, 'spam')
            message = 'Comment marked as spam and deleted.'

            if mango.settings.AKISMET_API_KEY and thread_id: # inform Akismet of its failure
                for comment in mango.settings.DISQUS.get_thread_posts(mango.settings.FORUM, thread, limit=9999):
                    if comment.id == post_id:
                        break
                else:
                    return text_response('Comment not found.', 500)

                args = {
                    'blog': baseurl(),
                    'user_ip': comment.ip_address,
                    'user_agent': '',
                    'referrer': comment.thread.url,
                    'permalink': comment.thread.url,
                    'comment_type': 'comment',
                    'comment_content': comment.message,
                }
                if comment.is_anonymous:
                    args['comment_author'] = comment.anonymous_author.name
                    url = comment.anonymous_author.url
                else:
                    args['comment_author'] = comment.author.username
                    url = comment.author.url

                if url:
                    args['comment_author_url'] = url

                f = urllib2.urlopen(akismet_request('submit-spam', args))
                f.close()

    return text_response(message)

@baseurl
def redirect(request, path, fragment=None):
    url = reverse('mango.views.post', args=(path,))
    return HttpResponseRedirect('%s#%s' % (url, fragment) if fragment else url)

@baseurl
def unsubscribe(request, path, subscription_id):
    subscription = get_object_or_404(Subscription, pk=subscription_id)
    subscription.delete()
    return text_response("You're no longer subscribed to this thread's comments.")
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.