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