ConnectionService.java

  1package com.cheogram.android;
  2
  3import java.lang.ref.WeakReference;
  4import java.util.Collections;
  5import java.util.HashSet;
  6import java.util.Set;
  7import java.util.Stack;
  8import java.util.Vector;
  9
 10import com.google.common.base.Joiner;
 11import com.google.common.collect.ImmutableSet;
 12
 13import android.os.Build;
 14import android.telecom.CallAudioState;
 15import android.telecom.Connection;
 16import android.telecom.ConnectionRequest;
 17import android.telecom.DisconnectCause;
 18import android.telecom.PhoneAccount;
 19import android.telecom.PhoneAccountHandle;
 20import android.telecom.StatusHints;
 21import android.telecom.TelecomManager;
 22import android.telephony.PhoneNumberUtils;
 23
 24import android.Manifest;
 25
 26import androidx.annotation.RequiresApi;
 27import androidx.core.content.ContextCompat;
 28import android.content.ComponentName;
 29import android.content.Context;
 30import android.content.Intent;
 31import android.content.pm.PackageManager;
 32import android.content.ServiceConnection;
 33import android.graphics.drawable.Icon;
 34import android.net.Uri;
 35import android.os.Bundle;
 36import android.os.IBinder;
 37import android.os.Parcel;
 38import android.util.Log;
 39
 40import com.intentfilter.androidpermissions.PermissionManager;
 41import com.intentfilter.androidpermissions.NotificationSettings;
 42import com.intentfilter.androidpermissions.models.DeniedPermissions;
 43import io.michaelrocks.libphonenumber.android.NumberParseException;
 44
 45import eu.siacs.conversations.R;
 46import eu.siacs.conversations.entities.Account;
 47import eu.siacs.conversations.services.AppRTCAudioManager;
 48import eu.siacs.conversations.services.AvatarService;
 49import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
 50import eu.siacs.conversations.services.XmppConnectionService;
 51import eu.siacs.conversations.ui.RtpSessionActivity;
 52import eu.siacs.conversations.utils.PhoneNumberUtilWrapper;
 53import eu.siacs.conversations.xmpp.Jid;
 54import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
 55import eu.siacs.conversations.xmpp.jingle.Media;
 56import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
 57
 58@RequiresApi(Build.VERSION_CODES.M)
 59public class ConnectionService extends android.telecom.ConnectionService {
 60	public XmppConnectionService xmppConnectionService = null;
 61	protected ServiceConnection mConnection = new ServiceConnection() {
 62		@Override
 63			public void onServiceConnected(ComponentName className, IBinder service) {
 64				XmppConnectionBinder binder = (XmppConnectionBinder) service;
 65				xmppConnectionService = binder.getService();
 66			}
 67
 68		@Override
 69		public void onServiceDisconnected(ComponentName arg0) {
 70			xmppConnectionService = null;
 71		}
 72	};
 73
 74	@Override
 75	public void onCreate() {
 76		// From XmppActivity.connectToBackend
 77		Intent intent = new Intent(this, XmppConnectionService.class);
 78		intent.setAction("ui");
 79		try {
 80			startService(intent);
 81		} catch (IllegalStateException e) {
 82			Log.w("com.cheogram.android.ConnectionService", "unable to start service from " + getClass().getSimpleName());
 83		}
 84		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
 85	}
 86
 87	@Override
 88	public void onDestroy() {
 89		unbindService(mConnection);
 90	}
 91
 92	@Override
 93	public Connection onCreateOutgoingConnection(
 94		PhoneAccountHandle phoneAccountHandle,
 95		ConnectionRequest request
 96	) {
 97		String[] gateway = phoneAccountHandle.getId().split("/", 2);
 98
 99		String rawTel = request.getAddress().getSchemeSpecificPart();
100		String postDial = PhoneNumberUtils.extractPostDialPortion(rawTel);
101
102		String tel = PhoneNumberUtils.extractNetworkPortion(rawTel);
103		try {
104			tel = PhoneNumberUtilWrapper.normalize(this, tel);
105		} catch (IllegalArgumentException | NumberParseException e) {
106			return Connection.createFailedConnection(
107				new DisconnectCause(DisconnectCause.ERROR)
108			);
109		}
110
111		if (xmppConnectionService == null) {
112			return Connection.createFailedConnection(
113				new DisconnectCause(DisconnectCause.ERROR)
114			);
115		}
116
117		if (xmppConnectionService.getJingleConnectionManager().isBusy() != null) {
118			return Connection.createFailedConnection(
119				new DisconnectCause(DisconnectCause.BUSY)
120			);
121		}
122
123		Account account = xmppConnectionService.findAccountByJid(Jid.of(gateway[0]));
124		if (account == null) {
125			return Connection.createFailedConnection(
126				new DisconnectCause(DisconnectCause.ERROR)
127			);
128		}
129
130		Jid with = Jid.ofLocalAndDomain(tel, gateway[1]);
131		CheogramConnection connection = new CheogramConnection(account, with, postDial);
132
133		PermissionManager permissionManager = PermissionManager.getInstance(this);
134		permissionManager.setNotificationSettings(
135			new NotificationSettings.Builder()
136				.withMessage(R.string.microphone_permission_for_call)
137				.withSmallIcon(R.drawable.ic_notification).build()
138		);
139
140		Set<String> permissions = new HashSet<>();
141		permissions.add(Manifest.permission.RECORD_AUDIO);
142		permissionManager.checkPermissions(permissions, new PermissionManager.PermissionRequestListener() {
143			@Override
144			public void onPermissionGranted() {
145				connection.setSessionId(xmppConnectionService.getJingleConnectionManager().proposeJingleRtpSession(
146					account,
147					with,
148					ImmutableSet.of(Media.AUDIO)
149				));
150			}
151
152			@Override
153			public void onPermissionDenied(DeniedPermissions deniedPermissions) {
154				connection.close(new DisconnectCause(DisconnectCause.ERROR));
155			}
156		});
157
158		connection.setInitializing();
159		connection.setAddress(
160			Uri.fromParts("tel", tel, null), // Normalized tel as tel: URI
161			TelecomManager.PRESENTATION_ALLOWED
162		);
163
164		xmppConnectionService.setOnRtpConnectionUpdateListener(
165			(XmppConnectionService.OnJingleRtpConnectionUpdate) connection
166		);
167
168		return connection;
169	}
170
171	@Override
172	public Connection onCreateIncomingConnection(PhoneAccountHandle handle, ConnectionRequest request) {
173		Bundle extras = request.getExtras();
174		String accountJid = extras.getString("account");
175		String withJid = extras.getString("with");
176		String sessionId = extras.getString("sessionId");
177
178		Account account = xmppConnectionService.findAccountByJid(Jid.of(accountJid));
179		Jid with = Jid.of(withJid);
180
181		CheogramConnection connection = new CheogramConnection(account, with, null);
182		connection.setSessionId(sessionId);
183		connection.setAddress(
184			Uri.fromParts("tel", with.getLocal(), null),
185			TelecomManager.PRESENTATION_ALLOWED
186		);
187		connection.setRinging();
188
189		xmppConnectionService.setOnRtpConnectionUpdateListener(connection);
190
191		return connection;
192	}
193
194	public class CheogramConnection extends Connection implements XmppConnectionService.OnJingleRtpConnectionUpdate {
195		protected Account account;
196		protected Jid with;
197		protected String sessionId = null;
198		protected Stack<String> postDial = new Stack<>();
199		protected Icon gatewayIcon;
200		protected WeakReference<JingleRtpConnection> rtpConnection = null;
201
202		CheogramConnection(Account account, Jid with, String postDialString) {
203			super();
204			this.account = account;
205			this.with = with;
206
207			gatewayIcon = Icon.createWithBitmap(xmppConnectionService.getAvatarService().get(
208				account.getRoster().getContact(Jid.of(with.getDomain())),
209				AvatarService.getSystemUiAvatarSize(xmppConnectionService),
210				false
211			));
212
213			if (postDialString != null) {
214				for (int i = postDialString.length() - 1; i >= 0; i--) {
215					postDial.push("" + postDialString.charAt(i));
216				}
217			}
218
219			setCallerDisplayName(
220				account.getDisplayName(),
221				TelecomManager.PRESENTATION_ALLOWED
222			);
223			setAudioModeIsVoip(true);
224			setConnectionCapabilities(
225				Connection.CAPABILITY_CAN_SEND_RESPONSE_VIA_CONNECTION
226			);
227		}
228
229		public void setSessionId(final String sessionId) {
230			this.sessionId = sessionId;
231		}
232
233		@Override
234		public void onJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state) {
235			if (sessionId == null || !sessionId.equals(this.sessionId)) return;
236			if (rtpConnection == null) {
237				this.with = with; // Store full JID of connection
238				findRtpConnection();
239			}
240
241			String statusLabel = null;
242
243			if (state == RtpEndUserState.FINDING_DEVICE) {
244				setInitialized();
245			} else if (state == RtpEndUserState.RINGING) {
246				setDialing();
247			} else if (state == RtpEndUserState.INCOMING_CALL) {
248				setRinging();
249			} else if (state == RtpEndUserState.CONNECTING) {
250				xmppConnectionService.setDiallerIntegrationActive(true);
251				setActive();
252				statusLabel = getString(R.string.rtp_state_connecting);
253			} else if (state == RtpEndUserState.CONNECTED) {
254				postDial();
255			} else if (state == RtpEndUserState.DECLINED_OR_BUSY) {
256				close(new DisconnectCause(DisconnectCause.BUSY));
257			} else if (state == RtpEndUserState.ENDED) {
258				close(new DisconnectCause(DisconnectCause.LOCAL));
259			} else if (state == RtpEndUserState.RETRACTED) {
260				close(new DisconnectCause(DisconnectCause.CANCELED));
261			} else if (RtpSessionActivity.END_CARD.contains(state)) {
262				close(new DisconnectCause(DisconnectCause.ERROR));
263			}
264
265			setStatusHints(new StatusHints(statusLabel, gatewayIcon, null));
266		}
267
268		@Override
269		public void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
270			if (Build.VERSION.SDK_INT < 26) return;
271
272			switch(selectedAudioDevice) {
273				case SPEAKER_PHONE:
274					setAudioRoute(CallAudioState.ROUTE_SPEAKER);
275				case WIRED_HEADSET:
276					setAudioRoute(CallAudioState.ROUTE_WIRED_HEADSET);
277				case EARPIECE:
278					setAudioRoute(CallAudioState.ROUTE_EARPIECE);
279				case BLUETOOTH:
280					setAudioRoute(CallAudioState.ROUTE_BLUETOOTH);
281				default:
282					setAudioRoute(CallAudioState.ROUTE_WIRED_OR_EARPIECE);
283			}
284		}
285
286		@Override
287		public void onAnswer() {
288			// For incoming calls, a connection update may not have been triggered before answering
289			// so we have to acquire the rtp connection object here
290			findRtpConnection();
291			if (rtpConnection == null || rtpConnection.get() == null) {
292				close(new DisconnectCause(DisconnectCause.CANCELED));
293			} else {
294				rtpConnection.get().acceptCall();
295			}
296		}
297
298		@Override
299		public void onReject() {
300			findRtpConnection();
301			if (rtpConnection != null && rtpConnection.get() != null) {
302				rtpConnection.get().rejectCall();
303			}
304			close(new DisconnectCause(DisconnectCause.LOCAL));
305		}
306
307		// Set the connection to the disconnected state and clean up the resources
308		// Note that we cannot do this from onStateChanged() because calling destroy
309		// there seems to trigger a deadlock somewhere in the telephony stack.
310		public void close(DisconnectCause reason) {
311			setDisconnected(reason);
312			destroy();
313			xmppConnectionService.setDiallerIntegrationActive(false);
314			xmppConnectionService.removeRtpConnectionUpdateListener(this);
315		}
316
317		@Override
318		public void onDisconnect() {
319			if (rtpConnection == null || rtpConnection.get() == null) {
320				xmppConnectionService.getJingleConnectionManager().retractSessionProposal(account, with.asBareJid());
321				close(new DisconnectCause(DisconnectCause.LOCAL));
322			} else {
323				rtpConnection.get().endCall();
324			}
325		}
326
327		@Override
328		public void onAbort() {
329			onDisconnect();
330		}
331
332		@Override
333		public void onPlayDtmfTone(char c) {
334			rtpConnection.get().applyDtmfTone("" + c);
335		}
336
337		@Override
338		public void onPostDialContinue(boolean c) {
339			if (c) postDial();
340		}
341
342		protected void findRtpConnection() {
343			if (rtpConnection != null) return;
344
345			rtpConnection = xmppConnectionService.getJingleConnectionManager().findJingleRtpConnection(account, with, sessionId);
346		}
347
348		protected void sleep(int ms) {
349			try {
350				Thread.sleep(ms);
351			} catch (InterruptedException ex) {
352				Thread.currentThread().interrupt();
353			}
354		}
355
356		protected void postDial() {
357			while (!postDial.empty()) {
358				String next = postDial.pop();
359				if (next.equals(";")) {
360					Vector<String> v = new Vector<>(postDial);
361					Collections.reverse(v);
362					setPostDialWait(Joiner.on("").join(v));
363					return;
364				} else if (next.equals(",")) {
365					sleep(2000);
366				} else {
367					rtpConnection.get().applyDtmfTone(next);
368					sleep(100);
369				}
370			}
371		}
372	}
373}