1package eu.siacs.conversations.ui;
2
3import android.annotation.SuppressLint;
4import android.annotation.TargetApi;
5import android.app.ActionBar;
6import android.app.Activity;
7import android.app.AlertDialog;
8import android.app.AlertDialog.Builder;
9import android.app.PendingIntent;
10import android.content.ClipData;
11import android.content.ClipboardManager;
12import android.content.ComponentName;
13import android.content.Context;
14import android.content.DialogInterface;
15import android.content.DialogInterface.OnClickListener;
16import android.content.Intent;
17import android.content.IntentSender.SendIntentException;
18import android.content.ServiceConnection;
19import android.content.SharedPreferences;
20import android.content.pm.PackageManager;
21import android.content.pm.ResolveInfo;
22import android.content.res.Resources;
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.Uri;
29import android.nfc.NdefMessage;
30import android.nfc.NdefRecord;
31import android.nfc.NfcAdapter;
32import android.nfc.NfcEvent;
33import android.os.AsyncTask;
34import android.os.Build;
35import android.os.Bundle;
36import android.os.Handler;
37import android.os.IBinder;
38import android.os.SystemClock;
39import android.preference.PreferenceManager;
40import android.text.InputType;
41import android.util.DisplayMetrics;
42import android.util.Log;
43import android.view.MenuItem;
44import android.view.View;
45import android.view.inputmethod.InputMethodManager;
46import android.widget.CompoundButton;
47import android.widget.EditText;
48import android.widget.ImageView;
49import android.widget.LinearLayout;
50import android.widget.TextView;
51import android.widget.Toast;
52
53import com.google.zxing.BarcodeFormat;
54import com.google.zxing.EncodeHintType;
55import com.google.zxing.WriterException;
56import com.google.zxing.common.BitMatrix;
57import com.google.zxing.qrcode.QRCodeWriter;
58import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
59
60import net.java.otr4j.session.SessionID;
61
62import org.whispersystems.libaxolotl.IdentityKey;
63
64import java.io.FileNotFoundException;
65import java.lang.ref.WeakReference;
66import java.util.ArrayList;
67import java.util.Hashtable;
68import java.util.List;
69import java.util.concurrent.RejectedExecutionException;
70
71import eu.siacs.conversations.Config;
72import eu.siacs.conversations.R;
73import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
74import eu.siacs.conversations.entities.Account;
75import eu.siacs.conversations.entities.Contact;
76import eu.siacs.conversations.entities.Conversation;
77import eu.siacs.conversations.entities.Message;
78import eu.siacs.conversations.entities.MucOptions;
79import eu.siacs.conversations.entities.Presences;
80import eu.siacs.conversations.services.AvatarService;
81import eu.siacs.conversations.services.XmppConnectionService;
82import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
83import eu.siacs.conversations.ui.widget.Switch;
84import eu.siacs.conversations.utils.CryptoHelper;
85import eu.siacs.conversations.utils.ExceptionHelper;
86import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
87import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
88import eu.siacs.conversations.xmpp.jid.InvalidJidException;
89import eu.siacs.conversations.xmpp.jid.Jid;
90
91public abstract class XmppActivity extends Activity {
92
93 protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
94 protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
95
96 public XmppConnectionService xmppConnectionService;
97 public boolean xmppConnectionServiceBound = false;
98 protected boolean registeredListeners = false;
99
100 protected int mPrimaryTextColor;
101 protected int mSecondaryTextColor;
102 protected int mTertiaryTextColor;
103 protected int mPrimaryBackgroundColor;
104 protected int mSecondaryBackgroundColor;
105 protected int mColorRed;
106 protected int mColorOrange;
107 protected int mColorGreen;
108 protected int mPrimaryColor;
109
110 protected boolean mUseSubject = true;
111
112 private DisplayMetrics metrics;
113 protected int mTheme;
114 protected boolean mUsingEnterKey = false;
115
116 private long mLastUiRefresh = 0;
117 private Handler mRefreshUiHandler = new Handler();
118 private Runnable mRefreshUiRunnable = new Runnable() {
119 @Override
120 public void run() {
121 mLastUiRefresh = SystemClock.elapsedRealtime();
122 refreshUiReal();
123 }
124 };
125
126 protected ConferenceInvite mPendingConferenceInvite = null;
127
128
129 protected final void refreshUi() {
130 final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh;
131 if (diff > Config.REFRESH_UI_INTERVAL) {
132 mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
133 runOnUiThread(mRefreshUiRunnable);
134 } else {
135 final long next = Config.REFRESH_UI_INTERVAL - diff;
136 mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable);
137 mRefreshUiHandler.postDelayed(mRefreshUiRunnable,next);
138 }
139 }
140
141 abstract protected void refreshUiReal();
142
143 protected interface OnValueEdited {
144 public void onValueEdited(String value);
145 }
146
147 public interface OnPresenceSelected {
148 public void onPresenceSelected();
149 }
150
151 protected ServiceConnection mConnection = new ServiceConnection() {
152
153 @Override
154 public void onServiceConnected(ComponentName className, IBinder service) {
155 XmppConnectionBinder binder = (XmppConnectionBinder) service;
156 xmppConnectionService = binder.getService();
157 xmppConnectionServiceBound = true;
158 if (!registeredListeners && shouldRegisterListeners()) {
159 registerListeners();
160 registeredListeners = true;
161 }
162 onBackendConnected();
163 }
164
165 @Override
166 public void onServiceDisconnected(ComponentName arg0) {
167 xmppConnectionServiceBound = false;
168 }
169 };
170
171 @Override
172 protected void onStart() {
173 super.onStart();
174 if (!xmppConnectionServiceBound) {
175 connectToBackend();
176 } else {
177 if (!registeredListeners) {
178 this.registerListeners();
179 this.registeredListeners = true;
180 }
181 this.onBackendConnected();
182 }
183 }
184
185 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
186 protected boolean shouldRegisterListeners() {
187 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
188 return !isDestroyed() && !isFinishing();
189 } else {
190 return !isFinishing();
191 }
192 }
193
194 public void connectToBackend() {
195 Intent intent = new Intent(this, XmppConnectionService.class);
196 intent.setAction("ui");
197 startService(intent);
198 bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
199 }
200
201 @Override
202 protected void onStop() {
203 super.onStop();
204 if (xmppConnectionServiceBound) {
205 if (registeredListeners) {
206 this.unregisterListeners();
207 this.registeredListeners = false;
208 }
209 unbindService(mConnection);
210 xmppConnectionServiceBound = false;
211 }
212 }
213
214 protected void hideKeyboard() {
215 InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
216
217 View focus = getCurrentFocus();
218
219 if (focus != null) {
220
221 inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
222 InputMethodManager.HIDE_NOT_ALWAYS);
223 }
224 }
225
226 public boolean hasPgp() {
227 return xmppConnectionService.getPgpEngine() != null;
228 }
229
230 public void showInstallPgpDialog() {
231 Builder builder = new AlertDialog.Builder(this);
232 builder.setTitle(getString(R.string.openkeychain_required));
233 builder.setIconAttribute(android.R.attr.alertDialogIcon);
234 builder.setMessage(getText(R.string.openkeychain_required_long));
235 builder.setNegativeButton(getString(R.string.cancel), null);
236 builder.setNeutralButton(getString(R.string.restart),
237 new OnClickListener() {
238
239 @Override
240 public void onClick(DialogInterface dialog, int which) {
241 if (xmppConnectionServiceBound) {
242 unbindService(mConnection);
243 xmppConnectionServiceBound = false;
244 }
245 stopService(new Intent(XmppActivity.this,
246 XmppConnectionService.class));
247 finish();
248 }
249 });
250 builder.setPositiveButton(getString(R.string.install),
251 new OnClickListener() {
252
253 @Override
254 public void onClick(DialogInterface dialog, int which) {
255 Uri uri = Uri
256 .parse("market://details?id=org.sufficientlysecure.keychain");
257 Intent marketIntent = new Intent(Intent.ACTION_VIEW,
258 uri);
259 PackageManager manager = getApplicationContext()
260 .getPackageManager();
261 List<ResolveInfo> infos = manager
262 .queryIntentActivities(marketIntent, 0);
263 if (infos.size() > 0) {
264 startActivity(marketIntent);
265 } else {
266 uri = Uri.parse("http://www.openkeychain.org/");
267 Intent browserIntent = new Intent(
268 Intent.ACTION_VIEW, uri);
269 startActivity(browserIntent);
270 }
271 finish();
272 }
273 });
274 builder.create().show();
275 }
276
277 abstract void onBackendConnected();
278
279 protected void registerListeners() {
280 if (this instanceof XmppConnectionService.OnConversationUpdate) {
281 this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
282 }
283 if (this instanceof XmppConnectionService.OnAccountUpdate) {
284 this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
285 }
286 if (this instanceof XmppConnectionService.OnRosterUpdate) {
287 this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
288 }
289 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
290 this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
291 }
292 if (this instanceof OnUpdateBlocklist) {
293 this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
294 }
295 if (this instanceof XmppConnectionService.OnShowErrorToast) {
296 this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this);
297 }
298 if (this instanceof OnKeyStatusUpdated) {
299 this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this);
300 }
301 }
302
303 protected void unregisterListeners() {
304 if (this instanceof XmppConnectionService.OnConversationUpdate) {
305 this.xmppConnectionService.removeOnConversationListChangedListener();
306 }
307 if (this instanceof XmppConnectionService.OnAccountUpdate) {
308 this.xmppConnectionService.removeOnAccountListChangedListener();
309 }
310 if (this instanceof XmppConnectionService.OnRosterUpdate) {
311 this.xmppConnectionService.removeOnRosterUpdateListener();
312 }
313 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
314 this.xmppConnectionService.removeOnMucRosterUpdateListener();
315 }
316 if (this instanceof OnUpdateBlocklist) {
317 this.xmppConnectionService.removeOnUpdateBlocklistListener();
318 }
319 if (this instanceof XmppConnectionService.OnShowErrorToast) {
320 this.xmppConnectionService.removeOnShowErrorToastListener();
321 }
322 if (this instanceof OnKeyStatusUpdated) {
323 this.xmppConnectionService.removeOnNewKeysAvailableListener();
324 }
325 }
326
327 @Override
328 public boolean onOptionsItemSelected(final MenuItem item) {
329 switch (item.getItemId()) {
330 case R.id.action_settings:
331 startActivity(new Intent(this, SettingsActivity.class));
332 break;
333 case R.id.action_accounts:
334 startActivity(new Intent(this, ManageAccountActivity.class));
335 break;
336 case android.R.id.home:
337 finish();
338 break;
339 case R.id.action_show_qr_code:
340 showQrCode();
341 break;
342 }
343 return super.onOptionsItemSelected(item);
344 }
345
346 @Override
347 protected void onCreate(Bundle savedInstanceState) {
348 super.onCreate(savedInstanceState);
349 metrics = getResources().getDisplayMetrics();
350 ExceptionHelper.init(getApplicationContext());
351 mPrimaryTextColor = getResources().getColor(R.color.black87);
352 mSecondaryTextColor = getResources().getColor(R.color.black54);
353 mTertiaryTextColor = getResources().getColor(R.color.black12);
354 mColorRed = getResources().getColor(R.color.red800);
355 mColorOrange = getResources().getColor(R.color.orange500);
356 mColorGreen = getResources().getColor(R.color.green500);
357 mPrimaryColor = getResources().getColor(R.color.green500);
358 mPrimaryBackgroundColor = getResources().getColor(R.color.grey50);
359 mSecondaryBackgroundColor = getResources().getColor(R.color.grey200);
360 this.mTheme = findTheme();
361 setTheme(this.mTheme);
362 this.mUsingEnterKey = usingEnterKey();
363 mUseSubject = getPreferences().getBoolean("use_subject", true);
364 final ActionBar ab = getActionBar();
365 if (ab!=null) {
366 ab.setDisplayHomeAsUpEnabled(true);
367 }
368 }
369
370 protected boolean usingEnterKey() {
371 return getPreferences().getBoolean("display_enter_key", false);
372 }
373
374 protected SharedPreferences getPreferences() {
375 return PreferenceManager
376 .getDefaultSharedPreferences(getApplicationContext());
377 }
378
379 public boolean useSubjectToIdentifyConference() {
380 return mUseSubject;
381 }
382
383 public void switchToConversation(Conversation conversation) {
384 switchToConversation(conversation, null, false);
385 }
386
387 public void switchToConversation(Conversation conversation, String text,
388 boolean newTask) {
389 switchToConversation(conversation,text,null,false,newTask);
390 }
391
392 public void highlightInMuc(Conversation conversation, String nick) {
393 switchToConversation(conversation, null, nick, false, false);
394 }
395
396 public void privateMsgInMuc(Conversation conversation, String nick) {
397 switchToConversation(conversation, null, nick, true, false);
398 }
399
400 private void switchToConversation(Conversation conversation, String text, String nick, boolean pm, boolean newTask) {
401 Intent viewConversationIntent = new Intent(this,
402 ConversationActivity.class);
403 viewConversationIntent.setAction(Intent.ACTION_VIEW);
404 viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
405 conversation.getUuid());
406 if (text != null) {
407 viewConversationIntent.putExtra(ConversationActivity.TEXT, text);
408 }
409 if (nick != null) {
410 viewConversationIntent.putExtra(ConversationActivity.NICK, nick);
411 viewConversationIntent.putExtra(ConversationActivity.PRIVATE_MESSAGE,pm);
412 }
413 viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
414 if (newTask) {
415 viewConversationIntent.setFlags(viewConversationIntent.getFlags()
416 | Intent.FLAG_ACTIVITY_NEW_TASK
417 | Intent.FLAG_ACTIVITY_SINGLE_TOP);
418 } else {
419 viewConversationIntent.setFlags(viewConversationIntent.getFlags()
420 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
421 }
422 startActivity(viewConversationIntent);
423 finish();
424 }
425
426 public void switchToContactDetails(Contact contact) {
427 switchToContactDetails(contact, null);
428 }
429
430 public void switchToContactDetails(Contact contact, String messageFingerprint) {
431 Intent intent = new Intent(this, ContactDetailsActivity.class);
432 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
433 intent.putExtra("account", contact.getAccount().getJid().toBareJid().toString());
434 intent.putExtra("contact", contact.getJid().toString());
435 intent.putExtra("fingerprint", messageFingerprint);
436 startActivity(intent);
437 }
438
439 public void switchToAccount(Account account) {
440 Intent intent = new Intent(this, EditAccountActivity.class);
441 intent.putExtra("jid", account.getJid().toBareJid().toString());
442 startActivity(intent);
443 }
444
445 protected void inviteToConversation(Conversation conversation) {
446 Intent intent = new Intent(getApplicationContext(),
447 ChooseContactActivity.class);
448 List<String> contacts = new ArrayList<>();
449 if (conversation.getMode() == Conversation.MODE_MULTI) {
450 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
451 Jid jid = user.getJid();
452 if (jid != null) {
453 contacts.add(jid.toBareJid().toString());
454 }
455 }
456 } else {
457 contacts.add(conversation.getJid().toBareJid().toString());
458 }
459 intent.putExtra("filter_contacts", contacts.toArray(new String[contacts.size()]));
460 intent.putExtra("conversation", conversation.getUuid());
461 intent.putExtra("multiple", true);
462 startActivityForResult(intent, REQUEST_INVITE_TO_CONVERSATION);
463 }
464
465 protected void announcePgp(Account account, final Conversation conversation) {
466 xmppConnectionService.getPgpEngine().generateSignature(account,
467 "online", new UiCallback<Account>() {
468
469 @Override
470 public void userInputRequried(PendingIntent pi,
471 Account account) {
472 try {
473 startIntentSenderForResult(pi.getIntentSender(),
474 REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
475 } catch (final SendIntentException ignored) {
476 }
477 }
478
479 @Override
480 public void success(Account account) {
481 xmppConnectionService.databaseBackend.updateAccount(account);
482 xmppConnectionService.sendPresence(account);
483 if (conversation != null) {
484 conversation.setNextEncryption(Message.ENCRYPTION_PGP);
485 xmppConnectionService.databaseBackend.updateConversation(conversation);
486 }
487 }
488
489 @Override
490 public void error(int error, Account account) {
491 displayErrorDialog(error);
492 }
493 });
494 }
495
496 protected void displayErrorDialog(final int errorCode) {
497 runOnUiThread(new Runnable() {
498
499 @Override
500 public void run() {
501 AlertDialog.Builder builder = new AlertDialog.Builder(
502 XmppActivity.this);
503 builder.setIconAttribute(android.R.attr.alertDialogIcon);
504 builder.setTitle(getString(R.string.error));
505 builder.setMessage(errorCode);
506 builder.setNeutralButton(R.string.accept, null);
507 builder.create().show();
508 }
509 });
510
511 }
512
513 protected void showAddToRosterDialog(final Conversation conversation) {
514 showAddToRosterDialog(conversation.getContact());
515 }
516
517 protected void showAddToRosterDialog(final Contact contact) {
518 AlertDialog.Builder builder = new AlertDialog.Builder(this);
519 builder.setTitle(contact.getJid().toString());
520 builder.setMessage(getString(R.string.not_in_roster));
521 builder.setNegativeButton(getString(R.string.cancel), null);
522 builder.setPositiveButton(getString(R.string.add_contact),
523 new DialogInterface.OnClickListener() {
524
525 @Override
526 public void onClick(DialogInterface dialog, int which) {
527 final Jid jid = contact.getJid();
528 Account account = contact.getAccount();
529 Contact contact = account.getRoster().getContact(jid);
530 xmppConnectionService.createContact(contact);
531 }
532 });
533 builder.create().show();
534 }
535
536 private void showAskForPresenceDialog(final Contact contact) {
537 AlertDialog.Builder builder = new AlertDialog.Builder(this);
538 builder.setTitle(contact.getJid().toString());
539 builder.setMessage(R.string.request_presence_updates);
540 builder.setNegativeButton(R.string.cancel, null);
541 builder.setPositiveButton(R.string.request_now,
542 new DialogInterface.OnClickListener() {
543
544 @Override
545 public void onClick(DialogInterface dialog, int which) {
546 if (xmppConnectionServiceBound) {
547 xmppConnectionService.sendPresencePacket(contact
548 .getAccount(), xmppConnectionService
549 .getPresenceGenerator()
550 .requestPresenceUpdatesFrom(contact));
551 }
552 }
553 });
554 builder.create().show();
555 }
556
557 private void warnMutalPresenceSubscription(final Conversation conversation,
558 final OnPresenceSelected listener) {
559 AlertDialog.Builder builder = new AlertDialog.Builder(this);
560 builder.setTitle(conversation.getContact().getJid().toString());
561 builder.setMessage(R.string.without_mutual_presence_updates);
562 builder.setNegativeButton(R.string.cancel, null);
563 builder.setPositiveButton(R.string.ignore, new OnClickListener() {
564
565 @Override
566 public void onClick(DialogInterface dialog, int which) {
567 conversation.setNextCounterpart(null);
568 if (listener != null) {
569 listener.onPresenceSelected();
570 }
571 }
572 });
573 builder.create().show();
574 }
575
576 protected void quickEdit(String previousValue, OnValueEdited callback) {
577 quickEdit(previousValue, callback, false);
578 }
579
580 protected void quickPasswordEdit(String previousValue,
581 OnValueEdited callback) {
582 quickEdit(previousValue, callback, true);
583 }
584
585 @SuppressLint("InflateParams")
586 private void quickEdit(final String previousValue,
587 final OnValueEdited callback, boolean password) {
588 AlertDialog.Builder builder = new AlertDialog.Builder(this);
589 View view = getLayoutInflater().inflate(R.layout.quickedit, null);
590 final EditText editor = (EditText) view.findViewById(R.id.editor);
591 OnClickListener mClickListener = new OnClickListener() {
592
593 @Override
594 public void onClick(DialogInterface dialog, int which) {
595 String value = editor.getText().toString();
596 if (!previousValue.equals(value) && value.trim().length() > 0) {
597 callback.onValueEdited(value);
598 }
599 }
600 };
601 if (password) {
602 editor.setInputType(InputType.TYPE_CLASS_TEXT
603 | InputType.TYPE_TEXT_VARIATION_PASSWORD);
604 editor.setHint(R.string.password);
605 builder.setPositiveButton(R.string.accept, mClickListener);
606 } else {
607 builder.setPositiveButton(R.string.edit, mClickListener);
608 }
609 editor.requestFocus();
610 editor.setText(previousValue);
611 builder.setView(view);
612 builder.setNegativeButton(R.string.cancel, null);
613 builder.create().show();
614 }
615
616 protected boolean addFingerprintRow(LinearLayout keys, final Account account, IdentityKey identityKey, boolean highlight) {
617 final String fingerprint = identityKey.getFingerprint().replaceAll("\\s", "");
618 final XmppAxolotlSession.Trust trust = account.getAxolotlService()
619 .getFingerprintTrust(fingerprint);
620 return addFingerprintRowWithListeners(keys, account, identityKey, highlight, trust, true,
621 new CompoundButton.OnCheckedChangeListener() {
622 @Override
623 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
624 account.getAxolotlService().setFingerprintTrust(fingerprint,
625 (isChecked) ? XmppAxolotlSession.Trust.TRUSTED :
626 XmppAxolotlSession.Trust.UNTRUSTED);
627 }
628 },
629 new View.OnClickListener() {
630 @Override
631 public void onClick(View v) {
632 account.getAxolotlService().setFingerprintTrust(fingerprint,
633 XmppAxolotlSession.Trust.UNTRUSTED);
634 v.setEnabled(true);
635 }
636 }
637
638 );
639 }
640
641 protected boolean addFingerprintRowWithListeners(LinearLayout keys, final Account account,
642 final IdentityKey identityKey,
643 boolean highlight,
644 XmppAxolotlSession.Trust trust,
645 boolean showTag,
646 CompoundButton.OnCheckedChangeListener
647 onCheckedChangeListener,
648 View.OnClickListener onClickListener) {
649 if (trust == XmppAxolotlSession.Trust.COMPROMISED) {
650 return false;
651 }
652 View view = getLayoutInflater().inflate(R.layout.contact_key, keys, false);
653 TextView key = (TextView) view.findViewById(R.id.key);
654 TextView keyType = (TextView) view.findViewById(R.id.key_type);
655 Switch trustToggle = (Switch) view.findViewById(R.id.tgl_trust);
656 trustToggle.setVisibility(View.VISIBLE);
657 trustToggle.setOnCheckedChangeListener(onCheckedChangeListener);
658 trustToggle.setOnClickListener(onClickListener);
659 view.setOnLongClickListener(new View.OnLongClickListener() {
660 @Override
661 public boolean onLongClick(View v) {
662 showPurgeKeyDialog(account, identityKey);
663 return true;
664 }
665 });
666
667 switch (trust) {
668 case UNTRUSTED:
669 case TRUSTED:
670 trustToggle.setChecked(trust == XmppAxolotlSession.Trust.TRUSTED, false);
671 trustToggle.setEnabled(true);
672 key.setTextColor(getPrimaryTextColor());
673 keyType.setTextColor(getSecondaryTextColor());
674 break;
675 case UNDECIDED:
676 trustToggle.setChecked(false, false);
677 trustToggle.setEnabled(false);
678 key.setTextColor(getPrimaryTextColor());
679 keyType.setTextColor(getSecondaryTextColor());
680 break;
681 case INACTIVE_UNTRUSTED:
682 case INACTIVE_UNDECIDED:
683 trustToggle.setOnClickListener(null);
684 trustToggle.setChecked(false, false);
685 trustToggle.setEnabled(false);
686 key.setTextColor(getTertiaryTextColor());
687 keyType.setTextColor(getTertiaryTextColor());
688 break;
689 case INACTIVE_TRUSTED:
690 trustToggle.setOnClickListener(null);
691 trustToggle.setChecked(true, false);
692 trustToggle.setEnabled(false);
693 key.setTextColor(getTertiaryTextColor());
694 keyType.setTextColor(getTertiaryTextColor());
695 break;
696 }
697
698 if (showTag) {
699 keyType.setText(getString(R.string.omemo_fingerprint));
700 } else {
701 keyType.setVisibility(View.GONE);
702 }
703 if (highlight) {
704 keyType.setTextColor(getResources().getColor(R.color.accent));
705 keyType.setText(getString(R.string.omemo_fingerprint_selected_message));
706 } else {
707 keyType.setText(getString(R.string.omemo_fingerprint));
708 }
709
710 key.setText(CryptoHelper.prettifyFingerprint(identityKey.getFingerprint()));
711 keys.addView(view);
712 return true;
713 }
714
715 public void showPurgeKeyDialog(final Account account, final IdentityKey identityKey) {
716 Builder builder = new Builder(this);
717 builder.setTitle(getString(R.string.purge_key));
718 builder.setIconAttribute(android.R.attr.alertDialogIcon);
719 builder.setMessage(getString(R.string.purge_key_desc_part1)
720 + "\n\n" + CryptoHelper.prettifyFingerprint(identityKey.getFingerprint())
721 + "\n\n" + getString(R.string.purge_key_desc_part2));
722 builder.setNegativeButton(getString(R.string.cancel), null);
723 builder.setPositiveButton(getString(R.string.accept),
724 new DialogInterface.OnClickListener() {
725 @Override
726 public void onClick(DialogInterface dialog, int which) {
727 account.getAxolotlService().purgeKey(identityKey);
728 refreshUi();
729 }
730 });
731 builder.create().show();
732 }
733
734 public void selectPresence(final Conversation conversation,
735 final OnPresenceSelected listener) {
736 final Contact contact = conversation.getContact();
737 if (conversation.hasValidOtrSession()) {
738 SessionID id = conversation.getOtrSession().getSessionID();
739 Jid jid;
740 try {
741 jid = Jid.fromString(id.getAccountID() + "/" + id.getUserID());
742 } catch (InvalidJidException e) {
743 jid = null;
744 }
745 conversation.setNextCounterpart(jid);
746 listener.onPresenceSelected();
747 } else if (!contact.showInRoster()) {
748 showAddToRosterDialog(conversation);
749 } else {
750 Presences presences = contact.getPresences();
751 if (presences.size() == 0) {
752 if (!contact.getOption(Contact.Options.TO)
753 && !contact.getOption(Contact.Options.ASKING)
754 && contact.getAccount().getStatus() == Account.State.ONLINE) {
755 showAskForPresenceDialog(contact);
756 } else if (!contact.getOption(Contact.Options.TO)
757 || !contact.getOption(Contact.Options.FROM)) {
758 warnMutalPresenceSubscription(conversation, listener);
759 } else {
760 conversation.setNextCounterpart(null);
761 listener.onPresenceSelected();
762 }
763 } else if (presences.size() == 1) {
764 String presence = presences.asStringArray()[0];
765 try {
766 conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence));
767 } catch (InvalidJidException e) {
768 conversation.setNextCounterpart(null);
769 }
770 listener.onPresenceSelected();
771 } else {
772 final StringBuilder presence = new StringBuilder();
773 AlertDialog.Builder builder = new AlertDialog.Builder(this);
774 builder.setTitle(getString(R.string.choose_presence));
775 final String[] presencesArray = presences.asStringArray();
776 int preselectedPresence = 0;
777 for (int i = 0; i < presencesArray.length; ++i) {
778 if (presencesArray[i].equals(contact.lastseen.presence)) {
779 preselectedPresence = i;
780 break;
781 }
782 }
783 presence.append(presencesArray[preselectedPresence]);
784 builder.setSingleChoiceItems(presencesArray,
785 preselectedPresence,
786 new DialogInterface.OnClickListener() {
787
788 @Override
789 public void onClick(DialogInterface dialog,
790 int which) {
791 presence.delete(0, presence.length());
792 presence.append(presencesArray[which]);
793 }
794 });
795 builder.setNegativeButton(R.string.cancel, null);
796 builder.setPositiveButton(R.string.ok, new OnClickListener() {
797
798 @Override
799 public void onClick(DialogInterface dialog, int which) {
800 try {
801 conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence.toString()));
802 } catch (InvalidJidException e) {
803 conversation.setNextCounterpart(null);
804 }
805 listener.onPresenceSelected();
806 }
807 });
808 builder.create().show();
809 }
810 }
811 }
812
813 protected void onActivityResult(int requestCode, int resultCode,
814 final Intent data) {
815 super.onActivityResult(requestCode, resultCode, data);
816 if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
817 mPendingConferenceInvite = ConferenceInvite.parse(data);
818 if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
819 mPendingConferenceInvite.execute(this);
820 mPendingConferenceInvite = null;
821 }
822 }
823 }
824
825 private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
826 @Override
827 public void success(final Conversation conversation) {
828 switchToConversation(conversation);
829 runOnUiThread(new Runnable() {
830 @Override
831 public void run() {
832 Toast.makeText(XmppActivity.this,R.string.conference_created,Toast.LENGTH_LONG).show();
833 }
834 });
835 }
836
837 @Override
838 public void error(final int errorCode, Conversation object) {
839 runOnUiThread(new Runnable() {
840 @Override
841 public void run() {
842 Toast.makeText(XmppActivity.this,errorCode,Toast.LENGTH_LONG).show();
843 }
844 });
845 }
846
847 @Override
848 public void userInputRequried(PendingIntent pi, Conversation object) {
849
850 }
851 };
852
853 public int getTertiaryTextColor() {
854 return this.mTertiaryTextColor;
855 }
856
857 public int getSecondaryTextColor() {
858 return this.mSecondaryTextColor;
859 }
860
861 public int getPrimaryTextColor() {
862 return this.mPrimaryTextColor;
863 }
864
865 public int getWarningTextColor() {
866 return this.mColorRed;
867 }
868
869 public int getOnlineColor() {
870 return this.mColorGreen;
871 }
872
873 public int getPrimaryBackgroundColor() {
874 return this.mPrimaryBackgroundColor;
875 }
876
877 public int getSecondaryBackgroundColor() {
878 return this.mSecondaryBackgroundColor;
879 }
880
881 public int getPixel(int dp) {
882 DisplayMetrics metrics = getResources().getDisplayMetrics();
883 return ((int) (dp * metrics.density));
884 }
885
886 public boolean copyTextToClipboard(String text, int labelResId) {
887 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
888 String label = getResources().getString(labelResId);
889 if (mClipBoardManager != null) {
890 ClipData mClipData = ClipData.newPlainText(label, text);
891 mClipBoardManager.setPrimaryClip(mClipData);
892 return true;
893 }
894 return false;
895 }
896
897 protected void registerNdefPushMessageCallback() {
898 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
899 if (nfcAdapter != null && nfcAdapter.isEnabled()) {
900 nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
901 @Override
902 public NdefMessage createNdefMessage(NfcEvent nfcEvent) {
903 return new NdefMessage(new NdefRecord[]{
904 NdefRecord.createUri(getShareableUri()),
905 NdefRecord.createApplicationRecord("eu.siacs.conversations")
906 });
907 }
908 }, this);
909 }
910 }
911
912 protected void unregisterNdefPushMessageCallback() {
913 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
914 if (nfcAdapter != null && nfcAdapter.isEnabled()) {
915 nfcAdapter.setNdefPushMessageCallback(null,this);
916 }
917 }
918
919 protected String getShareableUri() {
920 return null;
921 }
922
923 @Override
924 public void onResume() {
925 super.onResume();
926 if (this.getShareableUri()!=null) {
927 this.registerNdefPushMessageCallback();
928 }
929 }
930
931 protected int findTheme() {
932 if (getPreferences().getBoolean("use_larger_font", false)) {
933 return R.style.ConversationsTheme_LargerText;
934 } else {
935 return R.style.ConversationsTheme;
936 }
937 }
938
939 @Override
940 public void onPause() {
941 super.onPause();
942 this.unregisterNdefPushMessageCallback();
943 }
944
945 protected void showQrCode() {
946 String uri = getShareableUri();
947 if (uri!=null) {
948 Point size = new Point();
949 getWindowManager().getDefaultDisplay().getSize(size);
950 final int width = (size.x < size.y ? size.x : size.y);
951 Bitmap bitmap = createQrCodeBitmap(uri, width);
952 ImageView view = new ImageView(this);
953 view.setImageBitmap(bitmap);
954 AlertDialog.Builder builder = new AlertDialog.Builder(this);
955 builder.setView(view);
956 builder.create().show();
957 }
958 }
959
960 protected Bitmap createQrCodeBitmap(String input, int size) {
961 Log.d(Config.LOGTAG,"qr code requested size: "+size);
962 try {
963 final QRCodeWriter QR_CODE_WRITER = new QRCodeWriter();
964 final Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
965 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
966 final BitMatrix result = QR_CODE_WRITER.encode(input, BarcodeFormat.QR_CODE, size, size, hints);
967 final int width = result.getWidth();
968 final int height = result.getHeight();
969 final int[] pixels = new int[width * height];
970 for (int y = 0; y < height; y++) {
971 final int offset = y * width;
972 for (int x = 0; x < width; x++) {
973 pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.TRANSPARENT;
974 }
975 }
976 final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
977 Log.d(Config.LOGTAG,"output size: "+width+"x"+height);
978 bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
979 return bitmap;
980 } catch (final WriterException e) {
981 return null;
982 }
983 }
984
985 public static class ConferenceInvite {
986 private String uuid;
987 private List<Jid> jids = new ArrayList<>();
988
989 public static ConferenceInvite parse(Intent data) {
990 ConferenceInvite invite = new ConferenceInvite();
991 invite.uuid = data.getStringExtra("conversation");
992 if (invite.uuid == null) {
993 return null;
994 }
995 try {
996 if (data.getBooleanExtra("multiple", false)) {
997 String[] toAdd = data.getStringArrayExtra("contacts");
998 for (String item : toAdd) {
999 invite.jids.add(Jid.fromString(item));
1000 }
1001 } else {
1002 invite.jids.add(Jid.fromString(data.getStringExtra("contact")));
1003 }
1004 } catch (final InvalidJidException ignored) {
1005 return null;
1006 }
1007 return invite;
1008 }
1009
1010 public void execute(XmppActivity activity) {
1011 XmppConnectionService service = activity.xmppConnectionService;
1012 Conversation conversation = service.findConversationByUuid(this.uuid);
1013 if (conversation == null) {
1014 return;
1015 }
1016 if (conversation.getMode() == Conversation.MODE_MULTI) {
1017 for (Jid jid : jids) {
1018 service.invite(conversation, jid);
1019 }
1020 } else {
1021 jids.add(conversation.getJid().toBareJid());
1022 service.createAdhocConference(conversation.getAccount(), jids, activity.adhocCallback);
1023 }
1024 }
1025 }
1026
1027 public AvatarService avatarService() {
1028 return xmppConnectionService.getAvatarService();
1029 }
1030
1031 class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
1032 private final WeakReference<ImageView> imageViewReference;
1033 private Message message = null;
1034
1035 public BitmapWorkerTask(ImageView imageView) {
1036 imageViewReference = new WeakReference<>(imageView);
1037 }
1038
1039 @Override
1040 protected Bitmap doInBackground(Message... params) {
1041 message = params[0];
1042 try {
1043 return xmppConnectionService.getFileBackend().getThumbnail(
1044 message, (int) (metrics.density * 288), false);
1045 } catch (FileNotFoundException e) {
1046 return null;
1047 }
1048 }
1049
1050 @Override
1051 protected void onPostExecute(Bitmap bitmap) {
1052 if (bitmap != null) {
1053 final ImageView imageView = imageViewReference.get();
1054 if (imageView != null) {
1055 imageView.setImageBitmap(bitmap);
1056 imageView.setBackgroundColor(0x00000000);
1057 }
1058 }
1059 }
1060 }
1061
1062 public void loadBitmap(Message message, ImageView imageView) {
1063 Bitmap bm;
1064 try {
1065 bm = xmppConnectionService.getFileBackend().getThumbnail(message,
1066 (int) (metrics.density * 288), true);
1067 } catch (FileNotFoundException e) {
1068 bm = null;
1069 }
1070 if (bm != null) {
1071 imageView.setImageBitmap(bm);
1072 imageView.setBackgroundColor(0x00000000);
1073 } else {
1074 if (cancelPotentialWork(message, imageView)) {
1075 imageView.setBackgroundColor(0xff333333);
1076 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
1077 final AsyncDrawable asyncDrawable = new AsyncDrawable(
1078 getResources(), null, task);
1079 imageView.setImageDrawable(asyncDrawable);
1080 try {
1081 task.execute(message);
1082 } catch (final RejectedExecutionException ignored) {
1083 }
1084 }
1085 }
1086 }
1087
1088 public static boolean cancelPotentialWork(Message message,
1089 ImageView imageView) {
1090 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
1091
1092 if (bitmapWorkerTask != null) {
1093 final Message oldMessage = bitmapWorkerTask.message;
1094 if (oldMessage == null || message != oldMessage) {
1095 bitmapWorkerTask.cancel(true);
1096 } else {
1097 return false;
1098 }
1099 }
1100 return true;
1101 }
1102
1103 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
1104 if (imageView != null) {
1105 final Drawable drawable = imageView.getDrawable();
1106 if (drawable instanceof AsyncDrawable) {
1107 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
1108 return asyncDrawable.getBitmapWorkerTask();
1109 }
1110 }
1111 return null;
1112 }
1113
1114 static class AsyncDrawable extends BitmapDrawable {
1115 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1116
1117 public AsyncDrawable(Resources res, Bitmap bitmap,
1118 BitmapWorkerTask bitmapWorkerTask) {
1119 super(res, bitmap);
1120 bitmapWorkerTaskReference = new WeakReference<>(
1121 bitmapWorkerTask);
1122 }
1123
1124 public BitmapWorkerTask getBitmapWorkerTask() {
1125 return bitmapWorkerTaskReference.get();
1126 }
1127 }
1128}