1package eu.siacs.conversations.ui;
2
3import java.io.FileNotFoundException;
4import java.lang.ref.WeakReference;
5import java.util.List;
6import java.util.concurrent.RejectedExecutionException;
7
8import eu.siacs.conversations.Config;
9import eu.siacs.conversations.R;
10import eu.siacs.conversations.entities.Account;
11import eu.siacs.conversations.entities.Contact;
12import eu.siacs.conversations.entities.Conversation;
13import eu.siacs.conversations.entities.Message;
14import eu.siacs.conversations.entities.Presences;
15import eu.siacs.conversations.services.AvatarService;
16import eu.siacs.conversations.services.XmppConnectionService;
17import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder;
18import eu.siacs.conversations.utils.ExceptionHelper;
19import android.annotation.SuppressLint;
20import android.app.Activity;
21import android.app.AlertDialog;
22import android.app.PendingIntent;
23import android.app.AlertDialog.Builder;
24import android.content.ClipData;
25import android.content.ClipboardManager;
26import android.content.ComponentName;
27import android.content.Context;
28import android.content.DialogInterface;
29import android.content.SharedPreferences;
30import android.content.DialogInterface.OnClickListener;
31import android.content.IntentSender.SendIntentException;
32import android.content.pm.PackageManager;
33import android.content.pm.ResolveInfo;
34import android.content.res.Resources;
35import android.content.Intent;
36import android.content.ServiceConnection;
37import android.graphics.Bitmap;
38import android.graphics.drawable.BitmapDrawable;
39import android.graphics.drawable.Drawable;
40import android.net.Uri;
41import android.nfc.NfcAdapter;
42import android.os.AsyncTask;
43import android.os.Bundle;
44import android.os.IBinder;
45import android.preference.PreferenceManager;
46import android.text.InputType;
47import android.util.DisplayMetrics;
48import android.util.Log;
49import android.view.MenuItem;
50import android.view.View;
51import android.view.inputmethod.InputMethodManager;
52import android.widget.EditText;
53import android.widget.ImageView;
54
55public abstract class XmppActivity extends Activity {
56
57 protected static final int REQUEST_ANNOUNCE_PGP = 0x0101;
58 protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102;
59
60 public XmppConnectionService xmppConnectionService;
61 public boolean xmppConnectionServiceBound = false;
62
63 protected int mPrimaryTextColor;
64 protected int mSecondaryTextColor;
65 protected int mSecondaryBackgroundColor;
66 protected int mColorRed;
67 protected int mColorOrange;
68 protected int mColorGreen;
69 protected int mPrimaryColor;
70
71 protected boolean mUseSubject = true;
72
73 private DisplayMetrics metrics;
74
75 protected interface OnValueEdited {
76 public void onValueEdited(String value);
77 }
78
79 public interface OnPresenceSelected {
80 public void onPresenceSelected();
81 }
82
83 protected ServiceConnection mConnection = new ServiceConnection() {
84
85 @Override
86 public void onServiceConnected(ComponentName className, IBinder service) {
87 XmppConnectionBinder binder = (XmppConnectionBinder) service;
88 xmppConnectionService = binder.getService();
89 xmppConnectionServiceBound = true;
90 onBackendConnected();
91 }
92
93 @Override
94 public void onServiceDisconnected(ComponentName arg0) {
95 xmppConnectionServiceBound = false;
96 }
97 };
98
99 @Override
100 protected void onStart() {
101 super.onStart();
102 if (!xmppConnectionServiceBound) {
103 connectToBackend();
104 }
105 }
106
107 public void connectToBackend() {
108 Intent intent = new Intent(this, XmppConnectionService.class);
109 intent.setAction("ui");
110 startService(intent);
111 bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
112 }
113
114 @Override
115 protected void onStop() {
116 super.onStop();
117 if (xmppConnectionServiceBound) {
118 unbindService(mConnection);
119 xmppConnectionServiceBound = false;
120 }
121 }
122
123 protected void hideKeyboard() {
124 InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
125
126 View focus = getCurrentFocus();
127
128 if (focus != null) {
129
130 inputManager.hideSoftInputFromWindow(focus.getWindowToken(),
131 InputMethodManager.HIDE_NOT_ALWAYS);
132 }
133 }
134
135 public boolean hasPgp() {
136 return xmppConnectionService.getPgpEngine() != null;
137 }
138
139 public void showInstallPgpDialog() {
140 Builder builder = new AlertDialog.Builder(this);
141 builder.setTitle(getString(R.string.openkeychain_required));
142 builder.setIconAttribute(android.R.attr.alertDialogIcon);
143 builder.setMessage(getText(R.string.openkeychain_required_long));
144 builder.setNegativeButton(getString(R.string.cancel), null);
145 builder.setNeutralButton(getString(R.string.restart),
146 new OnClickListener() {
147
148 @Override
149 public void onClick(DialogInterface dialog, int which) {
150 if (xmppConnectionServiceBound) {
151 unbindService(mConnection);
152 xmppConnectionServiceBound = false;
153 }
154 stopService(new Intent(XmppActivity.this,
155 XmppConnectionService.class));
156 finish();
157 }
158 });
159 builder.setPositiveButton(getString(R.string.install),
160 new OnClickListener() {
161
162 @Override
163 public void onClick(DialogInterface dialog, int which) {
164 Uri uri = Uri
165 .parse("market://details?id=org.sufficientlysecure.keychain");
166 Intent marketIntent = new Intent(Intent.ACTION_VIEW,
167 uri);
168 PackageManager manager = getApplicationContext()
169 .getPackageManager();
170 List<ResolveInfo> infos = manager
171 .queryIntentActivities(marketIntent, 0);
172 if (infos.size() > 0) {
173 startActivity(marketIntent);
174 } else {
175 uri = Uri.parse("http://www.openkeychain.org/");
176 Intent browserIntent = new Intent(
177 Intent.ACTION_VIEW, uri);
178 startActivity(browserIntent);
179 }
180 finish();
181 }
182 });
183 builder.create().show();
184 }
185
186 abstract void onBackendConnected();
187
188 public boolean onOptionsItemSelected(MenuItem item) {
189 switch (item.getItemId()) {
190 case R.id.action_settings:
191 startActivity(new Intent(this, SettingsActivity.class));
192 break;
193 case R.id.action_accounts:
194 startActivity(new Intent(this, ManageAccountActivity.class));
195 break;
196 case android.R.id.home:
197 finish();
198 break;
199 }
200 return super.onOptionsItemSelected(item);
201 }
202
203 @Override
204 protected void onCreate(Bundle savedInstanceState) {
205 super.onCreate(savedInstanceState);
206 metrics = getResources().getDisplayMetrics();
207 ExceptionHelper.init(getApplicationContext());
208 mPrimaryTextColor = getResources().getColor(R.color.primarytext);
209 mSecondaryTextColor = getResources().getColor(R.color.secondarytext);
210 mColorRed = getResources().getColor(R.color.red);
211 mColorOrange = getResources().getColor(R.color.orange);
212 mColorGreen = getResources().getColor(R.color.green);
213 mPrimaryColor = getResources().getColor(R.color.primary);
214 mSecondaryBackgroundColor = getResources().getColor(
215 R.color.secondarybackground);
216 if (getPreferences().getBoolean("use_larger_font", false)) {
217 setTheme(R.style.ConversationsTheme_LargerText);
218 }
219 mUseSubject = getPreferences().getBoolean("use_subject", true);
220 }
221
222 protected SharedPreferences getPreferences() {
223 return PreferenceManager
224 .getDefaultSharedPreferences(getApplicationContext());
225 }
226
227 public boolean useSubjectToIdentifyConference() {
228 return mUseSubject;
229 }
230
231 public void switchToConversation(Conversation conversation) {
232 switchToConversation(conversation, null, false);
233 }
234
235 public void switchToConversation(Conversation conversation, String text,
236 boolean newTask) {
237 Intent viewConversationIntent = new Intent(this,
238 ConversationActivity.class);
239 viewConversationIntent.setAction(Intent.ACTION_VIEW);
240 viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
241 conversation.getUuid());
242 if (text != null) {
243 viewConversationIntent.putExtra(ConversationActivity.TEXT, text);
244 }
245 viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
246 if (newTask) {
247 viewConversationIntent.setFlags(viewConversationIntent.getFlags()
248 | Intent.FLAG_ACTIVITY_NEW_TASK
249 | Intent.FLAG_ACTIVITY_SINGLE_TOP);
250 } else {
251 viewConversationIntent.setFlags(viewConversationIntent.getFlags()
252 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
253 }
254 startActivity(viewConversationIntent);
255 finish();
256 }
257
258 public void switchToContactDetails(Contact contact) {
259 Intent intent = new Intent(this, ContactDetailsActivity.class);
260 intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT);
261 intent.putExtra("account", contact.getAccount().getJid());
262 intent.putExtra("contact", contact.getJid());
263 startActivity(intent);
264 }
265
266 public void switchToAccount(Account account) {
267 Intent intent = new Intent(this, EditAccountActivity.class);
268 intent.putExtra("jid", account.getJid());
269 startActivity(intent);
270 }
271
272 protected void inviteToConversation(Conversation conversation) {
273 Intent intent = new Intent(getApplicationContext(),
274 ChooseContactActivity.class);
275 intent.putExtra("conversation", conversation.getUuid());
276 startActivityForResult(intent, REQUEST_INVITE_TO_CONVERSATION);
277 }
278
279 protected void announcePgp(Account account, final Conversation conversation) {
280 xmppConnectionService.getPgpEngine().generateSignature(account,
281 "online", new UiCallback<Account>() {
282
283 @Override
284 public void userInputRequried(PendingIntent pi,
285 Account account) {
286 try {
287 startIntentSenderForResult(pi.getIntentSender(),
288 REQUEST_ANNOUNCE_PGP, null, 0, 0, 0);
289 } catch (SendIntentException e) {
290 }
291 }
292
293 @Override
294 public void success(Account account) {
295 xmppConnectionService.databaseBackend
296 .updateAccount(account);
297 xmppConnectionService.sendPresencePacket(account,
298 xmppConnectionService.getPresenceGenerator()
299 .sendPresence(account));
300 if (conversation != null) {
301 conversation
302 .setNextEncryption(Message.ENCRYPTION_PGP);
303 xmppConnectionService.databaseBackend
304 .updateConversation(conversation);
305 }
306 }
307
308 @Override
309 public void error(int error, Account account) {
310 displayErrorDialog(error);
311 }
312 });
313 }
314
315 protected void displayErrorDialog(final int errorCode) {
316 runOnUiThread(new Runnable() {
317
318 @Override
319 public void run() {
320 AlertDialog.Builder builder = new AlertDialog.Builder(
321 XmppActivity.this);
322 builder.setIconAttribute(android.R.attr.alertDialogIcon);
323 builder.setTitle(getString(R.string.error));
324 builder.setMessage(errorCode);
325 builder.setNeutralButton(R.string.accept, null);
326 builder.create().show();
327 }
328 });
329
330 }
331
332 protected void showAddToRosterDialog(final Conversation conversation) {
333 String jid = conversation.getContactJid();
334 AlertDialog.Builder builder = new AlertDialog.Builder(this);
335 builder.setTitle(jid);
336 builder.setMessage(getString(R.string.not_in_roster));
337 builder.setNegativeButton(getString(R.string.cancel), null);
338 builder.setPositiveButton(getString(R.string.add_contact),
339 new DialogInterface.OnClickListener() {
340
341 @Override
342 public void onClick(DialogInterface dialog, int which) {
343 String jid = conversation.getContactJid();
344 Account account = conversation.getAccount();
345 Contact contact = account.getRoster().getContact(jid);
346 xmppConnectionService.createContact(contact);
347 switchToContactDetails(contact);
348 }
349 });
350 builder.create().show();
351 }
352
353 private void showAskForPresenceDialog(final Contact contact) {
354 AlertDialog.Builder builder = new AlertDialog.Builder(this);
355 builder.setTitle(contact.getJid());
356 builder.setMessage(R.string.request_presence_updates);
357 builder.setNegativeButton(R.string.cancel, null);
358 builder.setPositiveButton(R.string.request_now,
359 new DialogInterface.OnClickListener() {
360
361 @Override
362 public void onClick(DialogInterface dialog, int which) {
363 if (xmppConnectionServiceBound) {
364 xmppConnectionService.sendPresencePacket(contact
365 .getAccount(), xmppConnectionService
366 .getPresenceGenerator()
367 .requestPresenceUpdatesFrom(contact));
368 }
369 }
370 });
371 builder.create().show();
372 }
373
374 private void warnMutalPresenceSubscription(final Conversation conversation,
375 final OnPresenceSelected listener) {
376 AlertDialog.Builder builder = new AlertDialog.Builder(this);
377 builder.setTitle(conversation.getContact().getJid());
378 builder.setMessage(R.string.without_mutual_presence_updates);
379 builder.setNegativeButton(R.string.cancel, null);
380 builder.setPositiveButton(R.string.ignore, new OnClickListener() {
381
382 @Override
383 public void onClick(DialogInterface dialog, int which) {
384 conversation.setNextPresence(null);
385 if (listener != null) {
386 listener.onPresenceSelected();
387 }
388 }
389 });
390 builder.create().show();
391 }
392
393 protected void quickEdit(String previousValue, OnValueEdited callback) {
394 quickEdit(previousValue, callback, false);
395 }
396
397 protected void quickPasswordEdit(String previousValue,
398 OnValueEdited callback) {
399 quickEdit(previousValue, callback, true);
400 }
401
402 @SuppressLint("InflateParams")
403 private void quickEdit(final String previousValue,
404 final OnValueEdited callback, boolean password) {
405 AlertDialog.Builder builder = new AlertDialog.Builder(this);
406 View view = getLayoutInflater().inflate(R.layout.quickedit, null);
407 final EditText editor = (EditText) view.findViewById(R.id.editor);
408 OnClickListener mClickListener = new OnClickListener() {
409
410 @Override
411 public void onClick(DialogInterface dialog, int which) {
412 String value = editor.getText().toString();
413 if (!previousValue.equals(value) && value.trim().length() > 0) {
414 callback.onValueEdited(value);
415 }
416 }
417 };
418 if (password) {
419 editor.setInputType(InputType.TYPE_CLASS_TEXT
420 | InputType.TYPE_TEXT_VARIATION_PASSWORD);
421 editor.setHint(R.string.password);
422 builder.setPositiveButton(R.string.accept, mClickListener);
423 } else {
424 builder.setPositiveButton(R.string.edit, mClickListener);
425 }
426 editor.requestFocus();
427 editor.setText(previousValue);
428 builder.setView(view);
429 builder.setNegativeButton(R.string.cancel, null);
430 builder.create().show();
431 }
432
433 public void selectPresence(final Conversation conversation,
434 final OnPresenceSelected listener) {
435 Contact contact = conversation.getContact();
436 if (!contact.showInRoster()) {
437 showAddToRosterDialog(conversation);
438 } else {
439 Presences presences = contact.getPresences();
440 if (presences.size() == 0) {
441 if (!contact.getOption(Contact.Options.TO)
442 && !contact.getOption(Contact.Options.ASKING)
443 && contact.getAccount().getStatus() == Account.STATUS_ONLINE) {
444 showAskForPresenceDialog(contact);
445 } else if (!contact.getOption(Contact.Options.TO)
446 || !contact.getOption(Contact.Options.FROM)) {
447 warnMutalPresenceSubscription(conversation, listener);
448 } else {
449 conversation.setNextPresence(null);
450 listener.onPresenceSelected();
451 }
452 } else if (presences.size() == 1) {
453 String presence = presences.asStringArray()[0];
454 conversation.setNextPresence(presence);
455 listener.onPresenceSelected();
456 } else {
457 final StringBuilder presence = new StringBuilder();
458 AlertDialog.Builder builder = new AlertDialog.Builder(this);
459 builder.setTitle(getString(R.string.choose_presence));
460 final String[] presencesArray = presences.asStringArray();
461 int preselectedPresence = 0;
462 for (int i = 0; i < presencesArray.length; ++i) {
463 if (presencesArray[i].equals(contact.lastseen.presence)) {
464 preselectedPresence = i;
465 break;
466 }
467 }
468 presence.append(presencesArray[preselectedPresence]);
469 builder.setSingleChoiceItems(presencesArray,
470 preselectedPresence,
471 new DialogInterface.OnClickListener() {
472
473 @Override
474 public void onClick(DialogInterface dialog,
475 int which) {
476 presence.delete(0, presence.length());
477 presence.append(presencesArray[which]);
478 }
479 });
480 builder.setNegativeButton(R.string.cancel, null);
481 builder.setPositiveButton(R.string.ok, new OnClickListener() {
482
483 @Override
484 public void onClick(DialogInterface dialog, int which) {
485 conversation.setNextPresence(presence.toString());
486 listener.onPresenceSelected();
487 }
488 });
489 builder.create().show();
490 }
491 }
492 }
493
494 protected void onActivityResult(int requestCode, int resultCode,
495 final Intent data) {
496 super.onActivityResult(requestCode, resultCode, data);
497 if (requestCode == REQUEST_INVITE_TO_CONVERSATION
498 && resultCode == RESULT_OK) {
499 String contactJid = data.getStringExtra("contact");
500 String conversationUuid = data.getStringExtra("conversation");
501 Conversation conversation = xmppConnectionService
502 .findConversationByUuid(conversationUuid);
503 if (conversation.getMode() == Conversation.MODE_MULTI) {
504 xmppConnectionService.invite(conversation, contactJid);
505 }
506 Log.d(Config.LOGTAG, "inviting " + contactJid + " to "
507 + conversation.getName());
508 }
509 }
510
511 public int getSecondaryTextColor() {
512 return this.mSecondaryTextColor;
513 }
514
515 public int getPrimaryTextColor() {
516 return this.mPrimaryTextColor;
517 }
518
519 public int getWarningTextColor() {
520 return this.mColorRed;
521 }
522
523 public int getPrimaryColor() {
524 return this.mPrimaryColor;
525 }
526
527 public int getSecondaryBackgroundColor() {
528 return this.mSecondaryBackgroundColor;
529 }
530
531 public int getPixel(int dp) {
532 DisplayMetrics metrics = getResources().getDisplayMetrics();
533 return ((int) (dp * metrics.density));
534 }
535
536 public boolean copyTextToClipboard(String text,int labelResId) {
537 ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
538 String label = getResources().getString(labelResId);
539 if (mClipBoardManager != null) {
540 ClipData mClipData = ClipData.newPlainText(label, text);
541 mClipBoardManager.setPrimaryClip(mClipData);
542 return true;
543 }
544 return false;
545 }
546
547 protected void registerNdefPushMessageCallback(NfcAdapter.CreateNdefMessageCallback callback) {
548 NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
549 if (nfcAdapter!=null && nfcAdapter.isEnabled()) {
550 nfcAdapter.setNdefPushMessageCallback(callback,this);
551 }
552 }
553
554 public AvatarService avatarService() {
555 return xmppConnectionService.getAvatarService();
556 }
557
558 class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> {
559 private final WeakReference<ImageView> imageViewReference;
560 private Message message = null;
561
562 public BitmapWorkerTask(ImageView imageView) {
563 imageViewReference = new WeakReference<ImageView>(imageView);
564 }
565
566 @Override
567 protected Bitmap doInBackground(Message... params) {
568 message = params[0];
569 try {
570 return xmppConnectionService.getFileBackend().getThumbnail(
571 message, (int) (metrics.density * 288), false);
572 } catch (FileNotFoundException e) {
573 return null;
574 }
575 }
576
577 @Override
578 protected void onPostExecute(Bitmap bitmap) {
579 if (imageViewReference != null && bitmap != null) {
580 final ImageView imageView = imageViewReference.get();
581 if (imageView != null) {
582 imageView.setImageBitmap(bitmap);
583 imageView.setBackgroundColor(0x00000000);
584 }
585 }
586 }
587 }
588
589 public void loadBitmap(Message message, ImageView imageView) {
590 Bitmap bm;
591 try {
592 bm = xmppConnectionService.getFileBackend().getThumbnail(message,
593 (int) (metrics.density * 288), true);
594 } catch (FileNotFoundException e) {
595 bm = null;
596 }
597 if (bm != null) {
598 imageView.setImageBitmap(bm);
599 imageView.setBackgroundColor(0x00000000);
600 } else {
601 if (cancelPotentialWork(message, imageView)) {
602 imageView.setBackgroundColor(0xff333333);
603 final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
604 final AsyncDrawable asyncDrawable = new AsyncDrawable(
605 getResources(), null, task);
606 imageView.setImageDrawable(asyncDrawable);
607 try {
608 task.execute(message);
609 } catch (RejectedExecutionException e) {
610 return;
611 }
612 }
613 }
614 }
615
616 public static boolean cancelPotentialWork(Message message,
617 ImageView imageView) {
618 final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
619
620 if (bitmapWorkerTask != null) {
621 final Message oldMessage = bitmapWorkerTask.message;
622 if (oldMessage == null || message != oldMessage) {
623 bitmapWorkerTask.cancel(true);
624 } else {
625 return false;
626 }
627 }
628 return true;
629 }
630
631 private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
632 if (imageView != null) {
633 final Drawable drawable = imageView.getDrawable();
634 if (drawable instanceof AsyncDrawable) {
635 final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
636 return asyncDrawable.getBitmapWorkerTask();
637 }
638 }
639 return null;
640 }
641
642 static class AsyncDrawable extends BitmapDrawable {
643 private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
644
645 public AsyncDrawable(Resources res, Bitmap bitmap,
646 BitmapWorkerTask bitmapWorkerTask) {
647 super(res, bitmap);
648 bitmapWorkerTaskReference = new WeakReference<BitmapWorkerTask>(
649 bitmapWorkerTask);
650 }
651
652 public BitmapWorkerTask getBitmapWorkerTask() {
653 return bitmapWorkerTaskReference.get();
654 }
655 }
656}