Quiz

Форк
0
/
user_websocket.js 
233 строки · 10.8 Кб
1
window.addEventListener('load', () => {
2

3
    // запуск сокета
4
    userSocket = new WebSocket (
5
        'ws://' + window.location.host + '/ws/user/' + user_id
6
    );
7

8
    // метод при открытии сокета (пусто)
9
    userSocket.onopen = (e) => {
10
        console.log('open')
11
        console.log(e)
12
    }
13

14
    // метод при получении сообщения
15
    userSocket.onmessage = (e) => {
16
        // получение объекта сообщения и действия из него
17
        const data = JSON.parse(e.data)['message'];
18
        let action = data['action'];
19
        if(action == 'invitation') {
20
            sender = data['sender'];
21
            $('.lobby_invitation_nickname').html(`Принять приглашение от ${sender['nickname']}`);
22
            $('.lobby_invitation_block').css('display', 'flex');
23
        } else if(action == 'queue') {
24
            // необходимые изменения интерфейса
25
            $('.lobby_start_game_span').html('Отменить поиск');
26
            $('.lobby_start_game_span').addClass('lobby_cancel_queue_button');
27
            $('.lobby_start_game_span').removeClass('lobby_start_game_span');
28

29
            start_count();
30
            create_queue_socket(data['queue_id']);
31
        } else if(action == 'cancel_queue') {
32
            cancel_queue(false);
33
        } else if(action == 'player_quit') {
34
            current_players -= 1;
35
            $(`#user_${data['quitter_pk']}`).remove();
36
            $(`#invite_friend_${data['quitter_pk']}`).addClass('header_friend_invite');
37
            $(`#invite_friend_${data['quitter_pk']}`).removeClass('header_friend_invited');
38
            $('.header_friend_invite').css('display', '');
39
            let blank_string = '<div class="lobby_player_blank"></div>';
40
            if(current_players % 2 == 1) {
41
                $('.lobby_the_player').before(blank_string);
42
            } else {
43
                $('.lobby_the_player').after(blank_string);
44
            }
45
            if(data['lobby_leader'] && data['new_leader_pk'] == user_id) {
46
                $('.lobby_start_game_span').addClass('lobby_start_game_button');
47
                $('.lobby_start_game_span').removeClass('lobby_start_game_span');
48
                $('.lobby_change_mode').css('display', '');
49
                $('.lobby_change_mode').val(data['current_mode']).change();
50
            };
51
            if(data['u_r_alone']) {
52
                $('#mode_ranked').css('display', '');
53
            };
54
        } else if(action == 'player_join') {
55
            current_players += 1;
56
            $(`#invite_friend_${data['quitter_pk']}`).removeClass('header_friend_invite');
57
            $(`#invite_friend_${data['quitter_pk']}`).addClass('header_friend_invited');
58
            let player_string = `<div id='user_${data["joiner_pk"]}' class="lobby_player_block">${data['joiner_nickname']}</div>`;
59
            if(current_players % 2 == 1) {
60
                $('.lobby_players_block>div:first-child').remove();
61
                $('.lobby_the_player').before(player_string);
62
            } else {
63
                $('.lobby_players_block>div:last-child').remove();
64
                $('.lobby_the_player').after(player_string);
65
            }
66
            $('#mode_ranked').css('display', 'none');
67
            if(data['last_place']) {
68
                $('.header_friend_invite').css('display', 'none');
69
            };
70
        } else if(action == 'add_theme') {
71
            let html_string = '<span>Выберите тему для игры:</span><select class="lobby_theme">';
72
            for (let theme of data['themes']) {
73
                html_string += `<option value='${theme[0]}'>${theme[0]}</option>`
74
            };
75
            html_string += '</select>';
76
            $('.lobby_mode').append(html_string);
77
        } else if(action == 'delete_theme') {
78
            $('.lobby_theme').remove();
79
        } else if(action == 'chat_message') {
80
            let message = JSON.parse(data['message'])[0];
81
            let message_sender = data['sender'];
82
            let text = message.fields.text;
83
            let date = message.fields.created_at.slice(0, 10);
84
            let time = message.fields.created_at.slice(11, 16);
85
            if (data['type'] == 'friend') {
86
                if($('.friend_chat_messages > .chat_date').length == 0 || $('.friend_chat_messages > .chat_date')[0].outerText != date) {
87
                    $('.friend_chat_messages').prepend(`<span class='chat_date'>${date}</span>`)
88
                }
89
                if (message.fields.sender == parseInt(user_id)) {
90
                    $('.friend_chat_messages').prepend(`<div class='chat_sent'><span class='chat_message_sender'>${message_sender}</span>
91
                    <span class='chat_message_text'>${text}<span class='chat_message_time'>${time}</span></span></div>`);
92
                } else {
93
                    if($('.friend_chat_block').css('display') == 'none' || $('.friend_chat_name').html != data['sender']) {
94
                        $(`#chat_friend_${message.fields.sender}`).click();
95
                    } else {
96
                        $('.friend_chat_messages').prepend(`<div class='chat_received'><span class='chat_message_sender'>${message_sender}</span>
97
                        <span class='chat_message_text'>${text}<span class='chat_message_time'>${time}</span></span></div>`);
98
                    }
99
                }
100
            } else if (data['type'] == 'lobby'){
101
                if($('.lobby_chat_messages > .chat_date').length == 0 || $('.lobby_chat_messages > .chat_date')[0].outerText != date) {
102
                    $('.lobby_chat_messages').prepend(`<span class='chat_date'>${date}</span>`)
103
                }
104
                if (message.fields.sender == parseInt(user_id)) {
105
                    $('.lobby_chat_messages').prepend(`<div class='chat_sent'><span class='chat_message_sender'>${message_sender}</span>
106
                    <span class='chat_message_text'>${text}<span class='chat_message_time'>${time}</span></span></div>`);
107
                } else {
108
                    $('.lobby_chat_messages').prepend(`<div class='chat_received'><span class='chat_message_sender'>${message_sender}</span>
109
                    <span class='chat_message_text'>${text}<span class='chat_message_time'>${time}</span></span></div>`);
110
                }
111
            }
112
        }
113
    };
114

115
    // метод при закрытии сокета (пусто)
116
    userSocket.onclose = (e) => {
117
        console.log('close')
118
        console.log(e);
119
    }
120

121
    // метод при ошибке у сокета (пусто)
122
    userSocket.onerror = (e) => {
123
        console.log('error')
124
        console.log(e)
125
    }
126

127
    $(document).on('click', '.header_friends_button', (event) => {
128
        if ($('.header_friends_block').css('display') == 'none') {
129
            $('.header_friends_block').css('display', 'flex');
130
        } else if (event.target.classList[0] == 'header_friends_button') {
131
            $('.header_friends_block').css('display', '');
132
        }
133
    })
134

135
    $(document).on('click', '.lobby_invitation_accept', () => {
136
        $.ajax({
137
            method: "get",
138
            url: "/games/join_lobby_ajax/",
139
            data: {sender_id: sender['pk']},
140
            success: (data) => {
141
                userSocket.send(
142
                    JSON.stringify({'message': {'action': 'accept'}})
143
                );
144
                if(data != 'full') {
145
                    window.location.href = data['url'];
146
                } else {
147
                    sender = undefined;
148
                    $('.lobby_invitation_nickname').html('');
149
                    $('.lobby_invitation_block').css('display', 'none');
150
                };
151
            },
152
            error: (data) => {
153
            }
154
        });
155
    });
156

157
    $(document).on('click', '.lobby_invitation_reject', () => {
158
        sender = undefined;
159
        $('.lobby_invitation_nickname').html('');
160
        $('.lobby_invitation_block').css('display', '');
161
        userSocket.send(
162
            JSON.stringify({'message': {'action': 'reject'}})
163
        );
164
    });
165

166
    $('.friend_chat_close').on('click', () => {
167
        $('.friend_chat_block').css('display', '');
168
    });
169

170
    $('.header_friend_chat').on('click', (event) => {
171
        $('.friend_chat_block').css('display', 'flex');
172
        let friend_pk = parseInt(event.target.id.replace('chat_friend_', ''));
173
        $.ajax({
174
            method: "get",
175
            url: "/chat/load_messages/",
176
            data: {friend_pk: friend_pk, type: 'friend'},
177
            success: (data) => {
178
                let messages = data['messages'];
179
                if (messages.length > 0) {
180
                    let date = messages[0].created_at.slice(0, 10);
181
                    let html_string = '';
182
                    for (let message of messages) {
183
                        let message_date = message.created_at.slice(0, 10);
184
                        if(date != message_date) {
185
                            html_string += `<span class='chat_date'>${date}</span>`;
186
                            date = message_date;
187
                        }
188
                        let time = message.created_at.slice(11, 16);
189
                        if (message.sender_id == parseInt(user_id)) {
190
                            let message_sender = data['user_nickname'];
191
                            html_string += `<div class='chat_sent'><span class='chat_message_sender'>${message_sender}</span>
192
                            <span class='chat_message_text'>${message.text}<span class='chat_message_time'>${time}</span></span></div>`;
193
                        }else{
194
                            let message_sender = data['friend_nickname'];
195
                            html_string += `<div class='chat_received'><span class='chat_message_sender'>${message_sender}</span>
196
                            <span class='chat_message_text'>${message.text}<span class='chat_message_time'>${time}</span></span></div>`;
197
                        }
198
                    };
199
                    html_string += `<span class='chat_date'>${date}</span>`;
200
                    $('.friend_chat_messages').html(html_string);
201
                };
202
                $('.friend_chat_name').html(data['friend_nickname']);
203
                $('.friend_chat_textarea').attr('id', `textarea_${friend_pk}`);
204
            },
205
            error: (data) => {
206
            }
207
        })
208
    });
209

210

211
    $('.friend_chat_textarea').on('keydown', (event) => {
212

213
        if (event.keyCode == 13) {
214
            event.preventDefault();
215
            let reciever_pk = parseInt(event.target.id.replace('textarea_', ''));
216
            let chat_message = event.target.value;
217
            event.target.value = '';
218
            $.ajax({
219
                method: "get",
220
                url: "/chat/create_messages/",
221
                data: {sender: user_id, receiver: reciever_pk, message: chat_message, type: 'friend'},
222
                success: (data) => {
223

224
                },
225
                error: (data) => {
226
                }
227
            })
228
        }
229
    })
230

231

232

233
});

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

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

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

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