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.SQLiteAxolotlStore;
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 SQLiteAxolotlStore.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 if (isChecked != (trust == SQLiteAxolotlStore.Trust.TRUSTED)) {
625 account.getAxolotlService().setFingerprintTrust(fingerprint,
626 (isChecked) ? SQLiteAxolotlStore.Trust.TRUSTED :
627 SQLiteAxolotlStore.Trust.UNTRUSTED);
628 }
629 }
630 },
631 new View.OnClickListener() {
632 @Override
633 public void onClick(View v) {
634 account.getAxolotlService().setFingerprintTrust(fingerprint,
635 SQLiteAxolotlStore.Trust.UNTRUSTED);
636 v.setEnabled(true);
637 }
638 }
639
640 );
641 }
642
643 protected boolean addFingerprintRowWithListeners(LinearLayout keys, final Account account,
644 final IdentityKey identityKey,
645 boolean highlight,
646 SQLiteAxolotlStore.Trust trust,
647 boolean showTag,
648 CompoundButton.OnCheckedChangeListener
649 onCheckedChangeListener,
650 View.OnClickListener onClickListener) {
651 if (trust == SQLiteAxolotlStore.Trust.COMPROMISED) {
652 return false;
653 }
654 View view = getLayoutInflater().inflate(R.layout.contact_key, keys, false);
655 TextView key = (TextView) view.findViewById(R.id.key);
656 TextView keyType = (TextView) view.findViewById(R.id.key_type);
657 Switch trustToggle = (Switch) view.findViewById(R.id.tgl_trust);
658 trustToggle.setVisibility(View.VISIBLE);
659 trustToggle.setOnCheckedChangeListener(onCheckedChangeListener);
660 trustToggle.setOnClickListener(onClickListener);
661 view.setOnLongClickListener(new View.OnLongClickListener() {
662 @Override
663 public boolean onLongClick(View v) {
664 showPurgeKeyDialog(account, identityKey);
665 return true;
666 }
667 });
668
669 switch (trust) {
670 case UNTRUSTED:
671 case TRUSTED:
672 trustToggle.setChecked(trust == SQLiteAxolotlStore.Trust.TRUSTED, false);
673 trustToggle.setEnabled(true);
674 key.setTextColor(getPrimaryTextColor());
675 keyType.setTextColor(getSecondaryTextColor());
676 break;
677 case UNDECIDED:
678 trustToggle.setChecked(false, false);
679 trustToggle.setEnabled(false);
680 key.setTextColor(getPrimaryTextColor());
681 keyType.setTextColor(getSecondaryTextColor());
682 break;
683 case INACTIVE:
684 trustToggle.setOnClickListener(null);
685 trustToggle.setChecked(true, false);
686 trustToggle.setEnabled(false);
687 key.setTextColor(getTertiaryTextColor());
688 keyType.setTextColor(getTertiaryTextColor());
689 break;
690 }
691
692 if (showTag) {
693 keyType.setText(getString(R.string.axolotl_fingerprint));
694 } else {
695 keyType.setVisibility(View.GONE);
696 }
697 if (highlight) {
698 keyType.setTextColor(getResources().getColor(R.color.accent));
699 keyType.setText(getString(R.string.axolotl_fingerprint_selected_message));
700 } else {
701 keyType.setText(getString(R.string.axolotl_fingerprint));
702 }
703
704 key.setText(CryptoHelper.prettifyFingerprint(identityKey.getFingerprint()));
705 keys.addView(view);
706 return true;
707 }
708
709 public void showPurgeKeyDialog(final Account account, final IdentityKey identityKey) {
710 Builder builder = new Builder(this);
711 builder.setTitle(getString(R.string.purge_key));
712 builder.setIconAttribute(android.R.attr.alertDialogIcon);
713 builder.setMessage(getString(R.string.purge_key_desc_part1)
714 + "\n\n" + CryptoHelper.prettifyFingerprint(identityKey.getFingerprint())
715 + "\n\n" + getString(R.string.purge_key_desc_part2));
716 builder.setNegativeButton(getString(R.string.cancel), null);
717 builder.setPositiveButton(getString(R.string.accept),
718 new DialogInterface.OnClickListener() {
719 @Override
720 public void onClick(DialogInterface dialog, int which) {
721 account.getAxolotlService().purgeKey(identityKey);
722 refreshUi();
723 }
724 });
725 builder.create().show();
726 }
727
728 public void selectPresence(final Conversation conversation,
729 final OnPresenceSelected listener) {
730 final Contact contact = conversation.getContact();
731 if (conversation.hasValidOtrSession()) {
732 SessionID id = conversation.getOtrSession().getSessionID();
733 Jid jid;
734 try {
735 jid = Jid.fromString(id.getAccountID() + "/" + id.getUserID());
736 } catch (InvalidJidException e) {
737 jid = null;
738 }
739 conversation.setNextCounterpart(jid);
740 listener.onPresenceSelected();
741 } else if (!contact.showInRoster()) {
742 showAddToRosterDialog(conversation);
743 } else {
744 Presences presences = contact.getPresences();
745 if (presences.size() == 0) {
746 if (!contact.getOption(Contact.Options.TO)
747 && !contact.getOption(Contact.Options.ASKING)
748 && contact.getAccount().getStatus() == Account.State.ONLINE) {
749 showAskForPresenceDialog(contact);
750 } else if (!contact.getOption(Contact.Options.TO)
751 || !contact.getOption(Contact.Options.FROM)) {
752 warnMutalPresenceSubscription(conversation, listener);
753 } else {
754 conversation.setNextCounterpart(null);
755 listener.onPresenceSelected();
756 }
757 } else if (presences.size() == 1) {
758 String presence = presences.asStringArray()[0];
759 try {
760 conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence));
761 } catch (InvalidJidException e) {
762 conversation.setNextCounterpart(null);
763 }
764 listener.onPresenceSelected();
765 } else {
766 final StringBuilder presence = new StringBuilder();
767 AlertDialog.Builder builder = new AlertDialog.Builder(this);
768 builder.setTitle(getString(R.string.choose_presence));
769 final String[] presencesArray = presences.asStringArray();
770 int preselectedPresence = 0;
771 for (int i = 0; i < presencesArray.length; ++i) {
772 if (presencesArray[i].equals(contact.lastseen.presence)) {
773 preselectedPresence = i;
774 break;
775 }
776 }
777 presence.append(presencesArray[preselectedPresence]);
778 builder.setSingleChoiceItems(presencesArray,
779 preselectedPresence,
780 new DialogInterface.OnClickListener() {
781
782 @Override
783 public void onClick(DialogInterface dialog,
784 int which) {
785 presence.delete(0, presence.length());
786 presence.append(presencesArray[which]);
787 }
788 });
789 builder.setNegativeButton(R.string.cancel, null);
790 builder.setPositiveButton(R.string.ok, new OnClickListener() {
791
792 @Override
793 public void onClick(DialogInterface dialog, int which) {
794 try {
795 conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence.toString()));
796 } catch (InvalidJidException e) {
797 conversation.setNextCounterpart(null);
798 }
799 listener.onPresenceSelected();
800 }
801 });
802 builder.create().show();
803 }
804 }
805 }
806
807 protected void onActivityResult(int requestCode, int resultCode,
808 final Intent data) {
809 super.onActivityResult(requestCode, resultCode, data);
810 if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
811 mPendingConferenceInvite = ConferenceInvite.parse(data);
812 if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
813 mPendingConferenceInvite.execute(this);
814 mPendingConferenceInvite = null;
815 }
816 }
817 }
818
819 private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
820 @Override
821 public void success(final Conversation conversation) {
822 switchToConversation(conversation);
823 runOnUiThread(new Runnable() {
824 @Override
825 public void run() {
826 Toast.makeText(XmppActivity.this,R.string.conference_created,Toast.LENGTH_LONG).show();
827 }
828 });
829 }
830
831 @Override
832 public void error(final int errorCode, Conversation object) {
833 runOnUiThread(new Runnable() {
834 @Override
835 public void run() {
836 Toast.makeText(XmppActivity.this,errorCode,Toast.LENGTH_LONG).show();
837 }
838 });
839 }
840
841 @Override
842 public void userInputRequried(PendingIntent pi, Conversation object) {
843
844 }
845 };
846
847 public int getTertiaryTextColor() {
848 return this.mTertiaryTextColor;
849 }
850
851 public int getSecondaryTextColor() {
852 return this.mSecondaryTextColor;
853 }
854
855 public int getPrimaryTextColor() {
856 return this.mPrimaryTextColor;
857 }
858
859 public int getWarningTextColor() {
860 return this.mColorRed;
861 }
862
863 public int getOnlineColor() {
864 return this.mColorGreen;
865 }
866
867 public int getPrimaryBackgroundColor() {
868 return this.mPrimaryBackgroundColor;
869 }
870
871 public int getSecondaryBackgroundColor() {
872 return this.mSecondaryBackgroundColor;
873 }
874
875 public int getPixel(int dp) {
876 DisplayMetrics metrics = getResources().getDisplayMetrics();
877 return ((int) (dp * metrics.density));
878 }
879
880 public boolean copyTextToClipboard(String text, int labelResId) {
881 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
882 String label = getResources().getString(labelResId);
883 if (mClipBoardManager != null) {
884 ClipData mClipData = ClipData.newPlainText(label, text);
885 mClipBoardManager.setPrimaryClip(mClipData);
886 return true;
887 }
888 return false;
889 }
890
891 protected void registerNdefPushMessageCallback() {
892 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
893 if (nfcAdapter != null && nfcAdapter.isEnabled()) {
894 nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
895 @Override
896 public NdefMessage createNdefMessage(NfcEvent nfcEvent) {
897 return new NdefMessage(new NdefRecord[]{
898 NdefRecord.createUri(getShareableUri()),
899 NdefRecord.createApplicationRecord("eu.siacs.conversations")
900 });
901 }
902 }, this);
903 }
904 }
905
906 protected void unregisterNdefPushMessageCallback() {
907 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
908 if (nfcAdapter != null && nfcAdapter.isEnabled()) {
909 nfcAdapter.setNdefPushMessageCallback(null,this);
910 }
911 }
912
913 protected String getShareableUri() {
914 return null;
915 }
916
917 @Override
918 public void onResume() {
919 super.onResume();
920 if (this.getShareableUri()!=null) {
921 this.registerNdefPushMessageCallback();
922 }
923 }
924
925 protected int findTheme() {
926 if (getPreferences().getBoolean("use_larger_font", false)) {
927 return R.style.ConversationsTheme_LargerText;
928 } else {
929 return R.style.ConversationsTheme;
930 }
931 }
932
933 @Override
934 public void onPause() {
935 super.onPause();
936 this.unregisterNdefPushMessageCallback();
937 }
938
939 protected void showQrCode() {
940 String uri = getShareableUri();
941 if (uri!=null) {
942 Point size = new Point();
943 getWindowManager().getDefaultDisplay().getSize(size);
944 final int width = (size.x < size.y ? size.x : size.y);
945 Bitmap bitmap = createQrCodeBitmap(uri, width);
946 ImageView view = new ImageView(this);
947 view.setImageBitmap(bitmap);
948 AlertDialog.Builder builder = new AlertDialog.Builder(this);
949 builder.setView(view);
950 builder.create().show();
951 }
952 }
953
954 protected Bitmap createQrCodeBitmap(String input, int size) {
955 Log.d(Config.LOGTAG,"qr code requested size: "+size);
956 try {
957 final QRCodeWriter QR_CODE_WRITER = new QRCodeWriter();
958 final Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
959 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
960 final BitMatrix result = QR_CODE_WRITER.encode(input, BarcodeFormat.QR_CODE, size, size, hints);
961 final int width = result.getWidth();
962 final int height = result.getHeight();
963 final int[] pixels = new int[width * height];
964 for (int y = 0; y < height; y++) {
965 final int offset = y * width;
966 for (int x = 0; x < width; x++) {
967 pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.TRANSPARENT;
968 }
969 }
970 final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
971 Log.d(Config.LOGTAG,"output size: "+width+"x"+height);
972 bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
973 return bitmap;
974 } catch (final WriterException e) {
975 return null;
976 }
977 }
978
979 public static class ConferenceInvite {
980 private String uuid;
981 private List<Jid> jids = new ArrayList<>();
982
983 public static ConferenceInvite parse(Intent data) {
984 ConferenceInvite invite = new ConferenceInvite();
985 invite.uuid = data.getStringExtra("conversation");
986 if (invite.uuid == null) {
987 return null;
988 }
989 try {
990 if (data.getBooleanExtra("multiple", false)) {
991 String[] toAdd = data.getStringArrayExtra("contacts");
992 for (String item : toAdd) {
993 invite.jids.add(Jid.fromString(item));
994 }
995 } else {
996 invite.jids.add(Jid.fromString(data.getStringExtra("contact")));
997 }
998 } catch (final InvalidJidException ignored) {
999 return null;
1000 }
1001 return invite;
1002 }
1003
1004 public void execute(XmppActivity activity) {
1005 XmppConnectionService service = activity.xmppConnectionService;
1006 Conversation conversation = service.findConversationByUuid(this.uuid);
1007 if (conversation == null) {
1008 return;
1009 }
1010 if (conversation.getMode() == Conversation.MODE_MULTI) {
1011 for (Jid jid : jids) {
1012 service.invite(conversation, jid);
1013 }
1014 } else {
1015 jids.add(conversation.getJid().toBareJid());
1016 service.createAdhocConference(conversation.getAccount(), jids, activity.adhocCallback);
1017 }
1018 }
1019 }
1020
1021 public AvatarService avatarService() {
1022 return xmppConnectionService.getAvatarService();
1023 }
1024
1025 class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
1026 private final WeakReference<ImageView> imageViewReference;
1027 private Message message = null;
1028
1029 public BitmapWorkerTask(ImageView imageView) {
1030 imageViewReference = new WeakReference<>(imageView);
1031 }
1032
1033 @Override
1034 protected Bitmap doInBackground(Message... params) {
1035 message = params[0];
1036 try {
1037 return xmppConnectionService.getFileBackend().getThumbnail(
1038 message, (int) (metrics.density * 288), false);
1039 } catch (FileNotFoundException e) {
1040 return null;
1041 }
1042 }
1043
1044 @Override
1045 protected void onPostExecute(Bitmap bitmap) {
1046 if (bitmap != null) {
1047 final ImageView imageView = imageViewReference.get();
1048 if (imageView != null) {
1049 imageView.setImageBitmap(bitmap);
1050 imageView.setBackgroundColor(0x00000000);
1051 }
1052 }
1053 }
1054 }
1055
1056 public void loadBitmap(Message message, ImageView imageView) {
1057 Bitmap bm;
1058 try {
1059 bm = xmppConnectionService.getFileBackend().getThumbnail(message,
1060 (int) (metrics.density * 288), true);
1061 } catch (FileNotFoundException e) {
1062 bm = null;
1063 }
1064 if (bm != null) {
1065 imageView.setImageBitmap(bm);
1066 imageView.setBackgroundColor(0x00000000);
1067 } else {
1068 if (cancelPotentialWork(message, imageView)) {
1069 imageView.setBackgroundColor(0xff333333);
1070 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
1071 final AsyncDrawable asyncDrawable = new AsyncDrawable(
1072 getResources(), null, task);
1073 imageView.setImageDrawable(asyncDrawable);
1074 try {
1075 task.execute(message);
1076 } catch (final RejectedExecutionException ignored) {
1077 }
1078 }
1079 }
1080 }
1081
1082 public static boolean cancelPotentialWork(Message message,
1083 ImageView imageView) {
1084 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
1085
1086 if (bitmapWorkerTask != null) {
1087 final Message oldMessage = bitmapWorkerTask.message;
1088 if (oldMessage == null || message != oldMessage) {
1089 bitmapWorkerTask.cancel(true);
1090 } else {
1091 return false;
1092 }
1093 }
1094 return true;
1095 }
1096
1097 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
1098 if (imageView != null) {
1099 final Drawable drawable = imageView.getDrawable();
1100 if (drawable instanceof AsyncDrawable) {
1101 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
1102 return asyncDrawable.getBitmapWorkerTask();
1103 }
1104 }
1105 return null;
1106 }
1107
1108 static class AsyncDrawable extends BitmapDrawable {
1109 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
1110
1111 public AsyncDrawable(Resources res, Bitmap bitmap,
1112 BitmapWorkerTask bitmapWorkerTask) {
1113 super(res, bitmap);
1114 bitmapWorkerTaskReference = new WeakReference<>(
1115 bitmapWorkerTask);
1116 }
1117
1118 public BitmapWorkerTask getBitmapWorkerTask() {
1119 return bitmapWorkerTaskReference.get();
1120 }
1121 }
1122}