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.Presences;
65import eu.siacs.conversations.services.AvatarService;
66import eu.siacs.conversations.services.BarcodeProvider;
67import eu.siacs.conversations.services.XmppConnectionService;
68import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
69import eu.siacs.conversations.ui.util.PresenceSelector;
70import eu.siacs.conversations.utils.ExceptionHelper;
71import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
72import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
73import rocks.xmpp.addr.Jid;
74
75public abstract class XmppActivity extends AppCompatActivity {
76
77 public static final String EXTRA_ACCOUNT = "account";
78 protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
79 protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
80 protected static final int REQUEST_CHOOSE_PGP_ID = 0x0103;
81 protected static final int REQUEST_BATTERY_OP = 0x49ff;
82 public XmppConnectionService xmppConnectionService;
83 public boolean xmppConnectionServiceBound = false;
84 protected boolean registeredListeners = false;
85
86 protected int mColorRed;
87 protected int mColorOrange;
88 protected int mColorGreen;
89
90 protected static final String FRAGMENT_TAG_DIALOG = "dialog";
91
92 private boolean isCameraFeatureAvailable = false;
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 this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
413
414 mColorRed = ContextCompat.getColor(this, R.color.red800);
415 mColorOrange = ContextCompat.getColor(this, R.color.orange500);
416 mColorGreen = ContextCompat.getColor(this, R.color.green500);
417
418 this.mTheme = findTheme();
419 setTheme(this.mTheme);
420
421 this.mUsingEnterKey = usingEnterKey();
422 mUseSubject = getPreferences().getBoolean("use_subject", getResources().getBoolean(R.bool.use_subject));
423 final ActionBar ab = getSupportActionBar();
424 if (ab != null) {
425 ab.setDisplayHomeAsUpEnabled(true);
426 }
427 }
428
429 protected boolean isCameraFeatureAvailable() {
430 return this.isCameraFeatureAvailable;
431 }
432
433 public boolean isDarkTheme() {
434 return this.mTheme == R.style.ConversationsTheme_Dark;
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 protected boolean noAccountUsesPgp() {
614 if (!hasPgp()) {
615 return true;
616 }
617 for (Account account : xmppConnectionService.getAccounts()) {
618 if (account.getPgpId() != 0) {
619 return false;
620 }
621 }
622 return true;
623 }
624
625 @SuppressWarnings("deprecation")
626 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
627 protected void setListItemBackgroundOnView(View view) {
628 int sdk = android.os.Build.VERSION.SDK_INT;
629 if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
630 view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
631 } else {
632 view.setBackground(getResources().getDrawable(R.drawable.greybackground));
633 }
634 }
635
636 protected void choosePgpSignId(Account account) {
637 xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
638 @Override
639 public void success(Account account1) {
640 }
641
642 @Override
643 public void error(int errorCode, Account object) {
644
645 }
646
647 @Override
648 public void userInputRequried(PendingIntent pi, Account object) {
649 try {
650 startIntentSenderForResult(pi.getIntentSender(),
651 REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
652 } catch (final SendIntentException ignored) {
653 }
654 }
655 });
656 }
657
658 protected void displayErrorDialog(final int errorCode) {
659 runOnUiThread(() -> {
660 Builder builder = new Builder(XmppActivity.this);
661 builder.setIconAttribute(android.R.attr.alertDialogIcon);
662 builder.setTitle(getString(R.string.error));
663 builder.setMessage(errorCode);
664 builder.setNeutralButton(R.string.accept, null);
665 builder.create().show();
666 });
667
668 }
669
670 protected void showAddToRosterDialog(final Contact contact) {
671 AlertDialog.Builder builder = new AlertDialog.Builder(this);
672 builder.setTitle(contact.getJid().toString());
673 builder.setMessage(getString(R.string.not_in_roster));
674 builder.setNegativeButton(getString(R.string.cancel), null);
675 builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> xmppConnectionService.createContact(contact,true));
676 builder.create().show();
677 }
678
679 private void showAskForPresenceDialog(final Contact contact) {
680 AlertDialog.Builder builder = new AlertDialog.Builder(this);
681 builder.setTitle(contact.getJid().toString());
682 builder.setMessage(R.string.request_presence_updates);
683 builder.setNegativeButton(R.string.cancel, null);
684 builder.setPositiveButton(R.string.request_now,
685 (dialog, which) -> {
686 if (xmppConnectionServiceBound) {
687 xmppConnectionService.sendPresencePacket(contact
688 .getAccount(), xmppConnectionService
689 .getPresenceGenerator()
690 .requestPresenceUpdatesFrom(contact));
691 }
692 });
693 builder.create().show();
694 }
695
696 protected void quickEdit(String previousValue, int hint, OnValueEdited callback) {
697 quickEdit(previousValue, callback, hint, false);
698 }
699
700 protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
701 quickEdit(previousValue, callback, R.string.password, true);
702 }
703
704 @SuppressLint("InflateParams")
705 private void quickEdit(final String previousValue,
706 final OnValueEdited callback,
707 final int hint,
708 boolean password) {
709 AlertDialog.Builder builder = new AlertDialog.Builder(this);
710 View view = getLayoutInflater().inflate(R.layout.quickedit, null);
711 final EditText editor = view.findViewById(R.id.editor);
712 if (password) {
713 editor.setInputType(InputType.TYPE_CLASS_TEXT
714 | InputType.TYPE_TEXT_VARIATION_PASSWORD);
715 }
716 builder.setPositiveButton(R.string.accept, null);
717 if (hint != 0) {
718 editor.setHint(hint);
719 }
720 editor.requestFocus();
721 editor.setText("");
722 if (previousValue != null) {
723 editor.getText().append(previousValue);
724 }
725 builder.setView(view);
726 builder.setNegativeButton(R.string.cancel, null);
727 final AlertDialog dialog = builder.create();
728 dialog.show();
729 View.OnClickListener clickListener = v -> {
730 String value = editor.getText().toString();
731 if (!value.equals(previousValue) && value.trim().length() > 0) {
732 String error = callback.onValueEdited(value);
733 if (error != null) {
734 editor.setError(error);
735 return;
736 }
737 }
738 dialog.dismiss();
739 };
740 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
741 }
742
743 protected boolean hasStoragePermission(int requestCode) {
744 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
745 if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
746 requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
747 return false;
748 } else {
749 return true;
750 }
751 } else {
752 return true;
753 }
754 }
755
756 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
757 super.onActivityResult(requestCode, resultCode, data);
758 if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
759 mPendingConferenceInvite = ConferenceInvite.parse(data);
760 if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
761 if (mPendingConferenceInvite.execute(this)) {
762 mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
763 mToast.show();
764 }
765 mPendingConferenceInvite = null;
766 }
767 }
768 }
769
770 public int getWarningTextColor() {
771 return this.mColorRed;
772 }
773
774 public int getOnlineColor() {
775 return this.mColorGreen;
776 }
777
778 public int getPixel(int dp) {
779 DisplayMetrics metrics = getResources().getDisplayMetrics();
780 return ((int) (dp * metrics.density));
781 }
782
783 public boolean copyTextToClipboard(String text, int labelResId) {
784 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
785 String label = getResources().getString(labelResId);
786 if (mClipBoardManager != null) {
787 ClipData mClipData = ClipData.newPlainText(label, text);
788 mClipBoardManager.setPrimaryClip(mClipData);
789 return true;
790 }
791 return false;
792 }
793
794 protected boolean neverCompressPictures() {
795 return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression)).equals("never");
796 }
797
798 protected boolean manuallyChangePresence() {
799 return getPreferences().getBoolean(SettingsActivity.MANUALLY_CHANGE_PRESENCE, getResources().getBoolean(R.bool.manually_change_presence));
800 }
801
802 protected String getShareableUri() {
803 return getShareableUri(false);
804 }
805
806 protected String getShareableUri(boolean http) {
807 return null;
808 }
809
810 protected void shareLink(boolean http) {
811 String uri = getShareableUri(http);
812 if (uri == null || uri.isEmpty()) {
813 return;
814 }
815 Intent intent = new Intent(Intent.ACTION_SEND);
816 intent.setType("text/plain");
817 intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
818 try {
819 startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
820 } catch (ActivityNotFoundException e) {
821 Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
822 }
823 }
824
825 protected void launchOpenKeyChain(long keyId) {
826 PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
827 try {
828 startIntentSenderForResult(
829 pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
830 0, 0);
831 } catch (Throwable e) {
832 Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
833 }
834 }
835
836 @Override
837 public void onResume() {
838 super.onResume();
839 }
840
841 protected int findTheme() {
842 Boolean dark = getPreferences().getString(SettingsActivity.THEME, getResources().getString(R.string.theme)).equals("dark");
843
844 if (dark) {
845 return R.style.ConversationsTheme_Dark;
846 } else {
847 return R.style.ConversationsTheme;
848 }
849 }
850
851 @Override
852 public void onPause() {
853 super.onPause();
854 }
855
856 protected void showQrCode() {
857 showQrCode(getShareableUri());
858 }
859
860 protected void showQrCode(final String uri) {
861 if (uri == null || uri.isEmpty()) {
862 return;
863 }
864 Point size = new Point();
865 getWindowManager().getDefaultDisplay().getSize(size);
866 final int width = (size.x < size.y ? size.x : size.y);
867 Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
868 ImageView view = new ImageView(this);
869 view.setBackgroundColor(Color.WHITE);
870 view.setImageBitmap(bitmap);
871 AlertDialog.Builder builder = new AlertDialog.Builder(this);
872 builder.setView(view);
873 builder.create().show();
874 }
875
876 protected Account extractAccount(Intent intent) {
877 String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
878 try {
879 return jid != null ? xmppConnectionService.findAccountByJid(Jid.of(jid)) : null;
880 } catch (IllegalArgumentException e) {
881 return null;
882 }
883 }
884
885 public AvatarService avatarService() {
886 return xmppConnectionService.getAvatarService();
887 }
888
889 public void loadBitmap(Message message, ImageView imageView) {
890 Bitmap bm;
891 try {
892 bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true);
893 } catch (FileNotFoundException e) {
894 bm = null;
895 }
896 if (bm != null) {
897 cancelPotentialWork(message, imageView);
898 imageView.setImageBitmap(bm);
899 imageView.setBackgroundColor(0x00000000);
900 } else {
901 if (cancelPotentialWork(message, imageView)) {
902 imageView.setBackgroundColor(0xff333333);
903 imageView.setImageDrawable(null);
904 final BitmapWorkerTask task = new BitmapWorkerTask(this, imageView);
905 final AsyncDrawable asyncDrawable = new AsyncDrawable(
906 getResources(), null, task);
907 imageView.setImageDrawable(asyncDrawable);
908 try {
909 task.execute(message);
910 } catch (final RejectedExecutionException ignored) {
911 ignored.printStackTrace();
912 }
913 }
914 }
915 }
916
917 protected interface OnValueEdited {
918 String onValueEdited(String value);
919 }
920
921 public static class ConferenceInvite {
922 private String uuid;
923 private List<Jid> jids = new ArrayList<>();
924
925 public static ConferenceInvite parse(Intent data) {
926 ConferenceInvite invite = new ConferenceInvite();
927 invite.uuid = data.getStringExtra("conversation");
928 if (invite.uuid == null) {
929 return null;
930 }
931 try {
932 if (data.getBooleanExtra("multiple", false)) {
933 String[] toAdd = data.getStringArrayExtra("contacts");
934 for (String item : toAdd) {
935 invite.jids.add(Jid.of(item));
936 }
937 } else {
938 invite.jids.add(Jid.of(data.getStringExtra("contact")));
939 }
940 } catch (final IllegalArgumentException ignored) {
941 return null;
942 }
943 return invite;
944 }
945
946 public boolean execute(XmppActivity activity) {
947 XmppConnectionService service = activity.xmppConnectionService;
948 Conversation conversation = service.findConversationByUuid(this.uuid);
949 if (conversation == null) {
950 return false;
951 }
952 if (conversation.getMode() == Conversation.MODE_MULTI) {
953 for (Jid jid : jids) {
954 service.invite(conversation, jid);
955 }
956 return false;
957 } else {
958 jids.add(conversation.getJid().asBareJid());
959 return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
960 }
961 }
962 }
963
964 static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
965 private final WeakReference<ImageView> imageViewReference;
966 private final WeakReference<XmppActivity> activity;
967 private Message message = null;
968
969 private BitmapWorkerTask(XmppActivity activity, ImageView imageView) {
970 this.activity = new WeakReference<>(activity);
971 this.imageViewReference = new WeakReference<>(imageView);
972 }
973
974 @Override
975 protected Bitmap doInBackground(Message... params) {
976 if (isCancelled()) {
977 return null;
978 }
979 message = params[0];
980 try {
981 XmppActivity activity = this.activity.get();
982 if (activity != null && activity.xmppConnectionService != null) {
983 return activity.xmppConnectionService.getFileBackend().getThumbnail(message, (int) (activity.metrics.density * 288), false);
984 } else {
985 return null;
986 }
987 } catch (FileNotFoundException e) {
988 return null;
989 }
990 }
991
992 @Override
993 protected void onPostExecute(Bitmap bitmap) {
994 if (bitmap != null && !isCancelled()) {
995 final ImageView imageView = imageViewReference.get();
996 if (imageView != null) {
997 imageView.setImageBitmap(bitmap);
998 imageView.setBackgroundColor(0x00000000);
999 }
1000 }
1001 }
1002 }
1003
1004 private static class AsyncDrawable extends BitmapDrawable {
1005 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1006
1007 private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
1008 super(res, bitmap);
1009 bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
1010 }
1011
1012 private BitmapWorkerTask getBitmapWorkerTask() {
1013 return bitmapWorkerTaskReference.get();
1014 }
1015 }
1016}