aboutsummaryrefslogtreecommitdiff
path: root/src/java/com/android/ims/RcsFeatureManager.java
blob: 3fe921290a3d6b90082ca3117ac8ddaf5b5ed15d (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
/*
 * Copyright (c) 2019 The Android Open Source Project
 *
 * 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.android.ims;

import android.content.Context;
import android.net.Uri;
import android.os.PersistableBundle;
import android.os.RemoteException;
import android.telephony.CarrierConfigManager;
import android.telephony.SubscriptionManager;
import android.telephony.ims.RcsContactUceCapability;
import android.telephony.ims.RegistrationManager;
import android.telephony.ims.aidl.IImsCapabilityCallback;
import android.telephony.ims.aidl.IImsRegistrationCallback;
import android.telephony.ims.aidl.IRcsFeatureListener;
import android.telephony.ims.feature.CapabilityChangeRequest;
import android.telephony.ims.feature.RcsFeature;
import android.telephony.ims.feature.RcsFeature.RcsImsCapabilities;
import android.telephony.ims.stub.ImsRegistrationImplBase;
import android.telephony.ims.stub.RcsCapabilityExchange;
import android.telephony.ims.stub.RcsPresenceExchangeImplBase;
import android.telephony.ims.stub.RcsSipOptionsImplBase;
import android.util.Log;

import com.android.ims.FeatureConnection.IFeatureUpdate;
import com.android.internal.annotations.VisibleForTesting;
import com.android.telephony.Rlog;

import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

/**
 * Encapsulates all logic related to the RcsFeature:
 * - Updating RcsFeature capabilities.
 * - Registering/Unregistering availability/registration callbacks.
 * - Querying Registration and Capability information.
 */
public class RcsFeatureManager implements IFeatureConnector {
    private static final String TAG = "RcsFeatureManager";
    private static boolean DBG = true;

    private static final int CAPABILITY_OPTIONS = RcsImsCapabilities.CAPABILITY_TYPE_OPTIONS_UCE;
    private static final int CAPABILITY_PRESENCE = RcsImsCapabilities.CAPABILITY_TYPE_PRESENCE_UCE;

    /**
     * Callbacks from the RcsFeature, which have an empty default implementation and can be
     * overridden for each Feature.
     */
    public static class RcsFeatureCallbacks {
        /** See {@link RcsCapabilityExchange#onCommandUpdate(int, int)} */
        void onCommandUpdate(int commandCode, int operationToken) {}

        /** See {@link RcsPresenceExchangeImplBase#onNetworkResponse(int, String, int)} */
        public void onNetworkResponse(int code, String reason, int operationToken) {}

        /** See {@link RcsPresenceExchangeImplBase#onCapabilityRequestResponse(List, int)} */
        public void onCapabilityRequestResponsePresence(List<RcsContactUceCapability> infos,
                int operationToken) {}

        /** See {@link RcsPresenceExchangeImplBase#onNotifyUpdateCapabilites(int)} */
        public void onNotifyUpdateCapabilities(int publishTriggerType) {}

        /** See {@link RcsPresenceExchangeImplBase#onUnpublish()} */
        public void onUnpublish() {}

        /**
         * See {@link RcsSipOptionsImplBase#onCapabilityRequestResponse(int,String,
         * RcsContactUceCapability, int)}
         */
        public void onCapabilityRequestResponseOptions(int code, String reason,
                RcsContactUceCapability info, int operationToken) {}

        /**
         * See {@link RcsSipOptionsImplBase#onRemoteCapabilityRequest(Uri, RcsContactUceCapability,
         * int)}
         */
        public void onRemoteCapabilityRequest(Uri contactUri, RcsContactUceCapability remoteInfo,
                int operationToken) {}
    }

    private final IRcsFeatureListener mRcsFeatureCallbackAdapter = new IRcsFeatureListener.Stub() {
        @Override
        public void onCommandUpdate(int commandCode, int operationToken) {
            mRcsFeatureCallbacks.forEach(listener-> listener.onCommandUpdate(commandCode,
                    operationToken));
        }

        @Override
        public void onNetworkResponse(int code, String reason, int operationToken) {
            mRcsFeatureCallbacks.forEach(listener-> listener.onNetworkResponse(code, reason,
                    operationToken));
        }

        @Override
        public void onCapabilityRequestResponsePresence(List<RcsContactUceCapability> infos,
                int operationToken) {
            mRcsFeatureCallbacks.forEach(listener-> listener.onCapabilityRequestResponsePresence(
                    infos, operationToken));
        }

        @Override
        public void onNotifyUpdateCapabilities(int publishTriggerType) {
            mRcsFeatureCallbacks.forEach(listener-> listener.onNotifyUpdateCapabilities(
                    publishTriggerType));
        }

        @Override
        public void onUnpublish() {
            mRcsFeatureCallbacks.forEach(listener-> listener.onUnpublish());
        }

        @Override
        public void onCapabilityRequestResponseOptions(int code, String reason,
                RcsContactUceCapability info, int operationToken) {
            mRcsFeatureCallbacks.forEach(listener -> listener.onCapabilityRequestResponseOptions(
                    code, reason, info, operationToken));
        }

        @Override
        public void onRemoteCapabilityRequest(Uri contactUri, RcsContactUceCapability remoteInfo,
                int operationToken) {
            mRcsFeatureCallbacks.forEach(listener -> listener.onRemoteCapabilityRequest(
                    contactUri, remoteInfo, operationToken));
        }
    };

    private final int mSlotId;
    private final Context mContext;
    @VisibleForTesting
    public final Set<IFeatureUpdate> mStatusCallbacks = new CopyOnWriteArraySet<>();
    private final Set<RcsFeatureCallbacks> mRcsFeatureCallbacks = new CopyOnWriteArraySet<>();

    @VisibleForTesting
    public RcsFeatureConnection mRcsFeatureConnection;

    public RcsFeatureManager(Context context, int slotId) {
        mContext = context;
        mSlotId = slotId;
        logi("RcsFeatureManager");

        createImsService();
    }

    // Binds the IMS service to the RcsFeature instance.
    private void createImsService() {
        mRcsFeatureConnection = RcsFeatureConnection.create(mContext, mSlotId,
                new IFeatureUpdate() {
                    @Override
                    public void notifyStateChanged() {
                        mStatusCallbacks.forEach(
                            FeatureConnection.IFeatureUpdate::notifyStateChanged);
                    }
                    @Override
                    public void notifyUnavailable() {
                        logi("RcsFeature is unavailable");
                        mStatusCallbacks.forEach(
                            FeatureConnection.IFeatureUpdate::notifyUnavailable);
                    }
                });
    }

    /**
     * Opens a persistent connection to the RcsFeature. This must be called before the RcsFeature
     * can be used to communicate. Triggers a {@link RcsFeature#onFeatureReady()} call on the
     * service side.
     */
    public void openConnection() throws android.telephony.ims.ImsException {
        try {
            mRcsFeatureConnection.setRcsFeatureListener(mRcsFeatureCallbackAdapter);
        } catch (RemoteException e){
            throw new android.telephony.ims.ImsException("Service is not available.",
                    android.telephony.ims.ImsException.CODE_ERROR_SERVICE_UNAVAILABLE);
        }
    }

    /**
     * Closes the persistent connection to the RcsFeature. This must be called when this manager
     * wishes to no longer be used to communicate with the RcsFeature.
     */
    public void releaseConnection() {
        try {
            mRcsFeatureConnection.setRcsFeatureListener(null);
        } catch (RemoteException e){
            // Connection may not be available at this point.
        }
        mStatusCallbacks.clear();
        mRcsFeatureConnection.close();
        mRcsFeatureCallbacks.clear();
    }

    /**
     * Adds a callback for {@link RcsFeatureCallbacks}.
     * Note: These callbacks will be sent on the binder thread used to notify the callback.
     */
    public void addFeatureListenerCallback(RcsFeatureCallbacks listener) {
        mRcsFeatureCallbacks.add(listener);
    }

    /**
     * Removes an existing {@link RcsFeatureCallbacks}.
     */
    public void removeFeatureListenerCallback(RcsFeatureCallbacks listener) {
        mRcsFeatureCallbacks.remove(listener);
    }

    /**
     * Update the capabilities for this RcsFeature.
     */
    public void updateCapabilities() throws android.telephony.ims.ImsException {
        boolean optionsSupport = isOptionsSupported();
        boolean presenceSupported = isPresenceSupported();

        logi("Update capabilities for slot " + mSlotId + ": options=" + optionsSupport
                + ", presence=" + presenceSupported);

        if (optionsSupport || presenceSupported) {
            CapabilityChangeRequest request = new CapabilityChangeRequest();
            if (optionsSupport) {
                addRcsUceCapability(request, CAPABILITY_OPTIONS);
            }
            if (presenceSupported) {
                addRcsUceCapability(request, CAPABILITY_PRESENCE);
            }
            sendCapabilityChangeRequest(request);
        } else {
            disableAllRcsUceCapabilities();
        }
    }

    /**
     * Add a {@link RegistrationManager.RegistrationCallback} callback that gets called when IMS
     * registration has changed for a specific subscription.
     */
    public void registerImsRegistrationCallback(int subId, IImsRegistrationCallback callback)
            throws android.telephony.ims.ImsException {
        try {
            mRcsFeatureConnection.addCallbackForSubscription(subId, callback);
        } catch (IllegalStateException e) {
            loge("registerImsRegistrationCallback error: ", e);
            throw new android.telephony.ims.ImsException("Can not register callback",
                    android.telephony.ims.ImsException.CODE_ERROR_SERVICE_UNAVAILABLE);
        }
    }

    /**
     * Add a {@link RegistrationManager.RegistrationCallback} callback that gets called when IMS
     * registration has changed, independent of the subscription it is currently on.
     */
    public void registerImsRegistrationCallback(IImsRegistrationCallback callback)
            throws android.telephony.ims.ImsException {
        try {
            mRcsFeatureConnection.addCallback(callback);
        } catch (IllegalStateException e) {
            loge("registerImsRegistrationCallback error: ", e);
            throw new android.telephony.ims.ImsException("Can not register callback",
                    android.telephony.ims.ImsException.CODE_ERROR_SERVICE_UNAVAILABLE);
        }
    }

    /**
     * Removes a previously registered {@link RegistrationManager.RegistrationCallback} callback
     * that is associated with a specific subscription.
     */
    public void unregisterImsRegistrationCallback(int subId, IImsRegistrationCallback callback) {
        mRcsFeatureConnection.removeCallbackForSubscription(subId, callback);
    }

    /**
     * Removes a previously registered {@link RegistrationManager.RegistrationCallback} callback
     * that was not associated with a subscription.
     */
    public void unregisterImsRegistrationCallback(IImsRegistrationCallback callback) {
        mRcsFeatureConnection.removeCallback(callback);
    }

    /**
     * Get the IMS RCS registration technology for this Phone,
     * defined in {@link ImsRegistrationImplBase}.
     */
    public void getImsRegistrationTech(Consumer<Integer> callback) {
        try {
            int tech = mRcsFeatureConnection.getRegistrationTech();
            callback.accept(tech);
        } catch (RemoteException e) {
            loge("getImsRegistrationTech error: ", e);
            callback.accept(ImsRegistrationImplBase.REGISTRATION_TECH_NONE);
        }
    }

    /**
     * Register an ImsCapabilityCallback with RCS service, which will provide RCS availability
     * updates.
     */
    public void registerRcsAvailabilityCallback(int subId, IImsCapabilityCallback callback)
            throws android.telephony.ims.ImsException {
        try {
            mRcsFeatureConnection.addCallbackForSubscription(subId, callback);
        } catch (IllegalStateException e) {
            loge("registerRcsAvailabilityCallback: ", e);
            throw new android.telephony.ims.ImsException("Can not register callback",
                    android.telephony.ims.ImsException.CODE_ERROR_SERVICE_UNAVAILABLE);
        }
    }

    /**
     * Remove an registered ImsCapabilityCallback from RCS service.
     */
    public void unregisterRcsAvailabilityCallback(int subId, IImsCapabilityCallback callback) {
            mRcsFeatureConnection.removeCallbackForSubscription(subId, callback);
    }

    /**
     * Query for the specific capability.
     */
    public boolean isCapable(
            @RcsImsCapabilities.RcsImsCapabilityFlag int capability,
            @ImsRegistrationImplBase.ImsRegistrationTech int radioTech)
            throws android.telephony.ims.ImsException {
        CountDownLatch latch = new CountDownLatch(1);
        AtomicReference<Boolean> capableRef = new AtomicReference<>();

        IImsCapabilityCallback callback = new IImsCapabilityCallback.Stub() {
            @Override
            public void onQueryCapabilityConfiguration(
                    int resultCapability, int resultRadioTech, boolean enabled) {
                if ((capability != resultCapability) || (radioTech != resultRadioTech)) {
                    return;
                }
                if (DBG) log("capable result:capability=" + capability + ", enabled=" + enabled);
                capableRef.set(enabled);
                latch.countDown();
            }

            @Override
            public void onCapabilitiesStatusChanged(int config) {
                // Don't handle it
            }

            @Override
            public void onChangeCapabilityConfigurationError(int capability, int radioTech,
                    int reason) {
                // Don't handle it
            }
        };

        try {
            if (DBG) log("Query capability: " + capability + ", radioTech=" + radioTech);
            mRcsFeatureConnection.queryCapabilityConfiguration(capability, radioTech, callback);
            return awaitResult(latch, capableRef);
        } catch (RemoteException e) {
            loge("isCapable error: ", e);
            throw new android.telephony.ims.ImsException("Can not determine capabilities",
                    android.telephony.ims.ImsException.CODE_ERROR_SERVICE_UNAVAILABLE);
        }
    }

    private static <T> T awaitResult(CountDownLatch latch, AtomicReference<T> resultRef) {
        try {
            latch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return resultRef.get();
    }

    /**
     * Query the availability of an IMS RCS capability.
     */
    public boolean isAvailable(@RcsImsCapabilities.RcsImsCapabilityFlag int capability)
            throws android.telephony.ims.ImsException {
        try {
            int currentStatus = mRcsFeatureConnection.queryCapabilityStatus();
            return new RcsImsCapabilities(currentStatus).isCapable(capability);
        } catch (RemoteException e) {
            loge("isAvailable error: ", e);
            throw new android.telephony.ims.ImsException("Can not determine availability",
                    android.telephony.ims.ImsException.CODE_ERROR_SERVICE_UNAVAILABLE);
        }
    }

    /**
     * Adds a callback for status changed events if the binder is already available. If it is not,
     * this method will throw an ImsException.
     */
    @Override
    public void addNotifyStatusChangedCallbackIfAvailable(FeatureConnection.IFeatureUpdate c)
            throws android.telephony.ims.ImsException {
        if (!mRcsFeatureConnection.isBinderAlive()) {
            throw new android.telephony.ims.ImsException("Can not connect to service.",
                    android.telephony.ims.ImsException.CODE_ERROR_SERVICE_UNAVAILABLE);
        }
        if (c != null) {
            mStatusCallbacks.add(c);
        }
    }

    @Override
    public void removeNotifyStatusChangedCallback(FeatureConnection.IFeatureUpdate c) {
        if (c != null) {
            mStatusCallbacks.remove(c);
        }
    }

    /**
     * Add UCE capabilities with given type.
     * @param capability the specific RCS UCE capability wants to enable
     */
    public void addRcsUceCapability(CapabilityChangeRequest request,
            @RcsImsCapabilities.RcsImsCapabilityFlag int capability) {
        request.addCapabilitiesToEnableForTech(capability,
                ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
        request.addCapabilitiesToEnableForTech(capability,
                ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN);
    }

    /**
     * Disable all of the UCE capabilities.
     */
    private void disableAllRcsUceCapabilities() throws android.telephony.ims.ImsException {
        final int techLte = ImsRegistrationImplBase.REGISTRATION_TECH_LTE;
        final int techIWlan = ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN;
        CapabilityChangeRequest request = new CapabilityChangeRequest();
        request.addCapabilitiesToDisableForTech(CAPABILITY_OPTIONS, techLte);
        request.addCapabilitiesToDisableForTech(CAPABILITY_OPTIONS, techIWlan);
        request.addCapabilitiesToDisableForTech(CAPABILITY_PRESENCE, techLte);
        request.addCapabilitiesToDisableForTech(CAPABILITY_PRESENCE, techIWlan);
        sendCapabilityChangeRequest(request);
    }

    private void sendCapabilityChangeRequest(CapabilityChangeRequest request)
            throws android.telephony.ims.ImsException {
        try {
            if (DBG) log("sendCapabilityChangeRequest: " + request);
            mRcsFeatureConnection.changeEnabledCapabilities(request, null);
        } catch (RemoteException e) {
            throw new android.telephony.ims.ImsException("Can not connect to service",
                    android.telephony.ims.ImsException.CODE_ERROR_SERVICE_UNAVAILABLE);
        }
    }

    private boolean isOptionsSupported() {
        return isCapabilityTypeSupported(mContext, mSlotId, CAPABILITY_OPTIONS);
    }

    private boolean isPresenceSupported() {
        return isCapabilityTypeSupported(mContext, mSlotId, CAPABILITY_PRESENCE);
    }

    /*
     * Check if the given type of capability is supported.
     */
    private static boolean isCapabilityTypeSupported(
        Context context, int slotId, int capabilityType) {

        int subId = sSubscriptionManagerProxy.getSubId(slotId);
        if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
            Log.e(TAG, "isCapabilityTypeSupported: Getting subIds is failure! slotId=" + slotId);
            return false;
        }

        CarrierConfigManager configManager =
            (CarrierConfigManager) context.getSystemService(Context.CARRIER_CONFIG_SERVICE);
        if (configManager == null) {
            Log.e(TAG, "isCapabilityTypeSupported: CarrierConfigManager is null, " + slotId);
            return false;
        }

        PersistableBundle b = configManager.getConfigForSubId(subId);
        if (b == null) {
            Log.e(TAG, "isCapabilityTypeSupported: PersistableBundle is null, " + slotId);
            return false;
        }

        if (capabilityType == CAPABILITY_OPTIONS) {
            return b.getBoolean(CarrierConfigManager.KEY_USE_RCS_SIP_OPTIONS_BOOL, false);
        } else if (capabilityType == CAPABILITY_PRESENCE) {
            return b.getBoolean(CarrierConfigManager.KEY_USE_RCS_PRESENCE_BOOL, false);
        }
        return false;
    }

    @Override
    public int getImsServiceState() throws ImsException {
        return mRcsFeatureConnection.getFeatureState();
    }

    /**
     * Testing interface used to mock SubscriptionManager in testing
     * @hide
     */
    @VisibleForTesting
    public interface SubscriptionManagerProxy {
        /**
         * Mock-able interface for {@link SubscriptionManager#getSubId(int)} used for testing.
         */
        int getSubId(int slotId);
    }

    private static SubscriptionManagerProxy sSubscriptionManagerProxy
            = slotId -> {
                int[] subIds = SubscriptionManager.getSubId(slotId);
                if (subIds != null) {
                    return subIds[0];
                }
                return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
            };

    /**
     * Testing function used to mock SubscriptionManager in testing
     * @hide
     */
    @VisibleForTesting
    public static void setSubscriptionManager(SubscriptionManagerProxy proxy) {
        sSubscriptionManagerProxy = proxy;
    }

    private void log(String s) {
        Rlog.d(TAG + " [" + mSlotId + "]", s);
    }

    private void logi(String s) {
        Rlog.i(TAG + " [" + mSlotId + "]", s);
    }

    private void loge(String s) {
        Rlog.e(TAG + " [" + mSlotId + "]", s);
    }

    private void loge(String s, Throwable t) {
        Rlog.e(TAG + " [" + mSlotId + "]", s, t);
    }
}