Source

pentasubmitter / src / submitter / models.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
# -*- coding: utf-8 -*-

"""Models for Submitter Application"""

import os
import re
import datetime
import subprocess
import logging
import urllib
import urllib2
import tagging
import cStringIO
import string
import unicodedata
from htmlentitydefs import name2codepoint
from PIL import Image
from BeautifulSoup import BeautifulSoup
from markdown import markdown
from django.db import models, IntegrityError
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.conf import settings
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
from django.core.files.base import ContentFile
from django.db.models.fields.files import ImageFieldFile
from registration.signals import user_activated
#from djangoratings.fields import RatingField
#from django.core.files.uploadedfile import SimpleUploadedFile
#from tagging.fields import TagField
#from tagging.utils import parse_tag_input
from submitter import tasks
from show.models import PentaShow
from south.modelsinspector import add_introspection_rules

#from pentasubmitter.debug import interact

# django-tagging from http://code.google.com/p/django-tagging/

#add_introspection_rules([], ["^submitter\.newsentry\.page_screenshot"])
add_introspection_rules([], ["^submitter\.models\.ThumbNailImageField"])

if os.environ.has_key('TMPDIR'):
    TMP_DIR = os.environ['TMPDIR']
else:
    TMP_DIR = '/tmp/'

CUTYCAPT = 'xvfb-run --server-args="-screen 0, 640x480x24" CutyCapt'

LOGFILE = TMP_DIR +'pentasubmitter-submitter.log'
logging.basicConfig(filename=LOGFILE, level=logging.DEBUG)
logging.debug("Submitter models run in debug mode")

def htmlentitydecode(s):
    """un escape html"""
    return re.sub('&(%s);' % '|'.join(name2codepoint),
            lambda m: unichr(name2codepoint[m.group(1)]), s)

def slugify(value):
    """
    Normalizes string, converts to lowercase, removes non-alpha characters,
    and converts spaces to hyphens.
    """
    value = unicode(value)
    value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
    value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
    value = unicode(re.sub(r'[^-|\w]+', '', value))
    value = re.sub('[-\s]+', '-', value)
    return value.strip('-')

def generate_thumb(img, thumb_size, format):
    """
    Generates a thumbnail image and returns a ContentFile object with the
    thumbnail
    
    Parameters:
    ===========
    img         File object
    
    thumb_size  desired thumbnail size, ie: (200,120)
    
    format      format of the original image ('jpeg','gif','png',...)
                (this format will be used for the generated thumbnail, too)
    """
    
    img.seek(0) # see http://code.djangoproject.com/ticket/8222 for details
    image = Image.open(img)
    
    # Convert to RGB if necessary
    if image.mode not in ('L', 'RGB', 'RGBA'):
        image = image.convert('RGB')

    # get size
    thumb_w, thumb_h = thumb_size
    # If you want to generate a square thumbnail
    if thumb_w == thumb_h:
        # quad
        xsize, ysize = image.size
        # get minimum size
        minsize = min(xsize,ysize)
        # largest square possible in the image
        xnewsize = (xsize-minsize)/2
        ynewsize = (ysize-minsize)/2
        # crop it
        image2 = image.crop((xnewsize, ynewsize, xsize-xnewsize,
                             ysize-ynewsize))
        # load is necessary after crop
        image2.load()
        # thumbnail of the cropped image (with ANTIALIAS to make it look better)
        image2.thumbnail(thumb_size, Image.ANTIALIAS)
    else:
        # not quad
        image2 = image
        image2.thumbnail(thumb_size, Image.ANTIALIAS)

    io = cStringIO.StringIO()
    # PNG and GIF are the same, JPG is JPEG
    if format.upper()=='JPG':
        format = 'JPEG'

    image2.save(io, format)
    return ContentFile(io.getvalue())

def fetch_page_screenshot(url, path):
    """fetch a screen shot of the page given by url

    url:str -- the URL to fetch
    path:str -- Path to the image in the file system

    returns:
    (True|False) -- True if page screen shot was successful
    """

    return_value = False

    if url:
        try:
            #print subprocess.list2cmdline(
            subprocess.check_call(
                ['xvfb-run',
                 r'--server-args=-screen 0, 640x480x24',
                 'CutyCapt',
                 '--url=' + url,
                 '--min-width=500',
                 '--max-wait=5000',
                 '--js-can-open-windows=off',
                 '--js-can-access-clipboard=off',
                 '--java=off',
                 '--user-agent=Mozilla/5.0 (compatible; PentaSubmitter 0.1)',
                 '--out=' + path],
            )
            return_value = True
            # CutyCapt always returns a pix. If there is a connection failure
            # it renders an empty picture.

        except subprocess.CalledProcessError:
            return_value = False

    return return_value

def send_to_bot(message):
    """Send messages dict to bot as configured in settings.JABBER_BOT_URL
    
    messages:unicode Message to send
    """
    if not hasattr(settings, 'JABBER_BOT_URL'):
        return
    logging.debug("message: %s\n" % (message))
    data = urllib.urlencode([("text", message.encode('utf-8'))])
    logging.debug("Server (%s) message: %s\n" % (settings.JABBER_BOT_URL, data))
    try:
        f = urllib2.urlopen(settings.JABBER_BOT_URL, data)
        response = "None"
        response = f.read()
        f.close()
    except:
        response = "Failed to connect"
    logging.debug("Server (%s) response: %s\n" % (
        settings.JABBER_BOT_URL, response))


class ThumbNailImageFieldFile(ImageFieldFile):
    """Overwrite models.ImageField to support thumbnails
    See ThumbNailImageField for docu!
    """

    def __init__(self, *args, **kwargs):
        super(ThumbNailImageFieldFile, self).__init__(*args, **kwargs)
        if self.field.thumbnail_sizes:
            def get_size(self, size):
                if not self:
                    return ''
                else:
                    split = self.url.rsplit('.',1)
                    thumb_url = '%s.%sx%s.%s' % (split[0],w,h,split[1])
                    return thumb_url

            for size in self.field.thumbnail_sizes:
                (w,h) = size
                setattr(self, 'url_%sx%s' % (w,h), get_size(self, size))

    def save(self, name, content, save=True):
        """save and generate thumbnails"""
        super(ThumbNailImageFieldFile, self).save(name, content, save)

        if self.field.thumbnail_sizes:
            for size in self.field.thumbnail_sizes:
                (w,h) = size
                split = self.name.rsplit('.',1)
                thumb_name = '%s.%sx%s.%s' % (split[0],w,h,split[1])

                # you can use another thumbnailing function if you like
                thumb_content = generate_thumb(content, size, split[1])

                thumb_name_ = self.storage.save(thumb_name, thumb_content)

                if not thumb_name == thumb_name_:
                    raise ValueError('There is already a file named %s' % (
                        thumb_name,)
                    )

    def delete(self, save=True):
        name=self.name
        super(ThumbNailImageFieldFile, self).delete(save)
        if self.field.thumbnail_sizes:
            for size in self.field.thumbnail_sizes:
                (w,h) = size
                split = name.rsplit('.',1)
                thumb_name = '%s.%sx%s.%s' % (split[0],w,h,split[1])
                try:
                    self.storage.delete(thumb_name)
                except:
                    pass


class ThumbNailImageField(models.ImageField):
    """Overwrite models.ImageField to support thumbnails

    Stolen from http://code.google.com/p/django-thumbs/ and pimped to fit
    this app here. Docu is also from django-thumbs

    Usage example:
    ==============
    photo = ImageWithThumbsField(upload_to='images', sizes=((125,125),(300,200),)

    To retrieve image URL, exactly the same way as with ImageField:
        my_object.photo.url
    To retrieve thumbnails URL's just add the size to it:
        my_object.photo.url_125x125
        my_object.photo.url_300x200

    Note: The 'sizes' attribute is not required. If you don't provide it, 
    ImageWithThumbsField will act as a normal ImageField

    How it works:
    =============
    For each size in the 'sizes' atribute of the field it generates a 
    thumbnail with that size and stores it following this format:

    available_filename.[width]x[height].extension

    Where 'available_filename' is the available filename returned by the storage
    backend for saving the original file.

    Following the usage example above: For storing a file called "photo.jpg" it
    saves:
    photo.jpg          (original file)
    photo.125x125.jpg  (first thumbnail)
    photo.300x200.jpg  (second thumbnail)

    With the default storage backend if photo.jpg already exists it will use
    these filenames:
    photo_.jpg
    photo_.125x125.jpg
    photo_.300x200.jpg

    Note: django-thumbs assumes that if filename "any_filename.jpg" is available
    filenames with this format "any_filename.[widht]x[height].jpg" will be
    available, too.

    To do:
    ======
    Add method to regenerate thubmnails

    """

    attr_class = ThumbNailImageFieldFile

    def __init__(self, verbose_name=None, name=None, width_field=None,
                 height_field=None, thumbnail_sizes=((80,80),), image_path=None,
                 **kwargs):
        self.verbose_name=verbose_name
        self.name=name
        self.width_field=width_field
        self.height_field=height_field
        self.thumbnail_sizes = thumbnail_sizes
        #self.image_path = image_path
        super(models.ImageField, self).__init__(**kwargs)


class Submitter(models.Model):
    """Submitter, the User settings
    """

    user = models.ForeignKey(
        User,
        verbose_name=_("Submitter"),
        unique=True
    )

    def get_absolute_url(self):
        return ('profiles_profile_detail', (),
                { 'username': self.user.username })
    get_absolute_url = models.permalink(get_absolute_url)

    def __unicode__(self):
        return self.user.username


class EntryCategory(models.Model):
    """Categories of entries.
    e.g. "Patent of the month, general news, ...
    """

    title = models.CharField(
        verbose_name=_("Title"),
        blank=False,
        max_length = 250,
    )

    slug = models.SlugField(
        verbose_name="Slug",
        unique=True,
        help_text=_(u"Suggested value automatically generated from title. "
                    u"Must be unique."),
    )

    description = models.TextField(
        verbose_name="Description",
        blank=True,
    )

    tags_string = tagging.fields.TagField(
        help_text="separate multiple tags by spaces",
    )

    def get_tag_list(self):
        return [ t.name for t in self.tags_string]

    class Meta:
        verbose_name_plural = "EntryCategories"

    def __unicode__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.description_html = markdown(self.description)

        # slug fix ups
        if not self.slug:
            self.slug = re.sub(r'[\s\W]', '', self.title.lower())[:10]
            # self.slug must not
            # be in EntryCategory.objects.filter(slug=self.slug)
            count = 0
            while [True for news_entry in EntryCategory.objects.filter(
                slug=self.slug)]:
                count += 1
                self.slug = re.sub(r'\s', '', self.title[:23].lower()) \
                        + "%0*d" % (3, count)
                if count > 999:
                    raise IntegrityError, ("column slug cannot be made unique")
        else:
            self.slug = re.sub(r'[\s\W]', '', self.slug.lower())[:26]

        super(EntryCategory, self).save(*args, **kwargs)

    @models.permalink
    def get_absolute_url(self):
        return ('entry_category_detail', (), {
            'slug': self.slug
        })


class NewsEntry(models.Model):
    """hold news entry such as text, URL or both"""

    LIVE_STATUS = 1     # seen by everyone
    DRAFT_STATUS = 2    # seen by submitting user only
    HIDDEN_STATUS = 3   # only seen by radio crew
    STATUS_CHOICES = (
        (LIVE_STATUS, "Live"),
        (DRAFT_STATUS, "Draft"),
        (HIDDEN_STATUS, "Hidden"),
    )

    title = models.CharField(
        verbose_name=_(u"Title"),
        blank=True,
        max_length=250,
    )

    slug = models.SlugField(
        verbose_name=_(u"Slug"),
        unique=True,
        help_text=_(u"Suggested value automatically generated from title. "
                    u"Must be unique."),
    )

    excerpt = models.TextField(
        verbose_name=_("Excerpt"),
        blank=True,
    )

    body = models.TextField(
        verbose_name=_("Description"),
        blank=True,
    )

    # Fields to store generated HTML.
    body_html = models.TextField(
        help_text=_(u"Use Markdown syntax"),
        editable=False,
        blank=True
    )

    excerpt_html = models.TextField(
        help_text=_(u"Use Markdown syntax"),
        editable=False,
        blank=True
    )

    external_url = models.URLField(
        verbose_name=_("URL"),
        verify_exists=False,
        max_length=230,
        blank=True,
    )

    # to hold a screenshot of the page
    page_screenshot = ThumbNailImageField(
        verbose_name=_(u"Page screenshot"),
        help_text=_(u"Auto generated if left blank."),
        blank=True,
        null=True,
        thumbnail_sizes=((80, 80), (120, 80)),
        upload_to='page_shots/%Y/%m/%d/',
    )

    # Metadata.
    slug = models.SlugField(
        #prepopulate_from=['title'],    # not valid in v1.0 anymore
        unique_for_date='submit_date',
        help_text=_("Suggested value automatically generated from title."),
        blank=True,
    )

    author = models.ForeignKey(
        Submitter,
        related_name='author',
        verbose_name=_("Submitter"),
        blank=False,
    )

    #rating = RatingField(
    #    range=5,
    #    can_change_vote = True,
    #    allow_anonymous = True,
    #)

    enable_comments = models.BooleanField(
        verbose_name=_("Comments allowed?"),
        default=True,
    )

    featured = models.BooleanField(
        verbose_name=_("featured entry?"),
        default=False,
    )

    status = models.IntegerField(
        verbose_name=_("Status"),
        choices=STATUS_CHOICES,
        default=LIVE_STATUS,
    )
#was the news item read?
#was_read = models.BooleanField(
#        verbose_name=_("Show was read?"),
#        default=False,
#    )

    submit_date = models.DateTimeField(
        verbose_name=_("Publication Date"),
        blank=True,
        #default=lambda: datetime.datetime.now(),
        #auto_now_add=True,   # set on NewsEntry() first save()
        #default=datetime.datetime.now()
    )

    show = models.ForeignKey(
        PentaShow,
        verbose_name=_("Penta Show"),
        null=True,
    )

    # Categorization.
    categories = models.ManyToManyField(
        EntryCategory,
        verbose_name=_("Category"),
        blank=True,
    )

    tags_string = tagging.fields.TagField(
        help_text=_("separate tags by spaces"),
    )

    def get_tag_list(self):
        return [ t.name for t in self.tags]

    class Meta:
        ordering = ['-submit_date']
        verbose_name_plural = "News Entries"

    def __unicode__(self):
        return self.title

    def save(self, *args, **kwargs):
        "save the NewsEntry(), gen html, fetch page shot, gen thumb nails ..."

        # Generate html from input field markup
        self.body_html = markdown(self.body)
        if self.excerpt:
            self.excerpt_html = markdown(self.excerpt)
        # Fetch title from URL if not set
        if self.external_url and not self.title:
            try:
                self.title = BeautifulSoup(
                    urllib2.urlopen(self.external_url)).title.string
                if self.title == u"":
                    self.title = u"Page has no title."

            except:
                self.title = u"Unknown Title"

        # need datetime for slug. If not correct, the Ajax update will get
        # confused
        if not self.submit_date:
            self.submit_date = datetime.datetime.now()

        # slug fix ups
        if not self.slug:
            slug = slugify(self.title[:50])
            # If there is no slug something is wrong (e.g. empty form
            if not slug:
                raise IntegrityError
            self.slug = slug
            # self.slug must not
            # be in EntryCategory.objects.filter(slug=self.slug)
            count = 0
            while [True for news_entry in NewsEntry.objects.filter(
                slug=self.slug)]:
                count += 1
                self.slug = slug[:47] + "%0*d" % (3, count)
                if count > 999:
                    raise IntegrityError, ("column slug cannot be made unique")
        else:
            self.slug = slugify(self.slug)

        self.title = htmlentitydecode(self.title)

        # generate bot message
        if not self.pk:
            bot_status_message = u'Sub new:'

            bot_message = u" ".join([
                bot_status_message,
                u'%s' %  (self.title,),
                u'%s/%s/%s/%s/%s' % (
                    settings.SUBMITTER_URL.rstrip('/'),
                    self.submit_date.strftime("%Y"),
                    self.submit_date.strftime("%m"),
                    self.submit_date.strftime("%d"),
                    self.slug,
                ),
            ])

            tasks.send_to_bot.delay(bot_message)

        super(NewsEntry, self).save(*args, **kwargs)

        # fetch page screen shot of the page
        if not self.page_screenshot:
            tasks.gen_screenshot.delay(self)

    @models.permalink
    def get_absolute_url(self):
        return ('news_entry_detail', (), {
            'year': self.submit_date.strftime("%Y"),
            'month': self.submit_date.strftime("%m"),
            'day': self.submit_date.strftime("%d"),
            'slug': self.slug
        })


# Signals


def make_user_submitter(sender, user, request, **kwargs):
    """Callback for registration.signals.user_activated to add User()
    to the submitter.Submitter() in order to let him do things on the page
    """
    submitter = Submitter()
    submitter.user = user
    submitter.save()

#user_activated.connect(make_user_submitter)

try:
    tagging.register(NewsEntry)
    tagging.register(EntryCategory)
except tagging.AlreadyRegistered:
    # You might wonder what is going on here.
    # This is a bug in the svn release.  For some reason, the authors' cannot
    # handle
    # re-registering gracefully, so we have to.
    # This should be fixed in later releases, but your code will still work
    # hereafter it is.
    pass

# vim: ts=4 et sw=4 fileencoding=utf-8 :