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