mirror of
https://github.com/jwinterm/modoboa.git
synced 2026-10-19 05:58:34 +02:00
63 lines
1.9 KiB
Python
63 lines
1.9 KiB
Python
# coding: utf-8
|
|
|
|
"""Models for the limits extensions."""
|
|
|
|
from django.conf import settings
|
|
from django.db import models
|
|
|
|
from modoboa.core import models as core_models
|
|
|
|
from . import utils
|
|
|
|
|
|
class ObjectLimit(models.Model):
|
|
"""Per-user limits on object creation."""
|
|
|
|
user = models.ForeignKey(settings.AUTH_USER_MODEL)
|
|
name = models.CharField(max_length=254)
|
|
content_type = models.ForeignKey("contenttypes.ContentType")
|
|
max_value = models.IntegerField(default=-2)
|
|
|
|
class Meta:
|
|
unique_together = (("user", "name"), )
|
|
|
|
@property
|
|
def definition(self):
|
|
"""Return the definition of this limit."""
|
|
for name, tpl in utils.get_limit_templates():
|
|
if name == self.name:
|
|
return tpl
|
|
return None
|
|
|
|
@property
|
|
def current_value(self):
|
|
"""Return the current number of objects."""
|
|
if "extra_filters" not in self.definition:
|
|
return core_models.ObjectAccess.objects.filter(
|
|
user=self.user, is_owner=True,
|
|
content_type=self.content_type).count()
|
|
id_list = core_models.ObjectAccess.objects.filter(
|
|
user=self.user, is_owner=True,
|
|
content_type=self.content_type).values_list("object_id", flat=True)
|
|
model_class = self.content_type.model_class()
|
|
return model_class.objects.filter(
|
|
pk__in=id_list, **self.definition["extra_filters"]).count()
|
|
|
|
@property
|
|
def usage(self):
|
|
"""Return current limit usage in %."""
|
|
if self.max_value < 0:
|
|
return -1
|
|
if self.max_value == 0:
|
|
return 0
|
|
return int(float(self.current_value) / self.max_value * 100)
|
|
|
|
@property
|
|
def label(self):
|
|
"""Return display name."""
|
|
return self.definition["label"]
|
|
|
|
def is_exceeded(self, count=1):
|
|
"""Check if limit will be reached if we add count object(s)."""
|
|
return self.current_value + 1 > self.max_value
|