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 eu.siacs.conversations.xmpp.jid.InvalidJidException;
75import eu.siacs.conversations.xmpp.jid.Jid;
76
77public abstract class XmppActivity extends AppCompatActivity {
78
79 public static final String EXTRA_ACCOUNT = "account";
80 protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
81 protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
82 protected static final int REQUEST_CHOOSE_PGP_ID = 0x0103;
83 protected static final int REQUEST_BATTERY_OP = 0x49ff;
84 public XmppConnectionService xmppConnectionService;
85 public boolean xmppConnectionServiceBound = false;
86 protected boolean registeredListeners = false;
87
88 protected int mPrimaryBackgroundColor;
89 protected int mSecondaryBackgroundColor;
90 protected int mColorRed;
91 protected int mColorOrange;
92 protected int mColorGreen;
93 protected int mPrimaryColor;
94
95 protected boolean mUseSubject = true;
96 protected int mTheme;
97 protected boolean mUsingEnterKey = false;
98 protected Toast mToast;
99 public Runnable onOpenPGPKeyPublished = () -> Toast.makeText(XmppActivity.this, R.string.openpgp_has_been_published, Toast.LENGTH_SHORT).show();
100 protected ConferenceInvite mPendingConferenceInvite = null;
101 protected ServiceConnection mConnection = new ServiceConnection() {
102
103 @Override
104 public void onServiceConnected(ComponentName className, IBinder service) {
105 XmppConnectionBinder binder = (XmppConnectionBinder) service;
106 xmppConnectionService = binder.getService();
107 xmppConnectionServiceBound = true;
108 if (!registeredListeners && shouldRegisterListeners()) {
109 registerListeners();
110 registeredListeners = true;
111 }
112 onBackendConnected();
113 }
114
115 @Override
116 public void onServiceDisconnected(ComponentName arg0) {
117 xmppConnectionServiceBound = false;
118 }
119 };
120 private DisplayMetrics metrics;
121 private long mLastUiRefresh = 0;
122 private Handler mRefreshUiHandler = new Handler();
123 private Runnable mRefreshUiRunnable = () -> {
124 mLastUiRefresh = SystemClock.elapsedRealtime();
125 refreshUiReal();
126 };
127 private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
128 @Override
129 public void success(final Conversation conversation) {
130 runOnUiThread(() -> {
131 switchToConversation(conversation);
132 hideToast();
133 });
134 }
135
136 @Override
137 public void error(final int errorCode, Conversation object) {
138 runOnUiThread(() -> replaceToast(getString(errorCode)));
139 }
140
141 @Override
142 public void userInputRequried(PendingIntent pi, Conversation object) {
143
144 }
145 };
146 public boolean mSkipBackgroundBinding = false;
147
148 public static boolean cancelPotentialWork(Message message, ImageView imageView) {
149 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
150
151 if (bitmapWorkerTask != null) {
152 final Message oldMessage = bitmapWorkerTask.message;
153 if (oldMessage == null || message != oldMessage) {
154 bitmapWorkerTask.cancel(true);
155 } else {
156 return false;
157 }
158 }
159 return true;
160 }
161
162 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
163 if (imageView != null) {
164 final Drawable drawable = imageView.getDrawable();
165 if (drawable instanceof AsyncDrawable) {
166 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
167 return asyncDrawable.getBitmapWorkerTask();
168 }
169 }
170 return null;
171 }
172
173 protected void hideToast() {
174 if (mToast != null) {
175 mToast.cancel();
176 }
177 }
178
179 protected void replaceToast(String msg) {
180 replaceToast(msg, true);
181 }
182
183 protected void replaceToast(String msg, boolean showlong) {
184 hideToast();
185 mToast = Toast.makeText(this, msg, showlong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
186 mToast.show();
187 }
188
189 protected final void refreshUi() {
190 final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh;
191 if (diff > Config.REFRESH_UI_INTERVAL) {
192 mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
193 runOnUiThread(mRefreshUiRunnable);
194 } else {
195 final long next = Config.REFRESH_UI_INTERVAL - diff;
196 mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
197 mRefreshUiHandler.postDelayed(mRefreshUiRunnable, next);
198 }
199 }
200
201 abstract protected void refreshUiReal();
202
203 @Override
204 protected void onStart() {
205 super.onStart();
206 if (!xmppConnectionServiceBound) {
207 if (this.mSkipBackgroundBinding) {
208 Log.d(Config.LOGTAG,"skipping background binding");
209 } else {
210 connectToBackend();
211 }
212 } else {
213 if (!registeredListeners) {
214 this.registerListeners();
215 this.registeredListeners = true;
216 }
217 this.onBackendConnected();
218 }
219 }
220
221 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
222 protected boolean shouldRegisterListeners() {
223 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
224 return !isDestroyed() && !isFinishing();
225 } else {
226 return !isFinishing();
227 }
228 }
229
230 public void connectToBackend() {
231 Intent intent = new Intent(this, XmppConnectionService.class);
232 intent.setAction("ui");
233 startService(intent);
234 bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
235 }
236
237 @Override
238 protected void onStop() {
239 super.onStop();
240 if (xmppConnectionServiceBound) {
241 if (registeredListeners) {
242 this.unregisterListeners();
243 this.registeredListeners = false;
244 }
245 unbindService(mConnection);
246 xmppConnectionServiceBound = false;
247 }
248 }
249
250 protected void hideKeyboard() {
251 final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
252 View focus = getCurrentFocus();
253 if (focus != null && inputManager != null) {
254 inputManager.hideSoftInputFromWindow(focus.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
255 }
256 }
257
258 public boolean hasPgp() {
259 return xmppConnectionService.getPgpEngine() != null;
260 }
261
262 public void showInstallPgpDialog() {
263 Builder builder = new AlertDialog.Builder(this);
264 builder.setTitle(getString(R.string.openkeychain_required));
265 builder.setIconAttribute(android.R.attr.alertDialogIcon);
266 builder.setMessage(getText(R.string.openkeychain_required_long));
267 builder.setNegativeButton(getString(R.string.cancel), null);
268 builder.setNeutralButton(getString(R.string.restart),
269 (dialog, which) -> {
270 if (xmppConnectionServiceBound) {
271 unbindService(mConnection);
272 xmppConnectionServiceBound = false;
273 }
274 stopService(new Intent(XmppActivity.this,
275 XmppConnectionService.class));
276 finish();
277 });
278 builder.setPositiveButton(getString(R.string.install),
279 (dialog, which) -> {
280 Uri uri = Uri
281 .parse("market://details?id=org.sufficientlysecure.keychain");
282 Intent marketIntent = new Intent(Intent.ACTION_VIEW,
283 uri);
284 PackageManager manager = getApplicationContext()
285 .getPackageManager();
286 List<ResolveInfo> infos = manager
287 .queryIntentActivities(marketIntent, 0);
288 if (infos.size() > 0) {
289 startActivity(marketIntent);
290 } else {
291 uri = Uri.parse("http://www.openkeychain.org/");
292 Intent browserIntent = new Intent(
293 Intent.ACTION_VIEW, uri);
294 startActivity(browserIntent);
295 }
296 finish();
297 });
298 builder.create().show();
299 }
300
301 abstract void onBackendConnected();
302
303 protected void registerListeners() {
304 if (this instanceof XmppConnectionService.OnConversationUpdate) {
305 this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
306 }
307 if (this instanceof XmppConnectionService.OnAccountUpdate) {
308 this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
309 }
310 if (this instanceof XmppConnectionService.OnCaptchaRequested) {
311 this.xmppConnectionService.setOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this);
312 }
313 if (this instanceof XmppConnectionService.OnRosterUpdate) {
314 this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
315 }
316 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
317 this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
318 }
319 if (this instanceof OnUpdateBlocklist) {
320 this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
321 }
322 if (this instanceof XmppConnectionService.OnShowErrorToast) {
323 this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
324 }
325 if (this instanceof OnKeyStatusUpdated) {
326 this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this);
327 }
328 }
329
330 protected void unregisterListeners() {
331 if (this instanceof XmppConnectionService.OnConversationUpdate) {
332 this.xmppConnectionService.removeOnConversationListChangedListener();
333 }
334 if (this instanceof XmppConnectionService.OnAccountUpdate) {
335 this.xmppConnectionService.removeOnAccountListChangedListener();
336 }
337 if (this instanceof XmppConnectionService.OnCaptchaRequested) {
338 this.xmppConnectionService.removeOnCaptchaRequestedListener();
339 }
340 if (this instanceof XmppConnectionService.OnRosterUpdate) {
341 this.xmppConnectionService.removeOnRosterUpdateListener();
342 }
343 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
344 this.xmppConnectionService.removeOnMucRosterUpdateListener();
345 }
346 if (this instanceof OnUpdateBlocklist) {
347 this.xmppConnectionService.removeOnUpdateBlocklistListener();
348 }
349 if (this instanceof XmppConnectionService.OnShowErrorToast) {
350 this.xmppConnectionService.removeOnShowErrorToastListener();
351 }
352 if (this instanceof OnKeyStatusUpdated) {
353 this.xmppConnectionService.removeOnNewKeysAvailableListener();
354 }
355 }
356
357 @Override
358 public boolean onOptionsItemSelected(final MenuItem item) {
359 switch (item.getItemId()) {
360 case R.id.action_settings:
361 startActivity(new Intent(this, SettingsActivity.class));
362 break;
363 case R.id.action_accounts:
364 startActivity(new Intent(this, ManageAccountActivity.class));
365 break;
366 case android.R.id.home:
367 finish();
368 break;
369 case R.id.action_show_qr_code:
370 showQrCode();
371 break;
372 }
373 return super.onOptionsItemSelected(item);
374 }
375
376 public void selectPresence(final Conversation conversation, final PresenceSelector.OnPresenceSelected listener) {
377 final Contact contact = conversation.getContact();
378 if (!contact.showInRoster()) {
379 showAddToRosterDialog(conversation.getContact());
380 } else {
381 final Presences presences = contact.getPresences();
382 if (presences.size() == 0) {
383 if (!contact.getOption(Contact.Options.TO)
384 && !contact.getOption(Contact.Options.ASKING)
385 && contact.getAccount().getStatus() == Account.State.ONLINE) {
386 showAskForPresenceDialog(contact);
387 } else if (!contact.getOption(Contact.Options.TO)
388 || !contact.getOption(Contact.Options.FROM)) {
389 PresenceSelector.warnMutualPresenceSubscription(this, conversation, listener);
390 } else {
391 conversation.setNextCounterpart(null);
392 listener.onPresenceSelected();
393 }
394 } else if (presences.size() == 1) {
395 String presence = presences.toResourceArray()[0];
396 try {
397 conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(), contact.getJid().getDomainpart(), presence));
398 } catch (InvalidJidException e) {
399 conversation.setNextCounterpart(null);
400 }
401 listener.onPresenceSelected();
402 } else {
403 PresenceSelector.showPresenceSelectionDialog(this, conversation, listener);
404 }
405 }
406 }
407
408 @Override
409 protected void onCreate(Bundle savedInstanceState) {
410 super.onCreate(savedInstanceState);
411 metrics = getResources().getDisplayMetrics();
412 ExceptionHelper.init(getApplicationContext());
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 mPrimaryColor = ContextCompat.getColor(this, R.color.primary500);
418 mPrimaryBackgroundColor = ContextCompat.getColor(this, R.color.grey50);
419 mSecondaryBackgroundColor = ContextCompat.getColor(this, R.color.grey200);
420
421 this.mTheme = findTheme();
422 if (isDarkTheme()) {
423 mPrimaryBackgroundColor = ContextCompat.getColor(this, R.color.grey800);
424 mSecondaryBackgroundColor = ContextCompat.getColor(this, R.color.grey900);
425 }
426 setTheme(this.mTheme);
427
428 this.mUsingEnterKey = usingEnterKey();
429 mUseSubject = getPreferences().getBoolean("use_subject", getResources().getBoolean(R.bool.use_subject));
430 final ActionBar ab = getSupportActionBar();
431 if (ab != null) {
432 ab.setDisplayHomeAsUpEnabled(true);
433 }
434 }
435
436 public boolean isDarkTheme() {
437 return this.mTheme == R.style.ConversationsTheme_Dark;
438 }
439
440 public int getThemeResource(int r_attr_name, int r_drawable_def) {
441 int[] attrs = {r_attr_name};
442 TypedArray ta = this.getTheme().obtainStyledAttributes(attrs);
443
444 int res = ta.getResourceId(0, r_drawable_def);
445 ta.recycle();
446
447 return res;
448 }
449
450 protected boolean isOptimizingBattery() {
451 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
452 final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
453 return pm != null
454 && !pm.isIgnoringBatteryOptimizations(getPackageName());
455 } else {
456 return false;
457 }
458 }
459
460 protected boolean isAffectedByDataSaver() {
461 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
462 final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
463 return cm != null
464 && cm.isActiveNetworkMetered()
465 && cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
466 } else {
467 return false;
468 }
469 }
470
471 protected boolean usingEnterKey() {
472 return getPreferences().getBoolean("display_enter_key", getResources().getBoolean(R.bool.display_enter_key));
473 }
474
475 protected SharedPreferences getPreferences() {
476 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
477 }
478
479 public boolean useSubjectToIdentifyConference() {
480 return mUseSubject;
481 }
482
483 public void switchToConversation(Conversation conversation) {
484 switchToConversation(conversation, null, false);
485 }
486
487 public void switchToConversation(Conversation conversation, String text,
488 boolean newTask) {
489 switchToConversation(conversation, text, null, false, newTask);
490 }
491
492 public void highlightInMuc(Conversation conversation, String nick) {
493 switchToConversation(conversation, null, nick, false, false);
494 }
495
496 public void privateMsgInMuc(Conversation conversation, String nick) {
497 switchToConversation(conversation, null, nick, true, false);
498 }
499
500 private void switchToConversation(Conversation conversation, String text, String nick, boolean pm, boolean newTask) {
501 Intent intent = new Intent(this, ConversationActivity.class);
502 intent.setAction(ConversationActivity.ACTION_VIEW_CONVERSATION);
503 intent.putExtra(ConversationActivity.EXTRA_CONVERSATION, conversation.getUuid());
504 if (text != null) {
505 intent.putExtra(ConversationActivity.EXTRA_TEXT, text);
506 }
507 if (nick != null) {
508 intent.putExtra(ConversationActivity.EXTRA_NICK, nick);
509 intent.putExtra(ConversationActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
510 }
511 if (newTask) {
512 intent.setFlags(intent.getFlags()
513 | Intent.FLAG_ACTIVITY_NEW_TASK
514 | Intent.FLAG_ACTIVITY_SINGLE_TOP);
515 } else {
516 intent.setFlags(intent.getFlags()
517 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
518 }
519 startActivity(intent);
520 finish();
521 }
522
523 public void switchToContactDetails(Contact contact) {
524 switchToContactDetails(contact, null);
525 }
526
527 public void switchToContactDetails(Contact contact, String messageFingerprint) {
528 Intent intent = new Intent(this, ContactDetailsActivity.class);
529 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
530 intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().toBareJid().toString());
531 intent.putExtra("contact", contact.getJid().toString());
532 intent.putExtra("fingerprint", messageFingerprint);
533 startActivity(intent);
534 }
535
536 public void switchToAccount(Account account) {
537 switchToAccount(account, false);
538 }
539
540 public void switchToAccount(Account account, boolean init) {
541 Intent intent = new Intent(this, EditAccountActivity.class);
542 intent.putExtra("jid", account.getJid().toBareJid().toString());
543 intent.putExtra("init", init);
544 if (init) {
545 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
546 }
547 startActivity(intent);
548 if (init) {
549 overridePendingTransition(0, 0);
550 }
551 }
552
553 protected void delegateUriPermissionsToService(Uri uri) {
554 Intent intent = new Intent(this,XmppConnectionService.class);
555 intent.setAction(Intent.ACTION_SEND);
556 intent.setData(uri);
557 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
558 startService(intent);
559 }
560
561 protected void inviteToConversation(Conversation conversation) {
562 startActivityForResult(ChooseContactActivity.create(this,conversation), REQUEST_INVITE_TO_CONVERSATION);
563 }
564
565 protected void announcePgp(Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
566 if (account.getPgpId() == 0) {
567 choosePgpSignId(account);
568 } else {
569 String status = null;
570 if (manuallyChangePresence()) {
571 status = account.getPresenceStatusMessage();
572 }
573 if (status == null) {
574 status = "";
575 }
576 xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<Account>() {
577
578 @Override
579 public void userInputRequried(PendingIntent pi, Account account) {
580 try {
581 startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
582 } catch (final SendIntentException ignored) {
583 }
584 }
585
586 @Override
587 public void success(Account account) {
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, Account account) {
602 if (error == 0 && account != null) {
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.fromString(jid)) : null;
882 } catch (InvalidJidException 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.fromString(item));
938 }
939 } else {
940 invite.jids.add(Jid.fromString(data.getStringExtra("contact")));
941 }
942 } catch (final InvalidJidException 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().toBareJid());
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}