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