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		ArrayList<String> names = new ArrayList<String>();
218		names.add(conversation.getMucOptions().getActualNick());
219		for(User user : members) {
220			names.add(user.getName());
221			if (names.size() > 4 ) {
222				break;
223			}
224		}
225		String[] mArrayNames = new String[names.size()];
226		names.toArray(mArrayNames);
227		return getUnknownContactPicture(mArrayNames, size, bgColor, fgColor);
228	}
229
230	public static Bitmap getContactPicture(Conversation conversation,
231			int dpSize, Context context, boolean notification) {
232		if (conversation.getMode() == Conversation.MODE_SINGLE) {
233			return getContactPicture(conversation.getContact(), dpSize,
234					context, notification);
235		} else {
236			int fgColor = UIHelper.FG_COLOR, bgColor = (notification) ? UIHelper.BG_COLOR
237					: UIHelper.TRANSPARENT;
238
239			return getMucContactPicture(conversation,
240					getRealPx(dpSize, context), bgColor, fgColor);
241		}
242	}
243
244	public static Bitmap getContactPicture(Contact contact, int dpSize,
245			Context context, boolean notification) {
246		String uri = contact.getProfilePhoto();
247		if (uri == null) {
248			return getContactPicture(contact.getDisplayName(), dpSize, context,
249					notification);
250		}
251		try {
252			Bitmap bm = BitmapFactory.decodeStream(context.getContentResolver()
253					.openInputStream(Uri.parse(uri)));
254			return Bitmap.createScaledBitmap(bm, getRealPx(dpSize, context),
255					getRealPx(dpSize, context), false);
256		} catch (FileNotFoundException e) {
257			return getContactPicture(contact.getDisplayName(), dpSize, context,
258					notification);
259		}
260	}
261
262	public static Bitmap getContactPicture(String name, int dpSize,
263			Context context, boolean notification) {
264		int fgColor = UIHelper.FG_COLOR, bgColor = (notification) ? UIHelper.BG_COLOR
265				: UIHelper.TRANSPARENT;
266
267		return getUnknownContactPicture(new String[] { name },
268				getRealPx(dpSize, context), bgColor, fgColor);
269	}
270
271	public static void showErrorNotification(Context context,
272			List<Account> accounts) {
273		NotificationManager mNotificationManager = (NotificationManager) context
274				.getSystemService(Context.NOTIFICATION_SERVICE);
275		List<Account> accountsWproblems = new ArrayList<Account>();
276		for (Account account : accounts) {
277			if (account.hasErrorStatus()) {
278				accountsWproblems.add(account);
279			}
280		}
281		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
282				context);
283		if (accountsWproblems.size() == 0) {
284			mNotificationManager.cancel(1111);
285			return;
286		} else if (accountsWproblems.size() == 1) {
287			mBuilder.setContentTitle(context
288					.getString(R.string.problem_connecting_to_account));
289			mBuilder.setContentText(accountsWproblems.get(0).getJid());
290		} else {
291			mBuilder.setContentTitle(context
292					.getString(R.string.problem_connecting_to_accounts));
293			mBuilder.setContentText(context.getString(R.string.touch_to_fix));
294		}
295		mBuilder.setOngoing(true);
296		mBuilder.setLights(0xffffffff, 2000, 4000);
297		mBuilder.setSmallIcon(R.drawable.ic_notification);
298		TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
299		stackBuilder.addParentStack(ConversationActivity.class);
300
301		Intent manageAccountsIntent = new Intent(context,
302				ManageAccountActivity.class);
303		stackBuilder.addNextIntent(manageAccountsIntent);
304
305		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
306				PendingIntent.FLAG_UPDATE_CURRENT);
307
308		mBuilder.setContentIntent(resultPendingIntent);
309		Notification notification = mBuilder.build();
310		mNotificationManager.notify(1111, notification);
311	}
312
313	private static Pattern generateNickHighlightPattern(String nick) {
314		// We expect a word boundary, i.e. space or start of string, followed by
315		// the
316		// nick (matched in case-insensitive manner), followed by optional
317		// punctuation (for example "bob: i disagree" or "how are you alice?"),
318		// followed by another word boundary.
319		return Pattern.compile("\\b" + nick + "\\p{Punct}?\\b",
320				Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
321	}
322
323	public static void updateNotification(Context context,
324			List<Conversation> conversations, Conversation currentCon,
325			boolean notify) {
326		NotificationManager mNotificationManager = (NotificationManager) context
327				.getSystemService(Context.NOTIFICATION_SERVICE);
328
329		SharedPreferences preferences = PreferenceManager
330				.getDefaultSharedPreferences(context);
331		boolean useSubject = preferences.getBoolean("use_subject_in_muc", true);
332		boolean showNofifications = preferences.getBoolean("show_notification",
333				true);
334		boolean vibrate = preferences.getBoolean("vibrate_on_notification",
335				true);
336		boolean alwaysNotify = preferences.getBoolean(
337				"notify_in_conversation_when_highlighted", false);
338
339		if (!showNofifications) {
340			mNotificationManager.cancel(2342);
341			return;
342		}
343
344		String targetUuid = "";
345
346		if ((currentCon != null)
347				&& (currentCon.getMode() == Conversation.MODE_MULTI)
348				&& (!alwaysNotify)) {
349			String nick = currentCon.getMucOptions().getActualNick();
350			Pattern highlight = generateNickHighlightPattern(nick);
351			Matcher m = highlight.matcher(currentCon.getLatestMessage()
352					.getBody());
353			notify = m.find();
354		}
355
356		List<Conversation> unread = new ArrayList<Conversation>();
357		for (Conversation conversation : conversations) {
358			if (conversation.getMode() == Conversation.MODE_MULTI) {
359				if ((!conversation.isRead())
360						&& ((wasHighlighted(conversation) || (alwaysNotify)))) {
361					unread.add(conversation);
362				}
363			} else {
364				if (!conversation.isRead()) {
365					unread.add(conversation);
366				}
367			}
368		}
369		String ringtone = preferences.getString("notification_ringtone", null);
370
371		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
372				context);
373		if (unread.size() == 0) {
374			mNotificationManager.cancel(2342);
375			return;
376		} else if (unread.size() == 1) {
377			Conversation conversation = unread.get(0);
378			targetUuid = conversation.getUuid();
379			mBuilder.setLargeIcon(UIHelper.getContactPicture(conversation, 64,
380					context, true));
381			mBuilder.setContentTitle(conversation.getName(useSubject));
382			if (notify) {
383				mBuilder.setTicker(conversation.getLatestMessage()
384						.getReadableBody(context));
385			}
386			StringBuilder bigText = new StringBuilder();
387			List<Message> messages = conversation.getMessages();
388			String firstLine = "";
389			for (int i = messages.size() - 1; i >= 0; --i) {
390				if (!messages.get(i).isRead()) {
391					if (i == messages.size() - 1) {
392						firstLine = messages.get(i).getReadableBody(context);
393						bigText.append(firstLine);
394					} else {
395						firstLine = messages.get(i).getReadableBody(context);
396						bigText.insert(0, firstLine + "\n");
397					}
398				} else {
399					break;
400				}
401			}
402			mBuilder.setContentText(firstLine);
403			mBuilder.setStyle(new NotificationCompat.BigTextStyle()
404					.bigText(bigText.toString()));
405		} else {
406			NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
407			style.setBigContentTitle(unread.size() + " "
408					+ context.getString(R.string.unread_conversations));
409			StringBuilder names = new StringBuilder();
410			for (int i = 0; i < unread.size(); ++i) {
411				targetUuid = unread.get(i).getUuid();
412				if (i < unread.size() - 1) {
413					names.append(unread.get(i).getName(useSubject) + ", ");
414				} else {
415					names.append(unread.get(i).getName(useSubject));
416				}
417				style.addLine(Html.fromHtml("<b>"
418						+ unread.get(i).getName(useSubject)
419						+ "</b> "
420						+ unread.get(i).getLatestMessage()
421								.getReadableBody(context)));
422			}
423			mBuilder.setContentTitle(unread.size() + " "
424					+ context.getString(R.string.unread_conversations));
425			mBuilder.setContentText(names.toString());
426			mBuilder.setStyle(style);
427		}
428		if ((currentCon != null) && (notify)) {
429			targetUuid = currentCon.getUuid();
430		}
431		if (unread.size() != 0) {
432			mBuilder.setSmallIcon(R.drawable.ic_notification);
433			if (notify) {
434				if (vibrate) {
435					int dat = 70;
436					long[] pattern = { 0, 3 * dat, dat, dat };
437					mBuilder.setVibrate(pattern);
438				}
439				mBuilder.setLights(0xffffffff, 2000, 4000);
440				if (ringtone != null) {
441					mBuilder.setSound(Uri.parse(ringtone));
442				}
443			}
444
445			TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
446			stackBuilder.addParentStack(ConversationActivity.class);
447
448			Intent viewConversationIntent = new Intent(context,
449					ConversationActivity.class);
450			viewConversationIntent.setAction(Intent.ACTION_VIEW);
451			viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
452					targetUuid);
453			viewConversationIntent
454					.setType(ConversationActivity.VIEW_CONVERSATION);
455
456			stackBuilder.addNextIntent(viewConversationIntent);
457
458			PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
459					0, PendingIntent.FLAG_UPDATE_CURRENT);
460
461			mBuilder.setContentIntent(resultPendingIntent);
462			Notification notification = mBuilder.build();
463			mNotificationManager.notify(2342, notification);
464		}
465	}
466
467	private static boolean wasHighlighted(Conversation conversation) {
468		List<Message> messages = conversation.getMessages();
469		String nick = conversation.getMucOptions().getActualNick();
470		Pattern highlight = generateNickHighlightPattern(nick);
471		for (int i = messages.size() - 1; i >= 0; --i) {
472			if (messages.get(i).isRead()) {
473				break;
474			} else {
475				Matcher m = highlight.matcher(messages.get(i).getBody());
476				if (m.find()) {
477					return true;
478				}
479			}
480		}
481		return false;
482	}
483
484	public static void prepareContactBadge(final Activity activity,
485			QuickContactBadge badge, final Contact contact, Context context) {
486		if (contact.getSystemAccount() != null) {
487			String[] systemAccount = contact.getSystemAccount().split("#");
488			long id = Long.parseLong(systemAccount[0]);
489			badge.assignContactUri(Contacts.getLookupUri(id, systemAccount[1]));
490		}
491		badge.setImageBitmap(contact.getImage(72, context));
492	}
493
494	public static AlertDialog getVerifyFingerprintDialog(
495			final ConversationActivity activity,
496			final Conversation conversation, final View msg) {
497		final Contact contact = conversation.getContact();
498		final Account account = conversation.getAccount();
499
500		AlertDialog.Builder builder = new AlertDialog.Builder(activity);
501		builder.setTitle("Verify fingerprint");
502		LayoutInflater inflater = activity.getLayoutInflater();
503		View view = inflater.inflate(R.layout.dialog_verify_otr, null);
504		TextView jid = (TextView) view.findViewById(R.id.verify_otr_jid);
505		TextView fingerprint = (TextView) view
506				.findViewById(R.id.verify_otr_fingerprint);
507		TextView yourprint = (TextView) view
508				.findViewById(R.id.verify_otr_yourprint);
509
510		jid.setText(contact.getJid());
511		fingerprint.setText(conversation.getOtrFingerprint());
512		yourprint.setText(account.getOtrFingerprint());
513		builder.setNegativeButton("Cancel", null);
514		builder.setPositiveButton("Verify", new OnClickListener() {
515
516			@Override
517			public void onClick(DialogInterface dialog, int which) {
518				contact.addOtrFingerprint(conversation.getOtrFingerprint());
519				msg.setVisibility(View.GONE);
520				activity.xmppConnectionService.syncRosterToDisk(account);
521			}
522		});
523		builder.setView(view);
524		return builder.create();
525	}
526
527	public static Bitmap getSelfContactPicture(Account account, int size,
528			boolean showPhoneSelfContactPicture, Context context) {
529		if (showPhoneSelfContactPicture) {
530			Uri selfiUri = PhoneHelper.getSefliUri(context);
531			if (selfiUri != null) {
532				try {
533					return BitmapFactory.decodeStream(context
534							.getContentResolver().openInputStream(selfiUri));
535				} catch (FileNotFoundException e) {
536					return getContactPicture(account.getJid(), size, context,
537							false);
538				}
539			}
540			return getContactPicture(account.getJid(), size, context, false);
541		} else {
542			return getContactPicture(account.getJid(), size, context, false);
543		}
544	}
545}