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