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