1package eu.siacs.conversations.ui;
2
3import android.app.Activity;
4import android.app.Dialog;
5import android.content.DialogInterface.OnClickListener;
6import android.content.DialogInterface;
7import android.os.Bundle;
8import android.text.Editable;
9import android.text.InputType;
10import android.text.TextWatcher;
11import android.util.Pair;
12import android.view.LayoutInflater;
13import android.view.View;
14import android.view.ViewGroup;
15import android.widget.AdapterView;
16import android.widget.ArrayAdapter;
17import android.widget.TextView;
18import android.widget.ToggleButton;
19
20import androidx.annotation.NonNull;
21import androidx.appcompat.app.AlertDialog;
22import androidx.databinding.DataBindingUtil;
23import androidx.fragment.app.DialogFragment;
24import androidx.recyclerview.widget.RecyclerView;
25import androidx.recyclerview.widget.LinearLayoutManager;
26
27import java.util.ArrayList;
28import java.util.Arrays;
29import java.util.Collection;
30import java.util.Collections;
31import java.util.List;
32import java.util.Map;
33
34import io.michaelrocks.libphonenumber.android.NumberParseException;
35
36import eu.siacs.conversations.Config;
37import eu.siacs.conversations.R;
38import eu.siacs.conversations.databinding.EnterJidDialogBinding;
39import eu.siacs.conversations.services.XmppConnectionService;
40import eu.siacs.conversations.entities.Account;
41import eu.siacs.conversations.entities.Contact;
42import eu.siacs.conversations.entities.Presence;
43import eu.siacs.conversations.entities.ServiceDiscoveryResult;
44import eu.siacs.conversations.ui.adapter.KnownHostsAdapter;
45import eu.siacs.conversations.ui.interfaces.OnBackendConnected;
46import eu.siacs.conversations.ui.util.DelayedHintHelper;
47import eu.siacs.conversations.utils.PhoneNumberUtilWrapper;
48import eu.siacs.conversations.xmpp.Jid;
49import eu.siacs.conversations.xmpp.OnGatewayResult;
50
51public class EnterJidDialog extends DialogFragment implements OnBackendConnected, TextWatcher {
52
53 private static final List<String> SUSPICIOUS_DOMAINS =
54 Arrays.asList("conference", "muc", "room", "rooms", "chat");
55
56 private OnEnterJidDialogPositiveListener mListener = null;
57
58 private static final String TITLE_KEY = "title";
59 private static final String POSITIVE_BUTTON_KEY = "positive_button";
60 private static final String PREFILLED_JID_KEY = "prefilled_jid";
61 private static final String ACCOUNT_KEY = "account";
62 private static final String ALLOW_EDIT_JID_KEY = "allow_edit_jid";
63 private static final String ACCOUNTS_LIST_KEY = "activated_accounts_list";
64 private static final String SANITY_CHECK_JID = "sanity_check_jid";
65
66 private KnownHostsAdapter knownHostsAdapter;
67 private Collection<String> whitelistedDomains = Collections.emptyList();
68
69 private EnterJidDialogBinding binding;
70 private AlertDialog dialog;
71 private boolean sanityCheckJid = false;
72
73 private boolean issuedWarning = false;
74 private GatewayListAdapter gatewayListAdapter = new GatewayListAdapter();
75
76 public static EnterJidDialog newInstance(
77 final List<String> activatedAccounts,
78 final String title,
79 final String positiveButton,
80 final String prefilledJid,
81 final String account,
82 boolean allowEditJid,
83 final boolean sanity_check_jid) {
84 EnterJidDialog dialog = new EnterJidDialog();
85 Bundle bundle = new Bundle();
86 bundle.putString(TITLE_KEY, title);
87 bundle.putString(POSITIVE_BUTTON_KEY, positiveButton);
88 bundle.putString(PREFILLED_JID_KEY, prefilledJid);
89 bundle.putString(ACCOUNT_KEY, account);
90 bundle.putBoolean(ALLOW_EDIT_JID_KEY, allowEditJid);
91 bundle.putStringArrayList(ACCOUNTS_LIST_KEY, (ArrayList<String>) activatedAccounts);
92 bundle.putBoolean(SANITY_CHECK_JID, sanity_check_jid);
93 dialog.setArguments(bundle);
94 return dialog;
95 }
96
97 @Override
98 public void onActivityCreated(Bundle savedInstanceState) {
99 super.onActivityCreated(savedInstanceState);
100 setRetainInstance(true);
101 }
102
103 @Override
104 public void onStart() {
105 super.onStart();
106 final Activity activity = getActivity();
107 if (activity instanceof XmppActivity
108 && ((XmppActivity) activity).xmppConnectionService != null) {
109 refreshKnownHosts();
110 }
111 }
112
113 @NonNull
114 @Override
115 public Dialog onCreateDialog(Bundle savedInstanceState) {
116 final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
117 builder.setTitle(getArguments().getString(TITLE_KEY));
118 binding =
119 DataBindingUtil.inflate(
120 getActivity().getLayoutInflater(), R.layout.enter_jid_dialog, null, false);
121 this.knownHostsAdapter = new KnownHostsAdapter(getActivity(), R.layout.simple_list_item);
122 binding.jid.setAdapter(this.knownHostsAdapter);
123 binding.jid.addTextChangedListener(this);
124 String prefilledJid = getArguments().getString(PREFILLED_JID_KEY);
125 if (prefilledJid != null) {
126 binding.jid.append(prefilledJid);
127 if (!getArguments().getBoolean(ALLOW_EDIT_JID_KEY)) {
128 binding.jid.setFocusable(false);
129 binding.jid.setFocusableInTouchMode(false);
130 binding.jid.setClickable(false);
131 binding.jid.setCursorVisible(false);
132 }
133 }
134 sanityCheckJid = getArguments().getBoolean(SANITY_CHECK_JID, false);
135
136 DelayedHintHelper.setHint(R.string.account_settings_example_jabber_id, binding.jid);
137
138 String account = getArguments().getString(ACCOUNT_KEY);
139 if (account == null) {
140 StartConversationActivity.populateAccountSpinner(
141 getActivity(),
142 getArguments().getStringArrayList(ACCOUNTS_LIST_KEY),
143 binding.account);
144 } else {
145 ArrayAdapter<String> adapter =
146 new ArrayAdapter<>(
147 getActivity(), R.layout.simple_list_item, new String[] {account});
148 binding.account.setEnabled(false);
149 adapter.setDropDownViewResource(R.layout.simple_list_item);
150 binding.account.setAdapter(adapter);
151 }
152
153 binding.gatewayList.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
154 binding.gatewayList.setAdapter(gatewayListAdapter);
155 gatewayListAdapter.setOnEmpty(() -> binding.gatewayList.setVisibility(View.GONE));
156 gatewayListAdapter.setOnNonEmpty(() -> binding.gatewayList.setVisibility(View.VISIBLE));
157
158 binding.account.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
159 @Override
160 public void onItemSelected(AdapterView accountSpinner, View view, int position, long id) {
161 XmppActivity context = (XmppActivity) getActivity();
162 if (context.xmppConnectionService == null || accountJid() == null) return;
163
164 gatewayListAdapter.clear();
165 final Account account = context.xmppConnectionService.findAccountByJid(accountJid());
166
167 for (final Contact contact : account.getRoster().getContacts()) {
168 if (contact.showInRoster() && (contact.getPresences().anyIdentity("gateway", null) || contact.getPresences().anySupport("jabber:iq:gateway"))) {
169 context.xmppConnectionService.fetchFromGateway(account, contact.getJid(), null, (final String prompt, String errorMessage) -> {
170 if (prompt == null && !contact.getPresences().anyIdentity("gateway", null)) return;
171
172 context.runOnUiThread(() -> {
173 gatewayListAdapter.add(contact, prompt);
174 });
175 });
176 }
177 }
178 }
179
180 @Override
181 public void onNothingSelected(AdapterView accountSpinner) {
182 gatewayListAdapter.clear();
183 }
184 });
185
186 builder.setView(binding.getRoot());
187 builder.setNegativeButton(R.string.cancel, null);
188 builder.setPositiveButton(getArguments().getString(POSITIVE_BUTTON_KEY), null);
189 this.dialog = builder.create();
190
191 View.OnClickListener dialogOnClick =
192 v -> {
193 handleEnter(binding, account);
194 };
195
196 binding.jid.setOnEditorActionListener(
197 (v, actionId, event) -> {
198 handleEnter(binding, account);
199 return true;
200 });
201
202 dialog.show();
203 dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(dialogOnClick);
204 return dialog;
205 }
206
207 protected Jid accountJid() {
208 try {
209 if (Config.DOMAIN_LOCK != null) {
210 return Jid.ofEscaped((String) binding.account.getSelectedItem(), Config.DOMAIN_LOCK, null);
211 } else {
212 return Jid.ofEscaped((String) binding.account.getSelectedItem());
213 }
214 } catch (final IllegalArgumentException e) {
215 return null;
216 }
217 }
218
219 private void handleEnter(EnterJidDialogBinding binding, String account) {
220 if (!binding.account.isEnabled() && account == null) {
221 return;
222 }
223 final Jid accountJid = accountJid();
224 final OnGatewayResult finish = (final String jidString, final String errorMessage) -> {
225 getActivity().runOnUiThread(() -> {
226 if (errorMessage != null) {
227 binding.jidLayout.setError(errorMessage);
228 return;
229 }
230 if (jidString == null) {
231 binding.jidLayout.setError(getActivity().getString(R.string.invalid_jid));
232 return;
233 }
234
235 final Jid contactJid;
236 try {
237 contactJid = Jid.ofEscaped(jidString);
238 } catch (final IllegalArgumentException e) {
239 binding.jidLayout.setError(getActivity().getString(R.string.invalid_jid));
240 return;
241 }
242
243 if (!issuedWarning && sanityCheckJid) {
244 if (contactJid.isDomainJid()) {
245 binding.jidLayout.setError(getActivity().getString(R.string.this_looks_like_a_domain));
246 dialog.getButton(AlertDialog.BUTTON_POSITIVE).setText(R.string.add_anway);
247 issuedWarning = true;
248 return;
249 }
250 if (suspiciousSubDomain(contactJid.getDomain().toEscapedString())) {
251 binding.jidLayout.setError(getActivity().getString(R.string.this_looks_like_channel));
252 dialog.getButton(AlertDialog.BUTTON_POSITIVE).setText(R.string.add_anway);
253 issuedWarning = true;
254 return;
255 }
256 }
257
258 if (mListener != null) {
259 try {
260 if (mListener.onEnterJidDialogPositive(accountJid, contactJid)) {
261 dialog.dismiss();
262 }
263 } catch (JidError error) {
264 binding.jidLayout.setError(error.toString());
265 dialog.getButton(AlertDialog.BUTTON_POSITIVE).setText(R.string.add);
266 issuedWarning = false;
267 }
268 }
269 });
270 };
271
272 Pair<String,Pair<Jid,Presence>> p = gatewayListAdapter.getSelected();
273 final String type = gatewayListAdapter.getSelectedType();
274
275 // Resolve based on local settings before submission
276 if (type.equals("pstn") || type.equals("sms")) {
277 try {
278 binding.jid.setText(PhoneNumberUtilWrapper.normalize(getActivity(), binding.jid.getText().toString()));
279 } catch (NumberParseException | NullPointerException e) { }
280 }
281
282 if (p == null) {
283 finish.onGatewayResult(binding.jid.getText().toString(), null);
284 } else if (p.first != null) { // Gateway already responsed to jabber:iq:gateway once
285 final Account acct = ((XmppActivity) getActivity()).xmppConnectionService.findAccountByJid(accountJid);
286 ((XmppActivity) getActivity()).xmppConnectionService.fetchFromGateway(acct, p.second.first, binding.jid.getText().toString(), finish);
287 } else if (p.second.first.isDomainJid() && p.second.second.getServiceDiscoveryResult().getFeatures().contains("jid\\20escaping")) {
288 finish.onGatewayResult(Jid.ofLocalAndDomain(binding.jid.getText().toString(), p.second.first.getDomain().toString()).toString(), null);
289 } else if (p.second.first.isDomainJid()) {
290 finish.onGatewayResult(Jid.ofLocalAndDomain(binding.jid.getText().toString().replace("@", "%"), p.second.first.getDomain().toString()).toString(), null);
291 } else {
292 finish.onGatewayResult(null, null);
293 }
294 }
295
296 public void setOnEnterJidDialogPositiveListener(OnEnterJidDialogPositiveListener listener) {
297 this.mListener = listener;
298 }
299
300 @Override
301 public void onBackendConnected() {
302 refreshKnownHosts();
303 }
304
305 private void refreshKnownHosts() {
306 final Activity activity = getActivity();
307 if (activity instanceof XmppActivity) {
308 final XmppConnectionService service = ((XmppActivity) activity).xmppConnectionService;
309 if (service == null) {
310 return;
311 }
312 final Collection<String> hosts = service.getKnownHosts();
313 this.knownHostsAdapter.refresh(hosts);
314 this.whitelistedDomains = hosts;
315 }
316 }
317
318 @Override
319 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
320
321 @Override
322 public void onTextChanged(CharSequence s, int start, int before, int count) {}
323
324 @Override
325 public void afterTextChanged(Editable s) {
326 if (issuedWarning) {
327 dialog.getButton(AlertDialog.BUTTON_POSITIVE).setText(R.string.add);
328 binding.jidLayout.setError(null);
329 issuedWarning = false;
330 }
331 }
332
333 public interface OnEnterJidDialogPositiveListener {
334 boolean onEnterJidDialogPositive(Jid account, Jid contact) throws EnterJidDialog.JidError;
335 }
336
337 public static class JidError extends Exception {
338 final String msg;
339
340 public JidError(final String msg) {
341 this.msg = msg;
342 }
343
344 @NonNull
345 public String toString() {
346 return msg;
347 }
348 }
349
350 @Override
351 public void onDestroyView() {
352 Dialog dialog = getDialog();
353 if (dialog != null && getRetainInstance()) {
354 dialog.setDismissMessage(null);
355 }
356 super.onDestroyView();
357 }
358
359 private boolean suspiciousSubDomain(String domain) {
360 if (this.whitelistedDomains.contains(domain)) {
361 return false;
362 }
363 final String[] parts = domain.split("\\.");
364 return parts.length >= 3 && SUSPICIOUS_DOMAINS.contains(parts[0]);
365 }
366
367 protected class GatewayListAdapter extends RecyclerView.Adapter<GatewayListAdapter.ViewHolder> {
368 protected class ViewHolder extends RecyclerView.ViewHolder {
369 protected ToggleButton button;
370 protected int index;
371
372 public ViewHolder(View view, int i) {
373 super(view);
374 this.button = (ToggleButton) view.findViewById(R.id.button);
375 setIndex(i);
376 button.setOnClickListener(new View.OnClickListener() {
377 @Override
378 public void onClick(View v) {
379 button.setChecked(true); // Force visual not to flap to unchecked
380 setSelected(index);
381 }
382 });
383 }
384
385 public void setIndex(int i) {
386 this.index = i;
387 button.setChecked(selected == i);
388 }
389
390 public void useButton(int res) {
391 button.setText(res);
392 button.setTextOff(button.getText());
393 button.setTextOn(button.getText());
394 button.setChecked(selected == this.index);
395 binding.gatewayList.setVisibility(View.VISIBLE);
396 button.setVisibility(View.VISIBLE);
397 }
398
399 public void useButton(String txt) {
400 button.setTextOff(txt);
401 button.setTextOn(txt);
402 button.setChecked(selected == this.index);
403 binding.gatewayList.setVisibility(View.VISIBLE);
404 button.setVisibility(View.VISIBLE);
405 }
406 }
407
408 protected List<Pair<Contact,String>> gateways = new ArrayList();
409 protected int selected = 0;
410 protected Runnable onEmpty = () -> {};
411 protected Runnable onNonEmpty = () -> {};
412
413 @Override
414 public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
415 View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.enter_jid_dialog_gateway_list_item, null);
416 return new ViewHolder(view, i);
417 }
418
419 @Override
420 public void onBindViewHolder(ViewHolder viewHolder, int i) {
421 viewHolder.setIndex(i);
422
423 if(i == 0) {
424 viewHolder.useButton(R.string.account_settings_jabber_id);
425 } else {
426 viewHolder.useButton(getLabel(i));
427 }
428 }
429
430 @Override
431 public int getItemCount() {
432 return this.gateways.size() + 1;
433 }
434
435 public void setSelected(int i) {
436 int old = this.selected;
437 this.selected = i;
438
439 if(i == 0) {
440 binding.jid.setThreshold(1);
441 binding.jid.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS | InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE);
442 binding.jidLayout.setHint(R.string.account_settings_jabber_id);
443 } else {
444 binding.jid.setThreshold(999999); // do not autocomplete
445
446 String type = getType(i);
447 if (type.equals("pstn") || type.equals("sms")) {
448 binding.jid.setInputType(InputType.TYPE_CLASS_PHONE);
449 } else if (type.equals("email") || type.equals("sip")) {
450 binding.jid.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
451 } else {
452 binding.jid.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
453 }
454
455 binding.jidLayout.setHint(this.gateways.get(i-1).second);
456 binding.jid.setHint(null);
457 binding.jid.setOnFocusChangeListener((v, hasFocus) -> {});
458 }
459
460 notifyItemChanged(old);
461 notifyItemChanged(i);
462 }
463
464 public String getLabel(Contact gateway) {
465 String type = getType(gateway);
466 if (type != null) return type;
467
468 return gateway.getDisplayName();
469 }
470
471 public String getLabel(int i) {
472 if (i == 0) return null;
473
474 return getLabel(this.gateways.get(i-1).first);
475 }
476
477 public String getType(int i) {
478 if (i == 0) return null;
479
480 return getType(this.gateways.get(i-1).first);
481 }
482
483 public String getType(Contact gateway) {
484 for(Presence p : gateway.getPresences().getPresences()) {
485 ServiceDiscoveryResult.Identity id;
486 if(p.getServiceDiscoveryResult() != null && (id = p.getServiceDiscoveryResult().getIdentity("gateway", null)) != null) {
487 return id.getType();
488 }
489 }
490
491 return null;
492 }
493
494 public String getSelectedType() {
495 return getType(selected);
496 }
497
498 public Pair<String, Pair<Jid,Presence>> getSelected() {
499 if(this.selected == 0) {
500 return null; // No gateway, just use direct JID entry
501 }
502
503 Pair<Contact,String> gateway = this.gateways.get(this.selected - 1);
504
505 Pair<Jid,Presence> presence = null;
506 for (Map.Entry<String,Presence> e : gateway.first.getPresences().getPresencesMap().entrySet()) {
507 Presence p = e.getValue();
508 if (p.getServiceDiscoveryResult() != null) {
509 if (p.getServiceDiscoveryResult().getFeatures().contains("jabber:iq:gateway")) {
510 if (e.getKey().equals("")) {
511 presence = new Pair<>(gateway.first.getJid(), p);
512 } else {
513 presence = new Pair<>(gateway.first.getJid().withResource(e.getKey()), p);
514 }
515 break;
516 }
517 if (p.getServiceDiscoveryResult().hasIdentity("gateway", null)) {
518 if (e.getKey().equals("")) {
519 presence = new Pair<>(gateway.first.getJid(), p);
520 } else {
521 presence = new Pair<>(gateway.first.getJid().withResource(e.getKey()), p);
522 }
523 }
524 }
525 }
526
527 return presence == null ? null : new Pair(gateway.second, presence);
528 }
529
530 public void setOnEmpty(Runnable r) {
531 onEmpty = r;
532 }
533
534 public void setOnNonEmpty(Runnable r) {
535 onNonEmpty = r;
536 }
537
538 public void clear() {
539 gateways.clear();
540 onEmpty.run();
541 notifyDataSetChanged();
542 setSelected(0);
543 }
544
545 public void add(Contact gateway, String prompt) {
546 if (getItemCount() < 2) onNonEmpty.run();
547 this.gateways.add(new Pair<>(gateway, prompt));
548 Collections.sort(this.gateways, (x, y) -> getLabel(x.first).compareTo(getLabel(y.first)));
549 notifyDataSetChanged();
550 }
551 }
552}