Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ModelHandler.java « protocol « humla « lublin « se « java « main « src - gitlab.com/quite/humla.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f8d18bc7bad677df324f8aeece3efa76608136ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
/*
 * Copyright (C) 2014 Andrew Comminos
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package se.lublin.humla.protocol;

import android.content.Context;
import android.util.Log;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import se.lublin.humla.R;
import se.lublin.humla.model.Channel;
import se.lublin.humla.model.IServerSettings;
import se.lublin.humla.model.Message;
import se.lublin.humla.model.ServerSettings;
import se.lublin.humla.model.User;
import se.lublin.humla.protobuf.Mumble;
import se.lublin.humla.util.HumlaLogger;
import se.lublin.humla.util.IHumlaObserver;
import se.lublin.humla.util.MessageFormatter;

/**
 * Handles network messages related to the user-channel tree model.
 * This includes channels, users, messages, and permissions.
 * Created by andrew on 18/07/13.
 */
public class ModelHandler extends HumlaTCPMessageListener.Stub {
    private static final String TAG = ModelHandler.class.getName();

    private final Context mContext;
    private final Map<Integer, Channel> mChannels;
    private final Map<Integer, User> mUsers;
    private final List<Integer> mLocalMuteHistory;
    private final List<Integer> mLocalIgnoreHistory;
    private final IHumlaObserver mObserver;
    private final HumlaLogger mLogger;
    private ServerSettings mServerSettings;
    private int mPermissions;
    private int mSession;

    public ModelHandler(Context context, IHumlaObserver observer, HumlaLogger logger,
                        @Nullable List<Integer> localMuteHistory,
                        @Nullable List<Integer> localIgnoreHistory) {
        mContext = context;
        mChannels = new HashMap<Integer, Channel>();
        mUsers = new HashMap<Integer, User>();
        mLocalMuteHistory = localMuteHistory;
        mLocalIgnoreHistory = localIgnoreHistory;
        mObserver = observer;
        mLogger = logger;
    }

    public Channel getChannel(int id) {
        return mChannels.get(id);
    }

    public User getUser(int session) {
        return mUsers.get(session);
    }

    public ServerSettings getServerSettings() {
        return mServerSettings;
    }

    /**
     * Creates a stub channel with the given ID.
     * Useful for keeping user references when we get a UserState message before a ChannelState.
     * @param id The channel ID.
     * @return The newly created stub channel.
     */
    private Channel createStubChannel(int id) {
        Channel channel = new Channel(id, false);
        mChannels.put(id, channel);
        return channel;
    }

    public Map<Integer, Channel> getChannels() {
        return Collections.unmodifiableMap(mChannels);
    }

    public Map<Integer, User> getUsers() {
        return Collections.unmodifiableMap(mUsers);
    }

    /**
     * Returns the current user's permissions.
     * @return The server-wide permissions.
     */
    public int getPermissions() {
        return mPermissions;
    }

    public void clear() {
        mChannels.clear();
        mUsers.clear();
    }

    @Override
    public void messageChannelState(Mumble.ChannelState msg) {
        if(!msg.hasChannelId())
            return;

        Channel channel = mChannels.get(msg.getChannelId());
        Channel parent = mChannels.get(msg.getParent());

        final boolean newChannel = channel == null;

        if(channel == null) {
            channel = new Channel(msg.getChannelId(), msg.getTemporary());
            mChannels.put(msg.getChannelId(), channel);
        }

        if(msg.hasName())
            channel.setName(msg.getName());

        if(msg.hasPosition())
            channel.setPosition(msg.getPosition());

        if(msg.hasParent()) {
            Channel oldParent = channel.getParent();
            channel.setParent(parent);
            parent.addSubchannel(channel);
            if(oldParent != null) {
                oldParent.removeSubchannel(channel);
            }
        }

        if(msg.hasDescriptionHash()) {
            channel.setDescriptionHash(msg.getDescriptionHash().toByteArray());
            channel.setDescription(null);
        }

        if(msg.hasDescription()) {
            channel.setDescription(msg.getDescription());
            channel.setDescriptionHash(null);
        }

        if(msg.getLinksCount() > 0) {
            channel.clearLinks();
            for(int link : msg.getLinksList()) {
                Channel linked = mChannels.get(link);
                channel.addLink(linked);
                // Don't add this channel to the other channel's link list- this update occurs on
                // server synchronization, and we will get a message for the other channels' links
                // laster.
            }
        }

        if(msg.getLinksRemoveCount() > 0) {
            for(int link : msg.getLinksRemoveList()) {
                Channel linked = mChannels.get(link);
                channel.removeLink(linked);
                linked.removeLink(channel);
            }
        }

        if(msg.getLinksAddCount() > 0) {
            for(int link : msg.getLinksAddList()) {
                Channel linked = mChannels.get(link);
                channel.addLink(linked);
                linked.addLink(channel);
            }
        }

        if(newChannel)
            mObserver.onChannelAdded(channel);
        else
            mObserver.onChannelStateUpdated(channel);
    }

    @Override
    public void messageChannelRemove(Mumble.ChannelRemove msg) {
        final Channel channel = mChannels.get(msg.getChannelId());
        if(channel != null && channel.getId() != 0) {
            mChannels.remove(channel.getId());
            Channel parent = channel.getParent();
            if(parent != null) {
                parent.removeSubchannel(channel);
            }
            mObserver.onChannelRemoved(channel);
        }
    }

    @Override
    public void messagePermissionQuery(Mumble.PermissionQuery msg) {
        if(msg.getFlush())
            for(Channel channel : mChannels.values())
                channel.setPermissions(0);

        final Channel channel = mChannels.get(msg.getChannelId());
        if(channel != null) {
            channel.setPermissions(msg.getPermissions());
            if(msg.getChannelId() == 0) // If we're provided permissions for the root channel, we'll apply these as our server permissions.
                mPermissions = channel.getPermissions();
            mObserver.onChannelPermissionsUpdated(channel);
        }
    }

    @Override
    public void messageUserState(Mumble.UserState msg) {
        User user = mUsers.get(msg.getSession());
        boolean newUser = false;

        User self = mUsers.get(mSession);

        if(user == null) {
            if(msg.hasName()) {
                user = new User(msg.getSession(), msg.getName());
                mUsers.put(msg.getSession(), user);
                newUser = true;
                // Add user to root channel by default. This works because for some reason, we don't get a channel ID when the user joins into root.
                Channel root = mChannels.get(0);
                if(root == null) root = createStubChannel(0);
                user.setChannel(root);
            }
            else
                return;
        }

        User actor = null;
        if(msg.hasActor())
            actor = getUser(msg.getActor());

        final User finalUser = user;

        if(msg.hasUserId()) {
            user.setUserId(msg.getUserId());
            // Restore local mute and ignore from history
            if (mLocalMuteHistory != null && mLocalMuteHistory.contains(user.getUserId())) {
                user.setLocalMuted(true);
            }
            if (mLocalIgnoreHistory != null && mLocalIgnoreHistory.contains(user.getUserId())) {
                user.setLocalIgnored(true);
            }
        }

        if(msg.hasHash()) {
            user.setHash(msg.getHash());

            /*
             * TODO:
             * - Check if user is local muted in database, if so re-mute them here
             * - Check if user is friend, if so indicate
             */
        }

        if(newUser)
            mLogger.logInfo(mContext.getString(R.string.chat_notify_connected, MessageFormatter.highlightString(user.getName())));

        if(msg.hasSelfDeaf() || msg.hasSelfMute()) {
            if(msg.hasSelfMute())
                user.setSelfMuted(msg.getSelfMute());
            if(msg.hasSelfDeaf())
                user.setSelfDeafened(msg.getSelfDeaf());

            if (self != null) {
                Channel userChan = user.getChannel();
                if (user.getSession() != self.getSession() && userChan != null && userChan.equals(self.getChannel())) {
                    if (user.isSelfMuted() && user.isSelfDeafened())
                        mLogger.logInfo(mContext.getString(R.string.chat_notify_now_muted_deafened, MessageFormatter.highlightString(user.getName())));
                    else if (user.isSelfMuted())
                        mLogger.logInfo(mContext.getString(R.string.chat_notify_now_muted, MessageFormatter.highlightString(user.getName())));
                    else
                        mLogger.logInfo(mContext.getString(R.string.chat_notify_now_unmuted, MessageFormatter.highlightString(user.getName())));
                } else if (user.getSession() == self.getSession()) {
                    if (user.isSelfMuted() && user.isSelfDeafened())
                        mLogger.logInfo(mContext.getString(R.string.chat_notify_muted_deafened));
                    else if (user.isSelfMuted())
                        mLogger.logInfo(mContext.getString(R.string.chat_notify_muted));
                    else
                        mLogger.logInfo(mContext.getString(R.string.chat_notify_unmuted));
                }
            }
        }

        if(msg.hasRecording()) {
            user.setRecording(msg.getRecording());

            if(self != null) {
                if(user.getSession() == self.getSession()) {
                    if(user.isRecording())
                        mLogger.logInfo(mContext.getString(R.string.chat_notify_self_recording_started));
                    else
                        mLogger.logInfo(mContext.getString(R.string.chat_notify_self_recording_stopped));
                } else {
                    Channel selfChannel = self.getChannel();
                    // If in a linked channel OR the same channel as the current user, notify the user about recording
                    if(selfChannel != null && (selfChannel.getLinks().contains(selfChannel) || selfChannel.equals(user.getChannel()))) {
                        if(user.isRecording())
                            mLogger.logInfo(mContext.getString(R.string.chat_notify_user_recording_started, MessageFormatter.highlightString(user.getName())));
                        else
                            mLogger.logInfo(mContext.getString(R.string.chat_notify_user_recording_stopped, MessageFormatter.highlightString(user.getName())));
                    }
                }
            }
        }

        if(msg.hasDeaf() || msg.hasMute() || msg.hasSuppress() || msg.hasPrioritySpeaker()) {
            if(msg.hasDeaf())
                user.setDeafened(msg.getDeaf());
            if(msg.hasMute())
                user.setMuted(msg.getMute());
            if(msg.hasSuppress())
                user.setSuppressed(msg.getSuppress());
            if(msg.hasPrioritySpeaker())
                user.setPrioritySpeaker(msg.getPrioritySpeaker());

//            if(self != null && ((user.getChannelId() == self.getChannelId()) || (actor.getSessionId() == self.getSessionId()))) {
//                if(user.getSessionId() == self.getSessionId()) {
//                    if(msg.hasMute() && msg.hasDeaf() && user.isMuted() && user.isDeafened()) {
//                        mLogger.logInfo();
//                    }
//                }
//            }

            /*
             * TODO: logging
             * Base this off of Messages.cpp:353
             */
        }

        if(msg.hasChannelId()) {
            final Channel channel = mChannels.get(msg.getChannelId());
            if(channel == null) {
                Log.e(TAG, "Invalid channel for user!");
                return; // TODO handle better
            }
            final Channel old = user.getChannel();

            user.setChannel(channel);

            if(!newUser) {
                mObserver.onUserJoinedChannel(finalUser, channel, old);
            }

            Channel sessionChannel = self != null ? self.getChannel() : null;

            // Notify the user of other users' current channel changes
            if (self != null && sessionChannel != null && old != null && !self.equals(user)) {
                // TODO add logic for other user moving self
                String actorString = actor != null ? MessageFormatter.highlightString(actor.getName()) : mContext.getString(R.string.the_server);
                if(!sessionChannel.equals(channel) && sessionChannel.equals(old)) {
                    // User moved out of self's channel
                    if(actor != null && actor.getSession() == user.getSession()) {
                        // By themselves
                        mLogger.logInfo(mContext.getString(R.string.chat_notify_user_left_channel, MessageFormatter.highlightString(user.getName()), MessageFormatter.highlightString(channel.getName())));
                    } else {
                        // By external actor
                        mLogger.logInfo(mContext.getString(R.string.chat_notify_user_left_channel_by, MessageFormatter.highlightString(user.getName()), MessageFormatter.highlightString(channel.getName()), actorString));
                    }
                } else if(sessionChannel.equals(channel)) {
                    // User moved into self's channel
                    if(actor != null && actor.getSession() == user.getSession()) {
                        // By themselves
                        mLogger.logInfo(mContext.getString(R.string.chat_notify_user_joined_channel, MessageFormatter.highlightString(user.getName())));
                    } else {
                        // By external actor
                        mLogger.logInfo(mContext.getString(R.string.chat_notify_user_joined_channel_by, MessageFormatter.highlightString(user.getName()), MessageFormatter.highlightString(old.getName()), actorString));
                    }
                }
            }

            /*
             * TODO: logging
             * Base this off of Messages.cpp:454
             */
        }

        if(msg.hasName())
            user.setName(msg.getName());

        if (msg.hasTextureHash()) {
            user.setTextureHash(msg.getTextureHash());
            user.setTexture(null); // clear cached texture when we receive a new hash
        }

        if (msg.hasTexture()) {
            // FIXME: is it reasonable to create a bitmap here? How expensive?
            user.setTexture(msg.getTexture());
            user.setTextureHash(null);
        }

        if(msg.hasCommentHash()) {
            user.setCommentHash(msg.getCommentHash());
            user.setComment(null);
        }

        if(msg.hasComment()) {
            user.setComment(msg.getComment());
            user.setCommentHash(null);
        }

        if (newUser)
            mObserver.onUserConnected(user);
        else
            mObserver.onUserStateUpdated(user);
    }

    @Override
    public void messageUserRemove(Mumble.UserRemove msg) {
        final User user = mUsers.get(msg.getSession());
        final User actor = mUsers.get(msg.getActor());
        final String reason = msg.getReason();

        // TODO? hackish fix of crash that was happening. The original logic
        // here is possible flawed, regarding presence of session, actor etc.
        // Consult Mumble.proto and official client?
        final String userName = user != null ? user.getName() : "unknown";
        final String actorName = actor != null ? actor.getName() : "unknown";
        if(msg.getSession() == mSession)
            mLogger.logWarning(mContext.getString(msg.getBan() ? R.string.chat_notify_kick_ban_self : R.string.chat_notify_kick_self, MessageFormatter.highlightString(actorName), reason));
        else if(actor != null)
            mLogger.logWarning(mContext.getString(msg.getBan() ? R.string.chat_notify_kick_ban : R.string.chat_notify_kick, MessageFormatter.highlightString(actorName), reason, MessageFormatter.highlightString(userName)));
        else
            mLogger.logInfo(mContext.getString(R.string.chat_notify_disconnected, MessageFormatter.highlightString(userName)));

        if (user != null) {
            user.setChannel(null);
        }
        mObserver.onUserRemoved(user, reason);
    }

    @Override
    public void messagePermissionDenied(final Mumble.PermissionDenied msg) {
        final String reason;
        switch (msg.getType()) {
            case ChannelName:
                reason = mContext.getString(R.string.deny_reason_channel_name);
                break;
            case TextTooLong:
                reason = mContext.getString(R.string.deny_reason_text_too_long);
                break;
            case TemporaryChannel:
                reason = mContext.getString(R.string.deny_reason_no_operation_temp);
                break;
            case MissingCertificate:
                reason = mContext.getString(R.string.deny_reason_no_certificate);
                break;
            case UserName:
                reason = mContext.getString(R.string.deny_reason_invalid_username);
                break;
            case ChannelFull:
                reason = mContext.getString(R.string.deny_reason_channel_full);
                break;
            case NestingLimit:
                reason = mContext.getString(R.string.deny_reason_channel_nesting);
                break;
            default:
                if(msg.hasReason()) reason = mContext.getString(R.string.deny_reason_other, msg.getReason());
                else reason = mContext.getString(R.string.perm_denied);

        }
        mObserver.onPermissionDenied(reason);
    }

    @Override
    public void messageTextMessage(Mumble.TextMessage msg) {
        User sender = mUsers.get(msg.getActor());

        if(sender != null && sender.isLocalIgnored())
            return;

        List<Channel> channels = new ArrayList<Channel>(msg.getChannelIdCount());
        for(int channelId : msg.getChannelIdList()) channels.add(mChannels.get(channelId));
        List<Channel> trees = new ArrayList<Channel>(msg.getTreeIdCount());
        for(int treeId : msg.getTreeIdList()) trees.add(mChannels.get(treeId));
        List<User> users = new ArrayList<User>(msg.getSessionCount());
        for(int userId : msg.getSessionList()) users.add(mUsers.get(userId));

        String actorName = sender != null ? sender.getName() : mContext.getString(R.string.server);

        Message message = new Message(msg.getActor(), actorName, channels, trees, users, msg.getMessage());
        mObserver.onMessageLogged(message);
    }

    @Override
    public void messageServerSync(Mumble.ServerSync msg) {
        mSession = msg.getSession();
        mLogger.logInfo(msg.getWelcomeText());
    }

    @Override
    public void messageServerConfig(Mumble.ServerConfig msg) {
        mServerSettings = new ServerSettings(msg);
    }
}