1package eu.siacs.conversations.ui;
2
3import android.Manifest;
4import android.annotation.SuppressLint;
5import android.annotation.TargetApi;
6import android.app.PendingIntent;
7import android.content.ActivityNotFoundException;
8import android.content.ClipData;
9import android.content.ClipboardManager;
10import android.content.ComponentName;
11import android.content.Context;
12import android.content.ContextWrapper;
13import android.content.DialogInterface;
14import android.content.Intent;
15import android.content.IntentSender.SendIntentException;
16import android.content.ServiceConnection;
17import android.content.SharedPreferences;
18import android.content.pm.PackageManager;
19import android.content.pm.ResolveInfo;
20import android.content.res.Resources;
21import android.content.res.TypedArray;
22import android.databinding.DataBindingUtil;
23import android.graphics.Bitmap;
24import android.graphics.Color;
25import android.graphics.Point;
26import android.graphics.drawable.BitmapDrawable;
27import android.graphics.drawable.Drawable;
28import android.net.ConnectivityManager;
29import android.net.Uri;
30import android.os.AsyncTask;
31import android.os.Build;
32import android.os.Bundle;
33import android.os.Handler;
34import android.os.IBinder;
35import android.os.PowerManager;
36import android.os.SystemClock;
37import android.preference.PreferenceManager;
38import android.support.annotation.BoolRes;
39import android.support.annotation.NonNull;
40import android.support.annotation.StringRes;
41import android.support.v7.app.AlertDialog;
42import android.support.v7.app.AlertDialog.Builder;
43import android.support.v7.app.AppCompatDelegate;
44import android.text.InputType;
45import android.util.DisplayMetrics;
46import android.util.Log;
47import android.view.Menu;
48import android.view.MenuItem;
49import android.view.View;
50import android.widget.ImageView;
51import android.widget.Toast;
52
53import java.io.IOException;
54import java.lang.ref.WeakReference;
55import java.util.ArrayList;
56import java.util.List;
57import java.util.concurrent.RejectedExecutionException;
58
59import eu.siacs.conversations.Config;
60import eu.siacs.conversations.R;
61import eu.siacs.conversations.crypto.PgpEngine;
62import eu.siacs.conversations.databinding.DialogQuickeditBinding;
63import eu.siacs.conversations.entities.Account;
64import eu.siacs.conversations.entities.Contact;
65import eu.siacs.conversations.entities.Conversation;
66import eu.siacs.conversations.entities.Message;
67import eu.siacs.conversations.entities.Presences;
68import eu.siacs.conversations.services.AvatarService;
69import eu.siacs.conversations.services.BarcodeProvider;
70import eu.siacs.conversations.services.XmppConnectionService;
71import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
72import eu.siacs.conversations.ui.service.EmojiService;
73import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
74import eu.siacs.conversations.ui.util.PresenceSelector;
75import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
76import eu.siacs.conversations.utils.AccountUtils;
77import eu.siacs.conversations.utils.ExceptionHelper;
78import eu.siacs.conversations.utils.ThemeHelper;
79import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
80import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
81import rocks.xmpp.addr.Jid;
82
83public abstract class XmppActivity extends ActionBarActivity {
84
85 public static final String EXTRA_ACCOUNT = "account";
86 protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
87 protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
88 protected static final int REQUEST_CHOOSE_PGP_ID = 0x0103;
89 protected static final int REQUEST_BATTERY_OP = 0x49ff;
90 public XmppConnectionService xmppConnectionService;
91 public boolean xmppConnectionServiceBound = false;
92
93 protected static final String FRAGMENT_TAG_DIALOG = "dialog";
94
95 private boolean isCameraFeatureAvailable = false;
96
97 protected int mTheme;
98 protected boolean mUsingEnterKey = false;
99 protected Toast mToast;
100 public Runnable onOpenPGPKeyPublished = () -> Toast.makeText(XmppActivity.this, R.string.openpgp_has_been_published, Toast.LENGTH_SHORT).show();
101 protected ConferenceInvite mPendingConferenceInvite = null;
102 protected ServiceConnection mConnection = new ServiceConnection() {
103
104 @Override
105 public void onServiceConnected(ComponentName className, IBinder service) {
106 XmppConnectionBinder binder = (XmppConnectionBinder) service;
107 xmppConnectionService = binder.getService();
108 xmppConnectionServiceBound = true;
109 registerListeners();
110 onBackendConnected();
111 }
112
113 @Override
114 public void onServiceDisconnected(ComponentName arg0) {
115 xmppConnectionServiceBound = false;
116 }
117 };
118 private DisplayMetrics metrics;
119 private long mLastUiRefresh = 0;
120 private Handler mRefreshUiHandler = new Handler();
121 private Runnable mRefreshUiRunnable = () -> {
122 mLastUiRefresh = SystemClock.elapsedRealtime();
123 refreshUiReal();
124 };
125 private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
126 @Override
127 public void success(final Conversation conversation) {
128 runOnUiThread(() -> {
129 switchToConversation(conversation);
130 hideToast();
131 });
132 }
133
134 @Override
135 public void error(final int errorCode, Conversation object) {
136 runOnUiThread(() -> replaceToast(getString(errorCode)));
137 }
138
139 @Override
140 public void userInputRequired(PendingIntent pi, Conversation object) {
141
142 }
143 };
144 public boolean mSkipBackgroundBinding = false;
145
146 public static boolean cancelPotentialWork(Message message, ImageView imageView) {
147 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
148
149 if (bitmapWorkerTask != null) {
150 final Message oldMessage = bitmapWorkerTask.message;
151 if (oldMessage == null || message != oldMessage) {
152 bitmapWorkerTask.cancel(true);
153 } else {
154 return false;
155 }
156 }
157 return true;
158 }
159
160 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
161 if (imageView != null) {
162 final Drawable drawable = imageView.getDrawable();
163 if (drawable instanceof AsyncDrawable) {
164 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
165 return asyncDrawable.getBitmapWorkerTask();
166 }
167 }
168 return null;
169 }
170
171 protected void hideToast() {
172 if (mToast != null) {
173 mToast.cancel();
174 }
175 }
176
177 protected void replaceToast(String msg) {
178 replaceToast(msg, true);
179 }
180
181 protected void replaceToast(String msg, boolean showlong) {
182 hideToast();
183 mToast = Toast.makeText(this, msg, showlong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
184 mToast.show();
185 }
186
187 protected final void refreshUi() {
188 final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh;
189 if (diff > Config.REFRESH_UI_INTERVAL) {
190 mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
191 runOnUiThread(mRefreshUiRunnable);
192 } else {
193 final long next = Config.REFRESH_UI_INTERVAL - diff;
194 mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
195 mRefreshUiHandler.postDelayed(mRefreshUiRunnable, next);
196 }
197 }
198
199 abstract protected void refreshUiReal();
200
201 @Override
202 protected void onStart() {
203 super.onStart();
204 if (!xmppConnectionServiceBound) {
205 if (this.mSkipBackgroundBinding) {
206 Log.d(Config.LOGTAG,"skipping background binding");
207 } else {
208 connectToBackend();
209 }
210 } else {
211 this.registerListeners();
212 this.onBackendConnected();
213 }
214 }
215
216 public void connectToBackend() {
217 Intent intent = new Intent(this, XmppConnectionService.class);
218 intent.setAction("ui");
219 try {
220 startService(intent);
221 } catch (IllegalStateException e) {
222 Log.w(Config.LOGTAG,"unable to start service from "+getClass().getSimpleName());
223 }
224 bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
225 }
226
227 @Override
228 protected void onStop() {
229 super.onStop();
230 if (xmppConnectionServiceBound) {
231 this.unregisterListeners();
232 unbindService(mConnection);
233 xmppConnectionServiceBound = false;
234 }
235 }
236
237
238 public boolean hasPgp() {
239 return xmppConnectionService.getPgpEngine() != null;
240 }
241
242 public void showInstallPgpDialog() {
243 Builder builder = new AlertDialog.Builder(this);
244 builder.setTitle(getString(R.string.openkeychain_required));
245 builder.setIconAttribute(android.R.attr.alertDialogIcon);
246 builder.setMessage(getText(R.string.openkeychain_required_long));
247 builder.setNegativeButton(getString(R.string.cancel), null);
248 builder.setNeutralButton(getString(R.string.restart),
249 (dialog, which) -> {
250 if (xmppConnectionServiceBound) {
251 unbindService(mConnection);
252 xmppConnectionServiceBound = false;
253 }
254 stopService(new Intent(XmppActivity.this,
255 XmppConnectionService.class));
256 finish();
257 });
258 builder.setPositiveButton(getString(R.string.install),
259 (dialog, which) -> {
260 Uri uri = Uri
261 .parse("market://details?id=org.sufficientlysecure.keychain");
262 Intent marketIntent = new Intent(Intent.ACTION_VIEW,
263 uri);
264 PackageManager manager = getApplicationContext()
265 .getPackageManager();
266 List<ResolveInfo> infos = manager
267 .queryIntentActivities(marketIntent, 0);
268 if (infos.size() > 0) {
269 startActivity(marketIntent);
270 } else {
271 uri = Uri.parse("http://www.openkeychain.org/");
272 Intent browserIntent = new Intent(
273 Intent.ACTION_VIEW, uri);
274 startActivity(browserIntent);
275 }
276 finish();
277 });
278 builder.create().show();
279 }
280
281 abstract void onBackendConnected();
282
283 protected void registerListeners() {
284 if (this instanceof XmppConnectionService.OnConversationUpdate) {
285 this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
286 }
287 if (this instanceof XmppConnectionService.OnAccountUpdate) {
288 this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
289 }
290 if (this instanceof XmppConnectionService.OnCaptchaRequested) {
291 this.xmppConnectionService.setOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
292 }
293 if (this instanceof XmppConnectionService.OnRosterUpdate) {
294 this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
295 }
296 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
297 this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
298 }
299 if (this instanceof OnUpdateBlocklist) {
300 this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
301 }
302 if (this instanceof XmppConnectionService.OnShowErrorToast) {
303 this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
304 }
305 if (this instanceof OnKeyStatusUpdated) {
306 this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this);
307 }
308 if (this instanceof XmppConnectionService.OnJingleRtpConnectionUpdate) {
309 this.xmppConnectionService.setOnRtpConnectionUpdateListener((XmppConnectionService.OnJingleRtpConnectionUpdate) this);
310 }
311 }
312
313 protected void unregisterListeners() {
314 if (this instanceof XmppConnectionService.OnConversationUpdate) {
315 this.xmppConnectionService.removeOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
316 }
317 if (this instanceof XmppConnectionService.OnAccountUpdate) {
318 this.xmppConnectionService.removeOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
319 }
320 if (this instanceof XmppConnectionService.OnCaptchaRequested) {
321 this.xmppConnectionService.removeOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
322 }
323 if (this instanceof XmppConnectionService.OnRosterUpdate) {
324 this.xmppConnectionService.removeOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
325 }
326 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
327 this.xmppConnectionService.removeOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
328 }
329 if (this instanceof OnUpdateBlocklist) {
330 this.xmppConnectionService.removeOnUpdateBlocklistListener((OnUpdateBlocklist) this);
331 }
332 if (this instanceof XmppConnectionService.OnShowErrorToast) {
333 this.xmppConnectionService.removeOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
334 }
335 if (this instanceof OnKeyStatusUpdated) {
336 this.xmppConnectionService.removeOnNewKeysAvailableListener((OnKeyStatusUpdated) this);
337 }
338 if (this instanceof XmppConnectionService.OnJingleRtpConnectionUpdate) {
339 this.xmppConnectionService.removeRtpConnectionUpdateListener((XmppConnectionService.OnJingleRtpConnectionUpdate) this);
340 }
341 }
342
343 @Override
344 public boolean onOptionsItemSelected(final MenuItem item) {
345 switch (item.getItemId()) {
346 case R.id.action_settings:
347 startActivity(new Intent(this, SettingsActivity.class));
348 break;
349 case R.id.action_accounts:
350 AccountUtils.launchManageAccounts(this);
351 break;
352 case R.id.action_account:
353 AccountUtils.launchManageAccount(this);
354 break;
355 case android.R.id.home:
356 finish();
357 break;
358 case R.id.action_show_qr_code:
359 showQrCode();
360 break;
361 }
362 return super.onOptionsItemSelected(item);
363 }
364
365 public void selectPresence(final Conversation conversation, final PresenceSelector.OnPresenceSelected listener) {
366 final Contact contact = conversation.getContact();
367 if (!contact.showInRoster()) {
368 showAddToRosterDialog(conversation.getContact());
369 } else {
370 final Presences presences = contact.getPresences();
371 if (presences.size() == 0) {
372 if (!contact.getOption(Contact.Options.TO)
373 && !contact.getOption(Contact.Options.ASKING)
374 && contact.getAccount().getStatus() == Account.State.ONLINE) {
375 showAskForPresenceDialog(contact);
376 } else if (!contact.getOption(Contact.Options.TO)
377 || !contact.getOption(Contact.Options.FROM)) {
378 PresenceSelector.warnMutualPresenceSubscription(this, conversation, listener);
379 } else {
380 conversation.setNextCounterpart(null);
381 listener.onPresenceSelected();
382 }
383 } else if (presences.size() == 1) {
384 String presence = presences.toResourceArray()[0];
385 try {
386 conversation.setNextCounterpart(Jid.of(contact.getJid().getLocal(), contact.getJid().getDomain(), presence));
387 } catch (IllegalArgumentException e) {
388 conversation.setNextCounterpart(null);
389 }
390 listener.onPresenceSelected();
391 } else {
392 PresenceSelector.showPresenceSelectionDialog(this, conversation, listener);
393 }
394 }
395 }
396
397 @SuppressLint("UnsupportedChromeOsCameraSystemFeature")
398 @Override
399 protected void onCreate(Bundle savedInstanceState) {
400 super.onCreate(savedInstanceState);
401 metrics = getResources().getDisplayMetrics();
402 ExceptionHelper.init(getApplicationContext());
403 new EmojiService(this).init();
404 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
405 this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
406 } else {
407 this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
408 }
409 this.mTheme = findTheme();
410 setTheme(this.mTheme);
411
412 this.mUsingEnterKey = usingEnterKey();
413 }
414
415 protected boolean isCameraFeatureAvailable() {
416 return this.isCameraFeatureAvailable;
417 }
418
419 public boolean isDarkTheme() {
420 return ThemeHelper.isDark(mTheme);
421 }
422
423 public int getThemeResource(int r_attr_name, int r_drawable_def) {
424 int[] attrs = {r_attr_name};
425 TypedArray ta = this.getTheme().obtainStyledAttributes(attrs);
426
427 int res = ta.getResourceId(0, r_drawable_def);
428 ta.recycle();
429
430 return res;
431 }
432
433 protected boolean isOptimizingBattery() {
434 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
435 final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
436 return pm != null
437 && !pm.isIgnoringBatteryOptimizations(getPackageName());
438 } else {
439 return false;
440 }
441 }
442
443 protected boolean isAffectedByDataSaver() {
444 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
445 final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
446 return cm != null
447 && cm.isActiveNetworkMetered()
448 && cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
449 } else {
450 return false;
451 }
452 }
453
454 protected boolean usingEnterKey() {
455 return getBooleanPreference("display_enter_key", R.bool.display_enter_key);
456 }
457
458 protected SharedPreferences getPreferences() {
459 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
460 }
461
462 protected boolean getBooleanPreference(String name, @BoolRes int res) {
463 return getPreferences().getBoolean(name, getResources().getBoolean(res));
464 }
465
466 public void switchToConversation(Conversation conversation) {
467 switchToConversation(conversation, null);
468 }
469
470 public void switchToConversationAndQuote(Conversation conversation, String text) {
471 switchToConversation(conversation, text, true, null, false, false);
472 }
473
474 public void switchToConversation(Conversation conversation, String text) {
475 switchToConversation(conversation, text, false, null, false, false);
476 }
477
478 public void switchToConversationDoNotAppend(Conversation conversation, String text) {
479 switchToConversation(conversation, text, false, null, false, true);
480 }
481
482 public void highlightInMuc(Conversation conversation, String nick) {
483 switchToConversation(conversation, null, false, nick, false, false);
484 }
485
486 public void privateMsgInMuc(Conversation conversation, String nick) {
487 switchToConversation(conversation, null, false, nick, true, false);
488 }
489
490 private void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend) {
491 Intent intent = new Intent(this, ConversationsActivity.class);
492 intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
493 intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
494 if (text != null) {
495 intent.putExtra(Intent.EXTRA_TEXT, text);
496 if (asQuote) {
497 intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true);
498 }
499 }
500 if (nick != null) {
501 intent.putExtra(ConversationsActivity.EXTRA_NICK, nick);
502 intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
503 }
504 if (doNotAppend) {
505 intent.putExtra(ConversationsActivity.EXTRA_DO_NOT_APPEND, true);
506 }
507 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP);
508 startActivity(intent);
509 finish();
510 }
511
512 public void switchToContactDetails(Contact contact) {
513 switchToContactDetails(contact, null);
514 }
515
516 public void switchToContactDetails(Contact contact, String messageFingerprint) {
517 Intent intent = new Intent(this, ContactDetailsActivity.class);
518 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
519 intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toString());
520 intent.putExtra("contact", contact.getJid().toString());
521 intent.putExtra("fingerprint", messageFingerprint);
522 startActivity(intent);
523 }
524
525 public void switchToAccount(Account account, String fingerprint) {
526 switchToAccount(account, false, fingerprint);
527 }
528
529 public void switchToAccount(Account account) {
530 switchToAccount(account, false, null);
531 }
532
533 public void switchToAccount(Account account, boolean init, String fingerprint) {
534 Intent intent = new Intent(this, EditAccountActivity.class);
535 intent.putExtra("jid", account.getJid().asBareJid().toString());
536 intent.putExtra("init", init);
537 if (init) {
538 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
539 }
540 if (fingerprint != null) {
541 intent.putExtra("fingerprint", fingerprint);
542 }
543 startActivity(intent);
544 if (init) {
545 overridePendingTransition(0, 0);
546 }
547 }
548
549 protected void delegateUriPermissionsToService(Uri uri) {
550 Intent intent = new Intent(this, XmppConnectionService.class);
551 intent.setAction(Intent.ACTION_SEND);
552 intent.setData(uri);
553 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
554 try {
555 startService(intent);
556 } catch (Exception e) {
557 Log.e(Config.LOGTAG,"unable to delegate uri permission",e);
558 }
559 }
560
561 protected void inviteToConversation(Conversation conversation) {
562 startActivityForResult(ChooseContactActivity.create(this,conversation), REQUEST_INVITE_TO_CONVERSATION);
563 }
564
565 protected void announcePgp(final Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
566 if (account.getPgpId() == 0) {
567 choosePgpSignId(account);
568 } else {
569 String status = null;
570 if (manuallyChangePresence()) {
571 status = account.getPresenceStatusMessage();
572 }
573 if (status == null) {
574 status = "";
575 }
576 xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() {
577
578 @Override
579 public void userInputRequired(PendingIntent pi, String signature) {
580 try {
581 startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
582 } catch (final SendIntentException ignored) {
583 }
584 }
585
586 @Override
587 public void success(String signature) {
588 account.setPgpSignature(signature);
589 xmppConnectionService.databaseBackend.updateAccount(account);
590 xmppConnectionService.sendPresence(account);
591 if (conversation != null) {
592 conversation.setNextEncryption(Message.ENCRYPTION_PGP);
593 xmppConnectionService.updateConversation(conversation);
594 refreshUi();
595 }
596 if (onSuccess != null) {
597 runOnUiThread(onSuccess);
598 }
599 }
600
601 @Override
602 public void error(int error, String signature) {
603 if (error == 0) {
604 account.setPgpSignId(0);
605 account.unsetPgpSignature();
606 xmppConnectionService.databaseBackend.updateAccount(account);
607 choosePgpSignId(account);
608 } else {
609 displayErrorDialog(error);
610 }
611 }
612 });
613 }
614 }
615
616 @SuppressWarnings("deprecation")
617 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
618 protected void setListItemBackgroundOnView(View view) {
619 int sdk = android.os.Build.VERSION.SDK_INT;
620 if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
621 view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
622 } else {
623 view.setBackground(getResources().getDrawable(R.drawable.greybackground));
624 }
625 }
626
627 protected void choosePgpSignId(Account account) {
628 xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
629 @Override
630 public void success(Account account1) {
631 }
632
633 @Override
634 public void error(int errorCode, Account object) {
635
636 }
637
638 @Override
639 public void userInputRequired(PendingIntent pi, Account object) {
640 try {
641 startIntentSenderForResult(pi.getIntentSender(),
642 REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
643 } catch (final SendIntentException ignored) {
644 }
645 }
646 });
647 }
648
649 protected void displayErrorDialog(final int errorCode) {
650 runOnUiThread(() -> {
651 Builder builder = new Builder(XmppActivity.this);
652 builder.setIconAttribute(android.R.attr.alertDialogIcon);
653 builder.setTitle(getString(R.string.error));
654 builder.setMessage(errorCode);
655 builder.setNeutralButton(R.string.accept, null);
656 builder.create().show();
657 });
658
659 }
660
661 protected void showAddToRosterDialog(final Contact contact) {
662 AlertDialog.Builder builder = new AlertDialog.Builder(this);
663 builder.setTitle(contact.getJid().toString());
664 builder.setMessage(getString(R.string.not_in_roster));
665 builder.setNegativeButton(getString(R.string.cancel), null);
666 builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> xmppConnectionService.createContact(contact,true));
667 builder.create().show();
668 }
669
670 private void showAskForPresenceDialog(final Contact contact) {
671 AlertDialog.Builder builder = new AlertDialog.Builder(this);
672 builder.setTitle(contact.getJid().toString());
673 builder.setMessage(R.string.request_presence_updates);
674 builder.setNegativeButton(R.string.cancel, null);
675 builder.setPositiveButton(R.string.request_now,
676 (dialog, which) -> {
677 if (xmppConnectionServiceBound) {
678 xmppConnectionService.sendPresencePacket(contact
679 .getAccount(), xmppConnectionService
680 .getPresenceGenerator()
681 .requestPresenceUpdatesFrom(contact));
682 }
683 });
684 builder.create().show();
685 }
686
687 protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) {
688 quickEdit(previousValue, callback, hint, false, false);
689 }
690
691 protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback, boolean permitEmpty) {
692 quickEdit(previousValue, callback, hint, false, permitEmpty);
693 }
694
695 protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
696 quickEdit(previousValue, callback, R.string.password, true, false);
697 }
698
699 @SuppressLint("InflateParams")
700 private void quickEdit(final String previousValue,
701 final OnValueEdited callback,
702 final @StringRes int hint,
703 boolean password,
704 boolean permitEmpty) {
705 AlertDialog.Builder builder = new AlertDialog.Builder(this);
706 DialogQuickeditBinding binding = DataBindingUtil.inflate(getLayoutInflater(),R.layout.dialog_quickedit, null, false);
707 if (password) {
708 binding.inputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
709 }
710 builder.setPositiveButton(R.string.accept, null);
711 if (hint != 0) {
712 binding.inputLayout.setHint(getString(hint));
713 }
714 binding.inputEditText.requestFocus();
715 if (previousValue != null) {
716 binding.inputEditText.getText().append(previousValue);
717 }
718 builder.setView(binding.getRoot());
719 builder.setNegativeButton(R.string.cancel, null);
720 final AlertDialog dialog = builder.create();
721 dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText));
722 dialog.show();
723 View.OnClickListener clickListener = v -> {
724 String value = binding.inputEditText.getText().toString();
725 if (!value.equals(previousValue) && (!value.trim().isEmpty() || permitEmpty)) {
726 String error = callback.onValueEdited(value);
727 if (error != null) {
728 binding.inputLayout.setError(error);
729 return;
730 }
731 }
732 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
733 dialog.dismiss();
734 };
735 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
736 dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener((v -> {
737 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
738 dialog.dismiss();
739 }));
740 dialog.setCanceledOnTouchOutside(false);
741 dialog.setOnDismissListener(dialog1 -> {
742 SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText);
743 });
744 }
745
746 protected boolean hasStoragePermission(int requestCode) {
747 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
748 if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
749 requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
750 return false;
751 } else {
752 return true;
753 }
754 } else {
755 return true;
756 }
757 }
758
759 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
760 super.onActivityResult(requestCode, resultCode, data);
761 if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
762 mPendingConferenceInvite = ConferenceInvite.parse(data);
763 if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
764 if (mPendingConferenceInvite.execute(this)) {
765 mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
766 mToast.show();
767 }
768 mPendingConferenceInvite = null;
769 }
770 }
771 }
772
773 public boolean copyTextToClipboard(String text, int labelResId) {
774 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
775 String label = getResources().getString(labelResId);
776 if (mClipBoardManager != null) {
777 ClipData mClipData = ClipData.newPlainText(label, text);
778 mClipBoardManager.setPrimaryClip(mClipData);
779 return true;
780 }
781 return false;
782 }
783
784 protected boolean manuallyChangePresence() {
785 return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence);
786 }
787
788 protected String getShareableUri() {
789 return getShareableUri(false);
790 }
791
792 protected String getShareableUri(boolean http) {
793 return null;
794 }
795
796 protected void shareLink(boolean http) {
797 String uri = getShareableUri(http);
798 if (uri == null || uri.isEmpty()) {
799 return;
800 }
801 Intent intent = new Intent(Intent.ACTION_SEND);
802 intent.setType("text/plain");
803 intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
804 try {
805 startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
806 } catch (ActivityNotFoundException e) {
807 Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
808 }
809 }
810
811 protected void launchOpenKeyChain(long keyId) {
812 PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
813 try {
814 startIntentSenderForResult(
815 pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
816 0, 0);
817 } catch (Throwable e) {
818 Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
819 }
820 }
821
822 @Override
823 public void onResume() {
824 super.onResume();
825 }
826
827 protected int findTheme() {
828 return ThemeHelper.find(this);
829 }
830
831 @Override
832 public void onPause() {
833 super.onPause();
834 }
835
836 @Override
837 public boolean onMenuOpened(int id, Menu menu) {
838 if(id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
839 MenuDoubleTabUtil.recordMenuOpen();
840 }
841 return super.onMenuOpened(id, menu);
842 }
843
844 protected void showQrCode() {
845 showQrCode(getShareableUri());
846 }
847
848 protected void showQrCode(final String uri) {
849 if (uri == null || uri.isEmpty()) {
850 return;
851 }
852 Point size = new Point();
853 getWindowManager().getDefaultDisplay().getSize(size);
854 final int width = (size.x < size.y ? size.x : size.y);
855 Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
856 ImageView view = new ImageView(this);
857 view.setBackgroundColor(Color.WHITE);
858 view.setImageBitmap(bitmap);
859 AlertDialog.Builder builder = new AlertDialog.Builder(this);
860 builder.setView(view);
861 builder.create().show();
862 }
863
864 protected Account extractAccount(Intent intent) {
865 final String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
866 try {
867 return jid != null ? xmppConnectionService.findAccountByJid(Jid.of(jid)) : null;
868 } catch (IllegalArgumentException e) {
869 return null;
870 }
871 }
872
873 public AvatarService avatarService() {
874 return xmppConnectionService.getAvatarService();
875 }
876
877 public void loadBitmap(Message message, ImageView imageView) {
878 Bitmap bm;
879 try {
880 bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true);
881 } catch (IOException e) {
882 bm = null;
883 }
884 if (bm != null) {
885 cancelPotentialWork(message, imageView);
886 imageView.setImageBitmap(bm);
887 imageView.setBackgroundColor(0x00000000);
888 } else {
889 if (cancelPotentialWork(message, imageView)) {
890 imageView.setBackgroundColor(0xff333333);
891 imageView.setImageDrawable(null);
892 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
893 final AsyncDrawable asyncDrawable = new AsyncDrawable(
894 getResources(), null, task);
895 imageView.setImageDrawable(asyncDrawable);
896 try {
897 task.execute(message);
898 } catch (final RejectedExecutionException ignored) {
899 ignored.printStackTrace();
900 }
901 }
902 }
903 }
904
905 protected interface OnValueEdited {
906 String onValueEdited(String value);
907 }
908
909 public static class ConferenceInvite {
910 private String uuid;
911 private List<Jid> jids = new ArrayList<>();
912
913 public static ConferenceInvite parse(Intent data) {
914 ConferenceInvite invite = new ConferenceInvite();
915 invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION);
916 if (invite.uuid == null) {
917 return null;
918 }
919 invite.jids.addAll(ChooseContactActivity.extractJabberIds(data));
920 return invite;
921 }
922
923 public boolean execute(XmppActivity activity) {
924 XmppConnectionService service = activity.xmppConnectionService;
925 Conversation conversation = service.findConversationByUuid(this.uuid);
926 if (conversation == null) {
927 return false;
928 }
929 if (conversation.getMode() == Conversation.MODE_MULTI) {
930 for (Jid jid : jids) {
931 service.invite(conversation, jid);
932 }
933 return false;
934 } else {
935 jids.add(conversation.getJid().asBareJid());
936 return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
937 }
938 }
939 }
940
941 static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
942 private final WeakReference<ImageView> imageViewReference;
943 private Message message = null;
944
945 private BitmapWorkerTask(ImageView imageView) {
946 this.imageViewReference = new WeakReference<>(imageView);
947 }
948
949 @Override
950 protected Bitmap doInBackground(Message... params) {
951 if (isCancelled()) {
952 return null;
953 }
954 message = params[0];
955 try {
956 final XmppActivity activity = find(imageViewReference);
957 if (activity != null && activity.xmppConnectionService != null) {
958 return activity.xmppConnectionService.getFileBackend().getThumbnail(message, (int) (activity.metrics.density * 288), false);
959 } else {
960 return null;
961 }
962 } catch (IOException e) {
963 return null;
964 }
965 }
966
967 @Override
968 protected void onPostExecute(final Bitmap bitmap) {
969 if (!isCancelled()) {
970 final ImageView imageView = imageViewReference.get();
971 if (imageView != null) {
972 imageView.setImageBitmap(bitmap);
973 imageView.setBackgroundColor(bitmap == null ? 0xff333333 : 0x00000000);
974 }
975 }
976 }
977 }
978
979 private static class AsyncDrawable extends BitmapDrawable {
980 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
981
982 private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
983 super(res, bitmap);
984 bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
985 }
986
987 private BitmapWorkerTask getBitmapWorkerTask() {
988 return bitmapWorkerTaskReference.get();
989 }
990 }
991
992 public static XmppActivity find(@NonNull WeakReference<ImageView> viewWeakReference) {
993 final View view = viewWeakReference.get();
994 return view == null ? null : find(view);
995 }
996
997 public static XmppActivity find(@NonNull final View view) {
998 Context context = view.getContext();
999 while (context instanceof ContextWrapper) {
1000 if (context instanceof XmppActivity) {
1001 return (XmppActivity) context;
1002 }
1003 context = ((ContextWrapper)context).getBaseContext();
1004 }
1005 return null;
1006 }
1007}