Remove ChatMessage

This commit is contained in:
FinnStutzenstein 2019-03-26 15:42:43 +01:00
parent b3c2b5f899
commit 665426e954
10 changed files with 24 additions and 171 deletions

View File

@ -23,14 +23,6 @@ class TagAccessPermissions(BaseAccessPermissions):
""" """
class ChatMessageAccessPermissions(BaseAccessPermissions):
"""
Access permissions container for ChatMessage and ChatMessageViewSet.
"""
base_permission = "core.can_use_chat"
class ProjectorMessageAccessPermissions(BaseAccessPermissions): class ProjectorMessageAccessPermissions(BaseAccessPermissions):
""" """
Access permissions for ProjectorMessage. Access permissions for ProjectorMessage.

View File

@ -2,7 +2,7 @@ import os
import sys import sys
from collections import OrderedDict from collections import OrderedDict
from operator import attrgetter from operator import attrgetter
from typing import Any, Dict, List, Set from typing import Any, Dict, List
from django.apps import AppConfig from django.apps import AppConfig
from django.conf import settings from django.conf import settings
@ -28,7 +28,6 @@ class CoreAppConfig(AppConfig):
post_permission_creation, post_permission_creation,
) )
from .views import ( from .views import (
ChatMessageViewSet,
ConfigViewSet, ConfigViewSet,
CountdownViewSet, CountdownViewSet,
HistoryViewSet, HistoryViewSet,
@ -45,7 +44,6 @@ class CoreAppConfig(AppConfig):
ListenToProjectors, ListenToProjectors,
PingPong, PingPong,
) )
from ..utils.access_permissions import required_user
from ..utils.rest_api import router from ..utils.rest_api import router
from ..utils.websocket import register_client_message from ..utils.websocket import register_client_message
@ -81,9 +79,6 @@ class CoreAppConfig(AppConfig):
self.get_model("Projectiondefault").get_collection_string(), self.get_model("Projectiondefault").get_collection_string(),
ProjectionDefaultViewSet, ProjectionDefaultViewSet,
) )
router.register(
self.get_model("ChatMessage").get_collection_string(), ChatMessageViewSet
)
router.register(self.get_model("Tag").get_collection_string(), TagViewSet) router.register(self.get_model("Tag").get_collection_string(), TagViewSet)
router.register( router.register(
self.get_model("ConfigStore").get_collection_string(), self.get_model("ConfigStore").get_collection_string(),
@ -112,11 +107,6 @@ class CoreAppConfig(AppConfig):
register_client_message(ListenToProjectors()) register_client_message(ListenToProjectors())
register_client_message(PingPong()) register_client_message(PingPong())
# register required_users
required_user.add_collection_string(
self.get_model("ChatMessage").get_collection_string(), required_users
)
def get_config_variables(self): def get_config_variables(self):
from .config_variables import get_config_variables from .config_variables import get_config_variables
@ -130,7 +120,6 @@ class CoreAppConfig(AppConfig):
for model_name in ( for model_name in (
"Projector", "Projector",
"ProjectionDefault", "ProjectionDefault",
"ChatMessage",
"Tag", "Tag",
"ProjectorMessage", "ProjectorMessage",
"Countdown", "Countdown",
@ -205,13 +194,6 @@ def call_save_default_values(**kwargs):
config.save_default_values() config.save_default_values()
def required_users(element: Dict[str, Any]) -> Set[int]:
"""
Returns all user ids that are displayed as chatters.
"""
return set((element["user_id"],))
def startup(): def startup():
""" """
Runs commands that are needed at startup. Runs commands that are needed at startup.

View File

@ -0,0 +1,21 @@
# Generated by Django 2.1.7 on 2019-03-29 06:45
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.db import migrations
def remove_chatmessage_permissions(apps, schema_editor):
content_type = ContentType.objects.filter(model="chatmessage", app_label="core")
Permission.objects.filter(content_type__in=content_type).delete()
class Migration(migrations.Migration):
dependencies = [("core", "0021_auto_20190415_0942")]
operations = [
migrations.RunPython(remove_chatmessage_permissions),
migrations.RemoveField(model_name="chatmessage", name="user"),
migrations.DeleteModel(name="ChatMessage"),
]

View File

@ -6,13 +6,8 @@ from jsonfield import JSONField
from ..utils.autoupdate import Element from ..utils.autoupdate import Element
from ..utils.cache import element_cache, get_element_id from ..utils.cache import element_cache, get_element_id
from ..utils.models import ( from ..utils.models import SET_NULL_AND_AUTOUPDATE, RESTModelMixin
CASCADE_AND_AUTOUODATE,
SET_NULL_AND_AUTOUPDATE,
RESTModelMixin,
)
from .access_permissions import ( from .access_permissions import (
ChatMessageAccessPermissions,
ConfigAccessPermissions, ConfigAccessPermissions,
CountdownAccessPermissions, CountdownAccessPermissions,
HistoryAccessPermissions, HistoryAccessPermissions,
@ -185,33 +180,6 @@ class ConfigStore(RESTModelMixin, models.Model):
return "core/config" return "core/config"
class ChatMessage(RESTModelMixin, models.Model):
"""
Model for chat messages.
At the moment we only have one global chat room for managers.
"""
access_permissions = ChatMessageAccessPermissions()
can_see_permission = "core.can_use_chat"
message = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE_AND_AUTOUODATE)
class Meta:
default_permissions = ()
permissions = (
("can_use_chat", "Can use the chat"),
("can_manage_chat", "Can manage the chat"),
)
def __str__(self):
return f"Message {self.timestamp}"
class ProjectorMessage(RESTModelMixin, models.Model): class ProjectorMessage(RESTModelMixin, models.Model):
""" """
Model for ProjectorMessages. Model for ProjectorMessages.

View File

@ -10,7 +10,6 @@ from ..utils.rest_api import (
) )
from ..utils.validate import validate_html from ..utils.validate import validate_html
from .models import ( from .models import (
ChatMessage,
ConfigStore, ConfigStore,
Countdown, Countdown,
History, History,
@ -141,17 +140,6 @@ class ConfigSerializer(ModelSerializer):
fields = ("id", "key", "value") fields = ("id", "key", "value")
class ChatMessageSerializer(ModelSerializer):
"""
Serializer for core.models.ChatMessage objects.
"""
class Meta:
model = ChatMessage
fields = ("id", "message", "timestamp", "user")
read_only_fields = ("user",)
class ProjectorMessageSerializer(ModelSerializer): class ProjectorMessageSerializer(ModelSerializer):
""" """
Serializer for core.models.ProjectorMessage objects. Serializer for core.models.ProjectorMessage objects.

View File

@ -42,8 +42,6 @@ def get_permission_change_data(sender, permissions, **kwargs):
elif permission.codename == "can_manage_projector": elif permission.codename == "can_manage_projector":
yield core_app.get_model("ProjectorMessage") yield core_app.get_model("ProjectorMessage")
yield core_app.get_model("Countdown") yield core_app.get_model("Countdown")
elif permission.codename == "can_use_chat":
yield core_app.get_model("ChatMessage")
def autoupdate_for_many_to_many_relations(sender, instance, **kwargs): def autoupdate_for_many_to_many_relations(sender, instance, **kwargs):

View File

@ -35,7 +35,6 @@ from ..utils.rest_api import (
list_route, list_route,
) )
from .access_permissions import ( from .access_permissions import (
ChatMessageAccessPermissions,
ConfigAccessPermissions, ConfigAccessPermissions,
CountdownAccessPermissions, CountdownAccessPermissions,
HistoryAccessPermissions, HistoryAccessPermissions,
@ -47,7 +46,6 @@ from .access_permissions import (
from .config import config from .config import config
from .exceptions import ConfigError, ConfigNotFound from .exceptions import ConfigError, ConfigNotFound
from .models import ( from .models import (
ChatMessage,
ConfigStore, ConfigStore,
Countdown, Countdown,
History, History,
@ -396,64 +394,6 @@ class ConfigViewSet(ModelViewSet):
return Response({"key": key, "value": value}) return Response({"key": key, "value": value})
class ChatMessageViewSet(ModelViewSet):
"""
API endpoint for chat messages.
There are the following views: metadata, list, retrieve and create.
The views partial_update, update and destroy are disabled.
"""
access_permissions = ChatMessageAccessPermissions()
queryset = ChatMessage.objects.all()
def check_view_permissions(self):
"""
Returns True if the user has required permissions.
"""
if self.action in ("list", "retrieve"):
result = self.get_access_permissions().check_permissions(self.request.user)
elif self.action in ("metadata", "create"):
# We do not want anonymous users to use the chat even the anonymous
# group has the permission core.can_use_chat.
result = self.request.user.is_authenticated and has_perm(
self.request.user, "core.can_use_chat"
)
elif self.action == "clear":
result = has_perm(self.request.user, "core.can_use_chat") and has_perm(
self.request.user, "core.can_manage_chat"
)
else:
result = False
return result
def perform_create(self, serializer):
"""
Customized method to inject the request.user into serializer's save
method so that the request.user can be saved into the model field.
"""
serializer.save(user=self.request.user)
# Send chatter via autoupdate because users without permission
# to see users may not have it but can get it now.
inform_changed_data([self.request.user])
@list_route(methods=["post"])
def clear(self, request):
"""
Deletes all chat messages.
"""
# Collect all chat messages with their collection_string and id
chatmessages = ChatMessage.objects.all()
args = []
for chatmessage in chatmessages:
args.append((chatmessage.get_collection_string(), chatmessage.pk))
chatmessages.delete()
# Trigger autoupdate and setup response.
if args:
inform_deleted_data(args)
return Response({"detail": "All chat messages deleted successfully."})
class ProjectorMessageViewSet(ModelViewSet): class ProjectorMessageViewSet(ModelViewSet):
""" """
API endpoint for messages. API endpoint for messages.

View File

@ -46,11 +46,9 @@ def create_builtin_groups_and_admin(**kwargs):
"core.can_manage_logos_and_fonts", "core.can_manage_logos_and_fonts",
"core.can_manage_projector", "core.can_manage_projector",
"core.can_manage_tags", "core.can_manage_tags",
"core.can_manage_chat",
"core.can_see_frontpage", "core.can_see_frontpage",
"core.can_see_history", "core.can_see_history",
"core.can_see_projector", "core.can_see_projector",
"core.can_use_chat",
"mediafiles.can_manage", "mediafiles.can_manage",
"mediafiles.can_see", "mediafiles.can_see",
"mediafiles.can_see_hidden", "mediafiles.can_see_hidden",
@ -141,7 +139,6 @@ def create_builtin_groups_and_admin(**kwargs):
permission_dict["core.can_see_projector"], permission_dict["core.can_see_projector"],
permission_dict["core.can_manage_projector"], permission_dict["core.can_manage_projector"],
permission_dict["core.can_manage_tags"], permission_dict["core.can_manage_tags"],
permission_dict["core.can_use_chat"],
permission_dict["mediafiles.can_see"], permission_dict["mediafiles.can_see"],
permission_dict["mediafiles.can_manage"], permission_dict["mediafiles.can_manage"],
permission_dict["mediafiles.can_upload"], permission_dict["mediafiles.can_upload"],

View File

@ -4,7 +4,7 @@ from rest_framework import status
from rest_framework.test import APIClient from rest_framework.test import APIClient
from openslides.core.config import config from openslides.core.config import config
from openslides.core.models import ChatMessage, Projector, Tag from openslides.core.models import Projector, Tag
from openslides.users.models import User from openslides.users.models import User
from openslides.utils.autoupdate import inform_changed_data from openslides.utils.autoupdate import inform_changed_data
from openslides.utils.test import TestCase from openslides.utils.test import TestCase
@ -26,19 +26,6 @@ def test_projector_db_queries():
assert count_queries(Projector.get_elements) == 2 assert count_queries(Projector.get_elements) == 2
@pytest.mark.django_db(transaction=False)
def test_chat_message_db_queries():
"""
Tests that only the following db queries are done:
* 1 requests to get the list of all chatmessages.
"""
user = User.objects.get(username="admin")
for index in range(10):
ChatMessage.objects.create(user=user)
assert count_queries(ChatMessage.get_elements) == 1
@pytest.mark.django_db(transaction=False) @pytest.mark.django_db(transaction=False)
def test_tag_db_queries(): def test_tag_db_queries():
""" """
@ -200,21 +187,3 @@ class Projection(TestCase):
self.assertEqual(self.projector.elements, []) self.assertEqual(self.projector.elements, [])
self.assertEqual(self.projector.elements_preview, elements) self.assertEqual(self.projector.elements_preview, elements)
self.assertEqual(self.projector.elements_history, []) self.assertEqual(self.projector.elements_history, [])
class ChatMessageViewSet(TestCase):
"""
Tests requests to deal with chat messages.
"""
def setUp(self):
admin = User.objects.get(username="admin")
self.client.force_login(admin)
ChatMessage.objects.create(
message="test_message_peechiel8IeZoohaem9e", user=admin
)
def test_clear_chat(self):
response = self.client.post(reverse("chatmessage-clear"))
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(ChatMessage.objects.all().count(), 0)

View File

@ -514,10 +514,8 @@ class GroupUpdate(TestCase):
"core.can_manage_config", "core.can_manage_config",
"core.can_manage_projector", "core.can_manage_projector",
"core.can_manage_tags", "core.can_manage_tags",
"core.can_manage_chat",
"core.can_see_frontpage", "core.can_see_frontpage",
"core.can_see_projector", "core.can_see_projector",
"core.can_use_chat",
"mediafiles.can_manage", "mediafiles.can_manage",
"mediafiles.can_see", "mediafiles.can_see",
"mediafiles.can_see_hidden", "mediafiles.can_see_hidden",