1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 from os.path import join, isfile
6 from django.core.urlresolvers import reverse
7 from django.db import models
8 from waiter.settings import WAITER_URL, WAITER_MAX_QUEUE
9 from waiter.utils import check_abspath
10 from picklefield import PickledObjectField
13 class WaitedFile(models.Model):
14 path = models.CharField(max_length=255, unique=True, db_index=True)
15 task_id = models.CharField(max_length=128, db_index=True, null=True, blank=True)
16 task = PickledObjectField(null=True, editable=False)
17 description = models.CharField(max_length=255, null=True, blank=True)
20 def exists(cls, path):
21 """Returns opened file or None.
23 `path` is relative to WAITER_ROOT.
24 Won't open a path leading outside of WAITER_ROOT.
26 abs_path = check_abspath(path)
27 # Pre-fetch objects for deletion to avoid minor race condition
28 relevant = [o.id for o in cls.objects.filter(path=path)]
30 cls.objects.filter(id__in=relevant).delete()
36 def can_order(cls, path):
37 return (cls.objects.filter(path=path).exists() or
39 cls.objects.count() < WAITER_MAX_QUEUE
44 # Race; just let the other task roll.
46 if self.task.status not in (u'PENDING', u'STARTED', u'SUCCESS', u'RETRY'):
51 def order(cls, path, task_creator, description=None):
53 Returns an URL for the user to follow.
54 If the file is ready, returns download URL.
55 If not, starts preparing it and returns waiting URL.
57 task_creator: function taking a path and generating the file;
58 description: a string or string proxy with a description for user;
60 already = cls.exists(path)
62 waited, created = cls.objects.get_or_create(path=path)
63 if created or waited.is_stale():
64 waited.task = task_creator(check_abspath(path))
65 waited.task_id = waited.task.task_id
66 waited.description = description
68 return reverse("waiter", args=[path])
69 return join(WAITER_URL, path)