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