JingleConnectionManager.java

   1package eu.siacs.conversations.xmpp.jingle;
   2
   3import android.telecom.TelecomManager;
   4import android.telecom.VideoProfile;
   5import android.util.Base64;
   6import android.util.Log;
   7
   8import androidx.annotation.Nullable;
   9
  10import com.google.common.base.Objects;
  11import com.google.common.base.Optional;
  12import com.google.common.base.Preconditions;
  13import com.google.common.cache.Cache;
  14import com.google.common.cache.CacheBuilder;
  15import com.google.common.collect.Collections2;
  16import com.google.common.collect.ComparisonChain;
  17import com.google.common.collect.ImmutableSet;
  18
  19import eu.siacs.conversations.R;
  20import eu.siacs.conversations.Config;
  21import eu.siacs.conversations.entities.Account;
  22import eu.siacs.conversations.entities.Contact;
  23import eu.siacs.conversations.entities.Conversation;
  24import eu.siacs.conversations.entities.Conversational;
  25import eu.siacs.conversations.entities.Message;
  26import eu.siacs.conversations.entities.RtpSessionStatus;
  27import eu.siacs.conversations.entities.Transferable;
  28import eu.siacs.conversations.services.AbstractConnectionManager;
  29import eu.siacs.conversations.services.CallIntegration;
  30import eu.siacs.conversations.services.CallIntegrationConnectionService;
  31import eu.siacs.conversations.services.XmppConnectionService;
  32import eu.siacs.conversations.xml.Element;
  33import eu.siacs.conversations.xml.Namespace;
  34import eu.siacs.conversations.xmpp.Jid;
  35import eu.siacs.conversations.xmpp.XmppConnection;
  36import eu.siacs.conversations.xmpp.jingle.stanzas.Content;
  37import eu.siacs.conversations.xmpp.jingle.stanzas.GenericDescription;
  38import eu.siacs.conversations.xmpp.jingle.stanzas.Propose;
  39import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
  40import eu.siacs.conversations.xmpp.jingle.stanzas.RtpDescription;
  41import eu.siacs.conversations.xmpp.jingle.transports.InbandBytestreamsTransport;
  42import eu.siacs.conversations.xmpp.jingle.transports.Transport;
  43
  44import im.conversations.android.xmpp.model.jingle.Jingle;
  45import im.conversations.android.xmpp.model.stanza.Iq;
  46
  47import java.lang.ref.WeakReference;
  48import java.security.SecureRandom;
  49import java.util.Arrays;
  50import java.util.Collection;
  51import java.util.HashMap;
  52import java.util.List;
  53import java.util.Map;
  54import java.util.Set;
  55import java.util.concurrent.ConcurrentHashMap;
  56import java.util.concurrent.Executors;
  57import java.util.concurrent.ScheduledExecutorService;
  58import java.util.concurrent.ScheduledFuture;
  59import java.util.concurrent.TimeUnit;
  60
  61public class JingleConnectionManager extends AbstractConnectionManager {
  62    public static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE =
  63            Executors.newSingleThreadScheduledExecutor();
  64    private final HashMap<RtpSessionProposal, DeviceDiscoveryState> rtpSessionProposals =
  65            new HashMap<>();
  66    private final ConcurrentHashMap<AbstractJingleConnection.Id, AbstractJingleConnection>
  67            connections = new ConcurrentHashMap<>();
  68
  69    private final Cache<PersistableSessionId, TerminatedRtpSession> terminatedSessions =
  70            CacheBuilder.newBuilder().expireAfterWrite(24, TimeUnit.HOURS).build();
  71
  72    public JingleConnectionManager(XmppConnectionService service) {
  73        super(service);
  74    }
  75
  76    static String nextRandomId() {
  77        final byte[] id = new byte[16];
  78        new SecureRandom().nextBytes(id);
  79        return Base64.encodeToString(id, Base64.NO_WRAP | Base64.NO_PADDING | Base64.URL_SAFE);
  80    }
  81
  82    public void deliverPacket(final Account account, final Iq packet) {
  83        final var jingle = packet.getExtension(Jingle.class);
  84        Preconditions.checkNotNull(
  85                jingle, "Passed iq packet w/o jingle extension to Connection Manager");
  86        final String sessionId = jingle.getSessionId();
  87        final Jingle.Action action = jingle.getAction();
  88        if (sessionId == null) {
  89            respondWithJingleError(account, packet, "unknown-session", "item-not-found", "cancel");
  90            return;
  91        }
  92        if (action == null) {
  93            respondWithJingleError(account, packet, null, "bad-request", "cancel");
  94            return;
  95        }
  96        final AbstractJingleConnection.Id id =
  97                AbstractJingleConnection.Id.of(account, packet, jingle);
  98        final AbstractJingleConnection existingJingleConnection = connections.get(id);
  99        if (existingJingleConnection != null) {
 100            existingJingleConnection.deliverPacket(packet);
 101        } else if (action == Jingle.Action.SESSION_INITIATE) {
 102            final Jid from = packet.getFrom();
 103            final Content content = jingle.getJingleContent();
 104            final String descriptionNamespace =
 105                    content == null ? null : content.getDescriptionNamespace();
 106            final AbstractJingleConnection connection;
 107            if (Namespace.JINGLE_APPS_FILE_TRANSFER.equals(descriptionNamespace)) {
 108                connection = new JingleFileTransferConnection(this, id, from);
 109            } else if (Namespace.JINGLE_APPS_RTP.equals(descriptionNamespace)
 110                    && isUsingClearNet(account)) {
 111                final boolean sessionEnded =
 112                        this.terminatedSessions.asMap().containsKey(PersistableSessionId.of(id));
 113                final boolean stranger =
 114                        isWithStrangerAndStrangerNotificationsAreOff(account, id.with);
 115                final boolean busy = isBusy();
 116                if (busy || sessionEnded || stranger) {
 117                    Log.d(
 118                            Config.LOGTAG,
 119                            id.account.getJid().asBareJid()
 120                                    + ": rejected session with "
 121                                    + id.with
 122                                    + " because busy. sessionEnded="
 123                                    + sessionEnded
 124                                    + ", stranger="
 125                                    + stranger);
 126                    sendSessionTerminate(account, packet, id);
 127                    if (busy || stranger) {
 128                        writeLogMissedIncoming(
 129                                account,
 130                                id.with,
 131                                id.sessionId,
 132                                null,
 133                                System.currentTimeMillis(),
 134                                stranger);
 135                    }
 136                    return;
 137                }
 138                connection = new JingleRtpConnection(this, id, from);
 139            } else {
 140                respondWithJingleError(
 141                        account, packet, "unsupported-info", "feature-not-implemented", "cancel");
 142                return;
 143            }
 144            connections.put(id, connection);
 145            mXmppConnectionService.updateConversationUi();
 146            connection.deliverPacket(packet);
 147            if (connection instanceof JingleRtpConnection rtpConnection) {
 148                addNewIncomingCall(rtpConnection);
 149            }
 150        } else {
 151            Log.d(Config.LOGTAG, "unable to route jingle packet: " + packet);
 152            respondWithJingleError(account, packet, "unknown-session", "item-not-found", "cancel");
 153        }
 154    }
 155
 156    private void addNewIncomingCall(final JingleRtpConnection rtpConnection) {
 157        if (true) {
 158            return; // We do this inside the startRinging in the rtpConnection now so that fallback is possible
 159        }
 160        if (rtpConnection.isTerminated()) {
 161            Log.d(
 162                    Config.LOGTAG,
 163                    "skip call integration because something must have gone during initiate");
 164            return;
 165        }
 166        if (CallIntegrationConnectionService.addNewIncomingCall(
 167                mXmppConnectionService, rtpConnection.getId())) {
 168            return;
 169        }
 170        rtpConnection.integrationFailure();
 171    }
 172
 173    private void sendSessionTerminate(
 174            final Account account, final Iq request, final AbstractJingleConnection.Id id) {
 175        mXmppConnectionService.sendIqPacket(
 176                account, request.generateResponse(Iq.Type.RESULT), null);
 177        final var iq = new Iq(Iq.Type.SET);
 178        iq.setTo(id.with);
 179        final var sessionTermination =
 180                iq.addExtension(new Jingle(Jingle.Action.SESSION_TERMINATE, id.sessionId));
 181        sessionTermination.setReason(Reason.BUSY, null);
 182        mXmppConnectionService.sendIqPacket(account, iq, null);
 183    }
 184
 185    private boolean isUsingClearNet(final Account account) {
 186        return !account.isOnion() && !mXmppConnectionService.useTorToConnect();
 187    }
 188
 189    public boolean isBusy() {
 190        for (final AbstractJingleConnection connection : this.connections.values()) {
 191            if (connection instanceof JingleRtpConnection rtpConnection) {
 192                if (connection.isTerminated() && rtpConnection.getCallIntegration().isDestroyed()) {
 193                    continue;
 194                }
 195                return true;
 196            }
 197        }
 198        synchronized (this.rtpSessionProposals) {
 199            if (this.rtpSessionProposals.containsValue(DeviceDiscoveryState.DISCOVERED)) return true;
 200            if (this.rtpSessionProposals.containsValue(DeviceDiscoveryState.SEARCHING)) return true;
 201            if (this.rtpSessionProposals.containsValue(DeviceDiscoveryState.SEARCHING_ACKNOWLEDGED)) return true;
 202            return false;
 203        }
 204    }
 205
 206    public boolean hasJingleRtpConnection(final Account account) {
 207        for (AbstractJingleConnection connection : this.connections.values()) {
 208            if (connection instanceof JingleRtpConnection rtpConnection) {
 209                if (rtpConnection.isTerminated()) {
 210                    continue;
 211                }
 212                if (rtpConnection.id.account == account) {
 213                    return true;
 214                }
 215            }
 216        }
 217        return false;
 218    }
 219
 220    private Optional<RtpSessionProposal> findMatchingSessionProposal(
 221            final Account account, final Jid with, final Set<Media> media) {
 222        synchronized (this.rtpSessionProposals) {
 223            for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 224                    this.rtpSessionProposals.entrySet()) {
 225                final RtpSessionProposal proposal = entry.getKey();
 226                final DeviceDiscoveryState state = entry.getValue();
 227                final boolean openProposal =
 228                        state == DeviceDiscoveryState.DISCOVERED
 229                                || state == DeviceDiscoveryState.SEARCHING
 230                                || state == DeviceDiscoveryState.SEARCHING_ACKNOWLEDGED;
 231                if (openProposal
 232                        && proposal.account == account
 233                        && proposal.with.equals(with.asBareJid())
 234                        && proposal.media.equals(media)) {
 235                    return Optional.of(proposal);
 236                }
 237            }
 238        }
 239        return Optional.absent();
 240    }
 241
 242    private String hasMatchingRtpSession(final Account account, final Jid with, final Set<Media> media) {
 243        for (AbstractJingleConnection connection : this.connections.values()) {
 244            if (connection instanceof JingleRtpConnection rtpConnection) {
 245                if (rtpConnection.isTerminated()) {
 246                    continue;
 247                }
 248                if (rtpConnection.getId().account == account
 249                        && rtpConnection.getId().with.asBareJid().equals(with.asBareJid())
 250                        && rtpConnection.getMedia().equals(media)) {
 251                    return rtpConnection.getId().sessionId;
 252                }
 253            }
 254        }
 255        return null;
 256    }
 257
 258    private boolean isWithStrangerAndStrangerNotificationsAreOff(final Account account, Jid with) {
 259        final var ringFromStrangers = mXmppConnectionService.getBooleanPreference("ring_from_strangers", R.bool.notifications_from_strangers);
 260        if (ringFromStrangers) return false;
 261        final var conversation = mXmppConnectionService.findOrCreateConversation(account, with, false, true);
 262        return conversation.isWithStranger();
 263    }
 264
 265    ScheduledFuture<?> schedule(
 266            final Runnable runnable, final long delay, final TimeUnit timeUnit) {
 267        return SCHEDULED_EXECUTOR_SERVICE.schedule(runnable, delay, timeUnit);
 268    }
 269
 270    void respondWithJingleError(
 271            final Account account,
 272            final Iq original,
 273            final String jingleCondition,
 274            final String condition,
 275            final String conditionType) {
 276        final Iq response = original.generateResponse(Iq.Type.ERROR);
 277        final Element error = response.addChild("error");
 278        error.setAttribute("type", conditionType);
 279        error.addChild(condition, "urn:ietf:params:xml:ns:xmpp-stanzas");
 280        if (jingleCondition != null) {
 281            error.addChild(jingleCondition, Namespace.JINGLE_ERRORS);
 282        }
 283        account.getXmppConnection().sendIqPacket(response, null);
 284    }
 285
 286    public void deliverMessage(
 287            final Account account,
 288            final Jid to,
 289            final Jid from,
 290            final Element message,
 291            String remoteMsgId,
 292            String serverMsgId,
 293            long timestamp) {
 294        Preconditions.checkArgument(Namespace.JINGLE_MESSAGE.equals(message.getNamespace()));
 295        final String sessionId = message.getAttribute("id");
 296        if (sessionId == null) {
 297            return;
 298        }
 299        if ("accept".equals(message.getName()) || "reject".equals(message.getName())) {
 300            for (AbstractJingleConnection connection : connections.values()) {
 301                if (connection instanceof JingleRtpConnection rtpConnection) {
 302                    final AbstractJingleConnection.Id id = connection.getId();
 303                    if (id.account == account && id.sessionId.equals(sessionId)) {
 304                        rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
 305                        return;
 306                    }
 307                }
 308            }
 309            if ("accept".equals(message.getName())) return;
 310        }
 311        final boolean fromSelf = from.asBareJid().equals(account.getJid().asBareJid());
 312        // XEP version 0.6.0 sends proceed, reject, ringing to bare jid
 313        final boolean addressedDirectly = to != null && to.equals(account.getJid());
 314        final AbstractJingleConnection.Id id;
 315        if (fromSelf) {
 316            if (to != null && to.isFullJid()) {
 317                id = AbstractJingleConnection.Id.of(account, to, sessionId);
 318            } else {
 319                return;
 320            }
 321        } else {
 322            id = AbstractJingleConnection.Id.of(account, from, sessionId);
 323        }
 324        final AbstractJingleConnection existingJingleConnection = connections.get(id);
 325        if (existingJingleConnection != null) {
 326            if (existingJingleConnection instanceof JingleRtpConnection) {
 327                ((JingleRtpConnection) existingJingleConnection)
 328                        .deliveryMessage(from, message, serverMsgId, timestamp);
 329            } else {
 330                Log.d(
 331                        Config.LOGTAG,
 332                        account.getJid().asBareJid()
 333                                + ": "
 334                                + existingJingleConnection.getClass().getName()
 335                                + " does not support jingle messages");
 336            }
 337            return;
 338        }
 339
 340        if (fromSelf) {
 341            if ("proceed".equals(message.getName())) {
 342                final Conversation c =
 343                        mXmppConnectionService.findOrCreateConversation(
 344                                account, id.with, false, false);
 345                final Message previousBusy = c.findRtpSession(sessionId, Message.STATUS_RECEIVED);
 346                if (previousBusy != null) {
 347                    previousBusy.setBody(new RtpSessionStatus(true, 0).toString());
 348                    if (serverMsgId != null) {
 349                        previousBusy.setServerMsgId(serverMsgId);
 350                    }
 351                    previousBusy.setTime(timestamp);
 352                    mXmppConnectionService.updateMessage(previousBusy, true);
 353                    Log.d(
 354                            Config.LOGTAG,
 355                            id.account.getJid().asBareJid()
 356                                    + ": updated previous busy because call got picked up by another device");
 357                    mXmppConnectionService.getNotificationService().clearMissedCall(previousBusy);
 358                    return;
 359                }
 360            }
 361            // TODO handle reject for cases where we don’t have carbon copies (normally reject is to
 362            // be sent to own bare jid as well)
 363            Log.d(
 364                    Config.LOGTAG,
 365                    account.getJid().asBareJid() + ": ignore jingle message from self");
 366            return;
 367        }
 368
 369        if ("propose".equals(message.getName())) {
 370            final Propose propose = Propose.upgrade(message);
 371            final List<GenericDescription> descriptions = propose.getDescriptions();
 372            final Collection<RtpDescription> rtpDescriptions =
 373                    Collections2.transform(
 374                            Collections2.filter(descriptions, d -> d instanceof RtpDescription),
 375                            input -> (RtpDescription) input);
 376            if (rtpDescriptions.size() > 0
 377                    && rtpDescriptions.size() == descriptions.size()
 378                    && isUsingClearNet(account)) {
 379                final Collection<Media> media =
 380                        Collections2.transform(rtpDescriptions, RtpDescription::getMedia);
 381                if (media.contains(Media.UNKNOWN)) {
 382                    Log.d(
 383                            Config.LOGTAG,
 384                            account.getJid().asBareJid()
 385                                    + ": encountered unknown media in session proposal. "
 386                                    + propose);
 387                    return;
 388                }
 389                final Optional<RtpSessionProposal> matchingSessionProposal =
 390                        findMatchingSessionProposal(account, id.with, ImmutableSet.copyOf(media));
 391                if (matchingSessionProposal.isPresent()) {
 392                    final String ourSessionId = matchingSessionProposal.get().sessionId;
 393                    final String theirSessionId = id.sessionId;
 394                    if (ComparisonChain.start()
 395                                    .compare(ourSessionId, theirSessionId)
 396                                    .compare(
 397                                            account.getJid().toEscapedString(),
 398                                            id.with.toEscapedString())
 399                                    .result()
 400                            > 0) {
 401                        Log.d(
 402                                Config.LOGTAG,
 403                                account.getJid().asBareJid()
 404                                        + ": our session lost tie break. automatically accepting their session. winning Session="
 405                                        + theirSessionId);
 406                        // TODO a retract for this reason should probably include some indication of
 407                        // tie break
 408                        retractSessionProposal(matchingSessionProposal.get());
 409                        final JingleRtpConnection rtpConnection =
 410                                new JingleRtpConnection(this, id, from);
 411                        this.connections.put(id, rtpConnection);
 412                        rtpConnection.setProposedMedia(ImmutableSet.copyOf(media));
 413                        rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
 414                        addNewIncomingCall(rtpConnection);
 415                        // TODO actually do the automatic accept?!
 416                    } else {
 417                        Log.d(
 418                                Config.LOGTAG,
 419                                account.getJid().asBareJid()
 420                                        + ": our session won tie break. waiting for other party to accept. winningSession="
 421                                        + ourSessionId);
 422                        // TODO reject their session with <tie-break/>?
 423                    }
 424                    return;
 425                }
 426                final boolean stranger =
 427                        isWithStrangerAndStrangerNotificationsAreOff(account, id.with);
 428                if (isBusy() || stranger) {
 429                    writeLogMissedIncoming(
 430                            account,
 431                            id.with.asBareJid(),
 432                            id.sessionId,
 433                            serverMsgId,
 434                            timestamp,
 435                            stranger);
 436                    if (stranger) {
 437                        Log.d(
 438                                Config.LOGTAG,
 439                                id.account.getJid().asBareJid()
 440                                        + ": ignoring call proposal from stranger "
 441                                        + id.with);
 442                        return;
 443                    }
 444                    final int activeDevices = account.activeDevicesWithRtpCapability();
 445                    Log.d(Config.LOGTAG, "active devices with rtp capability: " + activeDevices);
 446                    if (activeDevices == 0) {
 447                        final var reject =
 448                                mXmppConnectionService
 449                                        .getMessageGenerator()
 450                                        .sessionReject(from, sessionId);
 451                        mXmppConnectionService.sendMessagePacket(account, reject);
 452                    } else {
 453                        Log.d(
 454                                Config.LOGTAG,
 455                                id.account.getJid().asBareJid()
 456                                        + ": ignoring proposal because busy on this device but there are other devices");
 457                    }
 458                } else {
 459                    final JingleRtpConnection rtpConnection =
 460                            new JingleRtpConnection(this, id, from);
 461                    this.connections.put(id, rtpConnection);
 462                    rtpConnection.setProposedMedia(ImmutableSet.copyOf(media));
 463                    rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
 464                    addNewIncomingCall(rtpConnection);
 465                }
 466            } else {
 467                Log.d(
 468                        Config.LOGTAG,
 469                        account.getJid().asBareJid()
 470                                + ": unable to react to proposed session with "
 471                                + rtpDescriptions.size()
 472                                + " rtp descriptions of "
 473                                + descriptions.size()
 474                                + " total descriptions");
 475            }
 476        } else if (addressedDirectly && "proceed".equals(message.getName())) {
 477            synchronized (rtpSessionProposals) {
 478                final RtpSessionProposal proposal =
 479                        getRtpSessionProposal(account, from.asBareJid(), sessionId);
 480                if (proposal != null) {
 481                    rtpSessionProposals.remove(proposal);
 482                    final JingleRtpConnection rtpConnection =
 483                            new JingleRtpConnection(
 484                                    this, id, account.getJid(), proposal.callIntegration);
 485                    rtpConnection.setProposedMedia(proposal.media);
 486                    this.connections.put(id, rtpConnection);
 487                    rtpConnection.transitionOrThrow(AbstractJingleConnection.State.PROPOSED);
 488                    rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
 489                } else {
 490                    Log.d(
 491                            Config.LOGTAG,
 492                            account.getJid().asBareJid()
 493                                    + ": no rtp session ("
 494                                    + sessionId
 495                                    + ") proposal found for "
 496                                    + from
 497                                    + " to deliver proceed");
 498                    if (remoteMsgId == null) {
 499                        return;
 500                    }
 501                    final var errorMessage =
 502                            new im.conversations.android.xmpp.model.stanza.Message();
 503                    errorMessage.setTo(from);
 504                    errorMessage.setId(remoteMsgId);
 505                    errorMessage.setType(
 506                            im.conversations.android.xmpp.model.stanza.Message.Type.ERROR);
 507                    final Element error = errorMessage.addChild("error");
 508                    error.setAttribute("code", "404");
 509                    error.setAttribute("type", "cancel");
 510                    error.addChild("item-not-found", "urn:ietf:params:xml:ns:xmpp-stanzas");
 511                    mXmppConnectionService.sendMessagePacket(account, errorMessage);
 512                }
 513            }
 514        } else if (addressedDirectly && "reject".equals(message.getName())) {
 515            final RtpSessionProposal proposal =
 516                    getRtpSessionProposal(account, from.asBareJid(), sessionId);
 517            synchronized (rtpSessionProposals) {
 518                if (proposal != null) {
 519                    setTerminalSessionState(proposal, RtpEndUserState.DECLINED_OR_BUSY);
 520                    rtpSessionProposals.remove(proposal);
 521                    proposal.callIntegration.busy();
 522                    writeLogMissedOutgoing(
 523                            account, proposal.with, proposal.sessionId, serverMsgId, timestamp);
 524                    mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 525                            account,
 526                            proposal.with,
 527                            proposal.sessionId,
 528                            RtpEndUserState.DECLINED_OR_BUSY);
 529                } else {
 530                    Log.d(
 531                            Config.LOGTAG,
 532                            account.getJid().asBareJid()
 533                                    + ": no rtp session proposal found for "
 534                                    + from
 535                                    + " to deliver reject");
 536                }
 537            }
 538        } else if (addressedDirectly && "ringing".equals(message.getName())) {
 539            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + from + " started ringing");
 540            updateProposedSessionDiscovered(
 541                    account, from, sessionId, DeviceDiscoveryState.DISCOVERED);
 542        } else {
 543            Log.d(
 544                    Config.LOGTAG,
 545                    account.getJid()
 546                            + ": received out of order jingle message from="
 547                            + from
 548                            + ", message="
 549                            + message
 550                            + ", addressedDirectly="
 551                            + addressedDirectly);
 552        }
 553    }
 554
 555    private RtpSessionProposal getRtpSessionProposal(
 556            final Account account, Jid from, String sessionId) {
 557        for (RtpSessionProposal rtpSessionProposal : rtpSessionProposals.keySet()) {
 558            if (rtpSessionProposal.sessionId.equals(sessionId)
 559                    && rtpSessionProposal.with.equals(from)
 560                    && rtpSessionProposal.account.getJid().equals(account.getJid())) {
 561                return rtpSessionProposal;
 562            }
 563        }
 564        return null;
 565    }
 566
 567    private void writeLogMissedOutgoing(
 568            final Account account,
 569            Jid with,
 570            final String sessionId,
 571            String serverMsgId,
 572            long timestamp) {
 573        final Conversation conversation =
 574                mXmppConnectionService.findOrCreateConversation(
 575                        account, with.asBareJid(), false, false);
 576        final Message message =
 577                new Message(conversation, Message.STATUS_SEND, Message.TYPE_RTP_SESSION, sessionId);
 578        message.setBody(new RtpSessionStatus(false, 0).toString());
 579        message.setServerMsgId(serverMsgId);
 580        message.setTime(timestamp);
 581        writeMessage(message);
 582    }
 583
 584    private void writeLogMissedIncoming(
 585            final Account account,
 586            final Jid with,
 587            final String sessionId,
 588            final String serverMsgId,
 589            final long timestamp,
 590            final boolean stranger) {
 591        final Conversation conversation =
 592                mXmppConnectionService.findOrCreateConversation(
 593                        account, with.asBareJid(), false, false);
 594        final Message message =
 595                new Message(
 596                        conversation, Message.STATUS_RECEIVED, Message.TYPE_RTP_SESSION, sessionId);
 597        message.setBody(new RtpSessionStatus(false, 0).toString());
 598        message.setServerMsgId(serverMsgId);
 599        message.setTime(timestamp);
 600        message.setCounterpart(with);
 601        writeMessage(message);
 602        if (stranger) {
 603            return;
 604        }
 605        mXmppConnectionService.getNotificationService().pushMissedCallNow(message);
 606    }
 607
 608    private void writeMessage(final Message message) {
 609        final Conversational conversational = message.getConversation();
 610        if (conversational instanceof Conversation) {
 611            ((Conversation) conversational).add(message);
 612            mXmppConnectionService.databaseBackend.createMessage(message);
 613            mXmppConnectionService.updateConversationUi();
 614        } else {
 615            throw new IllegalStateException("Somehow the conversation in a message was a stub");
 616        }
 617    }
 618
 619    public void startJingleFileTransfer(final Message message) {
 620        Preconditions.checkArgument(
 621                message.isFileOrImage(), "Message is not of type file or image");
 622        final Transferable old = message.getTransferable();
 623        if (old != null) {
 624            old.cancel();
 625        }
 626        final JingleFileTransferConnection connection =
 627                new JingleFileTransferConnection(this, message);
 628        this.connections.put(connection.getId(), connection);
 629        connection.sendSessionInitialize();
 630    }
 631
 632    public Optional<OngoingRtpSession> getOngoingRtpConnection(final Contact contact) {
 633        for (final Map.Entry<AbstractJingleConnection.Id, AbstractJingleConnection> entry :
 634                this.connections.entrySet()) {
 635            if (entry.getValue() instanceof JingleRtpConnection jingleRtpConnection) {
 636                final AbstractJingleConnection.Id id = entry.getKey();
 637                if (id.account == contact.getAccount()
 638                        && id.with.asBareJid().equals(contact.getJid().asBareJid())) {
 639                    return Optional.of(jingleRtpConnection);
 640                }
 641            }
 642        }
 643        synchronized (this.rtpSessionProposals) {
 644            for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 645                    this.rtpSessionProposals.entrySet()) {
 646                final RtpSessionProposal proposal = entry.getKey();
 647                if (proposal.account == contact.getAccount()
 648                        && contact.getJid().asBareJid().equals(proposal.with)) {
 649                    final DeviceDiscoveryState preexistingState = entry.getValue();
 650                    if (preexistingState != null
 651                            && preexistingState != DeviceDiscoveryState.FAILED) {
 652                        return Optional.of(proposal);
 653                    }
 654                }
 655            }
 656        }
 657        return Optional.absent();
 658    }
 659
 660    public JingleRtpConnection getOngoingRtpConnection() {
 661        for (final AbstractJingleConnection jingleConnection : this.connections.values()) {
 662            if (jingleConnection instanceof JingleRtpConnection jingleRtpConnection) {
 663                if (jingleRtpConnection.isTerminated()) {
 664                    continue;
 665                }
 666                return jingleRtpConnection;
 667            }
 668        }
 669        return null;
 670    }
 671
 672    void finishConnectionOrThrow(final AbstractJingleConnection connection) {
 673        final AbstractJingleConnection.Id id = connection.getId();
 674        if (this.connections.remove(id) == null) {
 675            throw new IllegalStateException(
 676                    String.format("Unable to finish connection with id=%s", id));
 677        }
 678        // update chat UI to remove 'ongoing call' icon
 679        mXmppConnectionService.updateConversationUi();
 680    }
 681
 682    public boolean fireJingleRtpConnectionStateUpdates() {
 683        for (final AbstractJingleConnection connection : this.connections.values()) {
 684            if (connection instanceof JingleRtpConnection jingleRtpConnection) {
 685                if (jingleRtpConnection.isTerminated()) {
 686                    continue;
 687                }
 688                jingleRtpConnection.fireStateUpdate();
 689                return true;
 690            }
 691        }
 692        return false;
 693    }
 694
 695    public void retractSessionProposal(final Account account, final Jid with) {
 696        synchronized (this.rtpSessionProposals) {
 697            RtpSessionProposal matchingProposal = null;
 698            for (RtpSessionProposal proposal : this.rtpSessionProposals.keySet()) {
 699                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
 700                    matchingProposal = proposal;
 701                    break;
 702                }
 703            }
 704            if (matchingProposal != null) {
 705                retractSessionProposal(matchingProposal, false);
 706            }
 707        }
 708    }
 709
 710    private void retractSessionProposal(final RtpSessionProposal rtpSessionProposal) {
 711        retractSessionProposal(rtpSessionProposal, true);
 712    }
 713
 714    private void retractSessionProposal(
 715            final RtpSessionProposal rtpSessionProposal, final boolean refresh) {
 716        final Account account = rtpSessionProposal.account;
 717        Log.d(
 718                Config.LOGTAG,
 719                account.getJid().asBareJid()
 720                        + ": retracting rtp session proposal with "
 721                        + rtpSessionProposal.with);
 722        this.rtpSessionProposals.remove(rtpSessionProposal);
 723        rtpSessionProposal.callIntegration.retracted();
 724        if (refresh) {
 725            mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 726                    account,
 727                    rtpSessionProposal.with,
 728                    rtpSessionProposal.sessionId,
 729                    RtpEndUserState.RETRACTED);
 730        }
 731        final var messagePacket =
 732                mXmppConnectionService.getMessageGenerator().sessionRetract(rtpSessionProposal);
 733        writeLogMissedOutgoing(
 734                account,
 735                rtpSessionProposal.with,
 736                rtpSessionProposal.sessionId,
 737                null,
 738                System.currentTimeMillis());
 739        mXmppConnectionService.sendMessagePacket(account, messagePacket);
 740    }
 741
 742    public JingleRtpConnection initializeRtpSession(
 743            final Account account, final Jid with, final Set<Media> media) {
 744        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with);
 745        final JingleRtpConnection rtpConnection =
 746                new JingleRtpConnection(this, id, account.getJid());
 747        rtpConnection.setProposedMedia(media);
 748        rtpConnection.getCallIntegration().startAudioRouting();
 749        this.connections.put(id, rtpConnection);
 750        rtpConnection.sendSessionInitiate();
 751        return rtpConnection;
 752    }
 753
 754    public @Nullable RtpSessionProposal proposeJingleRtpSession(
 755            final Account account, final Jid with, final Set<Media> media) {
 756        synchronized (this.rtpSessionProposals) {
 757            for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 758                    this.rtpSessionProposals.entrySet()) {
 759                final RtpSessionProposal proposal = entry.getKey();
 760                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
 761                    final DeviceDiscoveryState preexistingState = entry.getValue();
 762                    if (preexistingState != null
 763                            && preexistingState != DeviceDiscoveryState.FAILED) {
 764                        final RtpEndUserState endUserState = preexistingState.toEndUserState();
 765                        mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 766                                account, with, proposal.sessionId, endUserState);
 767                        return proposal;
 768                    }
 769                }
 770            }
 771            if (isBusy()) {
 772                if (hasMatchingRtpSession(account, with, media) != null) {
 773                    Log.d(
 774                            Config.LOGTAG,
 775                            "ignoring request to propose jingle session because the other party already created one for us");
 776                    // TODO return something that we can parse the connection of of
 777                    return null;
 778                }
 779                throw new IllegalStateException("There is already a running RTP session");
 780            }
 781            final CallIntegration callIntegration =
 782                    new CallIntegration(mXmppConnectionService.getApplicationContext());
 783            callIntegration.setVideoState(
 784                    Media.audioOnly(media)
 785                            ? VideoProfile.STATE_AUDIO_ONLY
 786                            : VideoProfile.STATE_BIDIRECTIONAL);
 787            callIntegration.setAddress(
 788                    CallIntegration.address(with.asBareJid()), TelecomManager.PRESENTATION_ALLOWED);
 789            final var contact = account.getRoster().getContact(with);
 790            callIntegration.setCallerDisplayName(
 791                    contact.getDisplayName(), TelecomManager.PRESENTATION_ALLOWED);
 792            callIntegration.setInitialAudioDevice(CallIntegration.initialAudioDevice(media));
 793            callIntegration.startAudioRouting();
 794            final RtpSessionProposal proposal =
 795                    RtpSessionProposal.of(account, with.asBareJid(), media, callIntegration);
 796            callIntegration.setCallback(new ProposalStateCallback(proposal));
 797            this.rtpSessionProposals.put(proposal, DeviceDiscoveryState.SEARCHING);
 798            mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 799                    account, proposal.with, proposal.sessionId, RtpEndUserState.FINDING_DEVICE);
 800            final var messagePacket =
 801                    mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
 802            // in privacy preserving environments 'propose' is only ACKed when we have presence
 803            // subscription (to not leak presence). Therefor a timeout is only appropriate for
 804            // contacts where we can expect the 'ringing' response
 805            final boolean triggerTimeout =
 806                    Config.JINGLE_MESSAGE_INIT_STRICT_DEVICE_TIMEOUT
 807                            || contact.mutualPresenceSubscription();
 808            SCHEDULED_EXECUTOR_SERVICE.schedule(
 809                    () -> {
 810                        final var currentProposalState = rtpSessionProposals.get(proposal);
 811                        Log.d(
 812                                Config.LOGTAG,
 813                                "proposal state after timeout " + currentProposalState);
 814                        if (triggerTimeout
 815                                && Arrays.asList(
 816                                                DeviceDiscoveryState.SEARCHING,
 817                                                DeviceDiscoveryState.SEARCHING_ACKNOWLEDGED)
 818                                        .contains(currentProposalState)) {
 819                            deviceDiscoveryTimeout(account, proposal);
 820                        }
 821                    },
 822                    Config.DEVICE_DISCOVERY_TIMEOUT,
 823                    TimeUnit.MILLISECONDS);
 824            mXmppConnectionService.sendMessagePacket(account, messagePacket);
 825            return proposal;
 826        }
 827    }
 828
 829    private void deviceDiscoveryTimeout(final Account account, final RtpSessionProposal proposal) {
 830        // 'endUserState' is what we display in the UI. There is an argument to use 'BUSY' here
 831        // instead
 832        // we may or may not want to match this with the tone we are playing (see
 833        // callIntegration.error() or callIntegration.busy())
 834        final var endUserState = RtpEndUserState.CONNECTIVITY_ERROR;
 835        Log.d(Config.LOGTAG, "call proposal still in device discovery state after timeout");
 836        setTerminalSessionState(proposal, endUserState);
 837
 838        rtpSessionProposals.remove(proposal);
 839        // error and busy would probably be both appropriate tones to play
 840        // playing the error tone is probably more in line with what happens on a technical level
 841        // and would be a similar UX to what happens when you call a user that doesn't exist
 842        // playing the busy tone might be more in line with what some telephony networks play
 843        proposal.callIntegration.error();
 844        writeLogMissedOutgoing(
 845                account, proposal.with, proposal.sessionId, null, System.currentTimeMillis());
 846        mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 847                account, proposal.with, proposal.sessionId, endUserState);
 848
 849        final var retraction =
 850                mXmppConnectionService.getMessageGenerator().sessionRetract(proposal);
 851        mXmppConnectionService.sendMessagePacket(account, retraction);
 852    }
 853
 854    public void sendJingleMessageFinish(
 855            final Contact contact, final String sessionId, final Reason reason) {
 856        final var account = contact.getAccount();
 857        final var messagePacket =
 858                mXmppConnectionService
 859                        .getMessageGenerator()
 860                        .sessionFinish(contact.getJid(), sessionId, reason);
 861        mXmppConnectionService.sendMessagePacket(account, messagePacket);
 862    }
 863
 864    public Optional<RtpSessionProposal> matchingProposal(final Account account, final Jid with) {
 865        synchronized (this.rtpSessionProposals) {
 866            for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 867                    this.rtpSessionProposals.entrySet()) {
 868                final RtpSessionProposal proposal = entry.getKey();
 869                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
 870                    return Optional.of(proposal);
 871                }
 872            }
 873        }
 874        return Optional.absent();
 875    }
 876
 877    public boolean hasMatchingProposal(final Account account, final Jid with) {
 878        synchronized (this.rtpSessionProposals) {
 879            for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 880                    this.rtpSessionProposals.entrySet()) {
 881                final var state = entry.getValue();
 882                final RtpSessionProposal proposal = entry.getKey();
 883                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
 884                    // CallIntegrationConnectionService starts RtpSessionActivity with ACTION_VIEW
 885                    // and an EXTRA_LAST_REPORTED_STATE of DISCOVERING devices. however due to
 886                    // possible race conditions the state might have already moved on so we are
 887                    // going
 888                    // to update the UI
 889                    final RtpEndUserState endUserState = state.toEndUserState();
 890                    mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 891                            account, proposal.with, proposal.sessionId, endUserState);
 892                    return true;
 893                }
 894            }
 895        }
 896        return false;
 897    }
 898
 899    public void deliverIbbPacket(final Account account, final Iq packet) {
 900        final String sid;
 901        final Element payload;
 902        final InbandBytestreamsTransport.PacketType packetType;
 903        if (packet.hasChild("open", Namespace.IBB)) {
 904            packetType = InbandBytestreamsTransport.PacketType.OPEN;
 905            payload = packet.findChild("open", Namespace.IBB);
 906            sid = payload.getAttribute("sid");
 907        } else if (packet.hasChild("data", Namespace.IBB)) {
 908            packetType = InbandBytestreamsTransport.PacketType.DATA;
 909            payload = packet.findChild("data", Namespace.IBB);
 910            sid = payload.getAttribute("sid");
 911        } else if (packet.hasChild("close", Namespace.IBB)) {
 912            packetType = InbandBytestreamsTransport.PacketType.CLOSE;
 913            payload = packet.findChild("close", Namespace.IBB);
 914            sid = payload.getAttribute("sid");
 915        } else {
 916            packetType = null;
 917            payload = null;
 918            sid = null;
 919        }
 920        if (sid == null) {
 921            Log.d(
 922                    Config.LOGTAG,
 923                    account.getJid().asBareJid() + ": unable to deliver ibb packet. missing sid");
 924            account.getXmppConnection().sendIqPacket(packet.generateResponse(Iq.Type.ERROR), null);
 925            return;
 926        }
 927        for (final AbstractJingleConnection connection : this.connections.values()) {
 928            if (connection instanceof JingleFileTransferConnection fileTransfer) {
 929                final Transport transport = fileTransfer.getTransport();
 930                if (transport instanceof InbandBytestreamsTransport inBandTransport) {
 931                    if (sid.equals(inBandTransport.getStreamId())) {
 932                        if (inBandTransport.deliverPacket(packetType, packet.getFrom(), payload)) {
 933                            account.getXmppConnection()
 934                                    .sendIqPacket(packet.generateResponse(Iq.Type.RESULT), null);
 935                        } else {
 936                            account.getXmppConnection()
 937                                    .sendIqPacket(packet.generateResponse(Iq.Type.ERROR), null);
 938                        }
 939                        return;
 940                    }
 941                }
 942            }
 943        }
 944        Log.d(
 945                Config.LOGTAG,
 946                account.getJid().asBareJid() + ": unable to deliver ibb packet with sid=" + sid);
 947        account.getXmppConnection().sendIqPacket(packet.generateResponse(Iq.Type.ERROR), null);
 948    }
 949
 950    public void notifyRebound(final Account account) {
 951        for (final AbstractJingleConnection connection : this.connections.values()) {
 952            connection.notifyRebound();
 953        }
 954        final XmppConnection xmppConnection = account.getXmppConnection();
 955        if (xmppConnection != null && xmppConnection.getFeatures().sm()) {
 956            resendSessionProposals(account);
 957        }
 958    }
 959
 960    public WeakReference<JingleRtpConnection> findJingleRtpConnection(
 961            Account account, Jid with, String sessionId) {
 962        final AbstractJingleConnection.Id id =
 963                AbstractJingleConnection.Id.of(account, with, sessionId);
 964        final AbstractJingleConnection connection = connections.get(id);
 965        if (connection instanceof JingleRtpConnection) {
 966            return new WeakReference<>((JingleRtpConnection) connection);
 967        }
 968        return null;
 969    }
 970
 971    public JingleRtpConnection findJingleRtpConnection(final Account account, final Jid with) {
 972        for (final AbstractJingleConnection connection : this.connections.values()) {
 973            if (connection instanceof JingleRtpConnection rtpConnection) {
 974                if (rtpConnection.isTerminated()) {
 975                    continue;
 976                }
 977                final var id = rtpConnection.getId();
 978                if (id.account == account && account.getJid().equals(with)) {
 979                    return rtpConnection;
 980                }
 981            }
 982        }
 983        return null;
 984    }
 985
 986    private void resendSessionProposals(final Account account) {
 987        synchronized (this.rtpSessionProposals) {
 988            for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 989                    this.rtpSessionProposals.entrySet()) {
 990                final RtpSessionProposal proposal = entry.getKey();
 991                if (entry.getValue() == DeviceDiscoveryState.SEARCHING
 992                        && proposal.account == account) {
 993                    Log.d(
 994                            Config.LOGTAG,
 995                            account.getJid().asBareJid()
 996                                    + ": resending session proposal to "
 997                                    + proposal.with);
 998                    final var messagePacket =
 999                            mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
1000                    mXmppConnectionService.sendMessagePacket(account, messagePacket);
1001                }
1002            }
1003        }
1004    }
1005
1006    public void updateProposedSessionDiscovered(
1007            Account account, Jid from, String sessionId, final DeviceDiscoveryState target) {
1008        synchronized (this.rtpSessionProposals) {
1009            final RtpSessionProposal sessionProposal =
1010                    getRtpSessionProposal(account, from.asBareJid(), sessionId);
1011            final DeviceDiscoveryState currentState =
1012                    sessionProposal == null ? null : rtpSessionProposals.get(sessionProposal);
1013            if (currentState == null) {
1014                Log.d(
1015                        Config.LOGTAG,
1016                        "unable to find session proposal for session id "
1017                                + sessionId
1018                                + " target="
1019                                + target);
1020                return;
1021            }
1022            if (currentState == DeviceDiscoveryState.DISCOVERED) {
1023                Log.d(
1024                        Config.LOGTAG,
1025                        "session proposal already at discovered. not going to fall back");
1026                return;
1027            }
1028
1029            Log.d(
1030                    Config.LOGTAG,
1031                    account.getJid().asBareJid()
1032                            + ": flagging session "
1033                            + sessionId
1034                            + " as "
1035                            + target);
1036
1037            final RtpEndUserState endUserState = target.toEndUserState();
1038
1039            if (target == DeviceDiscoveryState.FAILED) {
1040                Log.d(Config.LOGTAG, "removing session proposal after failure");
1041                setTerminalSessionState(sessionProposal, endUserState);
1042                this.rtpSessionProposals.remove(sessionProposal);
1043                sessionProposal.getCallIntegration().error();
1044                mXmppConnectionService.notifyJingleRtpConnectionUpdate(
1045                        account, sessionProposal.with, sessionProposal.sessionId, endUserState);
1046                return;
1047            }
1048
1049            this.rtpSessionProposals.put(sessionProposal, target);
1050
1051            if (endUserState == RtpEndUserState.RINGING) {
1052                sessionProposal.callIntegration.setDialing();
1053            }
1054
1055            mXmppConnectionService.notifyJingleRtpConnectionUpdate(
1056                    account, sessionProposal.with, sessionProposal.sessionId, endUserState);
1057        }
1058    }
1059
1060    public void rejectRtpSession(final String sessionId) {
1061        for (final AbstractJingleConnection connection : this.connections.values()) {
1062            if (connection.getId().sessionId.equals(sessionId)) {
1063                if (connection instanceof JingleRtpConnection) {
1064                    try {
1065                        ((JingleRtpConnection) connection).rejectCall();
1066                        return;
1067                    } catch (final IllegalStateException e) {
1068                        Log.w(
1069                                Config.LOGTAG,
1070                                "race condition on rejecting call from notification",
1071                                e);
1072                    }
1073                }
1074            }
1075        }
1076    }
1077
1078    public void endRtpSession(final String sessionId) {
1079        for (final AbstractJingleConnection connection : this.connections.values()) {
1080            if (connection.getId().sessionId.equals(sessionId)) {
1081                if (connection instanceof JingleRtpConnection) {
1082                    ((JingleRtpConnection) connection).endCall();
1083                }
1084            }
1085        }
1086    }
1087
1088    public void failProceed(
1089            Account account, final Jid with, final String sessionId, final String message) {
1090        final AbstractJingleConnection.Id id =
1091                AbstractJingleConnection.Id.of(account, with, sessionId);
1092        final AbstractJingleConnection existingJingleConnection = connections.get(id);
1093        if (existingJingleConnection instanceof JingleRtpConnection) {
1094            ((JingleRtpConnection) existingJingleConnection).deliverFailedProceed(message);
1095        }
1096    }
1097
1098    void ensureConnectionIsRegistered(final AbstractJingleConnection connection) {
1099        if (connections.containsValue(connection)) {
1100            return;
1101        }
1102        final IllegalStateException e =
1103                new IllegalStateException(
1104                        "JingleConnection has not been registered with connection manager");
1105        Log.e(Config.LOGTAG, "ensureConnectionIsRegistered() failed. Going to throw", e);
1106        throw e;
1107    }
1108
1109    void setTerminalSessionState(
1110            AbstractJingleConnection.Id id, final RtpEndUserState state, final Set<Media> media) {
1111        this.terminatedSessions.put(
1112                PersistableSessionId.of(id), new TerminatedRtpSession(state, media));
1113    }
1114
1115    void setTerminalSessionState(final RtpSessionProposal proposal, final RtpEndUserState state) {
1116        this.terminatedSessions.put(
1117                PersistableSessionId.of(proposal), new TerminatedRtpSession(state, proposal.media));
1118    }
1119
1120    public TerminatedRtpSession getTerminalSessionState(final Jid with, final String sessionId) {
1121        return this.terminatedSessions.getIfPresent(new PersistableSessionId(with, sessionId));
1122    }
1123
1124    private static class PersistableSessionId {
1125        private final Jid with;
1126        private final String sessionId;
1127
1128        private PersistableSessionId(Jid with, String sessionId) {
1129            this.with = with;
1130            this.sessionId = sessionId;
1131        }
1132
1133        public static PersistableSessionId of(final AbstractJingleConnection.Id id) {
1134            return new PersistableSessionId(id.with, id.sessionId);
1135        }
1136
1137        public static PersistableSessionId of(final RtpSessionProposal proposal) {
1138            return new PersistableSessionId(proposal.with, proposal.sessionId);
1139        }
1140
1141        @Override
1142        public boolean equals(Object o) {
1143            if (this == o) return true;
1144            if (o == null || getClass() != o.getClass()) return false;
1145            PersistableSessionId that = (PersistableSessionId) o;
1146            return Objects.equal(with, that.with) && Objects.equal(sessionId, that.sessionId);
1147        }
1148
1149        @Override
1150        public int hashCode() {
1151            return Objects.hashCode(with, sessionId);
1152        }
1153    }
1154
1155    public static class TerminatedRtpSession {
1156        public final RtpEndUserState state;
1157        public final Set<Media> media;
1158
1159        TerminatedRtpSession(RtpEndUserState state, Set<Media> media) {
1160            this.state = state;
1161            this.media = media;
1162        }
1163    }
1164
1165    public enum DeviceDiscoveryState {
1166        SEARCHING,
1167        SEARCHING_ACKNOWLEDGED,
1168        DISCOVERED,
1169        FAILED;
1170
1171        public RtpEndUserState toEndUserState() {
1172            return switch (this) {
1173                case SEARCHING, SEARCHING_ACKNOWLEDGED -> RtpEndUserState.FINDING_DEVICE;
1174                case DISCOVERED -> RtpEndUserState.RINGING;
1175                default -> RtpEndUserState.CONNECTIVITY_ERROR;
1176            };
1177        }
1178    }
1179
1180    public static class RtpSessionProposal implements OngoingRtpSession {
1181        public final Jid with;
1182        public final String sessionId;
1183        public final Set<Media> media;
1184        private final Account account;
1185        private final CallIntegration callIntegration;
1186
1187        private RtpSessionProposal(
1188                Account account,
1189                Jid with,
1190                String sessionId,
1191                Set<Media> media,
1192                final CallIntegration callIntegration) {
1193            this.account = account;
1194            this.with = with;
1195            this.sessionId = sessionId;
1196            this.media = media;
1197            this.callIntegration = callIntegration;
1198        }
1199
1200        public static RtpSessionProposal of(
1201                Account account,
1202                Jid with,
1203                Set<Media> media,
1204                final CallIntegration callIntegration) {
1205            return new RtpSessionProposal(account, with, nextRandomId(), media, callIntegration);
1206        }
1207
1208        @Override
1209        public boolean equals(Object o) {
1210            if (this == o) return true;
1211            if (o == null || getClass() != o.getClass()) return false;
1212            RtpSessionProposal proposal = (RtpSessionProposal) o;
1213            return Objects.equal(account.getJid(), proposal.account.getJid())
1214                    && Objects.equal(with, proposal.with)
1215                    && Objects.equal(sessionId, proposal.sessionId);
1216        }
1217
1218        @Override
1219        public int hashCode() {
1220            return Objects.hashCode(account.getJid(), with, sessionId);
1221        }
1222
1223        @Override
1224        public Account getAccount() {
1225            return account;
1226        }
1227
1228        @Override
1229        public Jid getWith() {
1230            return with;
1231        }
1232
1233        @Override
1234        public String getSessionId() {
1235            return sessionId;
1236        }
1237
1238        @Override
1239        public CallIntegration getCallIntegration() {
1240            return this.callIntegration;
1241        }
1242
1243        @Override
1244        public Set<Media> getMedia() {
1245            return this.media;
1246        }
1247    }
1248
1249    public class ProposalStateCallback implements CallIntegration.Callback {
1250
1251        private final RtpSessionProposal proposal;
1252
1253        public ProposalStateCallback(final RtpSessionProposal proposal) {
1254            this.proposal = proposal;
1255        }
1256
1257        @Override
1258        public void onCallIntegrationShowIncomingCallUi() {}
1259
1260        @Override
1261        public void onCallIntegrationDisconnect() {
1262            Log.d(Config.LOGTAG, "a phone call has just been started. retracting proposal");
1263            retractSessionProposal(this.proposal);
1264        }
1265
1266        @Override
1267        public void onAudioDeviceChanged(
1268                final CallIntegration.AudioDevice selectedAudioDevice,
1269                final Set<CallIntegration.AudioDevice> availableAudioDevices) {
1270            mXmppConnectionService.notifyJingleRtpConnectionUpdate(
1271                    selectedAudioDevice, availableAudioDevices);
1272        }
1273
1274        @Override
1275        public void onCallIntegrationReject() {}
1276
1277        @Override
1278        public void onCallIntegrationAnswer() {}
1279
1280        @Override
1281        public void onCallIntegrationSilence() {}
1282
1283        @Override
1284        public void onCallIntegrationMicrophoneEnabled(boolean enabled) {}
1285
1286        @Override
1287        public boolean applyDtmfTone(final String dtmf) {
1288            return false;
1289        }
1290    }
1291}