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