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 == null || context.xmppConnectionService == null || accountJid() == null) return;
163
164 gatewayListAdapter.clear();
165 final Account account = context.xmppConnectionService.findAccountByJid(accountJid());
166 if (account == null) return;
167
168 for (final Contact contact : account.getRoster().getContacts()) {
169 if (contact.showInRoster() && (contact.getPresences().anyIdentity("gateway", null) || contact.getPresences().anySupport("jabber:iq:gateway"))) {
170 context.xmppConnectionService.fetchFromGateway(account, contact.getJid(), null, (final String prompt, String errorMessage) -> {
171 if (prompt == null && !contact.getPresences().anyIdentity("gateway", null)) return;
172
173 context.runOnUiThread(() -> {
174 gatewayListAdapter.add(contact, prompt);
175 });
176 });
177 }
178 }
179 }
180
181 @Override
182 public void onNothingSelected(AdapterView accountSpinner) {
183 gatewayListAdapter.clear();
184 }
185 });
186
187 builder.setView(binding.getRoot());
188 builder.setNegativeButton(R.string.cancel, null);
189 builder.setPositiveButton(getArguments().getString(POSITIVE_BUTTON_KEY), null);
190 this.dialog = builder.create();
191
192 View.OnClickListener dialogOnClick =
193 v -> {
194 handleEnter(binding, account);
195 };
196
197 binding.jid.setOnEditorActionListener(
198 (v, actionId, event) -> {
199 handleEnter(binding, account);
200 return true;
201 });
202
203 dialog.show();
204 dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(dialogOnClick);
205 return dialog;
206 }
207
208 protected Jid accountJid() {
209 try {
210 if (Config.DOMAIN_LOCK != null) {
211 return Jid.ofEscaped((String) binding.account.getSelectedItem(), Config.DOMAIN_LOCK, null);
212 } else {
213 return Jid.ofEscaped((String) binding.account.getSelectedItem());
214 }
215 } catch (final IllegalArgumentException e) {
216 return null;
217 }
218 }
219
220 private void handleEnter(EnterJidDialogBinding binding, String account) {
221 if (!binding.account.isEnabled() && account == null) {
222 return;
223 }
224 final Jid accountJid = accountJid();
225 final OnGatewayResult finish = (final String jidString, final String errorMessage) -> {
226 getActivity().runOnUiThread(() -> {
227 if (errorMessage != null) {
228 binding.jidLayout.setError(errorMessage);
229 return;
230 }
231 if (jidString == null) {
232 binding.jidLayout.setError(getActivity().getString(R.string.invalid_jid));
233 return;
234 }
235
236 final Jid contactJid;
237 try {
238 contactJid = Jid.ofEscaped(jidString);
239 } catch (final IllegalArgumentException e) {
240 binding.jidLayout.setError(getActivity().getString(R.string.invalid_jid));
241 return;
242 }
243
244 if (!issuedWarning && sanityCheckJid) {
245 if (contactJid.isDomainJid()) {
246 binding.jidLayout.setError(getActivity().getString(R.string.this_looks_like_a_domain));
247 dialog.getButton(AlertDialog.BUTTON_POSITIVE).setText(R.string.add_anway);
248 issuedWarning = true;
249 return;
250 }
251 if (suspiciousSubDomain(contactJid.getDomain().toEscapedString())) {
252 binding.jidLayout.setError(getActivity().getString(R.string.this_looks_like_channel));
253 dialog.getButton(AlertDialog.BUTTON_POSITIVE).setText(R.string.add_anway);
254 issuedWarning = true;
255 return;
256 }
257 }
258
259 if (mListener != null) {
260 try {
261 if (mListener.onEnterJidDialogPositive(accountJid, contactJid)) {
262 dialog.dismiss();
263 }
264 } catch (JidError error) {
265 binding.jidLayout.setError(error.toString());
266 dialog.getButton(AlertDialog.BUTTON_POSITIVE).setText(R.string.add);
267 issuedWarning = false;
268 }
269 }
270 });
271 };
272
273 Pair<String,Pair<Jid,Presence>> p = gatewayListAdapter.getSelected();
274 final String type = gatewayListAdapter.getSelectedType();
275
276 // Resolve based on local settings before submission
277 if (type != null && (type.equals("pstn") || type.equals("sms"))) {
278 try {
279 binding.jid.setText(PhoneNumberUtilWrapper.normalize(getActivity(), binding.jid.getText().toString()));
280 } catch (NumberParseException | IllegalArgumentException | NullPointerException e) { }
281 }
282
283 if (p == null) {
284 finish.onGatewayResult(binding.jid.getText().toString(), null);
285 } else if (p.first != null) { // Gateway already responsed to jabber:iq:gateway once
286 final Account acct = ((XmppActivity) getActivity()).xmppConnectionService.findAccountByJid(accountJid);
287 ((XmppActivity) getActivity()).xmppConnectionService.fetchFromGateway(acct, p.second.first, binding.jid.getText().toString(), finish);
288 } else if (p.second.first.isDomainJid() && p.second.second.getServiceDiscoveryResult().getFeatures().contains("jid\\20escaping")) {
289 finish.onGatewayResult(Jid.ofLocalAndDomain(binding.jid.getText().toString(), p.second.first.getDomain().toString()).toString(), null);
290 } else if (p.second.first.isDomainJid()) {
291 finish.onGatewayResult(Jid.ofLocalAndDomain(binding.jid.getText().toString().replace("@", "%"), p.second.first.getDomain().toString()).toString(), null);
292 } else {
293 finish.onGatewayResult(null, null);
294 }
295 }
296
297 public void setOnEnterJidDialogPositiveListener(OnEnterJidDialogPositiveListener listener) {
298 this.mListener = listener;
299 }
300
301 @Override
302 public void onBackendConnected() {
303 refreshKnownHosts();
304 }
305
306 private void refreshKnownHosts() {
307 final Activity activity = getActivity();
308 if (activity instanceof XmppActivity) {
309 final XmppConnectionService service = ((XmppActivity) activity).xmppConnectionService;
310 if (service == null) {
311 return;
312 }
313 final Collection<String> hosts = service.getKnownHosts();
314 this.knownHostsAdapter.refresh(hosts);
315 this.whitelistedDomains = hosts;
316 }
317 }
318
319 @Override
320 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
321
322 @Override
323 public void onTextChanged(CharSequence s, int start, int before, int count) {}
324
325 @Override
326 public void afterTextChanged(Editable s) {
327 if (issuedWarning) {
328 dialog.getButton(AlertDialog.BUTTON_POSITIVE).setText(R.string.add);
329 binding.jidLayout.setError(null);
330 issuedWarning = false;
331 }
332 }
333
334 public interface OnEnterJidDialogPositiveListener {
335 boolean onEnterJidDialogPositive(Jid account, Jid contact) throws EnterJidDialog.JidError;
336 }
337
338 public static class JidError extends Exception {
339 final String msg;
340
341 public JidError(final String msg) {
342 this.msg = msg;
343 }
344
345 @NonNull
346 public String toString() {
347 return msg;
348 }
349 }
350
351 @Override
352 public void onDestroyView() {
353 Dialog dialog = getDialog();
354 if (dialog != null && getRetainInstance()) {
355 dialog.setDismissMessage(null);
356 }
357 super.onDestroyView();
358 }
359
360 private boolean suspiciousSubDomain(String domain) {
361 if (this.whitelistedDomains.contains(domain)) {
362 return false;
363 }
364 final String[] parts = domain.split("\\.");
365 return parts.length >= 3 && SUSPICIOUS_DOMAINS.contains(parts[0]);
366 }
367
368 protected class GatewayListAdapter extends RecyclerView.Adapter<GatewayListAdapter.ViewHolder> {
369 protected class ViewHolder extends RecyclerView.ViewHolder {
370 protected ToggleButton button;
371 protected int index;
372
373 public ViewHolder(View view, int i) {
374 super(view);
375 this.button = (ToggleButton) view.findViewById(R.id.button);
376 setIndex(i);
377 button.setOnClickListener(new View.OnClickListener() {
378 @Override
379 public void onClick(View v) {
380 button.setChecked(true); // Force visual not to flap to unchecked
381 setSelected(index);
382 }
383 });
384 }
385
386 public void setIndex(int i) {
387 this.index = i;
388 button.setChecked(selected == i);
389 }
390
391 public void useButton(int res) {
392 button.setText(res);
393 button.setTextOff(button.getText());
394 button.setTextOn(button.getText());
395 button.setChecked(selected == this.index);
396 binding.gatewayList.setVisibility(View.VISIBLE);
397 button.setVisibility(View.VISIBLE);
398 }
399
400 public void useButton(String txt) {
401 button.setTextOff(txt);
402 button.setTextOn(txt);
403 button.setChecked(selected == this.index);
404 binding.gatewayList.setVisibility(View.VISIBLE);
405 button.setVisibility(View.VISIBLE);
406 }
407 }
408
409 protected List<Pair<Contact,String>> gateways = new ArrayList();
410 protected int selected = 0;
411 protected Runnable onEmpty = () -> {};
412 protected Runnable onNonEmpty = () -> {};
413
414 @Override
415 public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
416 View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.enter_jid_dialog_gateway_list_item, null);
417 return new ViewHolder(view, i);
418 }
419
420 @Override
421 public void onBindViewHolder(ViewHolder viewHolder, int i) {
422 viewHolder.setIndex(i);
423
424 if(i == 0) {
425 viewHolder.useButton(R.string.account_settings_jabber_id);
426 } else {
427 viewHolder.useButton(getLabel(i));
428 }
429 }
430
431 @Override
432 public int getItemCount() {
433 return this.gateways.size() + 1;
434 }
435
436 public void setSelected(int i) {
437 int old = this.selected;
438 this.selected = i;
439
440 if(i == 0) {
441 binding.jid.setThreshold(1);
442 binding.jid.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS | InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE);
443 binding.jidLayout.setHint(R.string.account_settings_jabber_id);
444
445 if(binding.jid.hasFocus()) {
446 binding.jid.setHint(R.string.account_settings_example_jabber_id);
447 } else {
448 DelayedHintHelper.setHint(R.string.account_settings_example_jabber_id, binding.jid);
449 }
450 } else {
451 binding.jid.setThreshold(999999); // do not autocomplete
452 binding.jid.setHint(null);
453 binding.jid.setOnFocusChangeListener((v, hasFocus) -> {});
454 binding.jidLayout.setHint(this.gateways.get(i-1).second);
455
456 String type = getType(i);
457 if (type == null) type = "";
458 if (type.equals("pstn") || type.equals("sms")) {
459 binding.jid.setInputType(InputType.TYPE_CLASS_PHONE);
460 } else if (type.equals("email") || type.equals("sip")) {
461 binding.jid.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
462
463 if(binding.jid.hasFocus()) {
464 binding.jid.setHint(R.string.account_settings_example_jabber_id);
465 } else {
466 DelayedHintHelper.setHint(R.string.account_settings_example_jabber_id, binding.jid);
467 }
468 } else {
469 binding.jid.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
470 }
471 }
472
473 notifyItemChanged(old);
474 notifyItemChanged(i);
475 }
476
477 public String getLabel(Contact gateway) {
478 String type = getType(gateway);
479 if (type != null) return type;
480
481 return gateway.getDisplayName();
482 }
483
484 public String getLabel(int i) {
485 if (i == 0) return null;
486
487 return getLabel(this.gateways.get(i-1).first);
488 }
489
490 public String getType(int i) {
491 if (i == 0) return null;
492
493 return getType(this.gateways.get(i-1).first);
494 }
495
496 public String getType(Contact gateway) {
497 for(Presence p : gateway.getPresences().getPresences()) {
498 ServiceDiscoveryResult.Identity id;
499 if(p.getServiceDiscoveryResult() != null && (id = p.getServiceDiscoveryResult().getIdentity("gateway", null)) != null) {
500 return id.getType();
501 }
502 }
503
504 return null;
505 }
506
507 public String getSelectedType() {
508 return getType(selected);
509 }
510
511 public Pair<String, Pair<Jid,Presence>> getSelected() {
512 if(this.selected == 0) {
513 return null; // No gateway, just use direct JID entry
514 }
515
516 Pair<Contact,String> gateway = this.gateways.get(this.selected - 1);
517
518 Pair<Jid,Presence> presence = null;
519 for (Map.Entry<String,Presence> e : gateway.first.getPresences().getPresencesMap().entrySet()) {
520 Presence p = e.getValue();
521 if (p.getServiceDiscoveryResult() != null) {
522 if (p.getServiceDiscoveryResult().getFeatures().contains("jabber:iq:gateway")) {
523 if (e.getKey().equals("")) {
524 presence = new Pair<>(gateway.first.getJid(), p);
525 } else {
526 presence = new Pair<>(gateway.first.getJid().withResource(e.getKey()), p);
527 }
528 break;
529 }
530 if (p.getServiceDiscoveryResult().hasIdentity("gateway", null)) {
531 if (e.getKey().equals("")) {
532 presence = new Pair<>(gateway.first.getJid(), p);
533 } else {
534 presence = new Pair<>(gateway.first.getJid().withResource(e.getKey()), p);
535 }
536 }
537 }
538 }
539
540 return presence == null ? null : new Pair(gateway.second, presence);
541 }
542
543 public void setOnEmpty(Runnable r) {
544 onEmpty = r;
545 }
546
547 public void setOnNonEmpty(Runnable r) {
548 onNonEmpty = r;
549 }
550
551 public void clear() {
552 gateways.clear();
553 onEmpty.run();
554 notifyDataSetChanged();
555 setSelected(0);
556 }
557
558 public void add(Contact gateway, String prompt) {
559 if (getItemCount() < 2) onNonEmpty.run();
560 this.gateways.add(new Pair<>(gateway, prompt));
561 Collections.sort(this.gateways, (x, y) -> getLabel(x.first).compareTo(getLabel(y.first)));
562 notifyDataSetChanged();
563 }
564 }
565}