Mango /

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 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.""" = data['id'] = data['author']
        self.created_at = datetime.strptime(data['createdAt'],
        self.message = data['raw_message']
        self.html = replace(_convert(self.message))
        self.thread = thread_ or thread.fetch(data['thread'])

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

    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))

    def approve(post_id):
        """Mark the post as approved."""

    def remove(post_id):
        """Mark the post as deleted."""

    def spam(post_id):
        """Mark the post as spam."""

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

        include = ['approved']

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

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

    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']

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

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

    def close(thread_id):
        """Mark the thread as closed."""