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