Source

django-tube / tube / models.py

# -*- coding: utf-8 -*-

import re

from django.db import models
from django.db.models import Manager, permalink
from django.utils.translation import ugettext_lazy as _


EMBED_HTML = """<iframe src="http://www.youtube.com/embed/%s?rel=0"
        width="640" height="360" frameborder="0" allowfullscreen></iframe>
"""

URL_PATTERN = re.compile(r'^(http[s]?://www\.youtube\.com/watch\?v='
                         r'|http[s]?://youtu\.be/)([-a-z0-9A-Z_]+)')


class VideoManager(Manager):
    use_for_related_fields = True

    def visible(self, *args, **kwargs):
        return super(VideoManager, self).filter(visible=True, *args, **kwargs)


class Video(models.Model):
    title = models.CharField(_('title'), max_length=60)
    slug = models.SlugField(
        _('slug'),
        help_text=_('Automatically built from the title. A slug is a short '
                    'label generally used in URLs.'),
    )
    youtube_url = models.URLField(
        _('YouTube URL'),
        help_text=_('Enter the YouTube video URL, e.g.: '
                    'http://www.youtube.com/watch?v=wuzgCwKElm4')
    )
    description = models.TextField(_('description'), blank=True)
    visible = models.BooleanField(_('visible'), default=True)
    date_added = models.DateTimeField(_('date added'), auto_now_add=True)
    date_modified = models.DateTimeField(_('date modified'), auto_now=True)
    date_recorded = models.DateField(_('date recorded'), blank=True, null=True)
    time_recorded = models.TimeField(_('time recorded'), blank=True, null=True)
    place = models.CharField(_('place'), blank=True, max_length=70)
    cameraman = models.CharField(
        _('cameraman'),
        blank=True,
        max_length=50
    )

    objects   = VideoManager()

    class Meta:
        get_latest_by = 'date_added'
        ordering      = ('-date_added',)
        verbose_name  = _('video')
        verbose_name_plural = _('videos')

    def __unicode__(self):
        return self.title

    @permalink
    def get_absolute_url(self):
        return ('tube-video', None, {
            'pk' : str(self.pk),
            'slug' : str(self.slug),
        })

    @property
    def youtube_id(self):
        match = re.match(URL_PATTERN, self.youtube_url)
        if match:
            return match.groups()[1]
        return None

    @property
    def thumbnail_url(self):
        return 'http://i.ytimg.com/vi/%s/default.jpg' % self.youtube_id

    @property
    def embed_html(self):
        return EMBED_HTML % self.youtube_id