oxdata/poster/models.py

78 lines
2.7 KiB
Python

# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
import os.path
import hashlib
from django.db import models
from django.db.models import Q
from django.contrib.auth.models import User
from django.core.files.base import ContentFile
import oxweb.criterion
import oxweb.movieposterdb
import oxweb.karagarga
import oxweb.imdb
from oxdata.lookup.models import MovieId, Karagarga
class Poster(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
movie_id = models.ForeignKey(MovieId, related_name='poster')
url = models.CharField(max_length=255)
def poster_path(instance, filename):
id = instance.service_id
return os.path.join('poster', instance.service, id[:1], id[:4], id, filename)
class PosterCache(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
movie_id = models.ForeignKey(MovieId, related_name='postercache')
url = models.CharField(max_length=1024)
service = models.CharField(max_length=255)
service_id = models.CharField(max_length=42)
image = models.ImageField(max_length=255, upload_to=poster_path)
def get(self):
if not self.image:
import oxlib.net
ext = 'jpg'
if self.url.endswith('.png'):
ext = 'png'
name = "%s.%s" % (hashlib.sha1(self.url).hexdigest(), ext)
data = oxlib.net.getUrl(self.url)
self.image.save(name, ContentFile(data))
return self.image
def getPosterUrls(m):
def addPoster(url, service, service_id):
p = PosterCache(url=url, service=service, service_id=service_id, movie_id=m)
p.save()
if m.imdb_id:
poster = oxweb.imdb.getMoviePoster(m.imdb_id)
if poster:
if PosterCache.objects.all().filter(url=poster).count() == 0:
addPoster(poster, 'imdb.com', m.imdb_id)
if m.criterion_id:
for poster in oxweb.criterion.getData(m.criterion_id)['posters']:
if PosterCache.objects.all().filter(url=poster).count() == 0:
addPoster(poster, 'criterion.com', m.criterion_id)
if m.wikipedia_id:
poster = oxweb.wikipedia.getPosterUrl(m.wikipedia_id)
if poster:
if PosterCache.objects.all().filter(url=poster).count() == 0:
addPoster(poster, 'wikipedia.org', m.wikipedia_id)
for kg in Karagarga.objects.all().filter(movie_id=m):
data = oxweb.karagarga.getData(kg.karagarga_id)
if data:
for poster in data['posters']:
if PosterCache.objects.all().filter(url=poster).count() == 0:
addPoster(poster, 'karagarga.net', kg.karagarga_id)