Mango / disqus.py

from datetime import datetime
import hashlib

# import `APIError` to provide a convenient alias for `disqusapi.APIError`
from disqusapi import APIError, DisqusAPI, Paginator
import pytz

from mango.settings import (COMMENTS_REQUIRE_APPROVAL,
                            DISQUS_API_KEY, DISQUS_SHORTNAME)
from mango.templatetags.mango import _convert
from mango.utils import replace

disqus = DisqusAPI(DISQUS_API_KEY)

api_key = hashlib.sha1(DISQUS_API_KEY).hexdigest()

class post(object):
    def __init__(self, data, thread_=None):
        """Initialize a `post` object from an appropriate dictionary."""
        self.id = data['id']
        self.author = data['author']
        self.created_at = datetime.strptime(data['createdAt'],
                '%Y-%m-%dT%H:%M:%S').replace(tzinfo=pytz.utc)
        self.message = data['raw_message']
        self.html = replace(_convert(self.message))
        self.thread = thread_ or thread.fetch(data['thread'])

    @staticmethod
    def fetch(post_id):
        """Fetch the post from Disqus and return it as a `post` object."""
        return post(disqus.posts.details(post=post_id))

    @staticmethod
    def create(**kwargs):
        """Create a new post and return it as a `post` object."""
        kwargs = dict((k, v) for k, v in kwargs.items() if v)
        return post(disqus.posts.create(state='unapproved', **kwargs))

    @staticmethod
    def approve(post_id):
        """Mark the post as approved."""
        disqus.posts.approve(post=post_id)

    @staticmethod
    def remove(post_id):
        """Mark the post as deleted."""
        disqus.posts.remove(post=post_id)

    @staticmethod
    def spam(post_id):
        """Mark the post as spam."""
        disqus.posts.spam(post=post_id)

class thread(object):
    def __init__(self, data):
        """Initialize a `thread` object from an appropriate dictionary."""
        self.id = data['id']
        self.allow_comments = not data['isClosed']
        self.title = data['title']

        include = ['approved']
        if not COMMENTS_REQUIRE_APPROVAL:
            include.append('unapproved')

        try:
            self.posts = [post(postdata, self)
                          for postdata in disqus.threads.listPosts(
                          thread=self.id, limit=100, include=include)]
        except APIError, error:
            # Threads created via the Disqus API are
            # not necessarily immediately available.
            self.posts = []
        else:
            self.posts.sort(key=lambda post: post.created_at)

    @staticmethod
    def cache_key(thread_id):
        """Return the thread's cache key."""
        return 'mango:disqus:thread:%s' % thread_id

    @staticmethod
    def id_from_identifier(identifier):
        """Return the id of the first thread matching `identifier`."""
        paginator = Paginator(disqus.threads.list, forum=DISQUS_SHORTNAME)
        for data in paginator():
            if identifier in data['identifiers']:
                return data['id']

    @staticmethod
    def fetch(thread_id):
        """Fetch the thread from Disqus and return it as a `thread` object."""
        return thread(disqus.threads.details(thread=thread_id))

    @staticmethod
    def create(**kwargs):
        """Create a new thread and return it as a `thread` object."""
        return thread(disqus.threads.create(forum=DISQUS_SHORTNAME, **kwargs))

    @staticmethod
    def close(thread_id):
        """Mark the thread as closed."""
        disqus.threads.close(thread=thread_id)
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.