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