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