1package eu.siacs.conversations.xmpp.jingle;
   2
   3import android.telecom.TelecomManager;
   4import android.telecom.VideoProfile;
   5import android.util.Base64;
   6import android.util.Log;
   7import androidx.annotation.Nullable;
   8import com.google.common.base.Objects;
   9import com.google.common.base.Optional;
  10import com.google.common.base.Preconditions;
  11import com.google.common.cache.Cache;
  12import com.google.common.cache.CacheBuilder;
  13import com.google.common.collect.Collections2;
  14import com.google.common.collect.ComparisonChain;
  15import com.google.common.collect.ImmutableSet;
  16
  17import eu.siacs.conversations.R;
  18import eu.siacs.conversations.Config;
  19import eu.siacs.conversations.entities.Account;
  20import eu.siacs.conversations.entities.Contact;
  21import eu.siacs.conversations.entities.Conversation;
  22import eu.siacs.conversations.entities.Conversational;
  23import eu.siacs.conversations.entities.Message;
  24import eu.siacs.conversations.entities.RtpSessionStatus;
  25import eu.siacs.conversations.entities.Transferable;
  26import eu.siacs.conversations.services.AbstractConnectionManager;
  27import eu.siacs.conversations.services.CallIntegration;
  28import eu.siacs.conversations.services.CallIntegrationConnectionService;
  29import eu.siacs.conversations.services.XmppConnectionService;
  30import eu.siacs.conversations.xml.Element;
  31import eu.siacs.conversations.xml.Namespace;
  32import eu.siacs.conversations.xmpp.Jid;
  33import eu.siacs.conversations.xmpp.XmppConnection;
  34import eu.siacs.conversations.xmpp.jingle.stanzas.Content;
  35import eu.siacs.conversations.xmpp.jingle.stanzas.GenericDescription;
  36import eu.siacs.conversations.xmpp.jingle.stanzas.Propose;
  37import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
  38import eu.siacs.conversations.xmpp.jingle.stanzas.RtpDescription;
  39import eu.siacs.conversations.xmpp.jingle.transports.InbandBytestreamsTransport;
  40import eu.siacs.conversations.xmpp.jingle.transports.Transport;
  41import im.conversations.android.xmpp.model.jingle.Jingle;
  42import im.conversations.android.xmpp.model.stanza.Iq;
  43import java.lang.ref.WeakReference;
  44import java.security.SecureRandom;
  45import java.util.Arrays;
  46import java.util.Collection;
  47import java.util.HashMap;
  48import java.util.List;
  49import java.util.Map;
  50import java.util.Set;
  51import java.util.concurrent.ConcurrentHashMap;
  52import java.util.concurrent.Executors;
  53import java.util.concurrent.ScheduledExecutorService;
  54import java.util.concurrent.ScheduledFuture;
  55import java.util.concurrent.TimeUnit;
  56
  57public class JingleConnectionManager extends AbstractConnectionManager {
  58    public static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE =
  59            Executors.newSingleThreadScheduledExecutor();
  60    private final HashMap<RtpSessionProposal, DeviceDiscoveryState> rtpSessionProposals =
  61            new HashMap<>();
  62    private final ConcurrentHashMap<AbstractJingleConnection.Id, AbstractJingleConnection>
  63            connections = new ConcurrentHashMap<>();
  64
  65    private final Cache<PersistableSessionId, TerminatedRtpSession> terminatedSessions =
  66            CacheBuilder.newBuilder().expireAfterWrite(24, TimeUnit.HOURS).build();
  67
  68    public JingleConnectionManager(XmppConnectionService service) {
  69        super(service);
  70    }
  71
  72    static String nextRandomId() {
  73        final byte[] id = new byte[16];
  74        new SecureRandom().nextBytes(id);
  75        return Base64.encodeToString(id, Base64.NO_WRAP | Base64.NO_PADDING | Base64.URL_SAFE);
  76    }
  77
  78    public void deliverPacket(final Account account, final Iq packet) {
  79        final var jingle = packet.getExtension(Jingle.class);
  80        Preconditions.checkNotNull(
  81                jingle, "Passed iq packet w/o jingle extension to Connection Manager");
  82        final String sessionId = jingle.getSessionId();
  83        final Jingle.Action action = jingle.getAction();
  84        if (sessionId == null) {
  85            respondWithJingleError(account, packet, "unknown-session", "item-not-found", "cancel");
  86            return;
  87        }
  88        if (action == null) {
  89            respondWithJingleError(account, packet, null, "bad-request", "cancel");
  90            return;
  91        }
  92        final AbstractJingleConnection.Id id =
  93                AbstractJingleConnection.Id.of(account, packet, jingle);
  94        final AbstractJingleConnection existingJingleConnection = connections.get(id);
  95        if (existingJingleConnection != null) {
  96            existingJingleConnection.deliverPacket(packet);
  97        } else if (action == Jingle.Action.SESSION_INITIATE) {
  98            final Jid from = packet.getFrom();
  99            final Content content = jingle.getJingleContent();
 100            final String descriptionNamespace =
 101                    content == null ? null : content.getDescriptionNamespace();
 102            final AbstractJingleConnection connection;
 103            if (Namespace.JINGLE_APPS_FILE_TRANSFER.equals(descriptionNamespace)) {
 104                connection = new JingleFileTransferConnection(this, id, from);
 105            } else if (Namespace.JINGLE_APPS_RTP.equals(descriptionNamespace)
 106                    && isUsingClearNet(account)) {
 107                final boolean sessionEnded =
 108                        this.terminatedSessions.asMap().containsKey(PersistableSessionId.of(id));
 109                final boolean stranger =
 110                        isWithStrangerAndStrangerNotificationsAreOff(account, id.with);
 111                final boolean busy = isBusy();
 112                if (busy || sessionEnded || stranger) {
 113                    Log.d(
 114                            Config.LOGTAG,
 115                            id.account.getJid().asBareJid()
 116                                    + ": rejected session with "
 117                                    + id.with
 118                                    + " because busy. sessionEnded="
 119                                    + sessionEnded
 120                                    + ", stranger="
 121                                    + stranger);
 122                    sendSessionTerminate(account, packet, id);
 123                    if (busy || stranger) {
 124                        writeLogMissedIncoming(
 125                                account,
 126                                id.with,
 127                                id.sessionId,
 128                                null,
 129                                System.currentTimeMillis(),
 130                                stranger);
 131                    }
 132                    return;
 133                }
 134                connection = new JingleRtpConnection(this, id, from);
 135            } else {
 136                respondWithJingleError(
 137                        account, packet, "unsupported-info", "feature-not-implemented", "cancel");
 138                return;
 139            }
 140            connections.put(id, connection);
 141            mXmppConnectionService.updateConversationUi();
 142            connection.deliverPacket(packet);
 143            if (connection instanceof JingleRtpConnection rtpConnection) {
 144                addNewIncomingCall(rtpConnection);
 145            }
 146        } else {
 147            Log.d(Config.LOGTAG, "unable to route jingle packet: " + packet);
 148            respondWithJingleError(account, packet, "unknown-session", "item-not-found", "cancel");
 149        }
 150    }
 151
 152    private void addNewIncomingCall(final JingleRtpConnection rtpConnection) {
 153        if (true) {
 154            return; // We do this inside the startRinging in the rtpConnection now so that fallback is possible
 155        }
 156        if (rtpConnection.isTerminated()) {
 157            Log.d(
 158                    Config.LOGTAG,
 159                    "skip call integration because something must have gone during initiate");
 160            return;
 161        }
 162        if (CallIntegrationConnectionService.addNewIncomingCall(
 163                mXmppConnectionService, rtpConnection.getId())) {
 164            return;
 165        }
 166        rtpConnection.integrationFailure();
 167    }
 168
 169    private void sendSessionTerminate(
 170            final Account account, final Iq request, final AbstractJingleConnection.Id id) {
 171        mXmppConnectionService.sendIqPacket(
 172                account, request.generateResponse(Iq.Type.RESULT), null);
 173        final var iq = new Iq(Iq.Type.SET);
 174        iq.setTo(id.with);
 175        final var sessionTermination =
 176                iq.addExtension(new Jingle(Jingle.Action.SESSION_TERMINATE, id.sessionId));
 177        sessionTermination.setReason(Reason.BUSY, null);
 178        mXmppConnectionService.sendIqPacket(account, iq, null);
 179    }
 180
 181    private boolean isUsingClearNet(final Account account) {
 182        return !account.isOnion() && !mXmppConnectionService.useTorToConnect();
 183    }
 184
 185    public boolean isBusy() {
 186        for (final AbstractJingleConnection connection : this.connections.values()) {
 187            if (connection instanceof JingleRtpConnection rtpConnection) {
 188                if (connection.isTerminated() && rtpConnection.getCallIntegration().isDestroyed()) {
 189                    continue;
 190                }
 191                return true;
 192            }
 193        }
 194        synchronized (this.rtpSessionProposals) {
 195            if (this.rtpSessionProposals.containsValue(DeviceDiscoveryState.DISCOVERED)) return true;
 196            if (this.rtpSessionProposals.containsValue(DeviceDiscoveryState.SEARCHING)) return true;
 197            if (this.rtpSessionProposals.containsValue(DeviceDiscoveryState.SEARCHING_ACKNOWLEDGED)) return true;
 198            return false;
 199        }
 200    }
 201
 202    public boolean hasJingleRtpConnection(final Account account) {
 203        for (AbstractJingleConnection connection : this.connections.values()) {
 204            if (connection instanceof JingleRtpConnection rtpConnection) {
 205                if (rtpConnection.isTerminated()) {
 206                    continue;
 207                }
 208                if (rtpConnection.id.account == account) {
 209                    return true;
 210                }
 211            }
 212        }
 213        return false;
 214    }
 215
 216    private Optional<RtpSessionProposal> findMatchingSessionProposal(
 217            final Account account, final Jid with, final Set<Media> media) {
 218        synchronized (this.rtpSessionProposals) {
 219            for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 220                    this.rtpSessionProposals.entrySet()) {
 221                final RtpSessionProposal proposal = entry.getKey();
 222                final DeviceDiscoveryState state = entry.getValue();
 223                final boolean openProposal =
 224                        state == DeviceDiscoveryState.DISCOVERED
 225                                || state == DeviceDiscoveryState.SEARCHING
 226                                || state == DeviceDiscoveryState.SEARCHING_ACKNOWLEDGED;
 227                if (openProposal
 228                        && proposal.account == account
 229                        && proposal.with.equals(with.asBareJid())
 230                        && proposal.media.equals(media)) {
 231                    return Optional.of(proposal);
 232                }
 233            }
 234        }
 235        return Optional.absent();
 236    }
 237
 238    private String hasMatchingRtpSession(final Account account, final Jid with, final Set<Media> media) {
 239        for (AbstractJingleConnection connection : this.connections.values()) {
 240            if (connection instanceof JingleRtpConnection rtpConnection) {
 241                if (rtpConnection.isTerminated()) {
 242                    continue;
 243                }
 244                if (rtpConnection.getId().account == account
 245                        && rtpConnection.getId().with.asBareJid().equals(with.asBareJid())
 246                        && rtpConnection.getMedia().equals(media)) {
 247                    return rtpConnection.getId().sessionId;
 248                }
 249            }
 250        }
 251        return null;
 252    }
 253
 254    private boolean isWithStrangerAndStrangerNotificationsAreOff(final Account account, Jid with) {
 255        final var ringFromStrangers = mXmppConnectionService.getBooleanPreference("ring_from_strangers", R.bool.notifications_from_strangers);
 256        if (ringFromStrangers) return false;
 257        final var conversation = mXmppConnectionService.findOrCreateConversation(account, with, false, true);
 258        return conversation.isWithStranger();
 259    }
 260
 261    ScheduledFuture<?> schedule(
 262            final Runnable runnable, final long delay, final TimeUnit timeUnit) {
 263        return SCHEDULED_EXECUTOR_SERVICE.schedule(runnable, delay, timeUnit);
 264    }
 265
 266    void respondWithJingleError(
 267            final Account account,
 268            final Iq original,
 269            final String jingleCondition,
 270            final String condition,
 271            final String conditionType) {
 272        final Iq response = original.generateResponse(Iq.Type.ERROR);
 273        final Element error = response.addChild("error");
 274        error.setAttribute("type", conditionType);
 275        error.addChild(condition, "urn:ietf:params:xml:ns:xmpp-stanzas");
 276        if (jingleCondition != null) {
 277            error.addChild(jingleCondition, Namespace.JINGLE_ERRORS);
 278        }
 279        account.getXmppConnection().sendIqPacket(response, null);
 280    }
 281
 282    public void deliverMessage(
 283            final Account account,
 284            final Jid to,
 285            final Jid from,
 286            final Element message,
 287            String remoteMsgId,
 288            String serverMsgId,
 289            long timestamp) {
 290        Preconditions.checkArgument(Namespace.JINGLE_MESSAGE.equals(message.getNamespace()));
 291        final String sessionId = message.getAttribute("id");
 292        if (sessionId == null) {
 293            return;
 294        }
 295        if ("accept".equals(message.getName()) || "reject".equals(message.getName())) {
 296            for (AbstractJingleConnection connection : connections.values()) {
 297                if (connection instanceof JingleRtpConnection rtpConnection) {
 298                    final AbstractJingleConnection.Id id = connection.getId();
 299                    if (id.account == account && id.sessionId.equals(sessionId)) {
 300                        rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
 301                        return;
 302                    }
 303                }
 304            }
 305            if ("accept".equals(message.getName())) return;
 306        }
 307        final boolean fromSelf = from.asBareJid().equals(account.getJid().asBareJid());
 308        // XEP version 0.6.0 sends proceed, reject, ringing to bare jid
 309        final boolean addressedDirectly = to != null && to.equals(account.getJid());
 310        final AbstractJingleConnection.Id id;
 311        if (fromSelf) {
 312            if (to != null && to.isFullJid()) {
 313                id = AbstractJingleConnection.Id.of(account, to, sessionId);
 314            } else {
 315                return;
 316            }
 317        } else {
 318            id = AbstractJingleConnection.Id.of(account, from, sessionId);
 319        }
 320        final AbstractJingleConnection existingJingleConnection = connections.get(id);
 321        if (existingJingleConnection != null) {
 322            if (existingJingleConnection instanceof JingleRtpConnection) {
 323                ((JingleRtpConnection) existingJingleConnection)
 324                        .deliveryMessage(from, message, serverMsgId, timestamp);
 325            } else {
 326                Log.d(
 327                        Config.LOGTAG,
 328                        account.getJid().asBareJid()
 329                                + ": "
 330                                + existingJingleConnection.getClass().getName()
 331                                + " does not support jingle messages");
 332            }
 333            return;
 334        }
 335
 336        if (fromSelf) {
 337            if ("proceed".equals(message.getName())) {
 338                final Conversation c =
 339                        mXmppConnectionService.findOrCreateConversation(
 340                                account, id.with, false, false);
 341                final Message previousBusy = c.findRtpSession(sessionId, Message.STATUS_RECEIVED);
 342                if (previousBusy != null) {
 343                    previousBusy.setBody(new RtpSessionStatus(true, 0).toString());
 344                    if (serverMsgId != null) {
 345                        previousBusy.setServerMsgId(serverMsgId);
 346                    }
 347                    previousBusy.setTime(timestamp);
 348                    mXmppConnectionService.updateMessage(previousBusy, true);
 349                    Log.d(
 350                            Config.LOGTAG,
 351                            id.account.getJid().asBareJid()
 352                                    + ": updated previous busy because call got picked up by"
 353                                    + " another device");
 354                    mXmppConnectionService.getNotificationService().clearMissedCall(previousBusy);
 355                    return;
 356                }
 357            }
 358            // TODO handle reject for cases where we don’t have carbon copies (normally reject is to
 359            // be sent to own bare jid as well)
 360            Log.d(
 361                    Config.LOGTAG,
 362                    account.getJid().asBareJid() + ": ignore jingle message from self");
 363            return;
 364        }
 365
 366        if ("propose".equals(message.getName())) {
 367            final Propose propose = Propose.upgrade(message);
 368            final List<GenericDescription> descriptions = propose.getDescriptions();
 369            final Collection<RtpDescription> rtpDescriptions =
 370                    Collections2.transform(
 371                            Collections2.filter(descriptions, d -> d instanceof RtpDescription),
 372                            input -> (RtpDescription) input);
 373            if (rtpDescriptions.size() > 0
 374                    && rtpDescriptions.size() == descriptions.size()
 375                    && isUsingClearNet(account)) {
 376                final Collection<Media> media =
 377                        Collections2.transform(rtpDescriptions, RtpDescription::getMedia);
 378                if (media.contains(Media.UNKNOWN)) {
 379                    Log.d(
 380                            Config.LOGTAG,
 381                            account.getJid().asBareJid()
 382                                    + ": encountered unknown media in session proposal. "
 383                                    + propose);
 384                    return;
 385                }
 386                final Optional<RtpSessionProposal> matchingSessionProposal =
 387                        findMatchingSessionProposal(account, id.with, ImmutableSet.copyOf(media));
 388                if (matchingSessionProposal.isPresent()) {
 389                    final String ourSessionId = matchingSessionProposal.get().sessionId;
 390                    final String theirSessionId = id.sessionId;
 391                    if (ComparisonChain.start()
 392                                    .compare(ourSessionId, theirSessionId)
 393                                    .compare(account.getJid().toString(), id.with.toString())
 394                                    .result()
 395                            > 0) {
 396                        Log.d(
 397                                Config.LOGTAG,
 398                                account.getJid().asBareJid()
 399                                        + ": our session lost tie break. automatically accepting"
 400                                        + " their session. winning Session="
 401                                        + theirSessionId);
 402                        // TODO a retract for this reason should probably include some indication of
 403                        // tie break
 404                        retractSessionProposal(matchingSessionProposal.get());
 405                        final JingleRtpConnection rtpConnection =
 406                                new JingleRtpConnection(this, id, from);
 407                        this.connections.put(id, rtpConnection);
 408                        rtpConnection.setProposedMedia(ImmutableSet.copyOf(media));
 409                        rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
 410                        addNewIncomingCall(rtpConnection);
 411                        // TODO actually do the automatic accept?!
 412                    } else {
 413                        Log.d(
 414                                Config.LOGTAG,
 415                                account.getJid().asBareJid()
 416                                        + ": our session won tie break. waiting for other party to"
 417                                        + " accept. winningSession="
 418                                        + ourSessionId);
 419                        // TODO reject their session with <tie-break/>?
 420                    }
 421                    return;
 422                }
 423                final boolean stranger =
 424                        isWithStrangerAndStrangerNotificationsAreOff(account, id.with);
 425                if (isBusy() || stranger) {
 426                    writeLogMissedIncoming(
 427                            account,
 428                            id.with.asBareJid(),
 429                            id.sessionId,
 430                            serverMsgId,
 431                            timestamp,
 432                            stranger);
 433                    if (stranger) {
 434                        Log.d(
 435                                Config.LOGTAG,
 436                                id.account.getJid().asBareJid()
 437                                        + ": ignoring call proposal from stranger "
 438                                        + id.with);
 439                        return;
 440                    }
 441                    final int activeDevices = account.activeDevicesWithRtpCapability();
 442                    Log.d(Config.LOGTAG, "active devices with rtp capability: " + activeDevices);
 443                    if (activeDevices == 0) {
 444                        final var reject =
 445                                mXmppConnectionService
 446                                        .getMessageGenerator()
 447                                        .sessionReject(from, sessionId);
 448                        mXmppConnectionService.sendMessagePacket(account, reject);
 449                    } else {
 450                        Log.d(
 451                                Config.LOGTAG,
 452                                id.account.getJid().asBareJid()
 453                                        + ": ignoring proposal because busy on this device but"
 454                                        + " there are other devices");
 455                    }
 456                } else {
 457                    final JingleRtpConnection rtpConnection =
 458                            new JingleRtpConnection(this, id, from);
 459                    this.connections.put(id, rtpConnection);
 460                    rtpConnection.setProposedMedia(ImmutableSet.copyOf(media));
 461                    rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
 462                    addNewIncomingCall(rtpConnection);
 463                }
 464            } else {
 465                Log.d(
 466                        Config.LOGTAG,
 467                        account.getJid().asBareJid()
 468                                + ": unable to react to proposed session with "
 469                                + rtpDescriptions.size()
 470                                + " rtp descriptions of "
 471                                + descriptions.size()
 472                                + " total descriptions");
 473            }
 474        } else if (addressedDirectly && "proceed".equals(message.getName())) {
 475            synchronized (rtpSessionProposals) {
 476                final RtpSessionProposal proposal =
 477                        getRtpSessionProposal(account, from.asBareJid(), sessionId);
 478                if (proposal != null) {
 479                    rtpSessionProposals.remove(proposal);
 480                    final JingleRtpConnection rtpConnection =
 481                            new JingleRtpConnection(
 482                                    this, id, account.getJid(), proposal.callIntegration);
 483                    rtpConnection.setProposedMedia(proposal.media);
 484                    this.connections.put(id, rtpConnection);
 485                    rtpConnection.transitionOrThrow(AbstractJingleConnection.State.PROPOSED);
 486                    rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
 487                } else {
 488                    Log.d(
 489                            Config.LOGTAG,
 490                            account.getJid().asBareJid()
 491                                    + ": no rtp session ("
 492                                    + sessionId
 493                                    + ") proposal found for "
 494                                    + from
 495                                    + " to deliver proceed");
 496                    if (remoteMsgId == null) {
 497                        return;
 498                    }
 499                    final var errorMessage =
 500                            new im.conversations.android.xmpp.model.stanza.Message();
 501                    errorMessage.setTo(from);
 502                    errorMessage.setId(remoteMsgId);
 503                    errorMessage.setType(
 504                            im.conversations.android.xmpp.model.stanza.Message.Type.ERROR);
 505                    final Element error = errorMessage.addChild("error");
 506                    error.setAttribute("code", "404");
 507                    error.setAttribute("type", "cancel");
 508                    error.addChild("item-not-found", "urn:ietf:params:xml:ns:xmpp-stanzas");
 509                    mXmppConnectionService.sendMessagePacket(account, errorMessage);
 510                }
 511            }
 512        } else if (addressedDirectly && "reject".equals(message.getName())) {
 513            final RtpSessionProposal proposal =
 514                    getRtpSessionProposal(account, from.asBareJid(), sessionId);
 515            synchronized (rtpSessionProposals) {
 516                if (proposal != null) {
 517                    setTerminalSessionState(proposal, RtpEndUserState.DECLINED_OR_BUSY);
 518                    rtpSessionProposals.remove(proposal);
 519                    proposal.callIntegration.busy();
 520                    writeLogMissedOutgoing(
 521                            account, proposal.with, proposal.sessionId, serverMsgId, timestamp);
 522                    mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 523                            account,
 524                            proposal.with,
 525                            proposal.sessionId,
 526                            RtpEndUserState.DECLINED_OR_BUSY);
 527                } else {
 528                    Log.d(
 529                            Config.LOGTAG,
 530                            account.getJid().asBareJid()
 531                                    + ": no rtp session proposal found for "
 532                                    + from
 533                                    + " to deliver reject");
 534                }
 535            }
 536        } else if (addressedDirectly && "ringing".equals(message.getName())) {
 537            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + from + " started ringing");
 538            updateProposedSessionDiscovered(
 539                    account, from, sessionId, DeviceDiscoveryState.DISCOVERED);
 540        } else {
 541            Log.d(
 542                    Config.LOGTAG,
 543                    account.getJid()
 544                            + ": received out of order jingle message from="
 545                            + from
 546                            + ", message="
 547                            + message
 548                            + ", addressedDirectly="
 549                            + addressedDirectly);
 550        }
 551    }
 552
 553    private RtpSessionProposal getRtpSessionProposal(
 554            final Account account, Jid from, String sessionId) {
 555        for (RtpSessionProposal rtpSessionProposal : rtpSessionProposals.keySet()) {
 556            if (rtpSessionProposal.sessionId.equals(sessionId)
 557                    && rtpSessionProposal.with.equals(from)
 558                    && rtpSessionProposal.account.getJid().equals(account.getJid())) {
 559                return rtpSessionProposal;
 560            }
 561        }
 562        return null;
 563    }
 564
 565    private void writeLogMissedOutgoing(
 566            final Account account,
 567            Jid with,
 568            final String sessionId,
 569            String serverMsgId,
 570            long timestamp) {
 571        final Conversation conversation =
 572                mXmppConnectionService.findOrCreateConversation(
 573                        account, with.asBareJid(), false, false);
 574        final Message message =
 575                new Message(conversation, Message.STATUS_SEND, Message.TYPE_RTP_SESSION, sessionId);
 576        message.setBody(new RtpSessionStatus(false, 0).toString());
 577        message.setServerMsgId(serverMsgId);
 578        message.setTime(timestamp);
 579        writeMessage(message);
 580    }
 581
 582    private void writeLogMissedIncoming(
 583            final Account account,
 584            final Jid with,
 585            final String sessionId,
 586            final String serverMsgId,
 587            final long timestamp,
 588            final boolean stranger) {
 589        final Conversation conversation =
 590                mXmppConnectionService.findOrCreateConversation(
 591                        account, with.asBareJid(), false, false);
 592        final Message message =
 593                new Message(
 594                        conversation, Message.STATUS_RECEIVED, Message.TYPE_RTP_SESSION, sessionId);
 595        message.setBody(new RtpSessionStatus(false, 0).toString());
 596        message.setServerMsgId(serverMsgId);
 597        message.setTime(timestamp);
 598        message.setCounterpart(with);
 599        writeMessage(message);
 600        if (stranger) {
 601            return;
 602        }
 603        mXmppConnectionService.getNotificationService().pushMissedCallNow(message);
 604    }
 605
 606    private void writeMessage(final Message message) {
 607        final Conversational conversational = message.getConversation();
 608        if (conversational instanceof Conversation) {
 609            ((Conversation) conversational).add(message);
 610            mXmppConnectionService.databaseBackend.createMessage(message);
 611            mXmppConnectionService.updateConversationUi();
 612        } else {
 613            throw new IllegalStateException("Somehow the conversation in a message was a stub");
 614        }
 615    }
 616
 617    public void startJingleFileTransfer(final Message message) {
 618        Preconditions.checkArgument(
 619                message.isFileOrImage(), "Message is not of type file or image");
 620        final Transferable old = message.getTransferable();
 621        if (old != null) {
 622            old.cancel();
 623        }
 624        final JingleFileTransferConnection connection =
 625                new JingleFileTransferConnection(this, message);
 626        this.connections.put(connection.getId(), connection);
 627        connection.sendSessionInitialize();
 628    }
 629
 630    public Optional<OngoingRtpSession> getOngoingRtpConnection(final Contact contact) {
 631        for (final Map.Entry<AbstractJingleConnection.Id, AbstractJingleConnection> entry :
 632                this.connections.entrySet()) {
 633            if (entry.getValue() instanceof JingleRtpConnection jingleRtpConnection) {
 634                final AbstractJingleConnection.Id id = entry.getKey();
 635                if (id.account == contact.getAccount()
 636                        && id.with.asBareJid().equals(contact.getJid().asBareJid())) {
 637                    return Optional.of(jingleRtpConnection);
 638                }
 639            }
 640        }
 641        synchronized (this.rtpSessionProposals) {
 642            for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 643                    this.rtpSessionProposals.entrySet()) {
 644                final RtpSessionProposal proposal = entry.getKey();
 645                if (proposal.account == contact.getAccount()
 646                        && contact.getJid().asBareJid().equals(proposal.with)) {
 647                    final DeviceDiscoveryState preexistingState = entry.getValue();
 648                    if (preexistingState != null
 649                            && preexistingState != DeviceDiscoveryState.FAILED) {
 650                        return Optional.of(proposal);
 651                    }
 652                }
 653            }
 654        }
 655        return Optional.absent();
 656    }
 657
 658    public JingleRtpConnection getOngoingRtpConnection() {
 659        for (final AbstractJingleConnection jingleConnection : this.connections.values()) {
 660            if (jingleConnection instanceof JingleRtpConnection jingleRtpConnection) {
 661                if (jingleRtpConnection.isTerminated()) {
 662                    continue;
 663                }
 664                return jingleRtpConnection;
 665            }
 666        }
 667        return null;
 668    }
 669
 670    void finishConnectionOrThrow(final AbstractJingleConnection connection) {
 671        final AbstractJingleConnection.Id id = connection.getId();
 672        if (this.connections.remove(id) == null) {
 673            throw new IllegalStateException(
 674                    String.format("Unable to finish connection with id=%s", id));
 675        }
 676        // update chat UI to remove 'ongoing call' icon
 677        mXmppConnectionService.updateConversationUi();
 678    }
 679
 680    public boolean fireJingleRtpConnectionStateUpdates() {
 681        for (final AbstractJingleConnection connection : this.connections.values()) {
 682            if (connection instanceof JingleRtpConnection jingleRtpConnection) {
 683                if (jingleRtpConnection.isTerminated()) {
 684                    continue;
 685                }
 686                jingleRtpConnection.fireStateUpdate();
 687                return true;
 688            }
 689        }
 690        return false;
 691    }
 692
 693    public void retractSessionProposal(final Account account, final Jid with) {
 694        synchronized (this.rtpSessionProposals) {
 695            RtpSessionProposal matchingProposal = null;
 696            for (RtpSessionProposal proposal : this.rtpSessionProposals.keySet()) {
 697                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
 698                    matchingProposal = proposal;
 699                    break;
 700                }
 701            }
 702            if (matchingProposal != null) {
 703                retractSessionProposal(matchingProposal, false);
 704            }
 705        }
 706    }
 707
 708    private void retractSessionProposal(final RtpSessionProposal rtpSessionProposal) {
 709        retractSessionProposal(rtpSessionProposal, true);
 710    }
 711
 712    private void retractSessionProposal(
 713            final RtpSessionProposal rtpSessionProposal, final boolean refresh) {
 714        final Account account = rtpSessionProposal.account;
 715        Log.d(
 716                Config.LOGTAG,
 717                account.getJid().asBareJid()
 718                        + ": retracting rtp session proposal with "
 719                        + rtpSessionProposal.with);
 720        this.rtpSessionProposals.remove(rtpSessionProposal);
 721        rtpSessionProposal.callIntegration.retracted();
 722        if (refresh) {
 723            mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 724                    account,
 725                    rtpSessionProposal.with,
 726                    rtpSessionProposal.sessionId,
 727                    RtpEndUserState.RETRACTED);
 728        }
 729        final var messagePacket =
 730                mXmppConnectionService.getMessageGenerator().sessionRetract(rtpSessionProposal);
 731        writeLogMissedOutgoing(
 732                account,
 733                rtpSessionProposal.with,
 734                rtpSessionProposal.sessionId,
 735                null,
 736                System.currentTimeMillis());
 737        mXmppConnectionService.sendMessagePacket(account, messagePacket);
 738    }
 739
 740    public JingleRtpConnection initializeRtpSession(
 741            final Account account, final Jid with, final Set<Media> media) {
 742        final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with);
 743        final JingleRtpConnection rtpConnection =
 744                new JingleRtpConnection(this, id, account.getJid());
 745        rtpConnection.setProposedMedia(media);
 746        rtpConnection.getCallIntegration().startAudioRouting();
 747        this.connections.put(id, rtpConnection);
 748        rtpConnection.sendSessionInitiate();
 749        return rtpConnection;
 750    }
 751
 752    public @Nullable RtpSessionProposal proposeJingleRtpSession(
 753            final Account account, final Jid with, final Set<Media> media) {
 754        synchronized (this.rtpSessionProposals) {
 755            for (final Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry :
 756                    this.rtpSessionProposals.entrySet()) {
 757                final RtpSessionProposal proposal = entry.getKey();
 758                if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
 759                    final DeviceDiscoveryState preexistingState = entry.getValue();
 760                    if (preexistingState != null
 761                            && preexistingState != DeviceDiscoveryState.FAILED) {
 762                        final RtpEndUserState endUserState = preexistingState.toEndUserState();
 763                        mXmppConnectionService.notifyJingleRtpConnectionUpdate(
 764                                account, with, proposal.sessionId, endUserState);
 765                        return proposal;
 766                    }
 767                }
 768            }
 769            if (isBusy()) {
 770                if (hasMatchingRtpSession(account, with, media) != null) {
 771                    Log.d(
 772                            Config.LOGTAG,
 773                            "ignoring request to propose jingle session because the other party"
 774                                    + " already created one for us");
 775                    // TODO return something that we can parse the connection of of
 776                    return null;
 777                }
 778                throw new IllegalStateException(
 779                        "There is already a running RTP session. This should have been caught by"
 780                                + " the UI");
 781            }
 782            final CallIntegration callIntegration =
 783                    new CallIntegration(mXmppConnectionService.getApplicationContext());
 784            callIntegration.setVideoState(
 785                    Media.audioOnly(media)
 786                            ? VideoProfile.STATE_AUDIO_ONLY
 787                            : VideoProfile.STATE_BIDIRECTIONAL);
 788            callIntegration.setAddress(
 789                    CallIntegration.address(with.asBareJid()), TelecomManager.PRESENTATION_ALLOWED);
 790            final var contact = account.getRoster().getContact(with);
 791            callIntegration.setCallerDisplayName(
 792                    contact.getDisplayName(), TelecomManager.PRESENTATION_ALLOWED);
 793            callIntegration.setInitialized();
 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}