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