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.view.MenuItem;
44import android.view.View;
45import android.view.inputmethod.InputMethodManager;
46import android.widget.EditText;
47import android.widget.ImageView;
48import android.widget.Toast;
49
50import java.io.FileNotFoundException;
51import java.lang.ref.WeakReference;
52import java.util.ArrayList;
53import java.util.List;
54import java.util.concurrent.RejectedExecutionException;
55
56import eu.siacs.conversations.Config;
57import eu.siacs.conversations.R;
58import eu.siacs.conversations.crypto.PgpEngine;
59import eu.siacs.conversations.entities.Account;
60import eu.siacs.conversations.entities.Contact;
61import eu.siacs.conversations.entities.Conversation;
62import eu.siacs.conversations.entities.Message;
63import eu.siacs.conversations.entities.MucOptions;
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 eu.siacs.conversations.xmpp.jid.InvalidJidException;
74import eu.siacs.conversations.xmpp.jid.Jid;
75
76public abstract class XmppActivity extends AppCompatActivity {
77
78 public static final String EXTRA_ACCOUNT = "account";
79 protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
80 protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
81 protected static final int REQUEST_CHOOSE_PGP_ID = 0x0103;
82 protected static final int REQUEST_BATTERY_OP = 0x13849ff;
83 public XmppConnectionService xmppConnectionService;
84 public boolean xmppConnectionServiceBound = false;
85 protected boolean registeredListeners = false;
86
87 protected int mPrimaryTextColor;
88 protected int mSecondaryTextColor;
89 protected int mTertiaryTextColor;
90 protected int mPrimaryBackgroundColor;
91 protected int mSecondaryBackgroundColor;
92 protected int mColorRed;
93 protected int mColorOrange;
94 protected int mColorGreen;
95 protected int mPrimaryColor;
96
97 protected boolean mUseSubject = true;
98 protected int mTheme;
99 protected boolean mUsingEnterKey = false;
100 protected Toast mToast;
101 public Runnable onOpenPGPKeyPublished = () -> Toast.makeText(XmppActivity.this, R.string.openpgp_has_been_published, Toast.LENGTH_SHORT).show();
102 protected ConferenceInvite mPendingConferenceInvite = null;
103 protected ServiceConnection mConnection = new ServiceConnection() {
104
105 @Override
106 public void onServiceConnected(ComponentName className, IBinder service) {
107 XmppConnectionBinder binder = (XmppConnectionBinder) service;
108 xmppConnectionService = binder.getService();
109 xmppConnectionServiceBound = true;
110 if (!registeredListeners && shouldRegisterListeners()) {
111 registerListeners();
112 registeredListeners = true;
113 }
114 onBackendConnected();
115 }
116
117 @Override
118 public void onServiceDisconnected(ComponentName arg0) {
119 xmppConnectionServiceBound = false;
120 }
121 };
122 private DisplayMetrics metrics;
123 private long mLastUiRefresh = 0;
124 private Handler mRefreshUiHandler = new Handler();
125 private Runnable mRefreshUiRunnable = () -> {
126 mLastUiRefresh = SystemClock.elapsedRealtime();
127 refreshUiReal();
128 };
129 private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
130 @Override
131 public void success(final Conversation conversation) {
132 runOnUiThread(() -> {
133 switchToConversation(conversation);
134 hideToast();
135 });
136 }
137
138 @Override
139 public void error(final int errorCode, Conversation object) {
140 runOnUiThread(() -> replaceToast(getString(errorCode)));
141 }
142
143 @Override
144 public void userInputRequried(PendingIntent pi, Conversation object) {
145
146 }
147 };
148
149 public static boolean cancelPotentialWork(Message message, ImageView imageView) {
150 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
151
152 if (bitmapWorkerTask != null) {
153 final Message oldMessage = bitmapWorkerTask.message;
154 if (oldMessage == null || message != oldMessage) {
155 bitmapWorkerTask.cancel(true);
156 } else {
157 return false;
158 }
159 }
160 return true;
161 }
162
163 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
164 if (imageView != null) {
165 final Drawable drawable = imageView.getDrawable();
166 if (drawable instanceof AsyncDrawable) {
167 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
168 return asyncDrawable.getBitmapWorkerTask();
169 }
170 }
171 return null;
172 }
173
174 protected void hideToast() {
175 if (mToast != null) {
176 mToast.cancel();
177 }
178 }
179
180 protected void replaceToast(String msg) {
181 replaceToast(msg, true);
182 }
183
184 protected void replaceToast(String msg, boolean showlong) {
185 hideToast();
186 mToast = Toast.makeText(this, msg, showlong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
187 mToast.show();
188 }
189
190 protected final void refreshUi() {
191 final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh;
192 if (diff > Config.REFRESH_UI_INTERVAL) {
193 mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
194 runOnUiThread(mRefreshUiRunnable);
195 } else {
196 final long next = Config.REFRESH_UI_INTERVAL - diff;
197 mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
198 mRefreshUiHandler.postDelayed(mRefreshUiRunnable, next);
199 }
200 }
201
202 abstract protected void refreshUiReal();
203
204 @Override
205 protected void onStart() {
206 super.onStart();
207 if (!xmppConnectionServiceBound) {
208 connectToBackend();
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.fromParts(contact.getJid().getLocalpart(), contact.getJid().getDomainpart(), presence));
395 } catch (InvalidJidException 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
411 mPrimaryTextColor = ContextCompat.getColor(this, R.color.black87);
412 mSecondaryTextColor = ContextCompat.getColor(this, R.color.black54);
413 mTertiaryTextColor = ContextCompat.getColor(this, R.color.black12);
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 mPrimaryTextColor = ContextCompat.getColor(this, R.color.white);
424 mSecondaryTextColor = ContextCompat.getColor(this, R.color.white70);
425 mTertiaryTextColor = ContextCompat.getColor(this, R.color.white12);
426 mPrimaryBackgroundColor = ContextCompat.getColor(this, R.color.grey800);
427 mSecondaryBackgroundColor = ContextCompat.getColor(this, R.color.grey900);
428 }
429 setTheme(this.mTheme);
430
431 this.mUsingEnterKey = usingEnterKey();
432 mUseSubject = getPreferences().getBoolean("use_subject", getResources().getBoolean(R.bool.use_subject));
433 final ActionBar ab = getSupportActionBar();
434 if (ab != null) {
435 ab.setDisplayHomeAsUpEnabled(true);
436 }
437 }
438
439 public boolean isDarkTheme() {
440 return this.mTheme == R.style.ConversationsTheme_Dark || this.mTheme == R.style.ConversationsTheme_Dark_LargerText;
441 }
442
443 public int getThemeResource(int r_attr_name, int r_drawable_def) {
444 int[] attrs = {r_attr_name};
445 TypedArray ta = this.getTheme().obtainStyledAttributes(attrs);
446
447 int res = ta.getResourceId(0, r_drawable_def);
448 ta.recycle();
449
450 return res;
451 }
452
453 protected boolean isOptimizingBattery() {
454 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
455 final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
456 return pm != null
457 && !pm.isIgnoringBatteryOptimizations(getPackageName());
458 } else {
459 return false;
460 }
461 }
462
463 protected boolean isAffectedByDataSaver() {
464 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
465 final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
466 return cm != null
467 && cm.isActiveNetworkMetered()
468 && cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
469 } else {
470 return false;
471 }
472 }
473
474 protected boolean usingEnterKey() {
475 return getPreferences().getBoolean("display_enter_key", getResources().getBoolean(R.bool.display_enter_key));
476 }
477
478 protected SharedPreferences getPreferences() {
479 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
480 }
481
482 public boolean useSubjectToIdentifyConference() {
483 return mUseSubject;
484 }
485
486 public void switchToConversation(Conversation conversation) {
487 switchToConversation(conversation, null, false);
488 }
489
490 public void switchToConversation(Conversation conversation, String text,
491 boolean newTask) {
492 switchToConversation(conversation, text, null, false, newTask);
493 }
494
495 public void highlightInMuc(Conversation conversation, String nick) {
496 switchToConversation(conversation, null, nick, false, false);
497 }
498
499 public void privateMsgInMuc(Conversation conversation, String nick) {
500 switchToConversation(conversation, null, nick, true, false);
501 }
502
503 private void switchToConversation(Conversation conversation, String text, String nick, boolean pm, boolean newTask) {
504 Intent intent = new Intent(this, ConversationActivity.class);
505 intent.setAction(ConversationActivity.ACTION_VIEW_CONVERSATION);
506 intent.putExtra(ConversationActivity.EXTRA_CONVERSATION, conversation.getUuid());
507 if (text != null) {
508 intent.putExtra(ConversationActivity.EXTRA_TEXT, text);
509 }
510 if (nick != null) {
511 intent.putExtra(ConversationActivity.EXTRA_NICK, nick);
512 intent.putExtra(ConversationActivity.EXTRA_IS_PRIVATE_MESSAGE, pm);
513 }
514 if (newTask) {
515 intent.setFlags(intent.getFlags()
516 | Intent.FLAG_ACTIVITY_NEW_TASK
517 | Intent.FLAG_ACTIVITY_SINGLE_TOP);
518 } else {
519 intent.setFlags(intent.getFlags()
520 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
521 }
522 startActivity(intent);
523 finish();
524 }
525
526 public void switchToContactDetails(Contact contact) {
527 switchToContactDetails(contact, null);
528 }
529
530 public void switchToContactDetails(Contact contact, String messageFingerprint) {
531 Intent intent = new Intent(this, ContactDetailsActivity.class);
532 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
533 intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().toBareJid().toString());
534 intent.putExtra("contact", contact.getJid().toString());
535 intent.putExtra("fingerprint", messageFingerprint);
536 startActivity(intent);
537 }
538
539 public void switchToAccount(Account account) {
540 switchToAccount(account, false);
541 }
542
543 public void switchToAccount(Account account, boolean init) {
544 Intent intent = new Intent(this, EditAccountActivity.class);
545 intent.putExtra("jid", account.getJid().toBareJid().toString());
546 intent.putExtra("init", init);
547 if (init) {
548 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
549 }
550 startActivity(intent);
551 if (init) {
552 overridePendingTransition(0, 0);
553 }
554 }
555
556 protected void delegateUriPermissionsToService(Uri uri) {
557 Intent intent = new Intent(this,XmppConnectionService.class);
558 intent.setAction(Intent.ACTION_SEND);
559 intent.setData(uri);
560 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
561 startService(intent);
562 }
563
564 protected void inviteToConversation(Conversation conversation) {
565 Intent intent = new Intent(this, ChooseContactActivity.class);
566 List<String> contacts = new ArrayList<>();
567 if (conversation.getMode() == Conversation.MODE_MULTI) {
568 for (MucOptions.User user : conversation.getMucOptions().getUsers(false)) {
569 Jid jid = user.getRealJid();
570 if (jid != null) {
571 contacts.add(jid.toBareJid().toString());
572 }
573 }
574 } else {
575 contacts.add(conversation.getJid().toBareJid().toString());
576 }
577 intent.putExtra("filter_contacts", contacts.toArray(new String[contacts.size()]));
578 intent.putExtra("conversation", conversation.getUuid());
579 intent.putExtra("multiple", true);
580 intent.putExtra("show_enter_jid", true);
581 intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
582 startActivityForResult(intent, REQUEST_INVITE_TO_CONVERSATION);
583 }
584
585 protected void announcePgp(Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
586 if (account.getPgpId() == 0) {
587 choosePgpSignId(account);
588 } else {
589 String status = null;
590 if (manuallyChangePresence()) {
591 status = account.getPresenceStatusMessage();
592 }
593 if (status == null) {
594 status = "";
595 }
596 xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<Account>() {
597
598 @Override
599 public void userInputRequried(PendingIntent pi, Account account) {
600 try {
601 startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
602 } catch (final SendIntentException ignored) {
603 }
604 }
605
606 @Override
607 public void success(Account account) {
608 xmppConnectionService.databaseBackend.updateAccount(account);
609 xmppConnectionService.sendPresence(account);
610 if (conversation != null) {
611 conversation.setNextEncryption(Message.ENCRYPTION_PGP);
612 xmppConnectionService.updateConversation(conversation);
613 refreshUi();
614 }
615 if (onSuccess != null) {
616 runOnUiThread(onSuccess);
617 }
618 }
619
620 @Override
621 public void error(int error, Account account) {
622 if (error == 0 && account != null) {
623 account.setPgpSignId(0);
624 account.unsetPgpSignature();
625 xmppConnectionService.databaseBackend.updateAccount(account);
626 choosePgpSignId(account);
627 } else {
628 displayErrorDialog(error);
629 }
630 }
631 });
632 }
633 }
634
635 protected boolean noAccountUsesPgp() {
636 if (!hasPgp()) {
637 return true;
638 }
639 for (Account account : xmppConnectionService.getAccounts()) {
640 if (account.getPgpId() != 0) {
641 return false;
642 }
643 }
644 return true;
645 }
646
647 @SuppressWarnings("deprecation")
648 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
649 protected void setListItemBackgroundOnView(View view) {
650 int sdk = android.os.Build.VERSION.SDK_INT;
651 if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
652 view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
653 } else {
654 view.setBackground(getResources().getDrawable(R.drawable.greybackground));
655 }
656 }
657
658 protected void choosePgpSignId(Account account) {
659 xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
660 @Override
661 public void success(Account account1) {
662 }
663
664 @Override
665 public void error(int errorCode, Account object) {
666
667 }
668
669 @Override
670 public void userInputRequried(PendingIntent pi, Account object) {
671 try {
672 startIntentSenderForResult(pi.getIntentSender(),
673 REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
674 } catch (final SendIntentException ignored) {
675 }
676 }
677 });
678 }
679
680 protected void displayErrorDialog(final int errorCode) {
681 runOnUiThread(() -> {
682 Builder builder = new Builder(XmppActivity.this);
683 builder.setIconAttribute(android.R.attr.alertDialogIcon);
684 builder.setTitle(getString(R.string.error));
685 builder.setMessage(errorCode);
686 builder.setNeutralButton(R.string.accept, null);
687 builder.create().show();
688 });
689
690 }
691
692 protected void showAddToRosterDialog(final Contact contact) {
693 AlertDialog.Builder builder = new AlertDialog.Builder(this);
694 builder.setTitle(contact.getJid().toString());
695 builder.setMessage(getString(R.string.not_in_roster));
696 builder.setNegativeButton(getString(R.string.cancel), null);
697 builder.setPositiveButton(getString(R.string.add_contact),
698 (dialog, which) -> {
699 final Jid jid = contact.getJid();
700 Account account = contact.getAccount();
701 Contact contact1 = account.getRoster().getContact(jid);
702 xmppConnectionService.createContact(contact1);
703 });
704 builder.create().show();
705 }
706
707 private void showAskForPresenceDialog(final Contact contact) {
708 AlertDialog.Builder builder = new AlertDialog.Builder(this);
709 builder.setTitle(contact.getJid().toString());
710 builder.setMessage(R.string.request_presence_updates);
711 builder.setNegativeButton(R.string.cancel, null);
712 builder.setPositiveButton(R.string.request_now,
713 (dialog, which) -> {
714 if (xmppConnectionServiceBound) {
715 xmppConnectionService.sendPresencePacket(contact
716 .getAccount(), xmppConnectionService
717 .getPresenceGenerator()
718 .requestPresenceUpdatesFrom(contact));
719 }
720 });
721 builder.create().show();
722 }
723
724 protected void quickEdit(String previousValue, int hint, OnValueEdited callback) {
725 quickEdit(previousValue, callback, hint, false);
726 }
727
728 protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
729 quickEdit(previousValue, callback, R.string.password, true);
730 }
731
732 @SuppressLint("InflateParams")
733 private void quickEdit(final String previousValue,
734 final OnValueEdited callback,
735 final int hint,
736 boolean password) {
737 AlertDialog.Builder builder = new AlertDialog.Builder(this);
738 View view = getLayoutInflater().inflate(R.layout.quickedit, null);
739 final EditText editor = view.findViewById(R.id.editor);
740 if (password) {
741 editor.setInputType(InputType.TYPE_CLASS_TEXT
742 | InputType.TYPE_TEXT_VARIATION_PASSWORD);
743 }
744 builder.setPositiveButton(R.string.accept, null);
745 if (hint != 0) {
746 editor.setHint(hint);
747 }
748 editor.requestFocus();
749 editor.setText("");
750 if (previousValue != null) {
751 editor.getText().append(previousValue);
752 }
753 builder.setView(view);
754 builder.setNegativeButton(R.string.cancel, null);
755 final AlertDialog dialog = builder.create();
756 dialog.show();
757 View.OnClickListener clickListener = v -> {
758 String value = editor.getText().toString();
759 if (!value.equals(previousValue) && value.trim().length() > 0) {
760 String error = callback.onValueEdited(value);
761 if (error != null) {
762 editor.setError(error);
763 return;
764 }
765 }
766 dialog.dismiss();
767 };
768 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
769 }
770
771 public boolean hasStoragePermission(int requestCode) {
772 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
773 if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
774 requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
775 return false;
776 } else {
777 return true;
778 }
779 } else {
780 return true;
781 }
782 }
783
784 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
785 super.onActivityResult(requestCode, resultCode, data);
786 if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
787 mPendingConferenceInvite = ConferenceInvite.parse(data);
788 if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
789 if (mPendingConferenceInvite.execute(this)) {
790 mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
791 mToast.show();
792 }
793 mPendingConferenceInvite = null;
794 }
795 }
796 }
797
798 public int getTertiaryTextColor() {
799 return this.mTertiaryTextColor;
800 }
801
802 public int getSecondaryTextColor() {
803 return this.mSecondaryTextColor;
804 }
805
806 public int getPrimaryTextColor() {
807 return this.mPrimaryTextColor;
808 }
809
810 public int getWarningTextColor() {
811 return this.mColorRed;
812 }
813
814 public int getOnlineColor() {
815 return this.mColorGreen;
816 }
817
818 public int getPixel(int dp) {
819 DisplayMetrics metrics = getResources().getDisplayMetrics();
820 return ((int) (dp * metrics.density));
821 }
822
823 public boolean copyTextToClipboard(String text, int labelResId) {
824 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
825 String label = getResources().getString(labelResId);
826 if (mClipBoardManager != null) {
827 ClipData mClipData = ClipData.newPlainText(label, text);
828 mClipBoardManager.setPrimaryClip(mClipData);
829 return true;
830 }
831 return false;
832 }
833
834 protected boolean neverCompressPictures() {
835 return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression)).equals("never");
836 }
837
838 protected boolean manuallyChangePresence() {
839 return getPreferences().getBoolean(SettingsActivity.MANUALLY_CHANGE_PRESENCE, getResources().getBoolean(R.bool.manually_change_presence));
840 }
841
842 protected String getShareableUri() {
843 return getShareableUri(false);
844 }
845
846 protected String getShareableUri(boolean http) {
847 return null;
848 }
849
850 protected void shareLink(boolean http) {
851 String uri = getShareableUri(http);
852 if (uri == null || uri.isEmpty()) {
853 return;
854 }
855 Intent intent = new Intent(Intent.ACTION_SEND);
856 intent.setType("text/plain");
857 intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
858 try {
859 startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
860 } catch (ActivityNotFoundException e) {
861 Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
862 }
863 }
864
865 protected void launchOpenKeyChain(long keyId) {
866 PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
867 try {
868 startIntentSenderForResult(
869 pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
870 0, 0);
871 } catch (Throwable e) {
872 Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
873 }
874 }
875
876 @Override
877 public void onResume() {
878 super.onResume();
879 }
880
881 protected int findTheme() {
882 Boolean dark = getPreferences().getString(SettingsActivity.THEME, getResources().getString(R.string.theme)).equals("dark");
883 Boolean larger = getPreferences().getBoolean("use_larger_font", getResources().getBoolean(R.bool.use_larger_font));
884
885 if (dark) {
886 if (larger)
887 return R.style.ConversationsTheme_Dark_LargerText;
888 else
889 return R.style.ConversationsTheme_Dark;
890 } else {
891 if (larger)
892 return R.style.ConversationsTheme_LargerText;
893 else
894 return R.style.ConversationsTheme;
895 }
896 }
897
898 @Override
899 public void onPause() {
900 super.onPause();
901 }
902
903 protected void showQrCode() {
904 showQrCode(getShareableUri());
905 }
906
907 protected void showQrCode(final String uri) {
908 if (uri == null || uri.isEmpty()) {
909 return;
910 }
911 Point size = new Point();
912 getWindowManager().getDefaultDisplay().getSize(size);
913 final int width = (size.x < size.y ? size.x : size.y);
914 Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
915 ImageView view = new ImageView(this);
916 view.setBackgroundColor(Color.WHITE);
917 view.setImageBitmap(bitmap);
918 AlertDialog.Builder builder = new AlertDialog.Builder(this);
919 builder.setView(view);
920 builder.create().show();
921 }
922
923 protected Account extractAccount(Intent intent) {
924 String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
925 try {
926 return jid != null ? xmppConnectionService.findAccountByJid(Jid.fromString(jid)) : null;
927 } catch (InvalidJidException e) {
928 return null;
929 }
930 }
931
932 public AvatarService avatarService() {
933 return xmppConnectionService.getAvatarService();
934 }
935
936 public void loadBitmap(Message message, ImageView imageView) {
937 Bitmap bm;
938 try {
939 bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true);
940 } catch (FileNotFoundException e) {
941 bm = null;
942 }
943 if (bm != null) {
944 cancelPotentialWork(message, imageView);
945 imageView.setImageBitmap(bm);
946 imageView.setBackgroundColor(0x00000000);
947 } else {
948 if (cancelPotentialWork(message, imageView)) {
949 imageView.setBackgroundColor(0xff333333);
950 imageView.setImageDrawable(null);
951 final BitmapWorkerTask task = new BitmapWorkerTask(this, imageView);
952 final AsyncDrawable asyncDrawable = new AsyncDrawable(
953 getResources(), null, task);
954 imageView.setImageDrawable(asyncDrawable);
955 try {
956 task.execute(message);
957 } catch (final RejectedExecutionException ignored) {
958 ignored.printStackTrace();
959 }
960 }
961 }
962 }
963
964 protected interface OnValueEdited {
965 String onValueEdited(String value);
966 }
967
968 public static class ConferenceInvite {
969 private String uuid;
970 private List<Jid> jids = new ArrayList<>();
971
972 public static ConferenceInvite parse(Intent data) {
973 ConferenceInvite invite = new ConferenceInvite();
974 invite.uuid = data.getStringExtra("conversation");
975 if (invite.uuid == null) {
976 return null;
977 }
978 try {
979 if (data.getBooleanExtra("multiple", false)) {
980 String[] toAdd = data.getStringArrayExtra("contacts");
981 for (String item : toAdd) {
982 invite.jids.add(Jid.fromString(item));
983 }
984 } else {
985 invite.jids.add(Jid.fromString(data.getStringExtra("contact")));
986 }
987 } catch (final InvalidJidException ignored) {
988 return null;
989 }
990 return invite;
991 }
992
993 public boolean execute(XmppActivity activity) {
994 XmppConnectionService service = activity.xmppConnectionService;
995 Conversation conversation = service.findConversationByUuid(this.uuid);
996 if (conversation == null) {
997 return false;
998 }
999 if (conversation.getMode() == Conversation.MODE_MULTI) {
1000 for (Jid jid : jids) {
1001 service.invite(conversation, jid);
1002 }
1003 return false;
1004 } else {
1005 jids.add(conversation.getJid().toBareJid());
1006 return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
1007 }
1008 }
1009 }
1010
1011 static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
1012 private final WeakReference<ImageView> imageViewReference;
1013 private final WeakReference<XmppActivity> activity;
1014 private Message message = null;
1015
1016 private BitmapWorkerTask(XmppActivity activity, ImageView imageView) {
1017 this.activity = new WeakReference<>(activity);
1018 this.imageViewReference = new WeakReference<>(imageView);
1019 }
1020
1021 @Override
1022 protected Bitmap doInBackground(Message... params) {
1023 if (isCancelled()) {
1024 return null;
1025 }
1026 message = params[0];
1027 try {
1028 XmppActivity activity = this.activity.get();
1029 if (activity != null && activity.xmppConnectionService != null) {
1030 return activity.xmppConnectionService.getFileBackend().getThumbnail(message, (int) (activity.metrics.density * 288), false);
1031 } else {
1032 return null;
1033 }
1034 } catch (FileNotFoundException e) {
1035 return null;
1036 }
1037 }
1038
1039 @Override
1040 protected void onPostExecute(Bitmap bitmap) {
1041 if (bitmap != null && !isCancelled()) {
1042 final ImageView imageView = imageViewReference.get();
1043 if (imageView != null) {
1044 imageView.setImageBitmap(bitmap);
1045 imageView.setBackgroundColor(0x00000000);
1046 }
1047 }
1048 }
1049 }
1050
1051 private static class AsyncDrawable extends BitmapDrawable {
1052 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1053
1054 private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
1055 super(res, bitmap);
1056 bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
1057 }
1058
1059 private BitmapWorkerTask getBitmapWorkerTask() {
1060 return bitmapWorkerTaskReference.get();
1061 }
1062 }
1063}