JingleConnectionManager.java

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