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