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