import json import datetime from django.contrib.gis.db import models from django.template.defaultfilters import slugify from django.utils.html import urlize from django.utils import timezone from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings import requests from locations.models import Location from .build import * from twython import Twython # http://freewisdom.org/projects/python-markdown/ import markdown #from twitter_text.autolink import Autolink from utils.widgets import markdown_to_html from locations.models import CheckIn from jrnl.models import render_images def twitter_truncate(txt): return txt.split("|")[0] class LuxNote(models.Model): title = models.CharField(max_length=250, null=True, blank=True) slug = models.SlugField(unique_for_date='pub_date', blank=True) pub_date = models.DateTimeField(default=timezone.now) body_html = models.TextField(blank=True) body_markdown = models.TextField('Note') point = models.PointField(blank=True, null=True) location = models.ForeignKey(Location, blank=True, null=True) PUB_STATUS = ( (0, 'Draft'), (1, 'Published'), ) status = models.IntegerField(choices=PUB_STATUS, default=1) def __str__(self): return self.title def get_absolute_url(self): return reverse("notes:detail", kwargs={"year": self.pub_date.year, "month": self.pub_date.strftime("%m"), "slug": self.slug}) @property def region(self): return self.location.state.country.lux_region @property def longitude(self): '''Get the site's longitude.''' return round(self.point.x, 2) @property def latitude(self): '''Get the site's latitude.''' return round(self.point.y, 2) @property def get_previous_published(self): return self.get_previous_by_pub_date() @property def get_next_published(self): return self.get_next_by_pub_date() def save(self, *args, **kwargs): md = render_images(self.body_markdown) self.body_html = markdown_to_html(md) if not self.point: self.point = CheckIn.objects.latest().point try: self.location = Location.objects.filter(geometry__contains=self.point).get() except Location.DoesNotExist: raise forms.ValidationError("There is no location associated with that point, add it: %sadmin/locations/location/add/" % (settings.BASE_URL)) if not self.id: self.pub_date= timezone.now() self.date_last_updated = timezone.now() super(LuxNote, self).save() class Note(models.Model): title = models.CharField(max_length=250, null=True, blank=True) slug = models.SlugField(unique_for_date='date_created', blank=True) date_created = models.DateTimeField('Date', blank=True) date_last_updated = models.DateTimeField('Date', blank=True) point = models.PointField() location = models.ForeignKey(Location, null=True, blank=True) city_name = models.CharField(max_length=250, null=True, blank=True) state_name = models.CharField(max_length=250, null=True, blank=True) country_name = models.CharField(max_length=150, null=True, blank=True) body_html = models.TextField(blank=True) body_markdown = models.TextField('Note') twitter_text = models.CharField('Twitter text', max_length=450, null=True, blank=True) twitter_id = models.CharField('twitter_id', max_length=450) twitter_send = models.BooleanField("send to twitter?", default=False) twitter_sent = models.BooleanField(default=False, blank=True) #in_reply_to = models.CharField('in reply to url', max_length=450) def __str__(self): return self.slug def get_absolute_url(self): return '/field-notes/%s/%s' % (self.date_created.strftime("%Y/%m").lower(), self.slug) @property def state(self): return self.location.state @property def country(self): return self.location.state.country @property def region(self): return self.location.state.country.lux_region @property def longitude(self): '''Get the site's longitude.''' return round(self.point.x, 2) @property def latitude(self): '''Get the site's latitude.''' return round(self.point.y, 2) @property def get_previous_published(self): return self.get_previous_by_date_created() @property def get_next_published(self): return self.get_next_by_date_created() def render(self): opts = {'username_include_symbol': True} temp = " ".join(self.body_markdown.split("|")) html = markdown.markdown(urlize(temp, 45), extensions=['extra'], safe_mode=False) return html def save(self): self.body_html = markdown.markdown(urlize(self.body_markdown, 45), extensions=['extra'], safe_mode=False) self.date_last_updated = datetime.datetime.now() if not self.date_created: self.date_created = datetime.datetime.now() if not self.slug: self.slug = slugify(self.title)[:30] if not self.twitter_text: self.twitter_text = twitter_truncate(self.body_markdown) super(Note, self).save() @receiver(post_save, sender=Note) def post_save_events(sender, instance, **kwargs): if kwargs["created"]: try: l = Location.objects.filter(geometry__contains=instance.point).get() instance.location = l instance.city_name = l.name instance.state_name = l.state.name instance.country_name = l.state.country.name except Location.DoesNotExist: r_str = 'http://nominatim.openstreetmap.org/reverse?format=json&lat=%s&lon=%s&zoom=18' % (instance.latitude, instance.longitude) response = requests.get(r_str) data = json.loads(response.text) adr = data.get('address', {}) instance.city_name = adr.get('hamlet') or adr.get('village') or adr.get('town') or adr.get('city') instance.state_name = adr.get('state') instance.country_name = adr.get('country') #if instance.in_reply_to: #crawl url, extract text, store it locally with a reference to instance pass if instance.twitter_send and not instance.twitter_sent: t = Twython(settings.TWITTER_API_KEY, settings.TWITTER_API_SECRET, settings.TWITTER_ACCESS_TOKEN, settings.TWITTER_ACCESS_SECRET) geo = t.reverse_geocode(lat=instance.latitude, lon=instance.longitude, accuracy=1500, granularity="city") geo_id = geo['result']['places'][0]['id'] status = t.update_status(status=instance.twitter_text, place_id=geo_id) instance.twitter_id = status['id'] instance.twitter_sent = True post_save.disconnect(post_save_events, sender=Note) instance.save() post_save.connect(post_save_events, sender=Note) b = BuildNotes() b.build() def write_note(sender, instance, **kwargs): if kwargs["created"]: pass class OriginNoteForReplies(models.Model): #created_at date_created = models.DateTimeField() #profile_image_url_https profile_image = models.CharField(max_length=450, null=True, blank=True) #screen_name screen_name = models.CharField(max_length=75, null=True, blank=True) #text body_html = models.TextField(blank=True) #url remote_url = models.CharField(max_length=450, null=True, blank=True)