2020-11-26 16:08:26 +00:00
|
|
|
"""Channels Messages storage"""
|
|
|
|
from asgiref.sync import async_to_sync
|
|
|
|
from channels.layers import get_channel_layer
|
2020-11-26 16:57:46 +00:00
|
|
|
from django.contrib.messages.storage.base import Message
|
2020-11-26 17:36:26 +00:00
|
|
|
from django.contrib.messages.storage.fallback import FallbackStorage
|
2020-11-26 16:08:26 +00:00
|
|
|
from django.core.cache import cache
|
|
|
|
from django.http.request import HttpRequest
|
|
|
|
|
|
|
|
|
2020-11-26 17:36:26 +00:00
|
|
|
class ChannelsStorage(FallbackStorage):
|
2020-11-26 16:08:26 +00:00
|
|
|
"""Send contrib.messages over websocket"""
|
|
|
|
|
|
|
|
def __init__(self, request: HttpRequest) -> None:
|
|
|
|
# pyright: reportGeneralTypeIssues=false
|
|
|
|
super().__init__(request)
|
|
|
|
self.channel = get_channel_layer()
|
|
|
|
|
|
|
|
def _store(self, messages: list[Message], response, *args, **kwargs):
|
2020-11-26 16:57:46 +00:00
|
|
|
prefix = f"user_{self.request.user.pk}_messages_"
|
2020-11-26 16:08:26 +00:00
|
|
|
keys = cache.keys(f"{prefix}*")
|
|
|
|
for key in keys:
|
|
|
|
uid = key.replace(prefix, "")
|
|
|
|
for message in messages:
|
|
|
|
async_to_sync(self.channel.send)(
|
|
|
|
uid,
|
|
|
|
{
|
|
|
|
"type": "event.update",
|
2020-12-01 16:27:19 +00:00
|
|
|
"level_tag": message.level_tag,
|
2020-11-26 16:08:26 +00:00
|
|
|
"tags": message.tags,
|
|
|
|
"message": message.message,
|
|
|
|
},
|
|
|
|
)
|
2020-11-26 16:57:46 +00:00
|
|
|
return super()._store(messages, response, *args, **kwargs)
|