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.persistance.FileBackend;
 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.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 DATE_NO_YEAR_FLAGS = DateUtils.FORMAT_SHOW_DATE
 56			| DateUtils.FORMAT_NO_YEAR | DateUtils.FORMAT_ABBREV_ALL;
 57
 58	public static String readableTimeDifference(Context context, long time) {
 59		if (time == 0) {
 60			return context.getString(R.string.just_now);
 61		}
 62		Date date = new Date(time);
 63		long difference = (System.currentTimeMillis() - time) / 1000;
 64		if (difference < 60) {
 65			return context.getString(R.string.just_now);
 66		} else if (difference < 60 * 2) {
 67			return context.getString(R.string.minute_ago);
 68		} else if (difference < 60 * 15) {
 69			return context.getString(R.string.minutes_ago,
 70					Math.round(difference / 60.0));
 71		} else if (today(date) || difference < 6 * 60 * 60) {
 72			java.text.DateFormat df = DateFormat.getTimeFormat(context);
 73			return df.format(date);
 74		} else {
 75			return DateUtils.formatDateTime(context, date.getTime(),
 76					DATE_NO_YEAR_FLAGS);
 77		}
 78	}
 79
 80	private static boolean today(Date date) {
 81		Calendar cal1 = Calendar.getInstance();
 82		Calendar cal2 = Calendar.getInstance();
 83		cal1.setTime(date);
 84		cal2.setTimeInMillis(System.currentTimeMillis());
 85		return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
 86				&& cal1.get(Calendar.DAY_OF_YEAR) == cal2
 87						.get(Calendar.DAY_OF_YEAR);
 88	}
 89
 90	public static String lastseen(Context context, long time) {
 91		if (time == 0) {
 92			return context.getString(R.string.never_seen);
 93		}
 94		long difference = (System.currentTimeMillis() - time) / 1000;
 95		if (difference < 60) {
 96			return context.getString(R.string.last_seen_now);
 97		} else if (difference < 60 * 2) {
 98			return context.getString(R.string.last_seen_min);
 99		} else if (difference < 60 * 60) {
100			return context.getString(R.string.last_seen_mins,
101					Math.round(difference / 60.0));
102		} else if (difference < 60 * 60 * 2) {
103			return context.getString(R.string.last_seen_hour);
104		} else if (difference < 60 * 60 * 24) {
105			return context.getString(R.string.last_seen_hours,
106					Math.round(difference / (60.0 * 60.0)));
107		} else if (difference < 60 * 60 * 48) {
108			return context.getString(R.string.last_seen_day);
109		} else {
110			return context.getString(R.string.last_seen_days,
111					Math.round(difference / (60.0 * 60.0 * 24.0)));
112		}
113	}
114
115	public static int getRealPx(int dp, Context context) {
116		final DisplayMetrics metrics = context.getResources()
117				.getDisplayMetrics();
118		return ((int) (dp * metrics.density));
119	}
120
121	private static int getNameColor(String name) {
122		/*int holoColors[] = { 0xFF1da9da, 0xFFb368d9, 0xFF83b600, 0xFFffa713,
123				0xFFe92727 };*/
124		int holoColors[] = {0xFFe91e63, 0xFF9c27b0, 0xFF673ab7, 0xFF3f51b5, 0xFF5677fc, 0xFF03a9f4, 0xFF00bcd4, 0xFF009688, 0xFFff5722, 0xFF795548, 0xFF607d8b};
125		return holoColors[(int) ((name.hashCode() & 0xffffffffl) % holoColors.length)];
126	}
127
128	private static void drawTile(Canvas canvas, String letter, int tileColor,
129			int textColor, int left, int top, int right, int bottom) {
130		Paint tilePaint = new Paint(), textPaint = new Paint();
131		tilePaint.setColor(tileColor);
132		textPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
133		textPaint.setColor(textColor);
134		textPaint.setTypeface(Typeface.create("sans-serif-light",
135				Typeface.NORMAL));
136		textPaint.setTextSize((float) ((right - left) * 0.8));
137		Rect rect = new Rect();
138
139		canvas.drawRect(new Rect(left, top, right, bottom), tilePaint);
140		textPaint.getTextBounds(letter, 0, 1, rect);
141		float width = textPaint.measureText(letter);
142		canvas.drawText(letter, (right + left) / 2 - width / 2, (top + bottom)
143				/ 2 + rect.height() / 2, textPaint);
144	}
145
146	private static Bitmap getUnknownContactPicture(String[] names, int size,
147			int bgColor, int fgColor) {
148		int tiles = (names.length > 4) ? 4 : (names.length < 1) ? 1
149				: names.length;
150		Bitmap bitmap = Bitmap
151				.createBitmap(size, size, Bitmap.Config.ARGB_8888);
152		Canvas canvas = new Canvas(bitmap);
153
154		String[] letters = new String[tiles];
155		int[] colors = new int[tiles];
156		if (names.length < 1) {
157			letters[0] = "?";
158			colors[0] = 0xFFe92727;
159		} else {
160			for (int i = 0; i < tiles; ++i) {
161				letters[i] = (names[i].length() > 0) ? names[i].substring(0, 1)
162						.toUpperCase(Locale.US) : " ";
163				colors[i] = getNameColor(names[i]);
164			}
165
166			if (names.length > 4) {
167				letters[3] = "\u2026"; // Unicode ellipsis
168				colors[3] = 0xFF202020;
169			}
170		}
171
172		bitmap.eraseColor(bgColor);
173
174		switch (tiles) {
175		case 1:
176			drawTile(canvas, letters[0], colors[0], fgColor, 0, 0, size, size);
177			break;
178
179		case 2:
180			drawTile(canvas, letters[0], colors[0], fgColor, 0, 0,
181					size / 2 - 1, size);
182			drawTile(canvas, letters[1], colors[1], fgColor, size / 2 + 1, 0,
183					size, size);
184			break;
185
186		case 3:
187			drawTile(canvas, letters[0], colors[0], fgColor, 0, 0,
188					size / 2 - 1, size);
189			drawTile(canvas, letters[1], colors[1], fgColor, size / 2 + 1, 0,
190					size, size / 2 - 1);
191			drawTile(canvas, letters[2], colors[2], fgColor, size / 2 + 1,
192					size / 2 + 1, size, size);
193			break;
194
195		case 4:
196			drawTile(canvas, letters[0], colors[0], fgColor, 0, 0,
197					size / 2 - 1, size / 2 - 1);
198			drawTile(canvas, letters[1], colors[1], fgColor, 0, size / 2 + 1,
199					size / 2 - 1, size);
200			drawTile(canvas, letters[2], colors[2], fgColor, size / 2 + 1, 0,
201					size, size / 2 - 1);
202			drawTile(canvas, letters[3], colors[3], fgColor, size / 2 + 1,
203					size / 2 + 1, size, size);
204			break;
205		}
206
207		return bitmap;
208	}
209
210	private static Bitmap getMucContactPicture(Conversation conversation,
211			int size, int bgColor, int fgColor) {
212		List<User> members = conversation.getMucOptions().getUsers();
213		if (members.size() == 0) {
214			return getUnknownContactPicture(
215					new String[] { conversation.getName(false) }, size,
216					bgColor, fgColor);
217		}
218		ArrayList<String> names = new ArrayList<String>();
219		names.add(conversation.getMucOptions().getActualNick());
220		for(User user : members) {
221			names.add(user.getName());
222			if (names.size() > 4 ) {
223				break;
224			}
225		}
226		String[] mArrayNames = new String[names.size()];
227		names.toArray(mArrayNames);
228		return getUnknownContactPicture(mArrayNames, size, bgColor, fgColor);
229	}
230
231	public static Bitmap getContactPicture(Conversation conversation,
232			int dpSize, Context context, boolean notification) {
233		if (conversation.getMode() == Conversation.MODE_SINGLE) {
234			return getContactPicture(conversation.getContact(), dpSize,
235					context, notification);
236		} else {
237			int fgColor = UIHelper.FG_COLOR, bgColor = (notification) ? UIHelper.BG_COLOR
238					: UIHelper.TRANSPARENT;
239
240			return getMucContactPicture(conversation,
241					getRealPx(dpSize, context), bgColor, fgColor);
242		}
243	}
244
245	public static Bitmap getContactPicture(Contact contact, int dpSize,
246			Context context, boolean notification) {
247		String uri = contact.getProfilePhoto();
248		if (uri == null) {
249			return getContactPicture(contact.getDisplayName(), dpSize, context,
250					notification);
251		}
252		try {
253			Bitmap bm = BitmapFactory.decodeStream(context.getContentResolver()
254					.openInputStream(Uri.parse(uri)));
255			return Bitmap.createScaledBitmap(bm, getRealPx(dpSize, context),
256					getRealPx(dpSize, context), false);
257		} catch (FileNotFoundException e) {
258			return getContactPicture(contact.getDisplayName(), dpSize, context,
259					notification);
260		}
261	}
262
263	public static Bitmap getContactPicture(String name, int dpSize,
264			Context context, boolean notification) {
265		int fgColor = UIHelper.FG_COLOR, bgColor = (notification) ? UIHelper.BG_COLOR
266				: UIHelper.TRANSPARENT;
267
268		return getUnknownContactPicture(new String[] { name },
269				getRealPx(dpSize, context), bgColor, fgColor);
270	}
271
272	public static void showErrorNotification(Context context,
273			List<Account> accounts) {
274		NotificationManager mNotificationManager = (NotificationManager) context
275				.getSystemService(Context.NOTIFICATION_SERVICE);
276		List<Account> accountsWproblems = new ArrayList<Account>();
277		for (Account account : accounts) {
278			if (account.hasErrorStatus()) {
279				accountsWproblems.add(account);
280			}
281		}
282		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
283				context);
284		if (accountsWproblems.size() == 0) {
285			mNotificationManager.cancel(1111);
286			return;
287		} else if (accountsWproblems.size() == 1) {
288			mBuilder.setContentTitle(context
289					.getString(R.string.problem_connecting_to_account));
290			mBuilder.setContentText(accountsWproblems.get(0).getJid());
291		} else {
292			mBuilder.setContentTitle(context
293					.getString(R.string.problem_connecting_to_accounts));
294			mBuilder.setContentText(context.getString(R.string.touch_to_fix));
295		}
296		mBuilder.setOngoing(true);
297		mBuilder.setLights(0xffffffff, 2000, 4000);
298		mBuilder.setSmallIcon(R.drawable.ic_notification);
299		TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
300		stackBuilder.addParentStack(ConversationActivity.class);
301
302		Intent manageAccountsIntent = new Intent(context,
303				ManageAccountActivity.class);
304		stackBuilder.addNextIntent(manageAccountsIntent);
305
306		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
307				PendingIntent.FLAG_UPDATE_CURRENT);
308
309		mBuilder.setContentIntent(resultPendingIntent);
310		Notification notification = mBuilder.build();
311		mNotificationManager.notify(1111, notification);
312	}
313
314	private static Pattern generateNickHighlightPattern(String nick) {
315		// We expect a word boundary, i.e. space or start of string, followed by
316		// the
317		// nick (matched in case-insensitive manner), followed by optional
318		// punctuation (for example "bob: i disagree" or "how are you alice?"),
319		// followed by another word boundary.
320		return Pattern.compile("\\b" + nick + "\\p{Punct}?\\b",
321				Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
322	}
323
324	public static void updateNotification(Context context,
325			List<Conversation> conversations, Conversation currentCon,
326			boolean notify) {
327		NotificationManager mNotificationManager = (NotificationManager) context
328				.getSystemService(Context.NOTIFICATION_SERVICE);
329
330		SharedPreferences preferences = PreferenceManager
331				.getDefaultSharedPreferences(context);
332		boolean useSubject = preferences.getBoolean("use_subject_in_muc", true);
333		boolean showNofifications = preferences.getBoolean("show_notification",
334				true);
335		boolean vibrate = preferences.getBoolean("vibrate_on_notification",
336				true);
337		boolean alwaysNotify = preferences.getBoolean(
338				"notify_in_conversation_when_highlighted", false);
339
340		if (!showNofifications) {
341			mNotificationManager.cancel(2342);
342			return;
343		}
344
345		String targetUuid = "";
346
347		if ((currentCon != null)
348				&& (currentCon.getMode() == Conversation.MODE_MULTI)
349				&& (!alwaysNotify) && notify) {
350			String nick = currentCon.getMucOptions().getActualNick();
351			Pattern highlight = generateNickHighlightPattern(nick);
352			Matcher m = highlight.matcher(currentCon.getLatestMessage()
353					.getBody());
354			notify = m.find();
355		}
356
357		List<Conversation> unread = new ArrayList<Conversation>();
358		for (Conversation conversation : conversations) {
359			if (conversation.getMode() == Conversation.MODE_MULTI) {
360				if ((!conversation.isRead())
361						&& ((wasHighlighted(conversation) || (alwaysNotify)))) {
362					unread.add(conversation);
363				}
364			} else {
365				if (!conversation.isRead()) {
366					unread.add(conversation);
367				}
368			}
369		}
370		String ringtone = preferences.getString("notification_ringtone", null);
371
372		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
373				context);
374		if (unread.size() == 0) {
375			mNotificationManager.cancel(2342);
376			return;
377		} else if (unread.size() == 1) {
378			Conversation conversation = unread.get(0);
379			targetUuid = conversation.getUuid();
380			mBuilder.setLargeIcon(conversation.getImage(context, 64));
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}