UIHelper.java

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