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