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 } else {
676 Log.d(Config.LOGTAG,"putting invite on pending");
677 }
678 }
679 }
680
681 private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() {
682 @Override
683 public void success(final Conversation conversation) {
684 switchToConversation(conversation);
685 runOnUiThread(new Runnable() {
686 @Override
687 public void run() {
688 Toast.makeText(XmppActivity.this,R.string.conference_created,Toast.LENGTH_LONG).show();
689 }
690 });
691 }
692
693 @Override
694 public void error(final int errorCode, Conversation object) {
695 runOnUiThread(new Runnable() {
696 @Override
697 public void run() {
698 Toast.makeText(XmppActivity.this,errorCode,Toast.LENGTH_LONG).show();
699 }
700 });
701 }
702
703 @Override
704 public void userInputRequried(PendingIntent pi, Conversation object) {
705
706 }
707 };
708
709 public int getSecondaryTextColor() {
710 return this.mSecondaryTextColor;
711 }
712
713 public int getPrimaryTextColor() {
714 return this.mPrimaryTextColor;
715 }
716
717 public int getWarningTextColor() {
718 return this.mColorRed;
719 }
720
721 public int getPrimaryColor() {
722 return this.mPrimaryColor;
723 }
724
725 public int getOnlineColor() {
726 return this.mColorGreen;
727 }
728
729 public int getPrimaryBackgroundColor() {
730 return this.mPrimaryBackgroundColor;
731 }
732
733 public int getSecondaryBackgroundColor() {
734 return this.mSecondaryBackgroundColor;
735 }
736
737 public int getPixel(int dp) {
738 DisplayMetrics metrics = getResources().getDisplayMetrics();
739 return ((int) (dp * metrics.density));
740 }
741
742 public boolean copyTextToClipboard(String text, int labelResId) {
743 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
744 String label = getResources().getString(labelResId);
745 if (mClipBoardManager != null) {
746 ClipData mClipData = ClipData.newPlainText(label, text);
747 mClipBoardManager.setPrimaryClip(mClipData);
748 return true;
749 }
750 return false;
751 }
752
753 protected void registerNdefPushMessageCallback() {
754 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
755 if (nfcAdapter != null && nfcAdapter.isEnabled()) {
756 nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() {
757 @Override
758 public NdefMessage createNdefMessage(NfcEvent nfcEvent) {
759 return new NdefMessage(new NdefRecord[]{
760 NdefRecord.createUri(getShareableUri()),
761 NdefRecord.createApplicationRecord("eu.siacs.conversations")
762 });
763 }
764 }, this);
765 }
766 }
767
768 protected void unregisterNdefPushMessageCallback() {
769 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
770 if (nfcAdapter != null && nfcAdapter.isEnabled()) {
771 nfcAdapter.setNdefPushMessageCallback(null,this);
772 }
773 }
774
775 protected String getShareableUri() {
776 return null;
777 }
778
779 @Override
780 public void onResume() {
781 super.onResume();
782 if (this.getShareableUri()!=null) {
783 this.registerNdefPushMessageCallback();
784 }
785 }
786
787 protected int findTheme() {
788 if (getPreferences().getBoolean("use_larger_font", false)) {
789 return R.style.ConversationsTheme_LargerText;
790 } else {
791 return R.style.ConversationsTheme;
792 }
793 }
794
795 @Override
796 public void onPause() {
797 super.onPause();
798 this.unregisterNdefPushMessageCallback();
799 }
800
801 protected void showQrCode() {
802 String uri = getShareableUri();
803 if (uri!=null) {
804 Point size = new Point();
805 getWindowManager().getDefaultDisplay().getSize(size);
806 final int width = (size.x < size.y ? size.x : size.y);
807 Bitmap bitmap = createQrCodeBitmap(uri, width);
808 ImageView view = new ImageView(this);
809 view.setImageBitmap(bitmap);
810 AlertDialog.Builder builder = new AlertDialog.Builder(this);
811 builder.setView(view);
812 builder.create().show();
813 }
814 }
815
816 protected Bitmap createQrCodeBitmap(String input, int size) {
817 Log.d(Config.LOGTAG,"qr code requested size: "+size);
818 try {
819 final QRCodeWriter QR_CODE_WRITER = new QRCodeWriter();
820 final Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
821 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
822 final BitMatrix result = QR_CODE_WRITER.encode(input, BarcodeFormat.QR_CODE, size, size, hints);
823 final int width = result.getWidth();
824 final int height = result.getHeight();
825 final int[] pixels = new int[width * height];
826 for (int y = 0; y < height; y++) {
827 final int offset = y * width;
828 for (int x = 0; x < width; x++) {
829 pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.TRANSPARENT;
830 }
831 }
832 final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
833 Log.d(Config.LOGTAG,"output size: "+width+"x"+height);
834 bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
835 return bitmap;
836 } catch (final WriterException e) {
837 return null;
838 }
839 }
840
841 public static class ConferenceInvite {
842 private String uuid;
843 private List<Jid> jids = new ArrayList<>();
844
845 public static ConferenceInvite parse(Intent data) {
846 ConferenceInvite invite = new ConferenceInvite();
847 invite.uuid = data.getStringExtra("conversation");
848 if (invite.uuid == null) {
849 return null;
850 }
851 try {
852 if (data.getBooleanExtra("multiple", false)) {
853 String[] toAdd = data.getStringArrayExtra("contacts");
854 for (String item : toAdd) {
855 invite.jids.add(Jid.fromString(item));
856 }
857 } else {
858 invite.jids.add(Jid.fromString(data.getStringExtra("contact")));
859 }
860 } catch (final InvalidJidException ignored) {
861 return null;
862 }
863 return invite;
864 }
865
866 public void execute(XmppActivity activity) {
867 XmppConnectionService service = activity.xmppConnectionService;
868 Conversation conversation = service.findConversationByUuid(this.uuid);
869 if (conversation == null) {
870 return;
871 }
872 if (conversation.getMode() == Conversation.MODE_MULTI) {
873 for (Jid jid : jids) {
874 service.invite(conversation, jid);
875 }
876 } else {
877 jids.add(conversation.getJid().toBareJid());
878 service.createAdhocConference(conversation.getAccount(), jids, activity.adhocCallback);
879 }
880 }
881 }
882
883 public AvatarService avatarService() {
884 return xmppConnectionService.getAvatarService();
885 }
886
887 class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
888 private final WeakReference<ImageView> imageViewReference;
889 private Message message = null;
890
891 public BitmapWorkerTask(ImageView imageView) {
892 imageViewReference = new WeakReference<>(imageView);
893 }
894
895 @Override
896 protected Bitmap doInBackground(Message... params) {
897 message = params[0];
898 try {
899 return xmppConnectionService.getFileBackend().getThumbnail(
900 message, (int) (metrics.density * 288), false);
901 } catch (FileNotFoundException e) {
902 return null;
903 }
904 }
905
906 @Override
907 protected void onPostExecute(Bitmap bitmap) {
908 if (bitmap != null) {
909 final ImageView imageView = imageViewReference.get();
910 if (imageView != null) {
911 imageView.setImageBitmap(bitmap);
912 imageView.setBackgroundColor(0x00000000);
913 }
914 }
915 }
916 }
917
918 public void loadBitmap(Message message, ImageView imageView) {
919 Bitmap bm;
920 try {
921 bm = xmppConnectionService.getFileBackend().getThumbnail(message,
922 (int) (metrics.density * 288), true);
923 } catch (FileNotFoundException e) {
924 bm = null;
925 }
926 if (bm != null) {
927 imageView.setImageBitmap(bm);
928 imageView.setBackgroundColor(0x00000000);
929 } else {
930 if (cancelPotentialWork(message, imageView)) {
931 imageView.setBackgroundColor(0xff333333);
932 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
933 final AsyncDrawable asyncDrawable = new AsyncDrawable(
934 getResources(), null, task);
935 imageView.setImageDrawable(asyncDrawable);
936 try {
937 task.execute(message);
938 } catch (final RejectedExecutionException ignored) {
939 }
940 }
941 }
942 }
943
944 public static boolean cancelPotentialWork(Message message,
945 ImageView imageView) {
946 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
947
948 if (bitmapWorkerTask != null) {
949 final Message oldMessage = bitmapWorkerTask.message;
950 if (oldMessage == null || message != oldMessage) {
951 bitmapWorkerTask.cancel(true);
952 } else {
953 return false;
954 }
955 }
956 return true;
957 }
958
959 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
960 if (imageView != null) {
961 final Drawable drawable = imageView.getDrawable();
962 if (drawable instanceof AsyncDrawable) {
963 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
964 return asyncDrawable.getBitmapWorkerTask();
965 }
966 }
967 return null;
968 }
969
970 static class AsyncDrawable extends BitmapDrawable {
971 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
972
973 public AsyncDrawable(Resources res, Bitmap bitmap,
974 BitmapWorkerTask bitmapWorkerTask) {
975 super(res, bitmap);
976 bitmapWorkerTaskReference = new WeakReference<>(
977 bitmapWorkerTask);
978 }
979
980 public BitmapWorkerTask getBitmapWorkerTask() {
981 return bitmapWorkerTaskReference.get();
982 }
983 }
984}