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

JumbleService.java « jumble « morlunk « com « java « main « src - github.com/Morlunk/Jumble.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b88831ce6b11b2e9edaf167f980d6732d97efbe3 (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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
/*
 * Copyright (C) 2013 Andrew Comminos
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.morlunk.jumble;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import com.morlunk.jumble.audio.Audio;
import com.morlunk.jumble.audio.AudioInput;
import com.morlunk.jumble.audio.AudioOutput;
import com.morlunk.jumble.model.Channel;
import com.morlunk.jumble.model.Message;
import com.morlunk.jumble.model.Server;
import com.morlunk.jumble.model.User;
import com.morlunk.jumble.net.JumbleConnection;
import com.morlunk.jumble.net.JumbleConnectionException;
import com.morlunk.jumble.net.JumbleTCPMessageType;
import com.morlunk.jumble.net.JumbleUDPMessageType;
import com.morlunk.jumble.protobuf.Mumble;
import com.morlunk.jumble.protocol.ChannelHandler;
import com.morlunk.jumble.protocol.TextMessageHandler;
import com.morlunk.jumble.protocol.UserHandler;

import java.security.Security;
import java.util.ArrayList;
import java.util.List;

public class JumbleService extends Service implements JumbleConnection.JumbleConnectionListener {

    static {
        // Use Spongy Castle for crypto implementation so we can create and manage PKCS #12 (.p12) certificates.
        Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
    }

    /** Intent to connect to a Mumble server. See extras. **/
    public static final String ACTION_CONNECT = "com.morlunk.jumble.CONNECT";
    public static final String EXTRAS_SERVER = "server";
    public static final String EXTRAS_AUTO_RECONNECT = "auto_reconnect";
    public static final String EXTRAS_AUTO_RECONNECT_DELAY = "auto_reconnect_delay";
    public static final String EXTRAS_CERTIFICATE = "certificate";
    public static final String EXTRAS_CERTIFICATE_PASSWORD = "certificate_password";
    public static final String EXTRAS_DETECTION_THRESHOLD = "detection_threshold";
    public static final String EXTRAS_TRANSMIT_MODE = "transmit_mode";
    public static final String EXTRAS_INPUT_QUALITY = "input_quality";
    public static final String EXTRAS_USE_OPUS = "use_opus";
    public static final String EXTRAS_FORCE_TCP = "force_tcp";
    public static final String EXTRAS_USE_TOR = "use_tor";
    public static final String EXTRAS_CLIENT_NAME = "client_name";
    public static final String EXTRAS_ACCESS_TOKENS = "access_tokens";

    public static final String ACTION_DISCONNECT = "com.morlunk.jumble.DISCONNECT";

    // Service settings
    public Server mServer;
    public boolean mAutoReconnect;
    public int mAutoReconnectDelay;
    public byte[] mCertificate;
    public String mCertificatePassword;
    public float mDetectionThreshold;
    public int mTransmitMode;
    public boolean mUseOpus;
    public int mInputQuality;
    public boolean mForceTcp;
    public boolean mUseTor;
    public String mClientName;
    public List<String> mAccessTokens;

    private JumbleConnection mConnection;
    private ChannelHandler mChannelHandler;
    private UserHandler mUserHandler;
    private TextMessageHandler mTextMessageHandler;
    private AudioOutput mAudioOutput;
    private AudioInput mAudioInput;
    private PowerManager.WakeLock mWakeLock;

    /* FIXME
    private AudioManager.OnAudioFocusChangeListener mAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        @Override
        public void onAudioFocusChange(int focusChange) {
            switch (focusChange) {
                case AudioManager.AUDIOFOCUS_GAIN:
                    mAudioOutput.startPlaying(false);
                    break;
                case AudioManager.AUDIOFOCUS_LOSS:
                    mAudioOutput.stopPlaying();
                    break;
            }
        }
    };
    */

    private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int audioState = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, AudioManager.SCO_AUDIO_STATE_ERROR);
            switch (audioState) {
                case AudioManager.SCO_AUDIO_STATE_CONNECTED:
                    Toast.makeText(JumbleService.this, R.string.bluetooth_connected, Toast.LENGTH_LONG).show();
                    mAudioOutput.stopPlaying();
                    if(isConnected())
                        mAudioOutput.startPlaying(true);
                    break;
                case AudioManager.SCO_AUDIO_STATE_DISCONNECTED:
                case AudioManager.SCO_AUDIO_STATE_ERROR:
                    if(mAudioOutput.isPlaying())
                        Toast.makeText(JumbleService.this, R.string.bluetooth_disconnected, Toast.LENGTH_LONG).show();
                    mAudioOutput.stopPlaying();
                    if(isConnected())
                        mAudioOutput.startPlaying(false);
                    break;
            }
        }
    };

    private AudioInput.AudioInputListener mAudioInputListener = new AudioInput.AudioInputListener() {
        @Override
        public void onFrameEncoded(byte[] data, int length, JumbleUDPMessageType messageType) {
            if(isConnected())
                mConnection.sendUDPMessage(data, length, false);
        }

        @Override
        public void onTalkStateChanged(final boolean talking) {

            try {
                if(!isConnected())
                    return;

                final User currentUser = getBinder().getSessionUser();

                new Handler(getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        currentUser.setTalkState(talking ? User.TalkState.TALKING : User.TalkState.PASSIVE);
                        notifyObservers(new ObserverRunnable() {
                            @Override
                            public void run(IJumbleObserver observer) throws RemoteException {
                                observer.onUserTalkStateUpdated(currentUser);
                            }
                        });
                    }
                });
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    };

    private int mPermissions;
    private List<Message> mMessageLog = new ArrayList<Message>();
    private boolean mReconnecting;

    private RemoteCallbackList<IJumbleObserver> mObservers = new RemoteCallbackList<IJumbleObserver>();

    /**
     * Interface to communicate with observers through the service.
     */
    public interface ObserverRunnable {
        public void run(IJumbleObserver observer) throws RemoteException;
    }

    private IJumbleService.Stub mBinder = new IJumbleService.Stub() {

        @Override
        public void disconnect() throws RemoteException {
            if(isConnected())
                JumbleService.this.disconnect();
        }

        @Override
        public boolean isConnected() throws RemoteException {
            if(mConnection != null)
                return mConnection.isConnected();
            return false;
        }

        @Override
        public boolean isConnecting() throws RemoteException {
            return mConnection != null && !mConnection.isConnected();
        }

        @Override
        public boolean isReconnecting() throws RemoteException {
            return mReconnecting;
        }

        @Override
        public void cancelReconnect() throws RemoteException {
            mReconnecting = false;
        }

        @Override
        public long getTCPLatency() throws RemoteException {
            return mConnection.getTCPLatency();
        }

        @Override
        public long getUDPLatency() throws RemoteException {
            return mConnection.getUDPLatency();
        }

        @Override
        public int getMaxBandwidth() throws RemoteException {
            return mConnection.getMaxBandwidth();
        }

        @Override
        public int getCurrentBandwidth() throws RemoteException {
            return 0;
        }

        @Override
        public int getServerVersion() throws RemoteException {
            return mConnection.getServerVersion();
        }

        @Override
        public String getServerRelease() throws RemoteException {
            return mConnection.getServerRelease();
        }

        @Override
        public String getServerOSName() throws RemoteException {
            return mConnection.getServerOSName();
        }

        @Override
        public String getServerOSVersion() throws RemoteException {
            return mConnection.getServerOSVersion();
        }

        @Override
        public int getSession() throws RemoteException {
            return mConnection.getSession();
        }

        @Override
        public User getSessionUser() throws RemoteException {
            return mUserHandler != null ? mUserHandler.getUser(getSession()) : null;
        }

        @Override
        public Channel getSessionChannel() throws RemoteException {
            User user = getSessionUser();
            return getChannel(user.getChannelId());
        }

        @Override
        public Server getConnectedServer() throws RemoteException {
            return mServer;
        }

        @Override
        public User getUser(int id) throws RemoteException {
            return mUserHandler.getUser(id);
        }

        @Override
        public Channel getChannel(int id) throws RemoteException {
            return mChannelHandler.getChannel(id);
        }

        @Override
        public List getUserList() throws RemoteException {
            return mUserHandler.getUsers();
        }

        @Override
        public List getChannelList() throws RemoteException {
            return mChannelHandler.getChannels();
        }

        @Override
        public int getPermissions() throws RemoteException {
            return mPermissions;
        }

        @Override
        public List getMessageLog() throws RemoteException {
            return mMessageLog;
        }

        @Override
        public void clearMessageLog() throws RemoteException {
            mMessageLog.clear();
        }

        @Override
        public int getTransmitMode() throws RemoteException {
            return mTransmitMode;
        }

        @Override
        public void setTransmitMode(int transmitMode) throws RemoteException {
            mTransmitMode = transmitMode;
            mAudioInput.setTransmitMode(mTransmitMode);

            // Reconfigure audio input/output to accommodate for change in transmit mode.
            if(mConnection != null && mConnection.isConnected()) {
                if(transmitMode == Constants.TRANSMIT_CONTINUOUS || transmitMode == Constants.TRANSMIT_VOICE_ACTIVITY)
                    mAudioInput.startRecording();
                else
                    mAudioInput.stopRecording();
            }
        }

        @Override
        public void setVADThreshold(float threshold) throws RemoteException {
            if(mAudioInput != null)
                mAudioInput.setVADThreshold(threshold);
        }

        @Override
        public int getCodec() throws RemoteException {
            return mConnection.getCodec();
        }

        @Override
        public boolean isTalking() throws RemoteException {
            return mAudioInput.isRecording();
        }

        @Override
        public void setTalkingState(boolean talking) throws RemoteException {
            if(talking) mAudioInput.startRecording();
            else mAudioInput.stopRecording();
        }

        @Override
        public boolean isBluetoothAvailable() throws RemoteException {
            AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
            return audioManager.isBluetoothScoOn();
        }

        @Override
        public void setBluetoothEnabled(boolean enabled) throws RemoteException {
            AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
            if(enabled) audioManager.startBluetoothSco();
            else audioManager.stopBluetoothSco();
        }

        @Override
        public void joinChannel(int channel) throws RemoteException {
            Mumble.UserState.Builder usb = Mumble.UserState.newBuilder();
            usb.setSession(mConnection.getSession());
            usb.setChannelId(channel);
            mConnection.sendTCPMessage(usb.build(), JumbleTCPMessageType.UserState);
        }

        @Override
        public void createChannel(int parent, String name, String description, int position, boolean temporary) throws RemoteException {
            Mumble.ChannelState.Builder csb = Mumble.ChannelState.newBuilder();
            csb.setParent(parent);
            csb.setName(name);
            csb.setDescription(description);
            csb.setPosition(position);
            csb.setTemporary(temporary);
            mConnection.sendTCPMessage(csb.build(), JumbleTCPMessageType.ChannelState);
        }

        @Override
        public void sendAccessTokens(List tokens) throws RemoteException {
            Mumble.Authenticate.Builder ab = Mumble.Authenticate.newBuilder();
            ab.addAllTokens(tokens);
            mConnection.sendTCPMessage(ab.build(), JumbleTCPMessageType.Authenticate);
        }

        @Override
        public void requestBanList() throws RemoteException {
            // TODO
        }

        @Override
        public void requestUserList() throws RemoteException {
            // TODO
        }

        @Override
        public void requestPermissions(int channel) throws RemoteException {
            Mumble.PermissionQuery.Builder pqb = Mumble.PermissionQuery.newBuilder();
            pqb.setChannelId(channel);
            mConnection.sendTCPMessage(pqb.build(), JumbleTCPMessageType.PermissionQuery);
        }

        @Override
        public void requestComment(int session) throws RemoteException {
            Mumble.RequestBlob.Builder rbb = Mumble.RequestBlob.newBuilder();
            rbb.addSessionComment(session);
            mConnection.sendTCPMessage(rbb.build(), JumbleTCPMessageType.RequestBlob);
        }

        @Override
        public void requestChannelDescription(int channel) throws RemoteException {
            Mumble.RequestBlob.Builder rbb = Mumble.RequestBlob.newBuilder();
            rbb.addChannelDescription(channel);
            mConnection.sendTCPMessage(rbb.build(), JumbleTCPMessageType.RequestBlob);
        }

        @Override
        public void registerUser(int session) throws RemoteException {
            Mumble.UserState.Builder usb = Mumble.UserState.newBuilder();
            usb.setSession(session);
            usb.setUserId(0);
            mConnection.sendTCPMessage(usb.build(), JumbleTCPMessageType.UserState);
        }

        @Override
        public void kickBanUser(int session, String reason, boolean ban) throws RemoteException {
            Mumble.UserRemove.Builder urb = Mumble.UserRemove.newBuilder();
            urb.setSession(session);
            urb.setReason(reason);
            urb.setBan(ban);
            mConnection.sendTCPMessage(urb.build(), JumbleTCPMessageType.UserRemove);
        }

        @Override
        public Message sendUserTextMessage(int session, String message) throws RemoteException {
            Mumble.TextMessage.Builder tmb = Mumble.TextMessage.newBuilder();
            tmb.addSession(session);
            tmb.setMessage(message);
            mConnection.sendTCPMessage(tmb.build(), JumbleTCPMessageType.TextMessage);

            User user = getUser(session);
            List<User> users = new ArrayList<User>(1);
            users.add(user);
            Message logMessage = new Message(getSession(), new ArrayList<Channel>(0), new ArrayList<Channel>(0), users, message);
            mMessageLog.add(logMessage);
            return logMessage;
        }

        @Override
        public Message sendChannelTextMessage(int channel, String message, boolean tree) throws RemoteException {
            Mumble.TextMessage.Builder tmb = Mumble.TextMessage.newBuilder();
            if(tree) tmb.addTreeId(channel);
            else tmb.addChannelId(channel);
            tmb.setMessage(message);
            mConnection.sendTCPMessage(tmb.build(), JumbleTCPMessageType.TextMessage);

            Channel targetChannel = getChannel(channel);
            List<Channel> targetChannels = new ArrayList<Channel>();
            targetChannels.add(targetChannel);
            Message logMessage = new Message(getSession(), targetChannels, tree ? targetChannels : new ArrayList<Channel>(0), new ArrayList<User>(0), message);
            mMessageLog.add(logMessage);
            return logMessage;
        }

        @Override
        public void setUserComment(int session, String comment) throws RemoteException {
            Mumble.UserState.Builder usb = Mumble.UserState.newBuilder();
            usb.setSession(session);
            usb.setComment(comment);
            mConnection.sendTCPMessage(usb.build(), JumbleTCPMessageType.UserState);
        }

        @Override
        public void setPrioritySpeaker(int session, boolean priority) throws RemoteException {
            Mumble.UserState.Builder usb = Mumble.UserState.newBuilder();
            usb.setSession(session);
            usb.setPrioritySpeaker(priority);
            mConnection.sendTCPMessage(usb.build(), JumbleTCPMessageType.UserState);
        }

        @Override
        public void removeChannel(int channel) throws RemoteException {
            Mumble.ChannelRemove.Builder crb = Mumble.ChannelRemove.newBuilder();
            crb.setChannelId(channel);
            mConnection.sendTCPMessage(crb.build(), JumbleTCPMessageType.ChannelRemove);
        }

        @Override
        public void setMuteDeafState(int session, boolean mute, boolean deaf) throws RemoteException {
            Mumble.UserState.Builder usb = Mumble.UserState.newBuilder();
            usb.setSession(session);
            usb.setMute(mute);
            usb.setDeaf(deaf);
            mConnection.sendTCPMessage(usb.build(), JumbleTCPMessageType.UserState);
        }

        @Override
        public void setSelfMuteDeafState(boolean mute, boolean deaf) throws RemoteException {
            Mumble.UserState.Builder usb = Mumble.UserState.newBuilder();
            usb.setSelfMute(mute);
            usb.setSelfDeaf(deaf);
            if(!mute && (mTransmitMode == Constants.TRANSMIT_CONTINUOUS || mTransmitMode == Constants.TRANSMIT_VOICE_ACTIVITY))
                mAudioInput.startRecording(); // Resume recording when unmuted for PTT.
            else
                mAudioInput.stopRecording(); // Stop recording when muted.
            mConnection.sendTCPMessage(usb.build(), JumbleTCPMessageType.UserState);
        }

        @Override
        public void registerObserver(IJumbleObserver observer) {
            mObservers.register(observer);
        }

        @Override
        public void unregisterObserver(IJumbleObserver observer) {
            mObservers.unregister(observer);
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent != null &&
                intent.getAction() != null &&
                intent.getExtras() != null &&
                intent.getAction().equals(ACTION_CONNECT)) {
            // Get connection parameters
            Bundle extras = intent.getExtras();
            mServer = extras.getParcelable(EXTRAS_SERVER);
            mAutoReconnect = extras.getBoolean(EXTRAS_AUTO_RECONNECT, true);
            mAutoReconnectDelay = extras.getInt(EXTRAS_AUTO_RECONNECT_DELAY, 5000);
            mCertificate = extras.getByteArray(EXTRAS_CERTIFICATE);
            mCertificatePassword = extras.getString(EXTRAS_CERTIFICATE_PASSWORD);
            mDetectionThreshold = extras.getFloat(EXTRAS_DETECTION_THRESHOLD, 0.5f);
            mTransmitMode = extras.getInt(EXTRAS_TRANSMIT_MODE, Constants.TRANSMIT_VOICE_ACTIVITY);
            mInputQuality = extras.getInt(EXTRAS_INPUT_QUALITY, Audio.SAMPLE_RATE);
            mUseOpus = extras.getBoolean(EXTRAS_USE_OPUS, true);
            mUseTor = extras.getBoolean(EXTRAS_USE_TOR, false);
            mForceTcp = extras.getBoolean(EXTRAS_FORCE_TCP, false) || mUseTor; // Tor requires TCP connections to work- if it's on, force TCP.
            mClientName = extras.containsKey(EXTRAS_CLIENT_NAME) ? extras.getString(EXTRAS_CLIENT_NAME) : "Jumble";
            mAccessTokens = extras.getStringArrayList(EXTRAS_ACCESS_TOKENS);
            connect();
        }
        return START_NOT_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Jumble");
    }

    @Override
    public void onDestroy() {
        mObservers.kill();
        super.onDestroy();
    }

    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public IJumbleService getBinder() {
        return mBinder;
    }

    public void connect() {
        try {
            mConnection = new JumbleConnection(this, this, mServer, mClientName, mCertificate, mCertificatePassword, mForceTcp, mUseOpus, mUseTor);
        } catch (final JumbleConnectionException e) {
            e.printStackTrace();

            notifyObservers(new ObserverRunnable() {
                @Override
                public void run(IJumbleObserver observer) throws RemoteException {
                    observer.onConnectionError(e.getMessage(), e.isAutoReconnectAllowed());
                }
            });

            return;
        }

        mPermissions = 0;
        mReconnecting = false;
        mChannelHandler = new ChannelHandler(this);
        mUserHandler = new UserHandler(this);
        mTextMessageHandler = new TextMessageHandler(this);
        mAudioOutput = new AudioOutput(this);
        mAudioInput = new AudioInput(this, JumbleUDPMessageType.UDPVoiceOpus, mInputQuality, mTransmitMode, mDetectionThreshold, mAudioInputListener);
        mConnection.addMessageHandlers(mChannelHandler, mUserHandler, mTextMessageHandler, mAudioOutput, mAudioInput);

        mConnection.connect();
    }

    public void disconnect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                mConnection.disconnect();
                mConnection = null;
            }
        }).start();
    }

    public boolean isConnected() {
        return mConnection != null && mConnection.isConnected();
    }

    @Override
    public void onConnectionEstablished() {
        Log.v(Constants.TAG, "Connected");
        mWakeLock.acquire();

        // Send access tokens
        Mumble.Authenticate.Builder ab = Mumble.Authenticate.newBuilder();
        ab.addAllTokens(mAccessTokens);
        mConnection.sendTCPMessage(ab.build(), JumbleTCPMessageType.Authenticate);

        mAudioOutput.startPlaying(false);

        // Configure audio manager FIXME audio focus
//        AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
//        int result = audioManager.requestAudioFocus(mAudioFocusChangeListener,
//                                                    AudioManager.STREAM_MUSIC,
//                                                    AudioManager.AUDIOFOCUS_GAIN);
        // TODO handle result
        // This sticky broadcast will initialize the audio output.
        registerReceiver(mBluetoothReceiver, new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED));
        if(mTransmitMode == Constants.TRANSMIT_CONTINUOUS || mTransmitMode == Constants.TRANSMIT_VOICE_ACTIVITY)
            mAudioInput.startRecording();

        notifyObservers(new ObserverRunnable() {
            @Override
            public void run(IJumbleObserver observer) throws RemoteException {
                observer.onConnected();
            }
        });
    }

    @Override
    public void onConnectionDisconnected() {
        Log.v(Constants.TAG, "Disconnected");
        if(mWakeLock.isHeld()) mWakeLock.release();

        try {
            unregisterReceiver(mBluetoothReceiver);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

        mAudioOutput.stopPlaying();
        mAudioInput.stopRecordingAndWait();
        mAudioInput.destroy();

        // Restore audio manager mode
        AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
//        audioManager.abandonAudioFocus(mAudioFocusChangeListener);
        audioManager.stopBluetoothSco();

        notifyObservers(new ObserverRunnable() {
            @Override
            public void run(IJumbleObserver observer) throws RemoteException {
                observer.onDisconnected();
            }
        });

        mMessageLog.clear();
    }

    @Override
    public void onConnectionError(final JumbleConnectionException e) {
        Log.e(Constants.TAG, "Connection error: "+e.getMessage());
        mReconnecting = mAutoReconnect && e.isAutoReconnectAllowed();
        if(mReconnecting) {
            Handler mainHandler = new Handler();
            mainHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(mReconnecting) connect();
                }
            }, mAutoReconnectDelay);
        }
        notifyObservers(new ObserverRunnable() {
            @Override
            public void run(IJumbleObserver observer) throws RemoteException {
                observer.onConnectionError(e.getMessage(), mReconnecting);
            }
        });
    }

    @Override
    public void onConnectionWarning(String warning) {
        logWarning(warning);
    }

    /**
     * Returns the user ID of this user session.
     * @return Identifier for the local user.
     */
    public int getSession() {
        return mConnection.getSession();
    }

    public UserHandler getUserHandler() {
        return mUserHandler;
    }

    public ChannelHandler getChannelHandler() {
        return mChannelHandler;
    }

    public void setPermissions(int permissions) {
        mPermissions = permissions;
    }

    /*
     * --- HERE BE CALLBACKS ---
     * This code will be called by components of the service like ChannelHandler.
     */

    /**
     * Logs a warning message to the client.
     * @param warning An HTML warning string to be messaged to the client.
     */
    public void logWarning(final String warning) {
        final Message message = new Message(Message.Type.WARNING, warning);
        logMessage(message);
    }

    /**
     * Logs an info message to the client.
     * @param info An HTML info string to be messaged to the client.
     */
    public void logInfo(final String info) {
        if(!mConnection.isSynchronized())
            return; // Don't log messages while synchronizing.

        final Message message = new Message(Message.Type.INFO, info);
        logMessage(message);
    }

    /**
     * Logs a message to the client.
     * @param message A message to log to the client.
     */
    public void logMessage(final Message message) {
        mMessageLog.add(message);
        notifyObservers(new ObserverRunnable() {
            @Override
            public void run(IJumbleObserver observer) throws RemoteException {
                observer.onMessageLogged(message);
            }
        });
    }

    /**
     * Iterates through all registered IJumbleObservers and performs the action implemented in the passed ObserverRunnable.
     * @param runnable A runnable to execute on each observer.
     */
    public void notifyObservers(ObserverRunnable runnable) {
        int i = mObservers.beginBroadcast();
        while(i > 0) {
            i--;
            try {
                runnable.run(mObservers.getBroadcastItem(i));
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        mObservers.finishBroadcast();
    }
}