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) {
525 switchToAccount(account, false);
526 }
527
528 public void switchToAccount(Account account, boolean init) {
529 Intent intent = new Intent(this, EditAccountActivity.class);
530 intent.putExtra("jid", account.getJid().asBareJid().toString());
531 intent.putExtra("init", init);
532 if (init) {
533 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
534 }
535 startActivity(intent);
536 if (init) {
537 overridePendingTransition(0, 0);
538 }
539 }
540
541 protected void delegateUriPermissionsToService(Uri uri) {
542 Intent intent = new Intent(this,XmppConnectionService.class);
543 intent.setAction(Intent.ACTION_SEND);
544 intent.setData(uri);
545 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
546 startService(intent);
547 }
548
549 protected void inviteToConversation(Conversation conversation) {
550 startActivityForResult(ChooseContactActivity.create(this,conversation), REQUEST_INVITE_TO_CONVERSATION);
551 }
552
553 protected void announcePgp(final Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) {
554 if (account.getPgpId() == 0) {
555 choosePgpSignId(account);
556 } else {
557 String status = null;
558 if (manuallyChangePresence()) {
559 status = account.getPresenceStatusMessage();
560 }
561 if (status == null) {
562 status = "";
563 }
564 xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() {
565
566 @Override
567 public void userInputRequried(PendingIntent pi, String signature) {
568 try {
569 startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
570 } catch (final SendIntentException ignored) {
571 }
572 }
573
574 @Override
575 public void success(String signature) {
576 account.setPgpSignature(signature);
577 xmppConnectionService.databaseBackend.updateAccount(account);
578 xmppConnectionService.sendPresence(account);
579 if (conversation != null) {
580 conversation.setNextEncryption(Message.ENCRYPTION_PGP);
581 xmppConnectionService.updateConversation(conversation);
582 refreshUi();
583 }
584 if (onSuccess != null) {
585 runOnUiThread(onSuccess);
586 }
587 }
588
589 @Override
590 public void error(int error, String signature) {
591 if (error == 0) {
592 account.setPgpSignId(0);
593 account.unsetPgpSignature();
594 xmppConnectionService.databaseBackend.updateAccount(account);
595 choosePgpSignId(account);
596 } else {
597 displayErrorDialog(error);
598 }
599 }
600 });
601 }
602 }
603
604 protected boolean noAccountUsesPgp() {
605 if (!hasPgp()) {
606 return true;
607 }
608 for (Account account : xmppConnectionService.getAccounts()) {
609 if (account.getPgpId() != 0) {
610 return false;
611 }
612 }
613 return true;
614 }
615
616 @SuppressWarnings("deprecation")
617 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
618 protected void setListItemBackgroundOnView(View view) {
619 int sdk = android.os.Build.VERSION.SDK_INT;
620 if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
621 view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground));
622 } else {
623 view.setBackground(getResources().getDrawable(R.drawable.greybackground));
624 }
625 }
626
627 protected void choosePgpSignId(Account account) {
628 xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() {
629 @Override
630 public void success(Account account1) {
631 }
632
633 @Override
634 public void error(int errorCode, Account object) {
635
636 }
637
638 @Override
639 public void userInputRequried(PendingIntent pi, Account object) {
640 try {
641 startIntentSenderForResult(pi.getIntentSender(),
642 REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0);
643 } catch (final SendIntentException ignored) {
644 }
645 }
646 });
647 }
648
649 protected void displayErrorDialog(final int errorCode) {
650 runOnUiThread(() -> {
651 Builder builder = new Builder(XmppActivity.this);
652 builder.setIconAttribute(android.R.attr.alertDialogIcon);
653 builder.setTitle(getString(R.string.error));
654 builder.setMessage(errorCode);
655 builder.setNeutralButton(R.string.accept, null);
656 builder.create().show();
657 });
658
659 }
660
661 protected void showAddToRosterDialog(final Contact contact) {
662 AlertDialog.Builder builder = new AlertDialog.Builder(this);
663 builder.setTitle(contact.getJid().toString());
664 builder.setMessage(getString(R.string.not_in_roster));
665 builder.setNegativeButton(getString(R.string.cancel), null);
666 builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> xmppConnectionService.createContact(contact,true));
667 builder.create().show();
668 }
669
670 private void showAskForPresenceDialog(final Contact contact) {
671 AlertDialog.Builder builder = new AlertDialog.Builder(this);
672 builder.setTitle(contact.getJid().toString());
673 builder.setMessage(R.string.request_presence_updates);
674 builder.setNegativeButton(R.string.cancel, null);
675 builder.setPositiveButton(R.string.request_now,
676 (dialog, which) -> {
677 if (xmppConnectionServiceBound) {
678 xmppConnectionService.sendPresencePacket(contact
679 .getAccount(), xmppConnectionService
680 .getPresenceGenerator()
681 .requestPresenceUpdatesFrom(contact));
682 }
683 });
684 builder.create().show();
685 }
686
687 protected void quickEdit(String previousValue, int hint, OnValueEdited callback) {
688 quickEdit(previousValue, callback, hint, false);
689 }
690
691 protected void quickPasswordEdit(String previousValue, OnValueEdited callback) {
692 quickEdit(previousValue, callback, R.string.password, true);
693 }
694
695 @SuppressLint("InflateParams")
696 private void quickEdit(final String previousValue,
697 final OnValueEdited callback,
698 final int hint,
699 boolean password) {
700 AlertDialog.Builder builder = new AlertDialog.Builder(this);
701 View view = getLayoutInflater().inflate(R.layout.quickedit, null);
702 final EditText editor = view.findViewById(R.id.editor);
703 if (password) {
704 editor.setInputType(InputType.TYPE_CLASS_TEXT
705 | InputType.TYPE_TEXT_VARIATION_PASSWORD);
706 }
707 builder.setPositiveButton(R.string.accept, null);
708 if (hint != 0) {
709 editor.setHint(hint);
710 }
711 editor.requestFocus();
712 editor.setText("");
713 if (previousValue != null) {
714 editor.getText().append(previousValue);
715 }
716 builder.setView(view);
717 builder.setNegativeButton(R.string.cancel, null);
718 final AlertDialog dialog = builder.create();
719 dialog.show();
720 View.OnClickListener clickListener = v -> {
721 String value = editor.getText().toString();
722 if (!value.equals(previousValue) && value.trim().length() > 0) {
723 String error = callback.onValueEdited(value);
724 if (error != null) {
725 editor.setError(error);
726 return;
727 }
728 }
729 dialog.dismiss();
730 };
731 dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener);
732 }
733
734 protected boolean hasStoragePermission(int requestCode) {
735 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
736 if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
737 requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
738 return false;
739 } else {
740 return true;
741 }
742 } else {
743 return true;
744 }
745 }
746
747 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
748 super.onActivityResult(requestCode, resultCode, data);
749 if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
750 mPendingConferenceInvite = ConferenceInvite.parse(data);
751 if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
752 if (mPendingConferenceInvite.execute(this)) {
753 mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
754 mToast.show();
755 }
756 mPendingConferenceInvite = null;
757 }
758 }
759 }
760
761 public int getWarningTextColor() {
762 return this.mColorRed;
763 }
764
765 public int getOnlineColor() {
766 return this.mColorGreen;
767 }
768
769 public int getPixel(int dp) {
770 DisplayMetrics metrics = getResources().getDisplayMetrics();
771 return ((int) (dp * metrics.density));
772 }
773
774 public boolean copyTextToClipboard(String text, int labelResId) {
775 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
776 String label = getResources().getString(labelResId);
777 if (mClipBoardManager != null) {
778 ClipData mClipData = ClipData.newPlainText(label, text);
779 mClipBoardManager.setPrimaryClip(mClipData);
780 return true;
781 }
782 return false;
783 }
784
785 protected boolean neverCompressPictures() {
786 return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression)).equals("never");
787 }
788
789 protected boolean manuallyChangePresence() {
790 return getPreferences().getBoolean(SettingsActivity.MANUALLY_CHANGE_PRESENCE, getResources().getBoolean(R.bool.manually_change_presence));
791 }
792
793 protected String getShareableUri() {
794 return getShareableUri(false);
795 }
796
797 protected String getShareableUri(boolean http) {
798 return null;
799 }
800
801 protected void shareLink(boolean http) {
802 String uri = getShareableUri(http);
803 if (uri == null || uri.isEmpty()) {
804 return;
805 }
806 Intent intent = new Intent(Intent.ACTION_SEND);
807 intent.setType("text/plain");
808 intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http));
809 try {
810 startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with)));
811 } catch (ActivityNotFoundException e) {
812 Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show();
813 }
814 }
815
816 protected void launchOpenKeyChain(long keyId) {
817 PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine();
818 try {
819 startIntentSenderForResult(
820 pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0,
821 0, 0);
822 } catch (Throwable e) {
823 Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show();
824 }
825 }
826
827 @Override
828 public void onResume() {
829 super.onResume();
830 }
831
832 protected int findTheme() {
833 return ThemeHelper.find(this);
834 }
835
836 @Override
837 public void onPause() {
838 super.onPause();
839 }
840
841 @Override
842 public boolean onMenuOpened(int id, Menu menu) {
843 if(id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) {
844 MenuDoubleTabUtil.recordMenuOpen();
845 }
846 return super.onMenuOpened(id, menu);
847 }
848
849 protected void showQrCode() {
850 showQrCode(getShareableUri());
851 }
852
853 protected void showQrCode(final String uri) {
854 if (uri == null || uri.isEmpty()) {
855 return;
856 }
857 Point size = new Point();
858 getWindowManager().getDefaultDisplay().getSize(size);
859 final int width = (size.x < size.y ? size.x : size.y);
860 Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width);
861 ImageView view = new ImageView(this);
862 view.setBackgroundColor(Color.WHITE);
863 view.setImageBitmap(bitmap);
864 AlertDialog.Builder builder = new AlertDialog.Builder(this);
865 builder.setView(view);
866 builder.create().show();
867 }
868
869 protected Account extractAccount(Intent intent) {
870 String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null;
871 try {
872 return jid != null ? xmppConnectionService.findAccountByJid(Jid.of(jid)) : null;
873 } catch (IllegalArgumentException e) {
874 return null;
875 }
876 }
877
878 public AvatarService avatarService() {
879 return xmppConnectionService.getAvatarService();
880 }
881
882 public void loadBitmap(Message message, ImageView imageView) {
883 Bitmap bm;
884 try {
885 bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true);
886 } catch (FileNotFoundException e) {
887 bm = null;
888 }
889 if (bm != null) {
890 cancelPotentialWork(message, imageView);
891 imageView.setImageBitmap(bm);
892 imageView.setBackgroundColor(0x00000000);
893 } else {
894 if (cancelPotentialWork(message, imageView)) {
895 imageView.setBackgroundColor(0xff333333);
896 imageView.setImageDrawable(null);
897 final BitmapWorkerTask task = new BitmapWorkerTask(this, imageView);
898 final AsyncDrawable asyncDrawable = new AsyncDrawable(
899 getResources(), null, task);
900 imageView.setImageDrawable(asyncDrawable);
901 try {
902 task.execute(message);
903 } catch (final RejectedExecutionException ignored) {
904 ignored.printStackTrace();
905 }
906 }
907 }
908 }
909
910 protected interface OnValueEdited {
911 String onValueEdited(String value);
912 }
913
914 public static class ConferenceInvite {
915 private String uuid;
916 private List<Jid> jids = new ArrayList<>();
917
918 public static ConferenceInvite parse(Intent data) {
919 ConferenceInvite invite = new ConferenceInvite();
920 invite.uuid = data.getStringExtra("conversation");
921 if (invite.uuid == null) {
922 return null;
923 }
924 try {
925 if (data.getBooleanExtra("multiple", false)) {
926 String[] toAdd = data.getStringArrayExtra("contacts");
927 for (String item : toAdd) {
928 invite.jids.add(Jid.of(item));
929 }
930 } else {
931 invite.jids.add(Jid.of(data.getStringExtra("contact")));
932 }
933 } catch (final IllegalArgumentException ignored) {
934 return null;
935 }
936 return invite;
937 }
938
939 public boolean execute(XmppActivity activity) {
940 XmppConnectionService service = activity.xmppConnectionService;
941 Conversation conversation = service.findConversationByUuid(this.uuid);
942 if (conversation == null) {
943 return false;
944 }
945 if (conversation.getMode() == Conversation.MODE_MULTI) {
946 for (Jid jid : jids) {
947 service.invite(conversation, jid);
948 }
949 return false;
950 } else {
951 jids.add(conversation.getJid().asBareJid());
952 return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback);
953 }
954 }
955 }
956
957 static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
958 private final WeakReference<ImageView> imageViewReference;
959 private final WeakReference<XmppActivity> activity;
960 private Message message = null;
961
962 private BitmapWorkerTask(XmppActivity activity, ImageView imageView) {
963 this.activity = new WeakReference<>(activity);
964 this.imageViewReference = new WeakReference<>(imageView);
965 }
966
967 @Override
968 protected Bitmap doInBackground(Message... params) {
969 if (isCancelled()) {
970 return null;
971 }
972 message = params[0];
973 try {
974 XmppActivity activity = this.activity.get();
975 if (activity != null && activity.xmppConnectionService != null) {
976 return activity.xmppConnectionService.getFileBackend().getThumbnail(message, (int) (activity.metrics.density * 288), false);
977 } else {
978 return null;
979 }
980 } catch (FileNotFoundException e) {
981 return null;
982 }
983 }
984
985 @Override
986 protected void onPostExecute(Bitmap bitmap) {
987 if (bitmap != null && !isCancelled()) {
988 final ImageView imageView = imageViewReference.get();
989 if (imageView != null) {
990 imageView.setImageBitmap(bitmap);
991 imageView.setBackgroundColor(0x00000000);
992 }
993 }
994 }
995 }
996
997 private static class AsyncDrawable extends BitmapDrawable {
998 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
999
1000 private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
1001 super(res, bitmap);
1002 bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask);
1003 }
1004
1005 private BitmapWorkerTask getBitmapWorkerTask() {
1006 return bitmapWorkerTaskReference.get();
1007 }
1008 }
1009}