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