Quiz

Форк
0
/
views.py 
62 строки · 3.4 Кб
1
from django.shortcuts import render
2
from django.core import serializers
3
from django.http import JsonResponse
4
from chat.models import GameMessage, FriendMessage, LobbyMessage
5
from django.db.models import Q
6
from authapp.models import AuthUser
7
from channels.layers import get_channel_layer
8
from asgiref.sync import async_to_sync
9
import json
10
from games.models import Lobby, Game
11

12

13
def load_messages(request):
14
    type_ = request.GET.get('type')
15
    if type_ == 'friend':
16
        friend_pk = int(request.GET.get('friend_pk'))
17
        friend = AuthUser.objects.get(pk=friend_pk)
18
        messages = FriendMessage.objects.filter(Q(sender__in=[request.user, friend])
19
                                                & Q(receiver__in=[request.user, friend])).order_by('-created_at')
20
        return JsonResponse({'messages': list(messages.values()), 'friend_nickname': friend.nickname, 'user_nickname': request.user.nickname}, safe=False)
21
    elif type_ == 'lobby':
22
        lobby = request.user.current_lobby
23
        messages = LobbyMessage.objects.filter(lobby=lobby).order_by('-created_at')
24
        players = lobby.players.all()
25
        return JsonResponse({'messages': list(messages.values()), 'players': {player.pk: player.nickname for player in players}}, safe=False)
26
    elif type_ == 'game':
27
        game = request.user.current_game
28
        messages = GameMessage.objects.filter(game=game).order_by('-created_at')
29
        players = AuthUser.objects.filter(pk__in=game.players)
30
        return JsonResponse(
31
            {'messages': list(messages.values()), 'players': {player.pk: player.nickname for player in players}},
32
            safe=False)
33

34

35
def create_messages(request):
36
    type_ = request.GET.get('type')
37
    if type_ == 'friend':
38
        button_message = request.GET.get('message')
39
        receiver_pk = int(request.GET.get('receiver'))
40
        sender_pk = int(request.GET.get('sender'))
41
        msg = FriendMessage.objects.create(text=button_message, receiver_id=receiver_pk, sender_id=sender_pk)
42
        data = {'action': 'chat_message', 'message': serializers.serialize('json', [msg]), 'sender': request.user.nickname, 'type': 'friend'}
43
        layer = get_channel_layer()
44
        for pk in [sender_pk, receiver_pk]:
45
            async_to_sync(layer.group_send)(f'user_{pk}', {'type': 'send_message', 'message': data})
46
    elif type_ == 'lobby':
47
        button_message = request.GET.get('message')
48
        lobby = request.user.current_lobby
49
        msg = LobbyMessage.objects.create(text=button_message, lobby_id=lobby.pk, sender_id=request.user.pk)
50
        data = {'action': 'chat_message', 'message': serializers.serialize('json', [msg]), 'sender': request.user.nickname, 'type': 'lobby'}
51
        layer = get_channel_layer()
52
        for player in lobby.players.all():
53
            async_to_sync(layer.group_send)(f'user_{player.pk}', {'type': 'send_message', 'message': data})
54
    elif type_ == 'game':
55
        button_message = request.GET.get('message')
56
        game = request.user.current_game.pk
57
        msg = GameMessage.objects.create(text=button_message, game_id=game, sender_id=request.user.pk)
58
        data = {'action': 'chat_message', 'message': serializers.serialize('json', [msg]), 'sender': request.user.nickname}
59
        layer = get_channel_layer()
60
        async_to_sync(layer.group_send)(f'game_{request.user.current_game.pk}', {'type': 'send_message', 'message': data})
61
        
62
    return JsonResponse({'ok': 'ok'})
63

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.