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