UIHelper.java

  1package eu.siacs.conversations.utils;
  2
  3import java.io.FileNotFoundException;
  4import java.util.ArrayList;
  5import java.util.Calendar;
  6import java.util.Date;
  7import java.util.List;
  8import java.util.Locale;
  9import java.util.regex.Pattern;
 10import java.util.regex.Matcher;
 11
 12import eu.siacs.conversations.R;
 13import eu.siacs.conversations.entities.Account;
 14import eu.siacs.conversations.entities.Contact;
 15import eu.siacs.conversations.entities.Conversation;
 16import eu.siacs.conversations.entities.Message;
 17import eu.siacs.conversations.entities.MucOptions.User;
 18import eu.siacs.conversations.ui.ConversationActivity;
 19import eu.siacs.conversations.ui.ManageAccountActivity;
 20import android.app.Activity;
 21import android.app.AlertDialog;
 22import android.app.Notification;
 23import android.app.NotificationManager;
 24import android.app.PendingIntent;
 25import android.content.Context;
 26import android.content.DialogInterface;
 27import android.content.DialogInterface.OnClickListener;
 28import android.content.Intent;
 29import android.content.SharedPreferences;
 30import android.graphics.Bitmap;
 31import android.graphics.BitmapFactory;
 32import android.graphics.Canvas;
 33import android.graphics.Paint;
 34import android.graphics.Rect;
 35import android.graphics.Typeface;
 36import android.net.Uri;
 37import android.preference.PreferenceManager;
 38import android.provider.ContactsContract.Contacts;
 39import android.support.v4.app.NotificationCompat;
 40import android.support.v4.app.TaskStackBuilder;
 41import android.text.format.DateFormat;
 42import android.text.format.DateUtils;
 43import android.text.Html;
 44import android.util.DisplayMetrics;
 45import android.view.LayoutInflater;
 46import android.view.View;
 47import android.widget.QuickContactBadge;
 48import android.widget.TextView;
 49
 50public class UIHelper {
 51	private static final int BG_COLOR = 0xFF181818;
 52	private static final int FG_COLOR = 0xFFFAFAFA;
 53	private static final int TRANSPARENT = 0x00000000;
 54	private static final int DATE_NO_YEAR_FLAGS = DateUtils.FORMAT_SHOW_DATE
 55			| DateUtils.FORMAT_NO_YEAR | DateUtils.FORMAT_ABBREV_ALL;
 56
 57	public static String readableTimeDifference(Context context, long time) {
 58		if (time == 0) {
 59			return context.getString(R.string.just_now);
 60		}
 61		Date date = new Date(time);
 62		long difference = (System.currentTimeMillis() - time) / 1000;
 63		if (difference < 60) {
 64			return context.getString(R.string.just_now);
 65		} else if (difference < 60 * 2) {
 66			return context.getString(R.string.minute_ago);
 67		} else if (difference < 60 * 15) {
 68			return context.getString(R.string.minutes_ago,
 69					Math.round(difference / 60.0));
 70		} else if (today(date) || difference < 6 * 60 * 60) {
 71			java.text.DateFormat df = DateFormat.getTimeFormat(context);
 72			return df.format(date);
 73		} else {
 74			return DateUtils.formatDateTime(context, date.getTime(),
 75					DATE_NO_YEAR_FLAGS);
 76		}
 77	}
 78
 79	private static boolean today(Date date) {
 80		Calendar cal1 = Calendar.getInstance();
 81		Calendar cal2 = Calendar.getInstance();
 82		cal1.setTime(date);
 83		cal2.setTimeInMillis(System.currentTimeMillis());
 84		return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
 85				&& cal1.get(Calendar.DAY_OF_YEAR) == cal2
 86						.get(Calendar.DAY_OF_YEAR);
 87	}
 88
 89	public static String lastseen(Context context, long time) {
 90		if (time == 0) {
 91			return context.getString(R.string.never_seen);
 92		}
 93		long difference = (System.currentTimeMillis() - time) / 1000;
 94		if (difference < 60) {
 95			return context.getString(R.string.last_seen_now);
 96		} else if (difference < 60 * 2) {
 97			return context.getString(R.string.last_seen_min);
 98		} else if (difference < 60 * 60) {
 99			return context.getString(R.string.last_seen_mins,
100					Math.round(difference / 60.0));
101		} else if (difference < 60 * 60 * 2) {
102			return context.getString(R.string.last_seen_hour);
103		} else if (difference < 60 * 60 * 24) {
104			return context.getString(R.string.last_seen_hours,
105					Math.round(difference / (60.0 * 60.0)));
106		} else if (difference < 60 * 60 * 48) {
107			return context.getString(R.string.last_seen_day);
108		} else {
109			return context.getString(R.string.last_seen_days,
110					Math.round(difference / (60.0 * 60.0 * 24.0)));
111		}
112	}
113
114	public static int getRealPx(int dp, Context context) {
115		final DisplayMetrics metrics = context.getResources()
116				.getDisplayMetrics();
117		return ((int) (dp * metrics.density));
118	}
119
120	private static int getNameColor(String name) {
121		/*int holoColors[] = { 0xFF1da9da, 0xFFb368d9, 0xFF83b600, 0xFFffa713,
122				0xFFe92727 };*/
123		int holoColors[] = {0xFFe91e63, 0xFF9c27b0, 0xFF673ab7, 0xFF3f51b5, 0xFF5677fc, 0xFF03a9f4, 0xFF00bcd4, 0xFF009688, 0xFFff5722, 0xFF795548, 0xFF607d8b};
124		return holoColors[(int) ((name.hashCode() & 0xffffffffl) % holoColors.length)];
125	}
126
127	private static void drawTile(Canvas canvas, String letter, int tileColor,
128			int textColor, int left, int top, int right, int bottom) {
129		Paint tilePaint = new Paint(), textPaint = new Paint();
130		tilePaint.setColor(tileColor);
131		textPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
132		textPaint.setColor(textColor);
133		textPaint.setTypeface(Typeface.create("sans-serif-light",
134				Typeface.NORMAL));
135		textPaint.setTextSize((float) ((right - left) * 0.8));
136		Rect rect = new Rect();
137
138		canvas.drawRect(new Rect(left, top, right, bottom), tilePaint);
139		textPaint.getTextBounds(letter, 0, 1, rect);
140		float width = textPaint.measureText(letter);
141		canvas.drawText(letter, (right + left) / 2 - width / 2, (top + bottom)
142				/ 2 + rect.height() / 2, textPaint);
143	}
144
145	private static Bitmap getUnknownContactPicture(String[] names, int size,
146			int bgColor, int fgColor) {
147		int tiles = (names.length > 4) ? 4 : (names.length < 1) ? 1
148				: names.length;
149		Bitmap bitmap = Bitmap
150				.createBitmap(size, size, Bitmap.Config.ARGB_8888);
151		Canvas canvas = new Canvas(bitmap);
152
153		String[] letters = new String[tiles];
154		int[] colors = new int[tiles];
155		if (names.length < 1) {
156			letters[0] = "?";
157			colors[0] = 0xFFe92727;
158		} else {
159			for (int i = 0; i < tiles; ++i) {
160				letters[i] = (names[i].length() > 0) ? names[i].substring(0, 1)
161						.toUpperCase(Locale.US) : " ";
162				colors[i] = getNameColor(names[i]);
163			}
164
165			if (names.length > 4) {
166				letters[3] = "\u2026"; // Unicode ellipsis
167				colors[3] = 0xFF202020;
168			}
169		}
170
171		bitmap.eraseColor(bgColor);
172
173		switch (tiles) {
174		case 1:
175			drawTile(canvas, letters[0], colors[0], fgColor, 0, 0, size, size);
176			break;
177
178		case 2:
179			drawTile(canvas, letters[0], colors[0], fgColor, 0, 0,
180					size / 2 - 1, size);
181			drawTile(canvas, letters[1], colors[1], fgColor, size / 2 + 1, 0,
182					size, size);
183			break;
184
185		case 3:
186			drawTile(canvas, letters[0], colors[0], fgColor, 0, 0,
187					size / 2 - 1, size);
188			drawTile(canvas, letters[1], colors[1], fgColor, size / 2 + 1, 0,
189					size, size / 2 - 1);
190			drawTile(canvas, letters[2], colors[2], fgColor, size / 2 + 1,
191					size / 2 + 1, size, size);
192			break;
193
194		case 4:
195			drawTile(canvas, letters[0], colors[0], fgColor, 0, 0,
196					size / 2 - 1, size / 2 - 1);
197			drawTile(canvas, letters[1], colors[1], fgColor, 0, size / 2 + 1,
198					size / 2 - 1, size);
199			drawTile(canvas, letters[2], colors[2], fgColor, size / 2 + 1, 0,
200					size, size / 2 - 1);
201			drawTile(canvas, letters[3], colors[3], fgColor, size / 2 + 1,
202					size / 2 + 1, size, size);
203			break;
204		}
205
206		return bitmap;
207	}
208
209	private static Bitmap getMucContactPicture(Conversation conversation,
210			int size, int bgColor, int fgColor) {
211		List<User> members = conversation.getMucOptions().getUsers();
212		if (members.size() == 0) {
213			return getUnknownContactPicture(
214					new String[] { conversation.getName(false) }, size,
215					bgColor, fgColor);
216		}
217		String[] names = new String[members.size() + 1];
218		names[0] = conversation.getMucOptions().getActualNick();
219		for (int i = 0; i < members.size(); ++i) {
220			names[i + 1] = members.get(i).getName();
221		}
222
223		return getUnknownContactPicture(names, size, bgColor, fgColor);
224	}
225
226	public static Bitmap getContactPicture(Conversation conversation,
227			int dpSize, Context context, boolean notification) {
228		if (conversation.getMode() == Conversation.MODE_SINGLE) {
229			return getContactPicture(conversation.getContact(), dpSize,
230					context, notification);
231		} else {
232			int fgColor = UIHelper.FG_COLOR, bgColor = (notification) ? UIHelper.BG_COLOR
233					: UIHelper.TRANSPARENT;
234
235			return getMucContactPicture(conversation,
236					getRealPx(dpSize, context), bgColor, fgColor);
237		}
238	}
239
240	public static Bitmap getContactPicture(Contact contact, int dpSize,
241			Context context, boolean notification) {
242		String uri = contact.getProfilePhoto();
243		if (uri == null) {
244			return getContactPicture(contact.getDisplayName(), dpSize, context,
245					notification);
246		}
247		try {
248			Bitmap bm = BitmapFactory.decodeStream(context.getContentResolver()
249					.openInputStream(Uri.parse(uri)));
250			return Bitmap.createScaledBitmap(bm, getRealPx(dpSize, context),
251					getRealPx(dpSize, context), false);
252		} catch (FileNotFoundException e) {
253			return getContactPicture(contact.getDisplayName(), dpSize, context,
254					notification);
255		}
256	}
257
258	public static Bitmap getContactPicture(String name, int dpSize,
259			Context context, boolean notification) {
260		int fgColor = UIHelper.FG_COLOR, bgColor = (notification) ? UIHelper.BG_COLOR
261				: UIHelper.TRANSPARENT;
262
263		return getUnknownContactPicture(new String[] { name },
264				getRealPx(dpSize, context), bgColor, fgColor);
265	}
266
267	public static void showErrorNotification(Context context,
268			List<Account> accounts) {
269		NotificationManager mNotificationManager = (NotificationManager) context
270				.getSystemService(Context.NOTIFICATION_SERVICE);
271		List<Account> accountsWproblems = new ArrayList<Account>();
272		for (Account account : accounts) {
273			if (account.hasErrorStatus()) {
274				accountsWproblems.add(account);
275			}
276		}
277		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
278				context);
279		if (accountsWproblems.size() == 0) {
280			mNotificationManager.cancel(1111);
281			return;
282		} else if (accountsWproblems.size() == 1) {
283			mBuilder.setContentTitle(context
284					.getString(R.string.problem_connecting_to_account));
285			mBuilder.setContentText(accountsWproblems.get(0).getJid());
286		} else {
287			mBuilder.setContentTitle(context
288					.getString(R.string.problem_connecting_to_accounts));
289			mBuilder.setContentText(context.getString(R.string.touch_to_fix));
290		}
291		mBuilder.setOngoing(true);
292		mBuilder.setLights(0xffffffff, 2000, 4000);
293		mBuilder.setSmallIcon(R.drawable.ic_notification);
294		TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
295		stackBuilder.addParentStack(ConversationActivity.class);
296
297		Intent manageAccountsIntent = new Intent(context,
298				ManageAccountActivity.class);
299		stackBuilder.addNextIntent(manageAccountsIntent);
300
301		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
302				PendingIntent.FLAG_UPDATE_CURRENT);
303
304		mBuilder.setContentIntent(resultPendingIntent);
305		Notification notification = mBuilder.build();
306		mNotificationManager.notify(1111, notification);
307	}
308
309	private static Pattern generateNickHighlightPattern(String nick) {
310		// We expect a word boundary, i.e. space or start of string, followed by
311		// the
312		// nick (matched in case-insensitive manner), followed by optional
313		// punctuation (for example "bob: i disagree" or "how are you alice?"),
314		// followed by another word boundary.
315		return Pattern.compile("\\b" + nick + "\\p{Punct}?\\b",
316				Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
317	}
318
319	public static void updateNotification(Context context,
320			List<Conversation> conversations, Conversation currentCon,
321			boolean notify) {
322		NotificationManager mNotificationManager = (NotificationManager) context
323				.getSystemService(Context.NOTIFICATION_SERVICE);
324
325		SharedPreferences preferences = PreferenceManager
326				.getDefaultSharedPreferences(context);
327		boolean useSubject = preferences.getBoolean("use_subject_in_muc", true);
328		boolean showNofifications = preferences.getBoolean("show_notification",
329				true);
330		boolean vibrate = preferences.getBoolean("vibrate_on_notification",
331				true);
332		boolean alwaysNotify = preferences.getBoolean(
333				"notify_in_conversation_when_highlighted", false);
334
335		if (!showNofifications) {
336			mNotificationManager.cancel(2342);
337			return;
338		}
339
340		String targetUuid = "";
341
342		if ((currentCon != null)
343				&& (currentCon.getMode() == Conversation.MODE_MULTI)
344				&& (!alwaysNotify)) {
345			String nick = currentCon.getMucOptions().getActualNick();
346			Pattern highlight = generateNickHighlightPattern(nick);
347			Matcher m = highlight.matcher(currentCon.getLatestMessage()
348					.getBody());
349			notify = m.find();
350		}
351
352		List<Conversation> unread = new ArrayList<Conversation>();
353		for (Conversation conversation : conversations) {
354			if (conversation.getMode() == Conversation.MODE_MULTI) {
355				if ((!conversation.isRead())
356						&& ((wasHighlighted(conversation) || (alwaysNotify)))) {
357					unread.add(conversation);
358				}
359			} else {
360				if (!conversation.isRead()) {
361					unread.add(conversation);
362				}
363			}
364		}
365		String ringtone = preferences.getString("notification_ringtone", null);
366
367		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
368				context);
369		if (unread.size() == 0) {
370			mNotificationManager.cancel(2342);
371			return;
372		} else if (unread.size() == 1) {
373			Conversation conversation = unread.get(0);
374			targetUuid = conversation.getUuid();
375			mBuilder.setLargeIcon(UIHelper.getContactPicture(conversation, 64,
376					context, true));
377			mBuilder.setContentTitle(conversation.getName(useSubject));
378			if (notify) {
379				mBuilder.setTicker(conversation.getLatestMessage()
380						.getReadableBody(context));
381			}
382			StringBuilder bigText = new StringBuilder();
383			List<Message> messages = conversation.getMessages();
384			String firstLine = "";
385			for (int i = messages.size() - 1; i >= 0; --i) {
386				if (!messages.get(i).isRead()) {
387					if (i == messages.size() - 1) {
388						firstLine = messages.get(i).getReadableBody(context);
389						bigText.append(firstLine);
390					} else {
391						firstLine = messages.get(i).getReadableBody(context);
392						bigText.insert(0, firstLine + "\n");
393					}
394				} else {
395					break;
396				}
397			}
398			mBuilder.setContentText(firstLine);
399			mBuilder.setStyle(new NotificationCompat.BigTextStyle()
400					.bigText(bigText.toString()));
401		} else {
402			NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
403			style.setBigContentTitle(unread.size() + " "
404					+ context.getString(R.string.unread_conversations));
405			StringBuilder names = new StringBuilder();
406			for (int i = 0; i < unread.size(); ++i) {
407				targetUuid = unread.get(i).getUuid();
408				if (i < unread.size() - 1) {
409					names.append(unread.get(i).getName(useSubject) + ", ");
410				} else {
411					names.append(unread.get(i).getName(useSubject));
412				}
413				style.addLine(Html.fromHtml("<b>"
414						+ unread.get(i).getName(useSubject)
415						+ "</b> "
416						+ unread.get(i).getLatestMessage()
417								.getReadableBody(context)));
418			}
419			mBuilder.setContentTitle(unread.size() + " "
420					+ context.getString(R.string.unread_conversations));
421			mBuilder.setContentText(names.toString());
422			mBuilder.setStyle(style);
423		}
424		if ((currentCon != null) && (notify)) {
425			targetUuid = currentCon.getUuid();
426		}
427		if (unread.size() != 0) {
428			mBuilder.setSmallIcon(R.drawable.ic_notification);
429			if (notify) {
430				if (vibrate) {
431					int dat = 70;
432					long[] pattern = { 0, 3 * dat, dat, dat };
433					mBuilder.setVibrate(pattern);
434				}
435				mBuilder.setLights(0xffffffff, 2000, 4000);
436				if (ringtone != null) {
437					mBuilder.setSound(Uri.parse(ringtone));
438				}
439			}
440
441			TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
442			stackBuilder.addParentStack(ConversationActivity.class);
443
444			Intent viewConversationIntent = new Intent(context,
445					ConversationActivity.class);
446			viewConversationIntent.setAction(Intent.ACTION_VIEW);
447			viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
448					targetUuid);
449			viewConversationIntent
450					.setType(ConversationActivity.VIEW_CONVERSATION);
451
452			stackBuilder.addNextIntent(viewConversationIntent);
453
454			PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
455					0, PendingIntent.FLAG_UPDATE_CURRENT);
456
457			mBuilder.setContentIntent(resultPendingIntent);
458			Notification notification = mBuilder.build();
459			mNotificationManager.notify(2342, notification);
460		}
461	}
462
463	private static boolean wasHighlighted(Conversation conversation) {
464		List<Message> messages = conversation.getMessages();
465		String nick = conversation.getMucOptions().getActualNick();
466		Pattern highlight = generateNickHighlightPattern(nick);
467		for (int i = messages.size() - 1; i >= 0; --i) {
468			if (messages.get(i).isRead()) {
469				break;
470			} else {
471				Matcher m = highlight.matcher(messages.get(i).getBody());
472				if (m.find()) {
473					return true;
474				}
475			}
476		}
477		return false;
478	}
479
480	public static void prepareContactBadge(final Activity activity,
481			QuickContactBadge badge, final Contact contact, Context context) {
482		if (contact.getSystemAccount() != null) {
483			String[] systemAccount = contact.getSystemAccount().split("#");
484			long id = Long.parseLong(systemAccount[0]);
485			badge.assignContactUri(Contacts.getLookupUri(id, systemAccount[1]));
486		}
487		badge.setImageBitmap(UIHelper.getContactPicture(contact, 72, context,
488				false));
489	}
490
491	public static AlertDialog getVerifyFingerprintDialog(
492			final ConversationActivity activity,
493			final Conversation conversation, final View msg) {
494		final Contact contact = conversation.getContact();
495		final Account account = conversation.getAccount();
496
497		AlertDialog.Builder builder = new AlertDialog.Builder(activity);
498		builder.setTitle("Verify fingerprint");
499		LayoutInflater inflater = activity.getLayoutInflater();
500		View view = inflater.inflate(R.layout.dialog_verify_otr, null);
501		TextView jid = (TextView) view.findViewById(R.id.verify_otr_jid);
502		TextView fingerprint = (TextView) view
503				.findViewById(R.id.verify_otr_fingerprint);
504		TextView yourprint = (TextView) view
505				.findViewById(R.id.verify_otr_yourprint);
506
507		jid.setText(contact.getJid());
508		fingerprint.setText(conversation.getOtrFingerprint());
509		yourprint.setText(account.getOtrFingerprint());
510		builder.setNegativeButton("Cancel", null);
511		builder.setPositiveButton("Verify", new OnClickListener() {
512
513			@Override
514			public void onClick(DialogInterface dialog, int which) {
515				contact.addOtrFingerprint(conversation.getOtrFingerprint());
516				msg.setVisibility(View.GONE);
517				activity.xmppConnectionService.syncRosterToDisk(account);
518			}
519		});
520		builder.setView(view);
521		return builder.create();
522	}
523
524	public static Bitmap getSelfContactPicture(Account account, int size,
525			boolean showPhoneSelfContactPicture, Context context) {
526		if (showPhoneSelfContactPicture) {
527			Uri selfiUri = PhoneHelper.getSefliUri(context);
528			if (selfiUri != null) {
529				try {
530					return BitmapFactory.decodeStream(context
531							.getContentResolver().openInputStream(selfiUri));
532				} catch (FileNotFoundException e) {
533					return getContactPicture(account.getJid(), size, context,
534							false);
535				}
536			}
537			return getContactPicture(account.getJid(), size, context, false);
538		} else {
539			return getContactPicture(account.getJid(), size, context, false);
540		}
541	}
542}