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