OpenSlides/openslides/agenda/models.py

546 lines
18 KiB
Python
Raw Normal View History

from collections import defaultdict
2018-08-22 22:00:08 +02:00
from typing import Dict, List, Set
2013-03-18 12:34:47 +01:00
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models, transaction
from django.utils import timezone
2015-06-29 12:08:15 +02:00
from openslides.core.config import config
2018-12-23 11:05:38 +01:00
from openslides.core.models import Countdown
from openslides.utils.autoupdate import inform_changed_data
2013-03-18 12:34:47 +01:00
from openslides.utils.exceptions import OpenSlidesError
2015-06-29 12:08:15 +02:00
from openslides.utils.models import RESTModelMixin
from openslides.utils.utils import to_roman
2011-07-31 10:46:29 +02:00
from ..utils.models import CASCADE_AND_AUTOUODATE, SET_NULL_AND_AUTOUPDATE
from .access_permissions import ItemAccessPermissions, ListOfSpeakersAccessPermissions
2012-04-14 11:18:47 +02:00
class ItemManager(models.Manager):
"""
Customized model manager with special methods for agenda tree and
numbering.
"""
2019-01-06 16:22:33 +01:00
def get_full_queryset(self):
2016-09-30 20:42:58 +02:00
"""
Returns the normal queryset with all items. In the background all
related items (topics, motions, assignments) are prefetched from the database.
2016-09-30 20:42:58 +02:00
"""
# TODO: Fix the django bug: we cannot include "content_object__agenda_items" here,
# because this is some kind of cyclic lookup. The _prefetched_objects_cache of every
# content object will hold wrong values for the agenda item.
# See issue #4738
return self.get_queryset().prefetch_related("content_object")
def get_only_non_public_items(self):
"""
Generator, which yields only internal and hidden items, that means only items
which type is INTERNAL_ITEM or HIDDEN_ITEM or which are children of hidden items.
"""
# Do not execute non-hidden items because this would create a lot of db queries
root_items, item_children = self.get_root_and_children(only_item_type=None)
def yield_items(items, parent_is_not_public=False):
"""
Generator that yields a list of items and their children.
"""
for item in items:
2019-01-06 16:22:33 +01:00
if parent_is_not_public or item.type in (
item.INTERNAL_ITEM,
item.HIDDEN_ITEM,
):
item_is_not_public = True
2016-01-25 22:10:00 +01:00
yield item
else:
item_is_not_public = False
yield from yield_items(
2019-01-06 16:22:33 +01:00
item_children[item.pk], parent_is_not_public=item_is_not_public
)
2016-01-25 22:10:00 +01:00
yield from yield_items(root_items)
def get_root_and_children(self, only_item_type=None):
"""
Returns a list with all root items and a dictonary where the key is an
item pk and the value is a list with all children of the item.
If only_item_type is given, the tree hides items with other types and
all of their children.
"""
2019-01-06 16:22:33 +01:00
queryset = self.order_by("weight")
2018-08-22 22:00:08 +02:00
item_children: Dict[int, List[Item]] = defaultdict(list)
root_items = []
for item in queryset:
if only_item_type is not None and item.type != only_item_type:
continue
if item.parent_id is not None:
item_children[item.parent_id].append(item)
else:
root_items.append(item)
return root_items, item_children
def get_tree(self, only_item_type=None, include_content=False):
"""
Generator that yields dictonaries. Each dictonary has two keys, id
and children, where id is the id of one agenda item and children is a
generator that yields dictonaries like the one discribed.
If only_item_type is given, the tree hides items with other types and
all of their children.
If include_content is True, the yielded dictonaries have no key 'id'
but a key 'item' with the entire object.
"""
2019-01-06 16:22:33 +01:00
root_items, item_children = self.get_root_and_children(
only_item_type=only_item_type
)
def get_children(items):
"""
Generator that yields the descibed diconaries.
"""
for item in items:
if include_content:
yield dict(item=item, children=get_children(item_children[item.pk]))
else:
2019-01-06 16:22:33 +01:00
yield dict(
id=item.pk, children=get_children(item_children[item.pk])
)
yield from get_children(root_items)
@transaction.atomic
def set_tree(self, tree):
"""
Sets the agenda tree.
The tree has to be a nested object. For example:
[{"id": 1}, {"id": 2, "children": [{"id": 3}]}]
"""
2019-01-06 16:22:33 +01:00
def walk_items(tree, parent=None):
"""
Generator that returns each item in the tree as tuple.
This tuples have tree values. The item id, the item parent and the
weight of the item.
"""
for weight, element in enumerate(tree):
2019-01-06 16:22:33 +01:00
yield (element["id"], parent, weight)
yield from walk_items(element.get("children", []), element["id"])
2018-08-22 22:00:08 +02:00
touched_items: Set[int] = set()
db_items = dict((item.pk, item) for item in Item.objects.all())
for item_id, parent_id, weight in walk_items(tree):
# Check that the item is only once in the tree to prevent invalid trees
if item_id in touched_items:
2019-01-12 23:01:42 +01:00
raise ValueError(f"Item {item_id} is more then once in the tree.")
touched_items.add(item_id)
try:
db_item = db_items[item_id]
except KeyError:
2019-01-12 23:01:42 +01:00
raise ValueError(f"Item {item_id} is not in the database.")
# Check if the item has changed and update it
# Note: Do not use Item.objects.update, so that the items are sent
# to the clients via autoupdate
if db_item.parent_id != parent_id or db_item.weight != weight:
db_item.parent_id = parent_id
db_item.weight = weight
db_item.save()
@transaction.atomic
2019-01-06 16:22:33 +01:00
def number_all(self, numeral_system="arabic"):
"""
Auto numbering of the agenda according to the numeral_system. Manually
added item numbers will be overwritten.
"""
2019-01-06 16:22:33 +01:00
def walk_tree(tree, number=None):
for index, tree_element in enumerate(tree):
2016-01-25 22:10:00 +01:00
# Calculate number of visable agenda items.
2019-01-06 16:22:33 +01:00
if numeral_system == "roman" and number is None:
item_number = to_roman(index + 1)
else:
item_number = str(index + 1)
if number is not None:
2019-01-06 16:22:33 +01:00
item_number = ".".join((number, item_number))
2016-01-25 22:10:00 +01:00
# Add prefix.
2019-01-06 16:22:33 +01:00
if config["agenda_number_prefix"]:
2019-01-12 23:01:42 +01:00
item_number_tmp = f"{config['agenda_number_prefix']} {item_number}"
else:
item_number_tmp = item_number
2016-01-25 22:10:00 +01:00
# Save the new value and go down the tree.
2019-01-06 16:22:33 +01:00
tree_element["item"].item_number = item_number_tmp
tree_element["item"].save()
walk_tree(tree_element["children"], item_number)
2016-01-25 22:10:00 +01:00
# Start numbering visable agenda items.
walk_tree(self.get_tree(only_item_type=Item.AGENDA_ITEM, include_content=True))
2016-01-25 22:10:00 +01:00
# Reset number of hidden items.
for item in self.get_only_non_public_items():
2019-01-06 16:22:33 +01:00
item.item_number = ""
2016-01-25 22:10:00 +01:00
item.save()
2015-06-29 13:31:07 +02:00
class Item(RESTModelMixin, models.Model):
2011-07-31 10:46:29 +02:00
"""
An Agenda Item
2011-07-31 10:46:29 +02:00
"""
2019-01-06 16:22:33 +01:00
access_permissions = ItemAccessPermissions()
objects = ItemManager()
2019-01-06 16:22:33 +01:00
can_see_permission = "agenda.can_see"
2012-02-09 02:29:38 +01:00
AGENDA_ITEM = 1
INTERNAL_ITEM = 2
HIDDEN_ITEM = 3
2013-01-05 23:52:29 +01:00
ITEM_TYPE = (
2019-01-12 23:01:42 +01:00
(AGENDA_ITEM, "Agenda item"),
(INTERNAL_ITEM, "Internal item"),
(HIDDEN_ITEM, "Hidden item"),
2019-01-06 16:22:33 +01:00
)
2013-01-05 23:52:29 +01:00
item_number = models.CharField(blank=True, max_length=255)
2013-03-18 12:34:47 +01:00
"""
Number of agenda item.
2013-03-18 12:34:47 +01:00
"""
2013-03-18 12:34:47 +01:00
comment = models.TextField(null=True, blank=True)
2013-03-18 12:34:47 +01:00
"""
Optional comment to the agenda item. Will not be shown to normal users.
2013-03-18 12:34:47 +01:00
"""
2013-03-18 12:34:47 +01:00
closed = models.BooleanField(default=False)
2013-03-18 12:34:47 +01:00
"""
Flag, if the item is finished.
"""
2013-03-18 12:34:47 +01:00
2019-01-06 16:22:33 +01:00
type = models.IntegerField(choices=ITEM_TYPE, default=HIDDEN_ITEM)
2013-03-18 12:34:47 +01:00
"""
Type of the agenda item.
See Item.ITEM_TYPE for more information.
2013-03-18 12:34:47 +01:00
"""
duration = models.IntegerField(null=True, blank=True)
2013-03-18 12:34:47 +01:00
"""
The intended duration for the topic.
"""
2013-03-18 12:34:47 +01:00
parent = models.ForeignKey(
2019-01-06 16:22:33 +01:00
"self",
on_delete=SET_NULL_AND_AUTOUPDATE,
null=True,
blank=True,
2019-01-06 16:22:33 +01:00
related_name="children",
)
2013-06-03 19:02:27 +02:00
"""
The parent item in the agenda tree.
"""
weight = models.IntegerField(default=10000)
2013-06-03 19:02:27 +02:00
"""
Weight to sort the item in the agenda.
"""
content_type = models.ForeignKey(
2019-01-06 16:22:33 +01:00
ContentType, on_delete=models.SET_NULL, null=True, blank=True
)
"""
Field for generic relation to a related object. Type of the object.
2013-03-18 12:34:47 +01:00
"""
object_id = models.PositiveIntegerField(null=True, blank=True)
"""
Field for generic relation to a related object. Id of the object.
"""
content_object = GenericForeignKey()
"""
Field for generic relation to a related object. General field to the related object.
2013-03-18 12:34:47 +01:00
"""
class Meta:
2015-12-10 00:20:59 +01:00
default_permissions = ()
permissions = (
2019-01-06 16:22:33 +01:00
("can_see", "Can see agenda"),
("can_manage", "Can manage agenda"),
(
"can_see_internal_items",
"Can see internal items and time scheduling of agenda",
),
)
unique_together = ("content_type", "object_id")
@property
2019-02-15 12:17:08 +01:00
def title_information(self):
"""
2019-02-15 12:17:08 +01:00
Return get_agenda_title_information() from the content_object.
"""
try:
2019-02-15 12:17:08 +01:00
return self.content_object.get_agenda_title_information()
except AttributeError:
2019-01-06 16:22:33 +01:00
raise NotImplementedError(
2019-02-15 12:17:08 +01:00
"You have to provide a get_agenda_title_information "
2019-01-06 16:22:33 +01:00
"method on your related model."
)
def is_internal(self):
"""
Returns True if the type of this object itself is a internal item or any
of its ancestors has such a type.
Attention! This executes one query for each ancestor of the item.
"""
2019-01-06 16:22:33 +01:00
return self.type == self.INTERNAL_ITEM or (
self.parent is not None and self.parent.is_internal()
)
def is_hidden(self):
2011-07-31 10:46:29 +02:00
"""
Returns True if the type of this object itself is a hidden item or any
of its ancestors has such a type.
Attention! This executes one query for each ancestor of the item.
2011-07-31 10:46:29 +02:00
"""
2019-01-06 16:22:33 +01:00
return self.type == self.HIDDEN_ITEM or (
self.parent is not None and self.parent.is_hidden()
)
2011-07-31 10:46:29 +02:00
@property
def level(self):
"""
Returns the level in agenda (=tree of all items). Level 0 means this
item is a root item in the agenda. Level 1 indicates that the parent is
a root item, level 2 that the parent's parent is a root item and so on.
Attention! This executes one query for each ancestor of the item.
"""
if self.parent is None:
return 0
else:
return self.parent.level + 1
class ListOfSpeakersManager(models.Manager):
"""
"""
def get_full_queryset(self):
"""
Returns the normal queryset with all items. In the background all
speakers and related items (topics, motions, assignments) are
prefetched from the database.
"""
return self.get_queryset().prefetch_related("speakers", "content_object")
class ListOfSpeakers(RESTModelMixin, models.Model):
"""
"""
access_permissions = ListOfSpeakersAccessPermissions()
objects = ListOfSpeakersManager()
can_see_permission = "agenda.can_see_list_of_speakers"
content_type = models.ForeignKey(
ContentType, on_delete=models.SET_NULL, null=True, blank=True
)
"""
Field for generic relation to a related object. Type of the object.
"""
object_id = models.PositiveIntegerField(null=True, blank=True)
"""
Field for generic relation to a related object. Id of the object.
"""
content_object = GenericForeignKey()
"""
Field for generic relation to a related object. General field to the related object.
"""
closed = models.BooleanField(default=False)
"""
True, if the list of speakers is closed.
"""
class Meta:
default_permissions = ()
permissions = (
("can_see_list_of_speakers", "Can see list of speakers"),
("can_manage_list_of_speakers", "Can manage list of speakers"),
)
unique_together = ("content_type", "object_id")
@property
def title_information(self):
"""
Return get_list_of_speakers_title_information() from the content_object.
"""
try:
return self.content_object.get_list_of_speakers_title_information()
except AttributeError:
raise NotImplementedError(
"You have to provide a get_list_of_speakers_title_information "
"method on your related model."
)
def get_next_speaker(self):
"""
Returns the speaker object of the speaker who is next.
"""
try:
2019-01-06 16:22:33 +01:00
return self.speakers.filter(begin_time=None).order_by("weight")[0]
except IndexError:
# The list of speakers is empty.
return None
2011-07-31 10:46:29 +02:00
2013-03-18 12:34:47 +01:00
class SpeakerManager(models.Manager):
"""
Manager for Speaker model. Provides a customized add method.
"""
2019-01-06 16:22:33 +01:00
def add(self, user, list_of_speakers, skip_autoupdate=False):
"""
Customized manager method to prevent anonymous users to be on the
list of speakers and that someone is twice on one list (off coming
speakers). Cares also initial sorting of the coming speakers.
"""
if self.filter(
user=user, list_of_speakers=list_of_speakers, begin_time=None
).exists():
2019-01-12 23:01:42 +01:00
raise OpenSlidesError(f"{user} is already on the list of speakers.")
if isinstance(user, AnonymousUser):
2019-01-12 23:01:42 +01:00
raise OpenSlidesError("An anonymous user can not be on lists of speakers.")
if config["agenda_present_speakers_only"] and not user.is_present:
raise OpenSlidesError("Only present users can be on the lists of speakers.")
2019-01-06 16:22:33 +01:00
weight = (
self.filter(list_of_speakers=list_of_speakers).aggregate(
models.Max("weight")
)["weight__max"]
or 0
)
speaker = self.model(
list_of_speakers=list_of_speakers, user=user, weight=weight + 1
2019-01-06 16:22:33 +01:00
)
2017-03-21 11:06:05 +01:00
speaker.save(force_insert=True, skip_autoupdate=skip_autoupdate)
return speaker
2013-03-18 12:34:47 +01:00
class Speaker(RESTModelMixin, models.Model):
2013-03-18 12:34:47 +01:00
"""
Model for the Speaker list.
"""
objects = SpeakerManager()
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE_AND_AUTOUODATE)
2013-03-18 12:34:47 +01:00
"""
ForeinKey to the user who speaks.
2013-03-18 12:34:47 +01:00
"""
list_of_speakers = models.ForeignKey(
ListOfSpeakers, on_delete=models.CASCADE, related_name="speakers"
)
2013-03-18 12:34:47 +01:00
"""
ForeinKey to the list of speakers to which the user want to speak.
2013-03-18 12:34:47 +01:00
"""
begin_time = models.DateTimeField(null=True)
"""
Saves the time, when the speaker begins to speak. None, if he has not spoken yet.
"""
end_time = models.DateTimeField(null=True)
2013-03-18 12:34:47 +01:00
"""
Saves the time, when the speaker ends his speech. None, if he is not finished yet.
2013-03-18 12:34:47 +01:00
"""
2013-03-18 12:34:47 +01:00
weight = models.IntegerField(null=True)
2013-03-18 12:34:47 +01:00
"""
The sort order of the list of speakers. None, if he has already spoken.
"""
2013-03-18 12:34:47 +01:00
2018-02-06 14:52:47 +01:00
marked = models.BooleanField(default=False)
"""
Marks a speaker.
"""
2013-03-18 12:34:47 +01:00
class Meta:
2015-12-10 00:20:59 +01:00
default_permissions = ()
2019-01-06 16:22:33 +01:00
permissions = (("can_be_speaker", "Can put oneself on the list of speakers"),)
2013-03-18 12:34:47 +01:00
def __str__(self):
return str(self.user)
2013-03-18 12:34:47 +01:00
def begin_speech(self):
2013-03-18 12:34:47 +01:00
"""
Let the user speak.
2013-03-18 12:34:47 +01:00
Set the weight to None and the time to now. If anyone is still
speaking, end his speech.
2013-03-18 12:34:47 +01:00
"""
try:
2019-01-06 16:22:33 +01:00
current_speaker = (
Speaker.objects.filter(
list_of_speakers=self.list_of_speakers, end_time=None
)
2019-01-06 16:22:33 +01:00
.exclude(begin_time=None)
.get()
)
except Speaker.DoesNotExist:
pass
else:
# Do not send an autoupdate for the countdown and the list_of_speakers. This is done
# by saving the list_of_speakers and countdown later.
current_speaker.end_speech(skip_autoupdate=True)
2013-03-18 12:34:47 +01:00
self.weight = None
self.begin_time = timezone.now()
self.save() # Here, the list_of_speakers is saved and causes an autoupdate.
2019-01-06 16:22:33 +01:00
if config["agenda_couple_countdown_and_speakers"]:
countdown, created = Countdown.objects.get_or_create(
pk=1,
defaults={
"default_time": config["projector_default_countdown"],
"title": "Default countdown",
2019-01-06 16:22:33 +01:00
"countdown_time": config["projector_default_countdown"],
},
)
if not created:
2019-01-06 16:22:33 +01:00
countdown.control(action="reset", skip_autoupdate=True)
countdown.control(action="start", skip_autoupdate=True)
2019-01-06 16:22:33 +01:00
inform_changed_data(
countdown
) # Here, the autoupdate for the countdown is triggered.
def end_speech(self, skip_autoupdate=False):
"""
The speech is finished. Set the time to now.
"""
self.end_time = timezone.now()
self.save(skip_autoupdate=skip_autoupdate)
2019-01-06 16:22:33 +01:00
if config["agenda_couple_countdown_and_speakers"]:
try:
countdown = Countdown.objects.get(pk=1)
except Countdown.DoesNotExist:
pass # Do not create a new countdown on stop action
else:
2019-01-06 16:22:33 +01:00
countdown.control(action="reset", skip_autoupdate=skip_autoupdate)
def get_root_rest_element(self):
"""
Returns the list_of_speakers to this instance which is the root REST element.
"""
return self.list_of_speakers