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