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