
import re
from datetime import datetime, timedelta
from time import timezone
from urllib2 import urlopen, quote

from django.db import models
from django.utils.html import urlize
from django.utils.simplejson import loads
from django.utils.translation import ugettext_lazy as _

from mezzanine.twitter.managers import TweetManager


re_usernames = re.compile("@([0-9a-zA-Z+_]+)", re.IGNORECASE)
re_hashtags = re.compile("#([0-9a-zA-Z+_]+)", re.IGNORECASE)
replace_hashtags = "<a href=\"http://twitter.com/search?q=%23\\1\">#\\1</a>"
replace_usernames = "<a href=\"http://twitter.com/\\1\">@\\1</a>"


class Query(models.Model):

    QUERY_TYPE_CHOICES = (
        ("user", _("User")),
        ("list", _("List")),
        ("search", _("Search")),
    )

    type = models.CharField(_("Type"), choices=QUERY_TYPE_CHOICES,
        max_length=10)
    value = models.CharField(_("Value"), max_length=140)
    interested = models.BooleanField("Interested", default=True)

    class Meta:
        verbose_name = _("Twitter query")
        verbose_name_plural = _("Twitter queries")
        ordering = ("-id",)

    def __unicode__(self):
        return "%s: %s" % (self.get_type_display(), self.value)

    def run(self):
        """
        Request new tweets from the Twitter API.
        """
        if self.type == "user":
            url = ("http://api.twitter.com/1/statuses/user_timeline/%s.json?"
                "include_rts=true" % self.value.lstrip("@"))
        elif self.type == "list":
            url = ("http://api.twitter.com/1/%s/statuses.json?include_rts"
                "=true" % self.value.lstrip("@").replace("/", "/lists/"))
        elif self.type == "search":
            url = ("http://search.twitter.com/search.json?q=%s" %
                quote(self.value))
        else:
            return
        try:
            tweets = loads(urlopen(url).read())
        except:
            return
        if self.type == "search":
            tweets = tweets["results"]
        for tweet_json in tweets:
            tweet, created = self.tweets.get_or_create(
                remote_id=str(tweet_json["id"]))
            if not created:
                continue
            if "retweeted_status" in tweet_json:
                user = tweet_json["user"]
                tweet.retweeter_user_name = user["screen_name"]
                tweet.retweeter_full_name = user["name"]
                tweet.retweeter_profile_image_url = user["profile_image_url"]
                tweet_json = tweet_json["retweeted_status"]
            if self.type == "search":
                tweet.user_name = tweet_json["from_user"]
                tweet.full_name = tweet_json["from_user"]
                tweet.profile_image_url = tweet_json["profile_image_url"]
                date_format = "%a, %d %b %Y %H:%M:%S +0000"
            else:
                user = tweet_json["user"]
                tweet.user_name = user["screen_name"]
                tweet.full_name = user["name"]
                tweet.profile_image_url = user["profile_image_url"]
                date_format = "%a %b %d %H:%M:%S +0000 %Y"
            tweet.text = urlize(tweet_json["text"])
            tweet.text = re_usernames.sub(replace_usernames, tweet.text)
            tweet.text = re_hashtags.sub(replace_hashtags, tweet.text)
            tweet.created_at = datetime.strptime(tweet_json["created_at"],
                date_format) - timedelta(seconds=timezone)
            tweet.save()
        self.interested = False
        self.save()


class Tweet(models.Model):
    remote_id = models.CharField(_("Twitter ID"), max_length=50)
    created_at = models.DateTimeField(_("Date/time"), null=True)
    text = models.TextField(_("Message"), null=True)
    profile_image_url = models.URLField(_("Profile image URL"), null=True)
    user_name = models.CharField(_("User name"), max_length=100, null=True)
    full_name = models.CharField(_("Full name"), max_length=100, null=True)
    retweeter_profile_image_url = models.URLField(
        _("Profile image URL (Retweeted by)"), null=True)
    retweeter_user_name = models.CharField(
        _("User name (Retweeted by)"), max_length=100, null=True)
    retweeter_full_name = models.CharField(
        _("Full name (Retweeted by)"), max_length=100, null=True)
    query = models.ForeignKey("Query", related_name="tweets")

    objects = TweetManager()

    class Meta:
        verbose_name = _("Tweet")
        verbose_name_plural = _("Tweets")
        ordering = ("-created_at",)

    def __unicode__(self):
        return "%s: %s" % (self.user_name, self.text)

    def is_retweet(self):
        return self.retweeter_user_name is not None

@@ -70,17 +70,16 @@
 timezone
-%0D
 %0Afrom ur
@@ -105,17 +105,16 @@
 n, quote
-%0D
 %0A%0Afrom d
@@ -323,17 +323,16 @@
 tManager
-%0D
 %0A%0A%0Are_us
@@ -593,18 +593,17 @@
 1%3C/a%3E%22%0A%0A
-%0D
 %0A
+
 class Qu
@@ -1017,17 +1017,16 @@
  query%22)
-%0D
 %0A       
@@ -1068,17 +1068,16 @@
 ueries%22)
-%0D
 %0A       
@@ -3528,17 +3528,16 @@
 .Model):
-%0D
 %0A    rem
@@ -3593,17 +3593,16 @@
 ngth=50)
-%0D
 %0A    cre
@@ -3654,25 +3654,24 @@
 , null=True)
-%0D
 %0A    text = 
@@ -3707,25 +3707,24 @@
 , null=True)
-%0D
 %0A    profile
@@ -3782,25 +3782,24 @@
 , null=True)
-%0D
 %0A    user_na
@@ -3858,25 +3858,24 @@
 , null=True)
-%0D
 %0A    full_na
@@ -3930,33 +3930,32 @@
 =100, null=True)
-%0D
 %0A    retweeter_p
@@ -4039,33 +4039,32 @@
 y)%22), null=True)
-%0D
 %0A    retweeter_u
@@ -4153,25 +4153,24 @@
 , null=True)
-%0D
 %0A    retweet
@@ -4267,17 +4267,16 @@
 ll=True)
-%0D
 %0A    que
@@ -4410,17 +4410,16 @@
 %22Tweet%22)
-%0D
 %0A       
@@ -4452,17 +4452,16 @@
 Tweets%22)
-%0D
 %0A       
@@ -4574,9 +4574,8 @@
 ext)
-%0D
 %0A%0A  

Cleaned up whitespace