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 abstract void onBackendConnected();
270
271 protected void registerListeners() {
272 if (this instanceof XmppConnectionService.OnConversationUpdate) {
273 this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this);
274 }
275 if (this instanceof XmppConnectionService.OnAccountUpdate) {
276 this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this);
277 }
278 if (this instanceof XmppConnectionService.OnRosterUpdate) {
279 this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this);
280 }
281 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
282 this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this);
283 }
284 if (this instanceof OnUpdateBlocklist) {
285 this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this);
286 }
287 }
288
289 protected void unregisterListeners() {
290 if (this instanceof XmppConnectionService.OnConversationUpdate) {
291 this.xmppConnectionService.removeOnConversationListChangedListener();
292 }
293 if (this instanceof XmppConnectionService.OnAccountUpdate) {
294 this.xmppConnectionService.removeOnAccountListChangedListener();
295 }
296 if (this instanceof XmppConnectionService.OnRosterUpdate) {
297 this.xmppConnectionService.removeOnRosterUpdateListener();
298 }
299 if (this instanceof XmppConnectionService.OnMucRosterUpdate) {
300 this.xmppConnectionService.removeOnMucRosterUpdateListener();
301 }
302 if (this instanceof OnUpdateBlocklist) {
303 this.xmppConnectionService.removeOnUpdateBlocklistListener();
304 }
305 }
306
307 @Override
308 public boolean onOptionsItemSelected(final MenuItem item) {
309 switch (item.getItemId()) {
310 case R.id.action_settings:
311 startActivity(new Intent(this, SettingsActivity.class));
312 break;
313 case R.id.action_accounts:
314 startActivity(new Intent(this, ManageAccountActivity.class));
315 break;
316 case android.R.id.home:
317 finish();
318 break;
319 case R.id.action_show_qr_code:
320 showQrCode();
321 break;
322 }
323 return super.onOptionsItemSelected(item);
324 }
325
326 @Override
327 protected void onCreate(Bundle savedInstanceState) {
328 super.onCreate(savedInstanceState);
329 metrics = getResources().getDisplayMetrics();
330 ExceptionHelper.init(getApplicationContext());
331 mPrimaryTextColor = getResources().getColor(R.color.primarytext);
332 mSecondaryTextColor = getResources().getColor(R.color.secondarytext);
333 mColorRed = getResources().getColor(R.color.red);
334 mColorOrange = getResources().getColor(R.color.orange);
335 mColorGreen = getResources().getColor(R.color.green);
336 mPrimaryColor = getResources().getColor(R.color.primary);
337 mPrimaryBackgroundColor = getResources().getColor(R.color.primarybackground);
338 mSecondaryBackgroundColor = getResources().getColor(R.color.secondarybackground);
339 this.mTheme = findTheme();
340 setTheme(this.mTheme);
341 this.mUsingEnterKey = usingEnterKey();
342 mUseSubject = getPreferences().getBoolean("use_subject", true);
343 final ActionBar ab = getActionBar();
344 if (ab!=null) {
345 ab.setDisplayHomeAsUpEnabled(true);
346 }
347 }
348
349 protected boolean usingEnterKey() {
350 return getPreferences().getBoolean("display_enter_key", false);
351 }
352
353 protected SharedPreferences getPreferences() {
354 return PreferenceManager
355 .getDefaultSharedPreferences(getApplicationContext());
356 }
357
358 public boolean useSubjectToIdentifyConference() {
359 return mUseSubject;
360 }
361
362 public void switchToConversation(Conversation conversation) {
363 switchToConversation(conversation, null, false);
364 }
365
366 public void switchToConversation(Conversation conversation, String text,
367 boolean newTask) {
368 switchToConversation(conversation,text,null,newTask);
369 }
370
371 public void highlightInMuc(Conversation conversation, String nick) {
372 switchToConversation(conversation, null, nick, false);
373 }
374
375 private void switchToConversation(Conversation conversation, String text, String nick, boolean newTask) {
376 Intent viewConversationIntent = new Intent(this,
377 ConversationActivity.class);
378 viewConversationIntent.setAction(Intent.ACTION_VIEW);
379 viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
380 conversation.getUuid());
381 if (text != null) {
382 viewConversationIntent.putExtra(ConversationActivity.TEXT, text);
383 }
384 if (nick != null) {
385 viewConversationIntent.putExtra(ConversationActivity.NICK, nick);
386 }
387 viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
388 if (newTask) {
389 viewConversationIntent.setFlags(viewConversationIntent.getFlags()
390 | Intent.FLAG_ACTIVITY_NEW_TASK
391 | Intent.FLAG_ACTIVITY_SINGLE_TOP);
392 } else {
393 viewConversationIntent.setFlags(viewConversationIntent.getFlags()
394 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
395 }
396 startActivity(viewConversationIntent);
397 finish();
398 }
399
400 public void switchToContactDetails(Contact contact) {
401 Intent intent = new Intent(this, ContactDetailsActivity.class);
402 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
403 intent.putExtra("account", contact.getAccount().getJid().toBareJid().toString());
404 intent.putExtra("contact", contact.getJid().toString());
405 startActivity(intent);
406 }
407
408 public void switchToAccount(Account account) {
409 Intent intent = new Intent(this, EditAccountActivity.class);
410 intent.putExtra("jid", account.getJid().toBareJid().toString());
411 startActivity(intent);
412 }
413
414 protected void inviteToConversation(Conversation conversation) {
415 Intent intent = new Intent(getApplicationContext(),
416 ChooseContactActivity.class);
417 List<String> contacts = new ArrayList<>();
418 if (conversation.getMode() == Conversation.MODE_MULTI) {
419 for (MucOptions.User user : conversation.getMucOptions().getUsers()) {
420 Jid jid = user.getJid();
421 if (jid != null) {
422 contacts.add(jid.toBareJid().toString());
423 }
424 }
425 } else {
426 contacts.add(conversation.getJid().toBareJid().toString());
427 }
428 intent.putExtra("filter_contacts", contacts.toArray(new String[contacts.size()]));
429 intent.putExtra("conversation", conversation.getUuid());
430 intent.putExtra("multiple", true);
431 startActivityForResult(intent, REQUEST_INVITE_TO_CONVERSATION);
432 }
433
434 protected void announcePgp(Account account, final Conversation conversation) {
435 xmppConnectionService.getPgpEngine().generateSignature(account,
436 "online", new UiCallback<Account>() {
437
438 @Override
439 public void userInputRequried(PendingIntent pi,
440 Account account) {
441 try {
442 startIntentSenderForResult(pi.getIntentSender(),
443 REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
444 } catch (final SendIntentException ignored) {
445 }
446 }
447
448 @Override
449 public void success(Account account) {
450 xmppConnectionService.databaseBackend
451 .updateAccount(account);
452 xmppConnectionService.sendPresence(account);
453 if (conversation != null) {
454 conversation
455 .setNextEncryption(Message.ENCRYPTION_PGP);
456 xmppConnectionService.databaseBackend
457 .updateConversation(conversation);
458 }
459 }
460
461 @Override
462 public void error(int error, Account account) {
463 displayErrorDialog(error);
464 }
465 });
466 }
467
468 protected void displayErrorDialog(final int errorCode) {
469 runOnUiThread(new Runnable() {
470
471 @Override
472 public void run() {
473 AlertDialog.Builder builder = new AlertDialog.Builder(
474 XmppActivity.this);
475 builder.setIconAttribute(android.R.attr.alertDialogIcon);
476 builder.setTitle(getString(R.string.error));
477 builder.setMessage(errorCode);
478 builder.setNeutralButton(R.string.accept, null);
479 builder.create().show();
480 }
481 });
482
483 }
484
485 protected void showAddToRosterDialog(final Conversation conversation) {
486 showAddToRosterDialog(conversation.getContact());
487 }
488
489 protected void showAddToRosterDialog(final Contact contact) {
490 AlertDialog.Builder builder = new AlertDialog.Builder(this);
491 builder.setTitle(contact.getJid().toString());
492 builder.setMessage(getString(R.string.not_in_roster));
493 builder.setNegativeButton(getString(R.string.cancel), null);
494 builder.setPositiveButton(getString(R.string.add_contact),
495 new DialogInterface.OnClickListener() {
496
497 @Override
498 public void onClick(DialogInterface dialog, int which) {
499 final Jid jid = contact.getJid();
500 Account account = contact.getAccount();
501 Contact contact = account.getRoster().getContact(jid);
502 xmppConnectionService.createContact(contact);
503 }
504 });
505 builder.create().show();
506 }
507
508 private void showAskForPresenceDialog(final Contact contact) {
509 AlertDialog.Builder builder = new AlertDialog.Builder(this);
510 builder.setTitle(contact.getJid().toString());
511 builder.setMessage(R.string.request_presence_updates);
512 builder.setNegativeButton(R.string.cancel, null);
513 builder.setPositiveButton(R.string.request_now,
514 new DialogInterface.OnClickListener() {
515
516 @Override
517 public void onClick(DialogInterface dialog, int which) {
518 if (xmppConnectionServiceBound) {
519 xmppConnectionService.sendPresencePacket(contact
520 .getAccount(), xmppConnectionService
521 .getPresenceGenerator()
522 .requestPresenceUpdatesFrom(contact));
523 }
524 }
525 });
526 builder.create().show();
527 }
528
529 private void warnMutalPresenceSubscription(final Conversation conversation,
530 final OnPresenceSelected listener) {
531 AlertDialog.Builder builder = new AlertDialog.Builder(this);
532 builder.setTitle(conversation.getContact().getJid().toString());
533 builder.setMessage(R.string.without_mutual_presence_updates);
534 builder.setNegativeButton(R.string.cancel, null);
535 builder.setPositiveButton(R.string.ignore, new OnClickListener() {
536
537 @Override
538 public void onClick(DialogInterface dialog, int which) {
539 conversation.setNextCounterpart(null);
540 if (listener != null) {
541 listener.onPresenceSelected();
542 }
543 }
544 });
545 builder.create().show();
546 }
547
548 protected void quickEdit(String previousValue, OnValueEdited callback) {
549 quickEdit(previousValue, callback, false);
550 }
551
552 protected void quickPasswordEdit(String previousValue,
553 OnValueEdited callback) {
554 quickEdit(previousValue, callback, true);
555 }
556
557 @SuppressLint("InflateParams")
558 private void quickEdit(final String previousValue,
559 final OnValueEdited callback, boolean password) {
560 AlertDialog.Builder builder = new AlertDialog.Builder(this);
561 View view = getLayoutInflater().inflate(R.layout.quickedit, null);
562 final EditText editor = (EditText) view.findViewById(R.id.editor);
563 OnClickListener mClickListener = new OnClickListener() {
564
565 @Override
566 public void onClick(DialogInterface dialog, int which) {
567 String value = editor.getText().toString();
568 if (!previousValue.equals(value) && value.trim().length() > 0) {
569 callback.onValueEdited(value);
570 }
571 }
572 };
573 if (password) {
574 editor.setInputType(InputType.TYPE_CLASS_TEXT
575 | InputType.TYPE_TEXT_VARIATION_PASSWORD);
576 editor.setHint(R.string.password);
577 builder.setPositiveButton(R.string.accept, mClickListener);
578 } else {
579 builder.setPositiveButton(R.string.edit, mClickListener);
580 }
581 editor.requestFocus();
582 editor.setText(previousValue);
583 builder.setView(view);
584 builder.setNegativeButton(R.string.cancel, null);
585 builder.create().show();
586 }
587
588 public void selectPresence(final Conversation conversation,
589 final OnPresenceSelected listener) {
590 final Contact contact = conversation.getContact();
591 if (conversation.hasValidOtrSession()) {
592 SessionID id = conversation.getOtrSession().getSessionID();
593 Jid jid;
594 try {
595 jid = Jid.fromString(id.getAccountID() + "/" + id.getUserID());
596 } catch (InvalidJidException e) {
597 jid = null;
598 }
599 conversation.setNextCounterpart(jid);
600 listener.onPresenceSelected();
601 } else if (!contact.showInRoster()) {
602 showAddToRosterDialog(conversation);
603 } else {
604 Presences presences = contact.getPresences();
605 if (presences.size() == 0) {
606 if (!contact.getOption(Contact.Options.TO)
607 && !contact.getOption(Contact.Options.ASKING)
608 && contact.getAccount().getStatus() == Account.State.ONLINE) {
609 showAskForPresenceDialog(contact);
610 } else if (!contact.getOption(Contact.Options.TO)
611 || !contact.getOption(Contact.Options.FROM)) {
612 warnMutalPresenceSubscription(conversation, listener);
613 } else {
614 conversation.setNextCounterpart(null);
615 listener.onPresenceSelected();
616 }
617 } else if (presences.size() == 1) {
618 String presence = presences.asStringArray()[0];
619 try {
620 conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence));
621 } catch (InvalidJidException e) {
622 conversation.setNextCounterpart(null);
623 }
624 listener.onPresenceSelected();
625 } else {
626 final StringBuilder presence = new StringBuilder();
627 AlertDialog.Builder builder = new AlertDialog.Builder(this);
628 builder.setTitle(getString(R.string.choose_presence));
629 final String[] presencesArray = presences.asStringArray();
630 int preselectedPresence = 0;
631 for (int i = 0; i < presencesArray.length; ++i) {
632 if (presencesArray[i].equals(contact.lastseen.presence)) {
633 preselectedPresence = i;
634 break;
635 }
636 }
637 presence.append(presencesArray[preselectedPresence]);
638 builder.setSingleChoiceItems(presencesArray,
639 preselectedPresence,
640 new DialogInterface.OnClickListener() {
641
642 @Override
643 public void onClick(DialogInterface dialog,
644 int which) {
645 presence.delete(0, presence.length());
646 presence.append(presencesArray[which]);
647 }
648 });
649 builder.setNegativeButton(R.string.cancel, null);
650 builder.setPositiveButton(R.string.ok, new OnClickListener() {
651
652 @Override
653 public void onClick(DialogInterface dialog, int which) {
654 try {
655 conversation.setNextCounterpart(Jid.fromParts(contact.getJid().getLocalpart(),contact.getJid().getDomainpart(),presence.toString()));
656 } catch (InvalidJidException e) {
657 conversation.setNextCounterpart(null);
658 }
659 listener.onPresenceSelected();
660 }
661 });
662 builder.create().show();
663 }
664 }
665 }
666
667 protected void onActivityResult(int requestCode, int resultCode,
668 final Intent data) {
669 super.onActivityResult(requestCode, resultCode, data);
670 if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) {
671 mPendingConferenceInvite = ConferenceInvite.parse(data);
672 if (xmppConnectionServiceBound && mPendingConferenceInvite != null) {
673 mPendingConferenceInvite.execute(this);
674 mPendingConferenceInvite = null;
675 }
676 }
677 }
678
679 private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
680 @Override
681 public void success(final Conversation conversation) {
682 switchToConversation(conversation);
683 runOnUiThread(new Runnable() {
684 @Override
685 public void run() {
686 Toast.makeText(XmppActivity.this,R.string.conference_created,Toast.LENGTH_LONG).show();
687 }
688 });
689 }
690
691 @Override
692 public void error(final int errorCode, Conversation object) {
693 runOnUiThread(new Runnable() {
694 @Override
695 public void run() {
696 Toast.makeText(XmppActivity.this,errorCode,Toast.LENGTH_LONG).show();
697 }
698 });
699 }
700
701 @Override
702 public void userInputRequried(PendingIntent pi, Conversation object) {
703
704 }
705 };
706
707 public int getSecondaryTextColor() {
708 return this.mSecondaryTextColor;
709 }
710
711 public int getPrimaryTextColor() {
712 return this.mPrimaryTextColor;
713 }
714
715 public int getWarningTextColor() {
716 return this.mColorRed;
717 }
718
719 public int getPrimaryColor() {
720 return this.mPrimaryColor;
721 }
722
723 public int getOnlineColor() {
724 return this.mColorGreen;
725 }
726
727 public int getPrimaryBackgroundColor() {
728 return this.mPrimaryBackgroundColor;
729 }
730
731 public int getSecondaryBackgroundColor() {
732 return this.mSecondaryBackgroundColor;
733 }
734
735 public int getPixel(int dp) {
736 DisplayMetrics metrics = getResources().getDisplayMetrics();
737 return ((int) (dp * metrics.density));
738 }
739
740 public boolean copyTextToClipboard(String text, int labelResId) {
741 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
742 String label = getResources().getString(labelResId);
743 if (mClipBoardManager != null) {
744 ClipData mClipData = ClipData.newPlainText(label, text);
745 mClipBoardManager.setPrimaryClip(mClipData);
746 return true;
747 }
748 return false;
749 }
750
751 protected void registerNdefPushMessageCallback() {
752 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
753 if (nfcAdapter != null && nfcAdapter.isEnabled()) {
754 nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
755 @Override
756 public NdefMessage createNdefMessage(NfcEvent nfcEvent) {
757 return new NdefMessage(new NdefRecord[]{
758 NdefRecord.createUri(getShareableUri()),
759 NdefRecord.createApplicationRecord("eu.siacs.conversations")
760 });
761 }
762 }, this);
763 }
764 }
765
766 protected void unregisterNdefPushMessageCallback() {
767 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
768 if (nfcAdapter != null && nfcAdapter.isEnabled()) {
769 nfcAdapter.setNdefPushMessageCallback(null,this);
770 }
771 }
772
773 protected String getShareableUri() {
774 return null;
775 }
776
777 @Override
778 public void onResume() {
779 super.onResume();
780 if (this.getShareableUri()!=null) {
781 this.registerNdefPushMessageCallback();
782 }
783 }
784
785 protected int findTheme() {
786 if (getPreferences().getBoolean("use_larger_font", false)) {
787 return R.style.ConversationsTheme_LargerText;
788 } else {
789 return R.style.ConversationsTheme;
790 }
791 }
792
793 @Override
794 public void onPause() {
795 super.onPause();
796 this.unregisterNdefPushMessageCallback();
797 }
798
799 protected void showQrCode() {
800 String uri = getShareableUri();
801 if (uri!=null) {
802 Point size = new Point();
803 getWindowManager().getDefaultDisplay().getSize(size);
804 final int width = (size.x < size.y ? size.x : size.y);
805 Bitmap bitmap = createQrCodeBitmap(uri, width);
806 ImageView view = new ImageView(this);
807 view.setImageBitmap(bitmap);
808 AlertDialog.Builder builder = new AlertDialog.Builder(this);
809 builder.setView(view);
810 builder.create().show();
811 }
812 }
813
814 protected Bitmap createQrCodeBitmap(String input, int size) {
815 Log.d(Config.LOGTAG,"qr code requested size: "+size);
816 try {
817 final QRCodeWriter QR_CODE_WRITER = new QRCodeWriter();
818 final Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
819 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
820 final BitMatrix result = QR_CODE_WRITER.encode(input, BarcodeFormat.QR_CODE, size, size, hints);
821 final int width = result.getWidth();
822 final int height = result.getHeight();
823 final int[] pixels = new int[width * height];
824 for (int y = 0; y < height; y++) {
825 final int offset = y * width;
826 for (int x = 0; x < width; x++) {
827 pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.TRANSPARENT;
828 }
829 }
830 final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
831 Log.d(Config.LOGTAG,"output size: "+width+"x"+height);
832 bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
833 return bitmap;
834 } catch (final WriterException e) {
835 return null;
836 }
837 }
838
839 public static class ConferenceInvite {
840 private String uuid;
841 private List<Jid> jids = new ArrayList<>();
842
843 public static ConferenceInvite parse(Intent data) {
844 ConferenceInvite invite = new ConferenceInvite();
845 invite.uuid = data.getStringExtra("conversation");
846 if (invite.uuid == null) {
847 return null;
848 }
849 try {
850 if (data.getBooleanExtra("multiple", false)) {
851 String[] toAdd = data.getStringArrayExtra("contacts");
852 for (String item : toAdd) {
853 invite.jids.add(Jid.fromString(item));
854 }
855 } else {
856 invite.jids.add(Jid.fromString(data.getStringExtra("contact")));
857 }
858 } catch (final InvalidJidException ignored) {
859 return null;
860 }
861 return invite;
862 }
863
864 public void execute(XmppActivity activity) {
865 XmppConnectionService service = activity.xmppConnectionService;
866 Conversation conversation = service.findConversationByUuid(this.uuid);
867 if (conversation == null) {
868 return;
869 }
870 if (conversation.getMode() == Conversation.MODE_MULTI) {
871 for (Jid jid : jids) {
872 service.invite(conversation, jid);
873 }
874 } else {
875 jids.add(conversation.getJid().toBareJid());
876 service.createAdhocConference(conversation.getAccount(), jids, activity.adhocCallback);
877 }
878 }
879 }
880
881 public AvatarService avatarService() {
882 return xmppConnectionService.getAvatarService();
883 }
884
885 class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
886 private final WeakReference<ImageView> imageViewReference;
887 private Message message = null;
888
889 public BitmapWorkerTask(ImageView imageView) {
890 imageViewReference = new WeakReference<>(imageView);
891 }
892
893 @Override
894 protected Bitmap doInBackground(Message... params) {
895 message = params[0];
896 try {
897 return xmppConnectionService.getFileBackend().getThumbnail(
898 message, (int) (metrics.density * 288), false);
899 } catch (FileNotFoundException e) {
900 return null;
901 }
902 }
903
904 @Override
905 protected void onPostExecute(Bitmap bitmap) {
906 if (bitmap != null) {
907 final ImageView imageView = imageViewReference.get();
908 if (imageView != null) {
909 imageView.setImageBitmap(bitmap);
910 imageView.setBackgroundColor(0x00000000);
911 }
912 }
913 }
914 }
915
916 public void loadBitmap(Message message, ImageView imageView) {
917 Bitmap bm;
918 try {
919 bm = xmppConnectionService.getFileBackend().getThumbnail(message,
920 (int) (metrics.density * 288), true);
921 } catch (FileNotFoundException e) {
922 bm = null;
923 }
924 if (bm != null) {
925 imageView.setImageBitmap(bm);
926 imageView.setBackgroundColor(0x00000000);
927 } else {
928 if (cancelPotentialWork(message, imageView)) {
929 imageView.setBackgroundColor(0xff333333);
930 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
931 final AsyncDrawable asyncDrawable = new AsyncDrawable(
932 getResources(), null, task);
933 imageView.setImageDrawable(asyncDrawable);
934 try {
935 task.execute(message);
936 } catch (final RejectedExecutionException ignored) {
937 }
938 }
939 }
940 }
941
942 public static boolean cancelPotentialWork(Message message,
943 ImageView imageView) {
944 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
945
946 if (bitmapWorkerTask != null) {
947 final Message oldMessage = bitmapWorkerTask.message;
948 if (oldMessage == null || message != oldMessage) {
949 bitmapWorkerTask.cancel(true);
950 } else {
951 return false;
952 }
953 }
954 return true;
955 }
956
957 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
958 if (imageView != null) {
959 final Drawable drawable = imageView.getDrawable();
960 if (drawable instanceof AsyncDrawable) {
961 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
962 return asyncDrawable.getBitmapWorkerTask();
963 }
964 }
965 return null;
966 }
967
968 static class AsyncDrawable extends BitmapDrawable {
969 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
970
971 public AsyncDrawable(Resources res, Bitmap bitmap,
972 BitmapWorkerTask bitmapWorkerTask) {
973 super(res, bitmap);
974 bitmapWorkerTaskReference = new WeakReference<>(
975 bitmapWorkerTask);
976 }
977
978 public BitmapWorkerTask getBitmapWorkerTask() {
979 return bitmapWorkerTaskReference.get();
980 }
981 }
982}