1package eu.siacs.conversations.xmpp.jingle;
2
3import android.util.Base64;
4import android.util.Log;
5
6import com.google.common.base.Objects;
7import com.google.common.base.Optional;
8import com.google.common.base.Preconditions;
9import com.google.common.cache.Cache;
10import com.google.common.cache.CacheBuilder;
11import com.google.common.collect.Collections2;
12import com.google.common.collect.ImmutableSet;
13
14import java.lang.ref.WeakReference;
15import java.security.SecureRandom;
16import java.util.Collection;
17import java.util.Collections;
18import java.util.HashMap;
19import java.util.List;
20import java.util.Map;
21import java.util.Set;
22import java.util.concurrent.ConcurrentHashMap;
23import java.util.concurrent.Executors;
24import java.util.concurrent.ScheduledExecutorService;
25import java.util.concurrent.ScheduledFuture;
26import java.util.concurrent.TimeUnit;
27
28import eu.siacs.conversations.Config;
29import eu.siacs.conversations.entities.Account;
30import eu.siacs.conversations.entities.Contact;
31import eu.siacs.conversations.entities.Conversation;
32import eu.siacs.conversations.entities.Conversational;
33import eu.siacs.conversations.entities.Message;
34import eu.siacs.conversations.entities.RtpSessionStatus;
35import eu.siacs.conversations.entities.Transferable;
36import eu.siacs.conversations.services.AbstractConnectionManager;
37import eu.siacs.conversations.services.XmppConnectionService;
38import eu.siacs.conversations.xml.Element;
39import eu.siacs.conversations.xml.Namespace;
40import eu.siacs.conversations.xmpp.OnIqPacketReceived;
41import eu.siacs.conversations.xmpp.jingle.stanzas.Content;
42import eu.siacs.conversations.xmpp.jingle.stanzas.FileTransferDescription;
43import eu.siacs.conversations.xmpp.jingle.stanzas.GenericDescription;
44import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
45import eu.siacs.conversations.xmpp.jingle.stanzas.Propose;
46import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
47import eu.siacs.conversations.xmpp.jingle.stanzas.RtpDescription;
48import eu.siacs.conversations.xmpp.stanzas.IqPacket;
49import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
50import rocks.xmpp.addr.Jid;
51
52public class JingleConnectionManager extends AbstractConnectionManager {
53 private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
54 private final HashMap<RtpSessionProposal, DeviceDiscoveryState> rtpSessionProposals = new HashMap<>();
55 private final Map<AbstractJingleConnection.Id, AbstractJingleConnection> connections = new ConcurrentHashMap<>();
56
57 private final Cache<PersistableSessionId, JingleRtpConnection.State> endedSessions = CacheBuilder.newBuilder()
58 .expireAfterWrite(30, TimeUnit.MINUTES)
59 .build();
60
61 private HashMap<Jid, JingleCandidate> primaryCandidates = new HashMap<>();
62
63 public JingleConnectionManager(XmppConnectionService service) {
64 super(service);
65 }
66
67 static String nextRandomId() {
68 final byte[] id = new byte[16];
69 new SecureRandom().nextBytes(id);
70 return Base64.encodeToString(id, Base64.NO_WRAP | Base64.NO_PADDING);
71 }
72
73 public void deliverPacket(final Account account, final JinglePacket packet) {
74 final String sessionId = packet.getSessionId();
75 if (sessionId == null) {
76 respondWithJingleError(account, packet, "unknown-session", "item-not-found", "cancel");
77 return;
78 }
79 final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, packet);
80 final AbstractJingleConnection existingJingleConnection = connections.get(id);
81 if (existingJingleConnection != null) {
82 existingJingleConnection.deliverPacket(packet);
83 } else if (packet.getAction() == JinglePacket.Action.SESSION_INITIATE) {
84 final Jid from = packet.getFrom();
85 final Content content = packet.getJingleContent();
86 final String descriptionNamespace = content == null ? null : content.getDescriptionNamespace();
87 final AbstractJingleConnection connection;
88 if (FileTransferDescription.NAMESPACES.contains(descriptionNamespace)) {
89 connection = new JingleFileTransferConnection(this, id, from);
90 } else if (Namespace.JINGLE_APPS_RTP.equals(descriptionNamespace) && !usesTor(account)) {
91 final boolean sessionEnded = this.endedSessions.asMap().containsKey(PersistableSessionId.of(id));
92 final boolean stranger = isWithStrangerAndStrangerNotificationsAreOff(account, id.with);
93 if (isBusy() || sessionEnded || stranger) {
94 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": rejected session with " + id.with + " because busy. sessionEnded=" + sessionEnded + ", stranger=" + stranger);
95 mXmppConnectionService.sendIqPacket(account, packet.generateResponse(IqPacket.TYPE.RESULT), null);
96 final JinglePacket sessionTermination = new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
97 sessionTermination.setTo(id.with);
98 sessionTermination.setReason(Reason.BUSY, null);
99 mXmppConnectionService.sendIqPacket(account, sessionTermination, null);
100 return;
101 }
102 connection = new JingleRtpConnection(this, id, from);
103 } else {
104 respondWithJingleError(account, packet, "unsupported-info", "feature-not-implemented", "cancel");
105 return;
106 }
107 connections.put(id, connection);
108 mXmppConnectionService.updateConversationUi();
109 connection.deliverPacket(packet);
110 } else {
111 Log.d(Config.LOGTAG, "unable to route jingle packet: " + packet);
112 respondWithJingleError(account, packet, "unknown-session", "item-not-found", "cancel");
113 }
114 }
115
116 private boolean usesTor(final Account account) {
117 return account.isOnion() || mXmppConnectionService.useTorToConnect();
118 }
119
120 public boolean isBusy() {
121 for (AbstractJingleConnection connection : this.connections.values()) {
122 if (connection instanceof JingleRtpConnection) {
123 if (((JingleRtpConnection) connection).isTerminated()) {
124 continue;
125 }
126 return true;
127 }
128 }
129 synchronized (this.rtpSessionProposals) {
130 return this.rtpSessionProposals.containsValue(DeviceDiscoveryState.DISCOVERED) || this.rtpSessionProposals.containsValue(DeviceDiscoveryState.SEARCHING);
131 }
132 }
133
134 private boolean isWithStrangerAndStrangerNotificationsAreOff(final Account account, Jid with) {
135 final boolean notifyForStrangers = mXmppConnectionService.getNotificationService().notificationsFromStrangers();
136 if (notifyForStrangers) {
137 return false;
138 }
139 final Contact contact = account.getRoster().getContact(with);
140 return !contact.showInContactList();
141 }
142
143 ScheduledFuture<?> schedule(final Runnable runnable, final long delay, final TimeUnit timeUnit) {
144 return this.scheduledExecutorService.schedule(runnable, delay, timeUnit);
145 }
146
147 void respondWithJingleError(final Account account, final IqPacket original, String jingleCondition, String condition, String conditionType) {
148 final IqPacket response = original.generateResponse(IqPacket.TYPE.ERROR);
149 final Element error = response.addChild("error");
150 error.setAttribute("type", conditionType);
151 error.addChild(condition, "urn:ietf:params:xml:ns:xmpp-stanzas");
152 error.addChild(jingleCondition, "urn:xmpp:jingle:errors:1");
153 account.getXmppConnection().sendIqPacket(response, null);
154 }
155
156 public void deliverMessage(final Account account, final Jid to, final Jid from, final Element message, String serverMsgId, long timestamp) {
157 Preconditions.checkArgument(Namespace.JINGLE_MESSAGE.equals(message.getNamespace()));
158 final String sessionId = message.getAttribute("id");
159 if (sessionId == null) {
160 return;
161 }
162 if ("accept".equals(message.getName())) {
163 for (AbstractJingleConnection connection : connections.values()) {
164 if (connection instanceof JingleRtpConnection) {
165 final JingleRtpConnection rtpConnection = (JingleRtpConnection) connection;
166 final AbstractJingleConnection.Id id = connection.getId();
167 if (id.account == account && id.sessionId.equals(sessionId)) {
168 rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
169 return;
170 }
171 }
172 }
173 return;
174 }
175 final boolean fromSelf = from.asBareJid().equals(account.getJid().asBareJid());
176 final AbstractJingleConnection.Id id;
177 if (fromSelf) {
178 if (to != null && to.isFullJid()) {
179 id = AbstractJingleConnection.Id.of(account, to, sessionId);
180 } else {
181 return;
182 }
183 } else {
184 id = AbstractJingleConnection.Id.of(account, from, sessionId);
185 }
186 final AbstractJingleConnection existingJingleConnection = connections.get(id);
187 if (existingJingleConnection != null) {
188 if (existingJingleConnection instanceof JingleRtpConnection) {
189 ((JingleRtpConnection) existingJingleConnection).deliveryMessage(from, message, serverMsgId, timestamp);
190 } else {
191 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": " + existingJingleConnection.getClass().getName() + " does not support jingle messages");
192 }
193 return;
194 }
195
196 if (fromSelf) {
197 if ("proceed".equals(message.getName())) {
198 final Conversation c = mXmppConnectionService.findOrCreateConversation(account, id.with, false, false);
199 final Message previousBusy = c.findRtpSession(sessionId, Message.STATUS_RECEIVED);
200 if (previousBusy != null) {
201 previousBusy.setBody(new RtpSessionStatus(true, 0).toString());
202 if (serverMsgId != null) {
203 previousBusy.setServerMsgId(serverMsgId);
204 }
205 previousBusy.setTime(timestamp);
206 mXmppConnectionService.updateMessage(previousBusy, true);
207 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": updated previous busy because call got picked up by another device");
208 return;
209 }
210 }
211 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignore jingle message from self");
212 return;
213 }
214
215 if ("propose".equals(message.getName())) {
216 final Propose propose = Propose.upgrade(message);
217 final List<GenericDescription> descriptions = propose.getDescriptions();
218 final Collection<RtpDescription> rtpDescriptions = Collections2.transform(
219 Collections2.filter(descriptions, d -> d instanceof RtpDescription),
220 input -> (RtpDescription) input
221 );
222 if (rtpDescriptions.size() > 0 && rtpDescriptions.size() == descriptions.size() && !usesTor(account)) {
223 final Collection<Media> media = Collections2.transform(rtpDescriptions, RtpDescription::getMedia);
224 if (media.contains(Media.UNKNOWN)) {
225 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": encountered unknown media in session proposal. " + propose);
226 return;
227 }
228 final boolean stranger = isWithStrangerAndStrangerNotificationsAreOff(account, id.with);
229 if (isBusy() || stranger) {
230 writeLogMissedIncoming(account, id.with.asBareJid(), id.sessionId, serverMsgId, timestamp);
231 if (stranger) {
232 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring call proposal from stranger " + id.with);
233 return;
234 }
235 final int activeDevices = account.countPresences();
236 Log.d(Config.LOGTAG, "active devices: " + activeDevices);
237 if (activeDevices == 0) {
238 final MessagePacket reject = mXmppConnectionService.getMessageGenerator().sessionReject(from, sessionId);
239 mXmppConnectionService.sendMessagePacket(account, reject);
240 } else {
241 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring proposal because busy on this device but there are other devices");
242 }
243 } else {
244 final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, from);
245 this.connections.put(id, rtpConnection);
246 rtpConnection.setProposedMedia(ImmutableSet.copyOf(media));
247 rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
248 }
249 } else {
250 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to react to proposed session with " + rtpDescriptions.size() + " rtp descriptions of " + descriptions.size() + " total descriptions");
251 }
252 } else if ("proceed".equals(message.getName())) {
253 synchronized (rtpSessionProposals) {
254 final RtpSessionProposal proposal = getRtpSessionProposal(account, from.asBareJid(), sessionId);
255 if (proposal != null) {
256 rtpSessionProposals.remove(proposal);
257 final JingleRtpConnection rtpConnection = new JingleRtpConnection(this, id, account.getJid());
258 rtpConnection.setProposedMedia(proposal.media);
259 this.connections.put(id, rtpConnection);
260 rtpConnection.transitionOrThrow(AbstractJingleConnection.State.PROPOSED);
261 rtpConnection.deliveryMessage(from, message, serverMsgId, timestamp);
262 } else {
263 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": no rtp session proposal found for " + from + " to deliver proceed");
264 }
265 }
266 } else if ("reject".equals(message.getName())) {
267 final RtpSessionProposal proposal = new RtpSessionProposal(account, from.asBareJid(), sessionId);
268 synchronized (rtpSessionProposals) {
269 if (rtpSessionProposals.remove(proposal) != null) {
270 writeLogMissedOutgoing(account, proposal.with, proposal.sessionId, serverMsgId, timestamp);
271 mXmppConnectionService.notifyJingleRtpConnectionUpdate(account, proposal.with, proposal.sessionId, RtpEndUserState.DECLINED_OR_BUSY);
272 } else {
273 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": no rtp session proposal found for " + from + " to deliver reject");
274 }
275 }
276 } else {
277 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retrieved out of order jingle message");
278 }
279
280 }
281
282 private RtpSessionProposal getRtpSessionProposal(final Account account, Jid from, String sessionId) {
283 for (RtpSessionProposal rtpSessionProposal : rtpSessionProposals.keySet()) {
284 if (rtpSessionProposal.sessionId.equals(sessionId) && rtpSessionProposal.with.equals(from) && rtpSessionProposal.account.getJid().equals(account.getJid())) {
285 return rtpSessionProposal;
286 }
287 }
288 return null;
289 }
290
291 private void writeLogMissedOutgoing(final Account account, Jid with, final String sessionId, String serverMsgId, long timestamp) {
292 final Conversation conversation = mXmppConnectionService.findOrCreateConversation(
293 account,
294 with.asBareJid(),
295 false,
296 false
297 );
298 final Message message = new Message(
299 conversation,
300 Message.STATUS_SEND,
301 Message.TYPE_RTP_SESSION,
302 sessionId
303 );
304 message.setBody(new RtpSessionStatus(false, 0).toString());
305 message.setServerMsgId(serverMsgId);
306 message.setTime(timestamp);
307 writeMessage(message);
308 }
309
310 private void writeLogMissedIncoming(final Account account, Jid with, final String sessionId, String serverMsgId, long timestamp) {
311 final Conversation conversation = mXmppConnectionService.findOrCreateConversation(
312 account,
313 with.asBareJid(),
314 false,
315 false
316 );
317 final Message message = new Message(
318 conversation,
319 Message.STATUS_RECEIVED,
320 Message.TYPE_RTP_SESSION,
321 sessionId
322 );
323 message.setBody(new RtpSessionStatus(false, 0).toString());
324 message.setServerMsgId(serverMsgId);
325 message.setTime(timestamp);
326 writeMessage(message);
327 }
328
329 private void writeMessage(final Message message) {
330 final Conversational conversational = message.getConversation();
331 if (conversational instanceof Conversation) {
332 ((Conversation) conversational).add(message);
333 mXmppConnectionService.databaseBackend.createMessage(message);
334 mXmppConnectionService.updateConversationUi();
335 } else {
336 throw new IllegalStateException("Somehow the conversation in a message was a stub");
337 }
338 }
339
340 public void startJingleFileTransfer(final Message message) {
341 Preconditions.checkArgument(message.isFileOrImage(), "Message is not of type file or image");
342 final Transferable old = message.getTransferable();
343 if (old != null) {
344 old.cancel();
345 }
346 final Account account = message.getConversation().getAccount();
347 final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(message);
348 final JingleFileTransferConnection connection = new JingleFileTransferConnection(this, id, account.getJid());
349 mXmppConnectionService.markMessage(message, Message.STATUS_WAITING);
350 this.connections.put(id, connection);
351 connection.init(message);
352 }
353
354 public Optional<AbstractJingleConnection.Id> getOngoingRtpConnection(final Contact contact) {
355 for(final Map.Entry<AbstractJingleConnection.Id,AbstractJingleConnection> entry : this.connections.entrySet()) {
356 if (entry.getValue() instanceof JingleRtpConnection) {
357 final AbstractJingleConnection.Id id = entry.getKey();
358 if (id.account == contact.getAccount() && id.with.asBareJid().equals(contact.getJid().asBareJid())) {
359 return Optional.of(id);
360 }
361 }
362 }
363 return Optional.absent();
364 }
365
366 void finishConnection(final AbstractJingleConnection connection) {
367 this.connections.remove(connection.getId());
368 }
369
370 void getPrimaryCandidate(final Account account, final boolean initiator, final OnPrimaryCandidateFound listener) {
371 if (Config.DISABLE_PROXY_LOOKUP) {
372 listener.onPrimaryCandidateFound(false, null);
373 return;
374 }
375 if (!this.primaryCandidates.containsKey(account.getJid().asBareJid())) {
376 final Jid proxy = account.getXmppConnection().findDiscoItemByFeature(Namespace.BYTE_STREAMS);
377 if (proxy != null) {
378 IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
379 iq.setTo(proxy);
380 iq.query(Namespace.BYTE_STREAMS);
381 account.getXmppConnection().sendIqPacket(iq, new OnIqPacketReceived() {
382
383 @Override
384 public void onIqPacketReceived(Account account, IqPacket packet) {
385 final Element streamhost = packet.query().findChild("streamhost", Namespace.BYTE_STREAMS);
386 final String host = streamhost == null ? null : streamhost.getAttribute("host");
387 final String port = streamhost == null ? null : streamhost.getAttribute("port");
388 if (host != null && port != null) {
389 try {
390 JingleCandidate candidate = new JingleCandidate(nextRandomId(), true);
391 candidate.setHost(host);
392 candidate.setPort(Integer.parseInt(port));
393 candidate.setType(JingleCandidate.TYPE_PROXY);
394 candidate.setJid(proxy);
395 candidate.setPriority(655360 + (initiator ? 30 : 0));
396 primaryCandidates.put(account.getJid().asBareJid(), candidate);
397 listener.onPrimaryCandidateFound(true, candidate);
398 } catch (final NumberFormatException e) {
399 listener.onPrimaryCandidateFound(false, null);
400 }
401 } else {
402 listener.onPrimaryCandidateFound(false, null);
403 }
404 }
405 });
406 } else {
407 listener.onPrimaryCandidateFound(false, null);
408 }
409
410 } else {
411 listener.onPrimaryCandidateFound(true,
412 this.primaryCandidates.get(account.getJid().asBareJid()));
413 }
414 }
415
416 public void retractSessionProposal(final Account account, final Jid with) {
417 synchronized (this.rtpSessionProposals) {
418 RtpSessionProposal matchingProposal = null;
419 for (RtpSessionProposal proposal : this.rtpSessionProposals.keySet()) {
420 if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
421 matchingProposal = proposal;
422 break;
423 }
424 }
425 if (matchingProposal != null) {
426 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retracting rtp session proposal with " + with);
427 this.rtpSessionProposals.remove(matchingProposal);
428 final MessagePacket messagePacket = mXmppConnectionService.getMessageGenerator().sessionRetract(matchingProposal);
429 writeLogMissedOutgoing(account, matchingProposal.with, matchingProposal.sessionId, null, System.currentTimeMillis());
430 mXmppConnectionService.sendMessagePacket(account, messagePacket);
431 }
432 }
433 }
434
435 public void proposeJingleRtpSession(final Account account, final Jid with, final Set<Media> media) {
436 synchronized (this.rtpSessionProposals) {
437 for (Map.Entry<RtpSessionProposal, DeviceDiscoveryState> entry : this.rtpSessionProposals.entrySet()) {
438 RtpSessionProposal proposal = entry.getKey();
439 if (proposal.account == account && with.asBareJid().equals(proposal.with)) {
440 final DeviceDiscoveryState preexistingState = entry.getValue();
441 if (preexistingState != null && preexistingState != DeviceDiscoveryState.FAILED) {
442 mXmppConnectionService.notifyJingleRtpConnectionUpdate(
443 account,
444 with,
445 proposal.sessionId,
446 preexistingState.toEndUserState()
447 );
448 return;
449 }
450 }
451 }
452 if (isBusy()) {
453 throw new IllegalStateException("There is already a running RTP session. This should have been caught by the UI");
454 }
455 final RtpSessionProposal proposal = RtpSessionProposal.of(account, with.asBareJid(), media);
456 this.rtpSessionProposals.put(proposal, DeviceDiscoveryState.SEARCHING);
457 mXmppConnectionService.notifyJingleRtpConnectionUpdate(
458 account,
459 proposal.with,
460 proposal.sessionId,
461 RtpEndUserState.FINDING_DEVICE
462 );
463 final MessagePacket messagePacket = mXmppConnectionService.getMessageGenerator().sessionProposal(proposal);
464 Log.d(Config.LOGTAG, messagePacket.toString());
465 mXmppConnectionService.sendMessagePacket(account, messagePacket);
466 }
467 }
468
469 public void deliverIbbPacket(Account account, IqPacket packet) {
470 final String sid;
471 final Element payload;
472 if (packet.hasChild("open", Namespace.IBB)) {
473 payload = packet.findChild("open", Namespace.IBB);
474 sid = payload.getAttribute("sid");
475 } else if (packet.hasChild("data", Namespace.IBB)) {
476 payload = packet.findChild("data", Namespace.IBB);
477 sid = payload.getAttribute("sid");
478 } else if (packet.hasChild("close", Namespace.IBB)) {
479 payload = packet.findChild("close", Namespace.IBB);
480 sid = payload.getAttribute("sid");
481 } else {
482 payload = null;
483 sid = null;
484 }
485 if (sid != null) {
486 for (final AbstractJingleConnection connection : this.connections.values()) {
487 if (connection instanceof JingleFileTransferConnection) {
488 final JingleFileTransferConnection fileTransfer = (JingleFileTransferConnection) connection;
489 final JingleTransport transport = fileTransfer.getTransport();
490 if (transport instanceof JingleInBandTransport) {
491 final JingleInBandTransport inBandTransport = (JingleInBandTransport) transport;
492 if (inBandTransport.matches(account, sid)) {
493 inBandTransport.deliverPayload(packet, payload);
494 }
495 return;
496 }
497 }
498 }
499 }
500 Log.d(Config.LOGTAG, "unable to deliver ibb packet: " + packet.toString());
501 account.getXmppConnection().sendIqPacket(packet.generateResponse(IqPacket.TYPE.ERROR), null);
502 }
503
504 public void notifyRebound() {
505 for (final AbstractJingleConnection connection : this.connections.values()) {
506 connection.notifyRebound();
507 }
508 }
509
510 public WeakReference<JingleRtpConnection> findJingleRtpConnection(Account account, Jid with, String sessionId) {
511 final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, Jid.ofEscaped(with), sessionId);
512 final AbstractJingleConnection connection = connections.get(id);
513 if (connection instanceof JingleRtpConnection) {
514 return new WeakReference<>((JingleRtpConnection) connection);
515 }
516 return null;
517 }
518
519 public void updateProposedSessionDiscovered(Account account, Jid from, String sessionId, final DeviceDiscoveryState target) {
520 synchronized (this.rtpSessionProposals) {
521 final RtpSessionProposal sessionProposal = getRtpSessionProposal(account, from.asBareJid(), sessionId);
522 final DeviceDiscoveryState currentState = sessionProposal == null ? null : rtpSessionProposals.get(sessionProposal);
523 if (currentState == null) {
524 Log.d(Config.LOGTAG, "unable to find session proposal for session id " + sessionId);
525 return;
526 }
527 if (currentState == DeviceDiscoveryState.DISCOVERED) {
528 Log.d(Config.LOGTAG, "session proposal already at discovered. not going to fall back");
529 return;
530 }
531 this.rtpSessionProposals.put(sessionProposal, target);
532 mXmppConnectionService.notifyJingleRtpConnectionUpdate(account, sessionProposal.with, sessionProposal.sessionId, target.toEndUserState());
533 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": flagging session " + sessionId + " as " + target);
534 }
535 }
536
537 public void rejectRtpSession(final String sessionId) {
538 for (final AbstractJingleConnection connection : this.connections.values()) {
539 if (connection.getId().sessionId.equals(sessionId)) {
540 if (connection instanceof JingleRtpConnection) {
541 ((JingleRtpConnection) connection).rejectCall();
542 }
543 }
544 }
545 }
546
547 public void endRtpSession(final String sessionId) {
548 for (final AbstractJingleConnection connection : this.connections.values()) {
549 if (connection.getId().sessionId.equals(sessionId)) {
550 if (connection instanceof JingleRtpConnection) {
551 ((JingleRtpConnection) connection).endCall();
552 }
553 }
554 }
555 }
556
557 public void failProceed(Account account, final Jid with, String sessionId) {
558 final AbstractJingleConnection.Id id = AbstractJingleConnection.Id.of(account, with, sessionId);
559 final AbstractJingleConnection existingJingleConnection = connections.get(id);
560 if (existingJingleConnection instanceof JingleRtpConnection) {
561 ((JingleRtpConnection) existingJingleConnection).deliverFailedProceed();
562 }
563 }
564
565 void ensureConnectionIsRegistered(final AbstractJingleConnection connection) {
566 if (connections.containsValue(connection)) {
567 return;
568 }
569 final IllegalStateException e = new IllegalStateException("JingleConnection has not been registered with connection manager");
570 Log.e(Config.LOGTAG, "ensureConnectionIsRegistered() failed. Going to throw", e);
571 throw e;
572 }
573
574 public void endSession(AbstractJingleConnection.Id id, final AbstractJingleConnection.State state) {
575 this.endedSessions.put(PersistableSessionId.of(id), state);
576 }
577
578 private static class PersistableSessionId {
579 private final Jid with;
580 private final String sessionId;
581
582 private PersistableSessionId(Jid with, String sessionId) {
583 this.with = with;
584 this.sessionId = sessionId;
585 }
586
587 public static PersistableSessionId of(AbstractJingleConnection.Id id) {
588 return new PersistableSessionId(id.with, id.sessionId);
589 }
590
591 @Override
592 public boolean equals(Object o) {
593 if (this == o) return true;
594 if (o == null || getClass() != o.getClass()) return false;
595 PersistableSessionId that = (PersistableSessionId) o;
596 return Objects.equal(with, that.with) &&
597 Objects.equal(sessionId, that.sessionId);
598 }
599
600 @Override
601 public int hashCode() {
602 return Objects.hashCode(with, sessionId);
603 }
604 }
605
606 public enum DeviceDiscoveryState {
607 SEARCHING, DISCOVERED, FAILED;
608
609 public RtpEndUserState toEndUserState() {
610 switch (this) {
611 case SEARCHING:
612 return RtpEndUserState.FINDING_DEVICE;
613 case DISCOVERED:
614 return RtpEndUserState.RINGING;
615 default:
616 return RtpEndUserState.CONNECTIVITY_ERROR;
617 }
618 }
619 }
620
621 public static class RtpSessionProposal {
622 public final Jid with;
623 public final String sessionId;
624 public final Set<Media> media;
625 private final Account account;
626
627 private RtpSessionProposal(Account account, Jid with, String sessionId) {
628 this(account, with, sessionId, Collections.emptySet());
629 }
630
631 private RtpSessionProposal(Account account, Jid with, String sessionId, Set<Media> media) {
632 this.account = account;
633 this.with = with;
634 this.sessionId = sessionId;
635 this.media = media;
636 }
637
638 public static RtpSessionProposal of(Account account, Jid with, Set<Media> media) {
639 return new RtpSessionProposal(account, with, nextRandomId(), media);
640 }
641
642 @Override
643 public boolean equals(Object o) {
644 if (this == o) return true;
645 if (o == null || getClass() != o.getClass()) return false;
646 RtpSessionProposal proposal = (RtpSessionProposal) o;
647 return Objects.equal(account.getJid(), proposal.account.getJid()) &&
648 Objects.equal(with, proposal.with) &&
649 Objects.equal(sessionId, proposal.sessionId);
650 }
651
652 @Override
653 public int hashCode() {
654 return Objects.hashCode(account.getJid(), with, sessionId);
655 }
656 }
657}