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.AxolotlService;
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.red500);
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 Intent intent = new Intent(this, ContactDetailsActivity.class);
428 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
429 intent.putExtra("account", contact.getAccount().getJid().toBareJid().toString());
430 intent.putExtra("contact", contact.getJid().toString());
431 startActivity(intent);
432 }
433
434 public void switchToAccount(Account account) {
435 Intent intent = new Intent(this, EditAccountActivity.class);
436 intent.putExtra("jid", account.getJid().toBareJid().toString());
437 startActivity(intent);
438 }
439
440 protected void inviteToConversation(Conversation conversation) {
441 Intent intent = new Intent(getApplicationContext(),
442 ChooseContactActivity.class);
443 List<String> contacts = new ArrayList<>();
444 if (conversation.getMode() == Conversation.MODE_MULTI) {
445 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
446 Jid jid = user.getJid();
447 if (jid != null) {
448 contacts.add(jid.toBareJid().toString());
449 }
450 }
451 } else {
452 contacts.add(conversation.getJid().toBareJid().toString());
453 }
454 intent.putExtra("filter_contacts", contacts.toArray(new String[contacts.size()]));
455 intent.putExtra("conversation", conversation.getUuid());
456 intent.putExtra("multiple", true);
457 startActivityForResult(intent, REQUEST_INVITE_TO_CONVERSATION);
458 }
459
460 protected void announcePgp(Account account, final Conversation conversation) {
461 xmppConnectionService.getPgpEngine().generateSignature(account,
462 "online", new UiCallback<Account>() {
463
464 @Override
465 public void userInputRequried(PendingIntent pi,
466 Account account) {
467 try {
468 startIntentSenderForResult(pi.getIntentSender(),
469 REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
470 } catch (final SendIntentException ignored) {
471 }
472 }
473
474 @Override
475 public void success(Account account) {
476 xmppConnectionService.databaseBackend.updateAccount(account);
477 xmppConnectionService.sendPresence(account);
478 if (conversation != null) {
479 conversation.setNextEncryption(Message.ENCRYPTION_PGP);
480 xmppConnectionService.databaseBackend.updateConversation(conversation);
481 }
482 }
483
484 @Override
485 public void error(int error, Account account) {
486 displayErrorDialog(error);
487 }
488 });
489 }
490
491 protected void displayErrorDialog(final int errorCode) {
492 runOnUiThread(new Runnable() {
493
494 @Override
495 public void run() {
496 AlertDialog.Builder builder = new AlertDialog.Builder(
497 XmppActivity.this);
498 builder.setIconAttribute(android.R.attr.alertDialogIcon);
499 builder.setTitle(getString(R.string.error));
500 builder.setMessage(errorCode);
501 builder.setNeutralButton(R.string.accept, null);
502 builder.create().show();
503 }
504 });
505
506 }
507
508 protected void showAddToRosterDialog(final Conversation conversation) {
509 showAddToRosterDialog(conversation.getContact());
510 }
511
512 protected void showAddToRosterDialog(final Contact contact) {
513 AlertDialog.Builder builder = new AlertDialog.Builder(this);
514 builder.setTitle(contact.getJid().toString());
515 builder.setMessage(getString(R.string.not_in_roster));
516 builder.setNegativeButton(getString(R.string.cancel), null);
517 builder.setPositiveButton(getString(R.string.add_contact),
518 new DialogInterface.OnClickListener() {
519
520 @Override
521 public void onClick(DialogInterface dialog, int which) {
522 final Jid jid = contact.getJid();
523 Account account = contact.getAccount();
524 Contact contact = account.getRoster().getContact(jid);
525 xmppConnectionService.createContact(contact);
526 }
527 });
528 builder.create().show();
529 }
530
531 private void showAskForPresenceDialog(final Contact contact) {
532 AlertDialog.Builder builder = new AlertDialog.Builder(this);
533 builder.setTitle(contact.getJid().toString());
534 builder.setMessage(R.string.request_presence_updates);
535 builder.setNegativeButton(R.string.cancel, null);
536 builder.setPositiveButton(R.string.request_now,
537 new DialogInterface.OnClickListener() {
538
539 @Override
540 public void onClick(DialogInterface dialog, int which) {
541 if (xmppConnectionServiceBound) {
542 xmppConnectionService.sendPresencePacket(contact
543 .getAccount(), xmppConnectionService
544 .getPresenceGenerator()
545 .requestPresenceUpdatesFrom(contact));
546 }
547 }
548 });
549 builder.create().show();
550 }
551
552 private void warnMutalPresenceSubscription(final Conversation conversation,
553 final OnPresenceSelected listener) {
554 AlertDialog.Builder builder = new AlertDialog.Builder(this);
555 builder.setTitle(conversation.getContact().getJid().toString());
556 builder.setMessage(R.string.without_mutual_presence_updates);
557 builder.setNegativeButton(R.string.cancel, null);
558 builder.setPositiveButton(R.string.ignore, new OnClickListener() {
559
560 @Override
561 public void onClick(DialogInterface dialog, int which) {
562 conversation.setNextCounterpart(null);
563 if (listener != null) {
564 listener.onPresenceSelected();
565 }
566 }
567 });
568 builder.create().show();
569 }
570
571 protected void quickEdit(String previousValue, OnValueEdited callback) {
572 quickEdit(previousValue, callback, false);
573 }
574
575 protected void quickPasswordEdit(String previousValue,
576 OnValueEdited callback) {
577 quickEdit(previousValue, callback, true);
578 }
579
580 @SuppressLint("InflateParams")
581 private void quickEdit(final String previousValue,
582 final OnValueEdited callback, boolean password) {
583 AlertDialog.Builder builder = new AlertDialog.Builder(this);
584 View view = getLayoutInflater().inflate(R.layout.quickedit, null);
585 final EditText editor = (EditText) view.findViewById(R.id.editor);
586 OnClickListener mClickListener = new OnClickListener() {
587
588 @Override
589 public void onClick(DialogInterface dialog, int which) {
590 String value = editor.getText().toString();
591 if (!previousValue.equals(value) && value.trim().length() > 0) {
592 callback.onValueEdited(value);
593 }
594 }
595 };
596 if (password) {
597 editor.setInputType(InputType.TYPE_CLASS_TEXT
598 | InputType.TYPE_TEXT_VARIATION_PASSWORD);
599 editor.setHint(R.string.password);
600 builder.setPositiveButton(R.string.accept, mClickListener);
601 } else {
602 builder.setPositiveButton(R.string.edit, mClickListener);
603 }
604 editor.requestFocus();
605 editor.setText(previousValue);
606 builder.setView(view);
607 builder.setNegativeButton(R.string.cancel, null);
608 builder.create().show();
609 }
610
611 protected boolean addFingerprintRow(LinearLayout keys, final Account account, IdentityKey identityKey) {
612 final String fingerprint = identityKey.getFingerprint().replaceAll("\\s", "");
613 final AxolotlService.SQLiteAxolotlStore.Trust trust = account.getAxolotlService()
614 .getFingerprintTrust(fingerprint);
615 return addFingerprintRowWithListeners(keys, account, identityKey, trust, true,
616 new CompoundButton.OnCheckedChangeListener() {
617 @Override
618 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
619 if (isChecked != (trust == AxolotlService.SQLiteAxolotlStore.Trust.TRUSTED)) {
620 account.getAxolotlService().setFingerprintTrust(fingerprint,
621 (isChecked) ? AxolotlService.SQLiteAxolotlStore.Trust.TRUSTED :
622 AxolotlService.SQLiteAxolotlStore.Trust.UNTRUSTED);
623 }
624 refreshUi();
625 xmppConnectionService.updateAccountUi();
626 xmppConnectionService.updateConversationUi();
627 }
628 },
629 new View.OnClickListener() {
630 @Override
631 public void onClick(View v) {
632 account.getAxolotlService().setFingerprintTrust(fingerprint,
633 AxolotlService.SQLiteAxolotlStore.Trust.UNTRUSTED);
634 refreshUi();
635 xmppConnectionService.updateAccountUi();
636 xmppConnectionService.updateConversationUi();
637 }
638 }
639
640 );
641 }
642
643 protected boolean addFingerprintRowWithListeners(LinearLayout keys, final Account account,
644 final IdentityKey identityKey,
645 AxolotlService.SQLiteAxolotlStore.Trust trust,
646 boolean showTag,
647 CompoundButton.OnCheckedChangeListener
648 onCheckedChangeListener,
649 View.OnClickListener onClickListener) {
650 if (trust == AxolotlService.SQLiteAxolotlStore.Trust.COMPROMISED) {
651 return false;
652 }
653 View view = getLayoutInflater().inflate(R.layout.contact_key, keys, false);
654 TextView key = (TextView) view.findViewById(R.id.key);
655 TextView keyType = (TextView) view.findViewById(R.id.key_type);
656 Switch trustToggle = (Switch) view.findViewById(R.id.tgl_trust);
657 trustToggle.setVisibility(View.VISIBLE);
658 trustToggle.setOnCheckedChangeListener(onCheckedChangeListener);
659 trustToggle.setOnClickListener(onClickListener);
660 view.setOnLongClickListener(new View.OnLongClickListener() {
661 @Override
662 public boolean onLongClick(View v) {
663 showPurgeKeyDialog(account, identityKey);
664 return true;
665 }
666 });
667
668 switch (trust) {
669 case UNTRUSTED:
670 case TRUSTED:
671 trustToggle.setChecked(trust == AxolotlService.SQLiteAxolotlStore.Trust.TRUSTED, false);
672 trustToggle.setEnabled(true);
673 key.setTextColor(getPrimaryTextColor());
674 keyType.setTextColor(getSecondaryTextColor());
675 break;
676 case UNDECIDED:
677 trustToggle.setChecked(false, false);
678 trustToggle.setEnabled(false);
679 key.setTextColor(getPrimaryTextColor());
680 keyType.setTextColor(getSecondaryTextColor());
681 break;
682 case INACTIVE:
683 trustToggle.setChecked(true, false);
684 trustToggle.setEnabled(false);
685 key.setTextColor(getTertiaryTextColor());
686 keyType.setTextColor(getTertiaryTextColor());
687 break;
688 }
689
690 if (showTag) {
691 keyType.setText(getString(R.string.axolotl_fingerprint));
692 } else {
693 keyType.setVisibility(View.GONE);
694 }
695
696 key.setText(CryptoHelper.prettifyFingerprint(identityKey.getFingerprint()));
697 keys.addView(view);
698 return true;
699 }
700
701 public void showPurgeKeyDialog(final Account account, final IdentityKey identityKey) {
702 Builder builder = new Builder(this);
703 builder.setTitle(getString(R.string.purge_key));
704 builder.setIconAttribute(android.R.attr.alertDialogIcon);
705 builder.setMessage(getString(R.string.purge_key_desc_part1)
706 + "\n\n" + CryptoHelper.prettifyFingerprint(identityKey.getFingerprint())
707 + "\n\n" + getString(R.string.purge_key_desc_part2));
708 builder.setNegativeButton(getString(R.string.cancel), null);
709 builder.setPositiveButton(getString(R.string.accept),
710 new DialogInterface.OnClickListener() {
711 @Override
712 public void onClick(DialogInterface dialog, int which) {
713 account.getAxolotlService().purgeKey(identityKey);
714 refreshUi();
715 }
716 });
717 builder.create().show();
718 }
719
720 public void selectPresence(final Conversation conversation,
721 final OnPresenceSelected listener) {
722 final Contact contact = conversation.getContact();
723 if (conversation.hasValidOtrSession()) {
724 SessionID id = conversation.getOtrSession().getSessionID();
725 Jid jid;
726 try {
727 jid = Jid.fromString(id.getAccountID() + "/" + id.getUserID());
728 } catch (InvalidJidException e) {
729 jid = null;
730 }
731 conversation.setNextCounterpart(jid);
732 listener.onPresenceSelected();
733 } else if (!contact.showInRoster()) {
734 showAddToRosterDialog(conversation);
735 } else {
736 Presences presences = contact.getPresences();
737 if (presences.size() == 0) {
738 if (!contact.getOption(Contact.Options.TO)
739 && !contact.getOption(Contact.Options.ASKING)
740 && contact.getAccount().getStatus() == Account.State.ONLINE) {
741 showAskForPresenceDialog(contact);
742 } else if (!contact.getOption(Contact.Options.TO)
743 || !contact.getOption(Contact.Options.FROM)) {
744 warnMutalPresenceSubscription(conversation, listener);
745 } else {
746 conversation.setNextCounterpart(null);
747 listener.onPresenceSelected();
748 }
749 } else if (presences.size() == 1) {
750 String presence = presences.asStringArray()[0];
751 try {
752 conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence));
753 } catch (InvalidJidException e) {
754 conversation.setNextCounterpart(null);
755 }
756 listener.onPresenceSelected();
757 } else {
758 final StringBuilder presence = new StringBuilder();
759 AlertDialog.Builder builder = new AlertDialog.Builder(this);
760 builder.setTitle(getString(R.string.choose_presence));
761 final String[] presencesArray = presences.asStringArray();
762 int preselectedPresence = 0;
763 for (int i = 0; i < presencesArray.length; ++i) {
764 if (presencesArray[i].equals(contact.lastseen.presence)) {
765 preselectedPresence = i;
766 break;
767 }
768 }
769 presence.append(presencesArray[preselectedPresence]);
770 builder.setSingleChoiceItems(presencesArray,
771 preselectedPresence,
772 new DialogInterface.OnClickListener() {
773
774 @Override
775 public void onClick(DialogInterface dialog,
776 int which) {
777 presence.delete(0, presence.length());
778 presence.append(presencesArray[which]);
779 }
780 });
781 builder.setNegativeButton(R.string.cancel, null);
782 builder.setPositiveButton(R.string.ok, new OnClickListener() {
783
784 @Override
785 public void onClick(DialogInterface dialog, int which) {
786 try {
787 conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence.toString()));
788 } catch (InvalidJidException e) {
789 conversation.setNextCounterpart(null);
790 }
791 listener.onPresenceSelected();
792 }
793 });
794 builder.create().show();
795 }
796 }
797 }
798
799 protected void onActivityResult(int requestCode, int resultCode,
800 final Intent data) {
801 super.onActivityResult(requestCode, resultCode, data);
802 if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
803 mPendingConferenceInvite = ConferenceInvite.parse(data);
804 if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
805 mPendingConferenceInvite.execute(this);
806 mPendingConferenceInvite = null;
807 }
808 }
809 }
810
811 private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
812 @Override
813 public void success(final Conversation conversation) {
814 switchToConversation(conversation);
815 runOnUiThread(new Runnable() {
816 @Override
817 public void run() {
818 Toast.makeText(XmppActivity.this,R.string.conference_created,Toast.LENGTH_LONG).show();
819 }
820 });
821 }
822
823 @Override
824 public void error(final int errorCode, Conversation object) {
825 runOnUiThread(new Runnable() {
826 @Override
827 public void run() {
828 Toast.makeText(XmppActivity.this,errorCode,Toast.LENGTH_LONG).show();
829 }
830 });
831 }
832
833 @Override
834 public void userInputRequried(PendingIntent pi, Conversation object) {
835
836 }
837 };
838
839 public int getTertiaryTextColor() {
840 return this.mTertiaryTextColor;
841 }
842
843 public int getSecondaryTextColor() {
844 return this.mSecondaryTextColor;
845 }
846
847 public int getPrimaryTextColor() {
848 return this.mPrimaryTextColor;
849 }
850
851 public int getWarningTextColor() {
852 return this.mColorRed;
853 }
854
855 public int getOnlineColor() {
856 return this.mColorGreen;
857 }
858
859 public int getPrimaryBackgroundColor() {
860 return this.mPrimaryBackgroundColor;
861 }
862
863 public int getSecondaryBackgroundColor() {
864 return this.mSecondaryBackgroundColor;
865 }
866
867 public int getPixel(int dp) {
868 DisplayMetrics metrics = getResources().getDisplayMetrics();
869 return ((int) (dp * metrics.density));
870 }
871
872 public boolean copyTextToClipboard(String text, int labelResId) {
873 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
874 String label = getResources().getString(labelResId);
875 if (mClipBoardManager != null) {
876 ClipData mClipData = ClipData.newPlainText(label, text);
877 mClipBoardManager.setPrimaryClip(mClipData);
878 return true;
879 }
880 return false;
881 }
882
883 protected void registerNdefPushMessageCallback() {
884 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
885 if (nfcAdapter != null && nfcAdapter.isEnabled()) {
886 nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
887 @Override
888 public NdefMessage createNdefMessage(NfcEvent nfcEvent) {
889 return new NdefMessage(new NdefRecord[]{
890 NdefRecord.createUri(getShareableUri()),
891 NdefRecord.createApplicationRecord("eu.siacs.conversations")
892 });
893 }
894 }, this);
895 }
896 }
897
898 protected void unregisterNdefPushMessageCallback() {
899 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
900 if (nfcAdapter != null && nfcAdapter.isEnabled()) {
901 nfcAdapter.setNdefPushMessageCallback(null,this);
902 }
903 }
904
905 protected String getShareableUri() {
906 return null;
907 }
908
909 @Override
910 public void onResume() {
911 super.onResume();
912 if (this.getShareableUri()!=null) {
913 this.registerNdefPushMessageCallback();
914 }
915 }
916
917 protected int findTheme() {
918 if (getPreferences().getBoolean("use_larger_font", false)) {
919 return R.style.ConversationsTheme_LargerText;
920 } else {
921 return R.style.ConversationsTheme;
922 }
923 }
924
925 @Override
926 public void onPause() {
927 super.onPause();
928 this.unregisterNdefPushMessageCallback();
929 }
930
931 protected void showQrCode() {
932 String uri = getShareableUri();
933 if (uri!=null) {
934 Point size = new Point();
935 getWindowManager().getDefaultDisplay().getSize(size);
936 final int width = (size.x < size.y ? size.x : size.y);
937 Bitmap bitmap = createQrCodeBitmap(uri, width);
938 ImageView view = new ImageView(this);
939 view.setImageBitmap(bitmap);
940 AlertDialog.Builder builder = new AlertDialog.Builder(this);
941 builder.setView(view);
942 builder.create().show();
943 }
944 }
945
946 protected Bitmap createQrCodeBitmap(String input, int size) {
947 Log.d(Config.LOGTAG,"qr code requested size: "+size);
948 try {
949 final QRCodeWriter QR_CODE_WRITER = new QRCodeWriter();
950 final Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
951 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
952 final BitMatrix result = QR_CODE_WRITER.encode(input, BarcodeFormat.QR_CODE, size, size, hints);
953 final int width = result.getWidth();
954 final int height = result.getHeight();
955 final int[] pixels = new int[width * height];
956 for (int y = 0; y < height; y++) {
957 final int offset = y * width;
958 for (int x = 0; x < width; x++) {
959 pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.TRANSPARENT;
960 }
961 }
962 final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
963 Log.d(Config.LOGTAG,"output size: "+width+"x"+height);
964 bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
965 return bitmap;
966 } catch (final WriterException e) {
967 return null;
968 }
969 }
970
971 public static class ConferenceInvite {
972 private String uuid;
973 private List<Jid> jids = new ArrayList<>();
974
975 public static ConferenceInvite parse(Intent data) {
976 ConferenceInvite invite = new ConferenceInvite();
977 invite.uuid = data.getStringExtra("conversation");
978 if (invite.uuid == null) {
979 return null;
980 }
981 try {
982 if (data.getBooleanExtra("multiple", false)) {
983 String[] toAdd = data.getStringArrayExtra("contacts");
984 for (String item : toAdd) {
985 invite.jids.add(Jid.fromString(item));
986 }
987 } else {
988 invite.jids.add(Jid.fromString(data.getStringExtra("contact")));
989 }
990 } catch (final InvalidJidException ignored) {
991 return null;
992 }
993 return invite;
994 }
995
996 public void execute(XmppActivity activity) {
997 XmppConnectionService service = activity.xmppConnectionService;
998 Conversation conversation = service.findConversationByUuid(this.uuid);
999 if (conversation == null) {
1000 return;
1001 }
1002 if (conversation.getMode() == Conversation.MODE_MULTI) {
1003 for (Jid jid : jids) {
1004 service.invite(conversation, jid);
1005 }
1006 } else {
1007 jids.add(conversation.getJid().toBareJid());
1008 service.createAdhocConference(conversation.getAccount(), jids, activity.adhocCallback);
1009 }
1010 }
1011 }
1012
1013 public AvatarService avatarService() {
1014 return xmppConnectionService.getAvatarService();
1015 }
1016
1017 class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
1018 private final WeakReference<ImageView> imageViewReference;
1019 private Message message = null;
1020
1021 public BitmapWorkerTask(ImageView imageView) {
1022 imageViewReference = new WeakReference<>(imageView);
1023 }
1024
1025 @Override
1026 protected Bitmap doInBackground(Message... params) {
1027 message = params[0];
1028 try {
1029 return xmppConnectionService.getFileBackend().getThumbnail(
1030 message, (int) (metrics.density * 288), false);
1031 } catch (FileNotFoundException e) {
1032 return null;
1033 }
1034 }
1035
1036 @Override
1037 protected void onPostExecute(Bitmap bitmap) {
1038 if (bitmap != null) {
1039 final ImageView imageView = imageViewReference.get();
1040 if (imageView != null) {
1041 imageView.setImageBitmap(bitmap);
1042 imageView.setBackgroundColor(0x00000000);
1043 }
1044 }
1045 }
1046 }
1047
1048 public void loadBitmap(Message message, ImageView imageView) {
1049 Bitmap bm;
1050 try {
1051 bm = xmppConnectionService.getFileBackend().getThumbnail(message,
1052 (int) (metrics.density * 288), true);
1053 } catch (FileNotFoundException e) {
1054 bm = null;
1055 }
1056 if (bm != null) {
1057 imageView.setImageBitmap(bm);
1058 imageView.setBackgroundColor(0x00000000);
1059 } else {
1060 if (cancelPotentialWork(message, imageView)) {
1061 imageView.setBackgroundColor(0xff333333);
1062 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
1063 final AsyncDrawable asyncDrawable = new AsyncDrawable(
1064 getResources(), null, task);
1065 imageView.setImageDrawable(asyncDrawable);
1066 try {
1067 task.execute(message);
1068 } catch (final RejectedExecutionException ignored) {
1069 }
1070 }
1071 }
1072 }
1073
1074 public static boolean cancelPotentialWork(Message message,
1075 ImageView imageView) {
1076 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
1077
1078 if (bitmapWorkerTask != null) {
1079 final Message oldMessage = bitmapWorkerTask.message;
1080 if (oldMessage == null || message != oldMessage) {
1081 bitmapWorkerTask.cancel(true);
1082 } else {
1083 return false;
1084 }
1085 }
1086 return true;
1087 }
1088
1089 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
1090 if (imageView != null) {
1091 final Drawable drawable = imageView.getDrawable();
1092 if (drawable instanceof AsyncDrawable) {
1093 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
1094 return asyncDrawable.getBitmapWorkerTask();
1095 }
1096 }
1097 return null;
1098 }
1099
1100 static class AsyncDrawable extends BitmapDrawable {
1101 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1102
1103 public AsyncDrawable(Resources res, Bitmap bitmap,
1104 BitmapWorkerTask bitmapWorkerTask) {
1105 super(res, bitmap);
1106 bitmapWorkerTaskReference = new WeakReference<>(
1107 bitmapWorkerTask);
1108 }
1109
1110 public BitmapWorkerTask getBitmapWorkerTask() {
1111 return bitmapWorkerTaskReference.get();
1112 }
1113 }
1114}