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