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