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