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