videopdf/item/models.py

93 lines
2.8 KiB
Python
Raw Normal View History

2013-02-12 07:09:52 +00:00
# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
# GPL 2013
from __future__ import division, with_statement
import os
import random
from urllib import quote
import json
from django.db import models
from django.core.files.base import ContentFile
from django.db.models.signals import pre_delete
from django.contrib.auth.models import User, Group
import ox
from ox.django import fields
def new_slug():
current_max = Item.objects.all().count() * 2
slug = ox.to32(random.randint(0, max(10, current_max))).capitalize()
if Item.objects.all().filter(slug=slug).count() > 0:
return new_slug()
return slug
class Item(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
user = models.ForeignKey(User, related_name='items')
slug = models.SlugField(unique=True, default=new_slug)
file = models.FileField(upload_to=lambda f, x: f.path(x), max_length=1024)
filename = models.CharField(max_length=1024)
overlay = fields.DictField(default={}, editable=True)
done = models.BooleanField(default=False)
def get_overlay(self):
return json.dumps(self.overlay)
def size(self):
try:
size = self.file and self.file.size or 0
except:
size = 0
return ox.format_bytes(size)
def get_absolute_url(self):
return '/%s' % self.slug
def get_absolute_pdf_url(self):
filename = self.filename
if not filename.endswith('.pdf'):
filename += '.pdf'
return '/%s/%s' % (self.slug, quote(filename))
def path(self, filename):
if len(filename) > 1024:
filename = os.path.splitext(filename)
filename = filename[0][:1024-len(filename[-1])-3] + '...' + filename[-1]
return os.path.join('item', self.slug, filename)
def __unicode__(self):
return u"%s/%s" %(self.slug, self.filename)
def save_chunk(self, chunk, name='data.bin'):
if not self.done:
if not self.file:
if len(name) > 1024:
name = os.path.splitext(name)
name = name[0][:1024-len(name[-1])-3] + '...' + name[-1]
self.file.save(name, ContentFile(chunk))
self.filename = name
self.save()
os.chmod(self.file.path, 0644)
else:
f = open(self.file.path, 'a')
f.write(chunk)
f.close()
return True
return False
def delete_file(sender, **kwargs):
item= kwargs['instance']
if item.file:
path = item.file.path
item.file.delete()
try:
os.rmdir(os.path.dirname(path))
except OSError:
pass
pre_delete.connect(delete_file, sender=Item)