Skip to content

Instantly share code, notes, and snippets.

@durdn
Created June 7, 2010 14:35
Show Gist options
  • Save durdn/428718 to your computer and use it in GitHub Desktop.
Save durdn/428718 to your computer and use it in GitHub Desktop.
models.py
from datetime import datetime
from StringIO import StringIO
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from tagging.models import Tag
import account.models
from utils.translation import TranslatedContent
from utils.urlresolvers import reverse
from filebrowser.fields import FileBrowseField
from django_markup.fields import MarkupField
from tms.parser import Record, TMSParser, TMSAuthorParser
from tms.query import QueryProcessor
from arttube.videos.models import Video
class TMSManager(object):
""" Knows how to query a TMS backend to get Records
The Manager is injected into TMSObject(s)
"""
parser = TMSParser()
processor = QueryProcessor()
def _localize_media(self,what,lang):
for i,media_item in enumerate(what):
if len(media_item) > 1:
if media_item[1].get(lang):
media_item[1] = media_item[1][lang]
else:
media_item[1] = None
def _localize(self,obj,lang):
for attribute in obj.__dict__:
try:
if obj.__getattribute__(attribute).get(lang):
obj.__setattr__(attribute,obj.__getattribute__(attribute)[lang])
else:
obj.__setattr__(attribute,obj.__getattribute__(attribute)[obj.__getattribute__(attribute).keys()[0]])
except AttributeError:
pass
try:
self._localize_media(obj.audio,lang)
except AttributeError:
pass
try:
self._localize_media(obj.video,lang)
except AttributeError:
pass
try:
self._localize_media(obj.image,lang)
except AttributeError:
pass
try:
self._localize_media(obj.link,lang)
except AttributeError:
pass
for i,cr in enumerate(obj.creator):
if cr['lang'] != lang:
del(obj.creator[i])
return obj
def find(self, lang=None,*args, **kwargs):
xml_response = StringIO(self.processor.find(*args,**kwargs))
result = []
records = self.parser.parse(xml_response)
for record in records:
if lang:
record = self._localize(record,lang)
# we now persist the object if it does not exist yet
obj,created = TMSObject.objects.get_or_create(tms_id=record.identifier)
# we link the record we got from the TMS system
obj.record = record
# we save it
obj.save()
# append it to the list of results
result.append(obj)
return result
def filter(self, query=None, start=None, end=None,test_response=None,
lang=None,sort=None, *args, **kwargs):
#if this is a test the response of the filter is the file passed to
# test_response
if test_response:
xml_response = file(test_response)
else:
xml_response = StringIO(self.processor.cit(query = query,start=start, end=end, sort=sort, **kwargs))
result = []
records = self.parser.parse(xml_response)
for record in records:
if lang:
record = self._localize(record,lang)
# we now persist the object if it does not exist yet
obj,created = TMSObject.objects.get_or_create(tms_id=record.identifier)
# we link the record we got from the TMS system
obj.record = record
# we save it
obj.save()
# append it to the list of results
result.append(obj)
return result
class TMSAuthorManager(object):
""" Knows how to query a TMS backend to get Authors
The Manager is injected into TMSObject(s)
"""
parser = TMSAuthorParser()
processor = QueryProcessor()
def _localize(self,obj,lang):
for attribute in obj.__dict__:
try:
if obj.__getattribute__(attribute).get(lang):
obj.__setattr__(attribute,obj.__getattribute__(attribute)[lang])
else:
obj.__setattr__(attribute,obj.__getattribute__(attribute)[obj.__getattribute__(attribute).keys()[0]])
except AttributeError:
pass
return obj
def find(self, authorname, lang=None):
xml_response = StringIO(self.processor.get_author(authorname))
result = []
authors = self.parser.parse(xml_response)
for author in authors:
if lang:
author = self._localize(author,lang)
# we now persist the object if it does not exist yet
obj,created = TMSAuthor.objects.get_or_create(tms_id=author.ccidentifier)
# we link the record we got from the TMS system
obj.author = author
# we save it
obj.save()
# append it to the list of results
result.append(obj)
return result
class TMSObject(models.Model):
""" Represents an Object in the TMS System.
In some cases we have to enrich the data coming from TMS with additional meta-data
Specifically we a TMSObject has:
- Zero or more Arttube Videos
- Zero or more Alma objects
- Media Elements (served by TMS or not?)
- a Creator
"""
tms_id = models.CharField(_("Unique Identifier in TMS System"),max_length=128)
records = TMSManager()
authors = TMSAuthorManager()
#collections site can overwrite the description coming from TMS with a
# rich text field (localized). For now I picked a textile mode
translated = TranslatedContent('translations', fail_silently=True, fall_back_language='nl')
# an object can be in many arttube videos and an arttube videos can talk
# about many objects
videos = models.ManyToManyField(Video, related_name='tms_objects', null=True, blank=True)
def tags(self):
return Tag.objects.usage_for_model(account.models.TagAction, filters=dict(tms_object__tms_id=self.tms_id))
def cloud(self):
return Tag.objects.cloud_for_model(account.models.TagAction, steps=4,
distribution=tagging.LOGARITHMIC,filters=dict(tms_object__id=self.id))
def update(self, lang=None):
""" Collects own data from TMS filling the record field """
try:
self.record = self.records.find(identifier = self.tms_id, lang = lang)[0].record
return True
except IndexError:
return False
def update_author(self, lang=None):
""" Collects own data from TMS filling the record field """
self.update(lang=lang)
self.author = self.authors.find(self.record.creator[0],lang=lang)[0].author
def __init__(self,*args,**kwargs):
#the record attribute is not part of the model but comes from the TMS
# interface so we store it n the object but remove it from the
# attribute list before passing it along to the ancestor model.Models
self.record = kwargs.get('record')
if kwargs.has_key('record'):
del(kwargs['record'])
models.Model.__init__(self, *args, **kwargs)
def get_absolute_url(self, request=None):
return reverse('collectie-work', args=[self.tms_id], request=request)
def __unicode__(self):
return self.tms_id
class TMSObjectTranslation(models.Model):
""" Translation for TMSObject content, namely the description """
tms_object = models.ForeignKey(TMSObject, related_name="translations")
language = models.CharField(max_length=5, choices=settings.LANGUAGES)
#collections site can overwrite the description coming from TMS with a
# rich text field (localized). For now I picked a textile mode
description = models.TextField(_("Description"),blank=True,null=True)
description_markup = MarkupField(default='textile',blank=True, null=True)
def __unicode__(self):
return self.description
class Meta:
unique_together = (("tms_object", "language"),)
class TMSAuthor(models.Model):
""" Represents an Author in the TMS System. """
tms_id = models.CharField(_("Unique Identifier in TMS System"),max_length=128)
class TMSMediaElement(models.Model):
""" Represents some media related to a TMSObject the TMS System. """
tms_id = models.CharField(_("Unique Identifier in TMS System"),max_length=128)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment