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;
9
10import eu.siacs.conversations.R;
11import eu.siacs.conversations.entities.Account;
12import eu.siacs.conversations.entities.Contact;
13import eu.siacs.conversations.entities.Conversation;
14import eu.siacs.conversations.entities.Message;
15import eu.siacs.conversations.ui.ConversationActivity;
16import eu.siacs.conversations.ui.ManageAccountActivity;
17
18import android.app.Activity;
19import android.app.AlertDialog;
20import android.app.Notification;
21import android.app.NotificationManager;
22import android.app.PendingIntent;
23import android.content.Context;
24import android.content.DialogInterface;
25import android.content.DialogInterface.OnClickListener;
26import android.content.Intent;
27import android.content.SharedPreferences;
28import android.content.res.Resources;
29import android.graphics.Bitmap;
30import android.graphics.BitmapFactory;
31import android.graphics.Canvas;
32import android.graphics.Paint;
33import android.graphics.Rect;
34import android.net.Uri;
35import android.preference.PreferenceManager;
36import android.provider.ContactsContract.Contacts;
37import android.support.v4.app.NotificationCompat;
38import android.support.v4.app.NotificationCompat.InboxStyle;
39import android.support.v4.app.TaskStackBuilder;
40import android.text.Html;
41import android.util.Log;
42import android.view.LayoutInflater;
43import android.view.View;
44import android.widget.LinearLayout;
45import android.widget.QuickContactBadge;
46import android.widget.TextView;
47
48public class UIHelper {
49 public static String readableTimeDifference(long time) {
50 if (time == 0) {
51 return "just now";
52 }
53 Date date = new Date(time);
54 long difference = (System.currentTimeMillis() - time) / 1000;
55 if (difference < 60) {
56 return "just now";
57 } else if (difference < 60 * 10) {
58 return difference / 60 + " min ago";
59 } else if (difference < 60 * 60 * 24) {
60 SimpleDateFormat sdf = new SimpleDateFormat("HH:mm",Locale.US);
61 return sdf.format(date);
62 } else {
63 SimpleDateFormat sdf = new SimpleDateFormat("MM/dd",Locale.US);
64 return sdf.format(date);
65 }
66 }
67
68 private static Bitmap getUnknownContactPicture(String name, int size) {
69 String firstLetter = (name.length() > 0) ? name.substring(0, 1).toUpperCase(Locale.US) : " ";
70
71 int holoColors[] = { 0xFF1da9da, 0xFFb368d9, 0xFF83b600, 0xFFffa713,
72 0xFFe92727 };
73
74 int color = holoColors[Math.abs(name.toLowerCase(Locale.getDefault()).hashCode()) % holoColors.length];
75
76 Bitmap bitmap = Bitmap
77 .createBitmap(size, size, Bitmap.Config.ARGB_8888);
78 Canvas canvas = new Canvas(bitmap);
79
80 bitmap.eraseColor(color);
81
82 Paint paint = new Paint();
83 paint.setColor(0xffe5e5e5);
84 paint.setTextSize((float) (size * 0.9));
85 paint.setAntiAlias(true);
86 Rect rect = new Rect();
87 paint.getTextBounds(firstLetter, 0, 1, rect);
88 float width = paint.measureText(firstLetter);
89 canvas.drawText(firstLetter, (size / 2) - (width / 2), (size / 2)
90 + (rect.height() / 2), paint);
91
92 return bitmap;
93 }
94
95 public static Bitmap getContactPicture(Conversation conversation, int size, Context context) {
96 if(conversation.getMode() == Conversation.MODE_SINGLE) {
97 if (conversation.getContact() != null){
98 return getContactPicture(conversation.getContact(), size, context);
99 } else {
100 return getContactPicture(conversation.getName(false), size);
101 }
102 } else{
103 return getContactPicture(conversation.getName(false), size);
104 }
105 }
106
107 public static Bitmap getContactPicture(Contact contact, int size, Context context) {
108 String uri = contact.getProfilePhoto();
109 if (uri==null) {
110 return getContactPicture(contact.getDisplayName(), size);
111 }
112 try {
113 Bitmap bm = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(Uri.parse(uri)));
114 return Bitmap.createScaledBitmap(bm, size, size, false);
115 } catch (FileNotFoundException e) {
116 return getContactPicture(contact.getDisplayName(), size);
117 }
118 }
119
120 public static Bitmap getContactPicture(String name, int size, Context context) {
121 return getContactPicture(name, size);
122 }
123
124 public static Bitmap getContactPicture(String name, int size) {
125 return getUnknownContactPicture(name, size);
126 }
127 public static Bitmap getErrorPicture(int size) {
128 Bitmap bitmap = Bitmap
129 .createBitmap(size, size, Bitmap.Config.ARGB_8888);
130 Canvas canvas = new Canvas(bitmap);
131
132 bitmap.eraseColor(0xFFe92727);
133
134 Paint paint = new Paint();
135 paint.setColor(0xffe5e5e5);
136 paint.setTextSize((float) (size * 0.9));
137 paint.setAntiAlias(true);
138 Rect rect = new Rect();
139 paint.getTextBounds("!", 0, 1, rect);
140 float width = paint.measureText("!");
141 canvas.drawText("!", (size / 2) - (width / 2),
142 (size / 2) + (rect.height() / 2), paint);
143
144 return bitmap;
145 }
146
147 public static void showErrorNotification(Context context, List<Account> accounts) {
148 NotificationManager mNotificationManager = (NotificationManager) context
149 .getSystemService(Context.NOTIFICATION_SERVICE);
150 List<Account> accountsWproblems = new ArrayList<Account>();
151 for(Account account : accounts) {
152 if (account.hasErrorStatus()) {
153 accountsWproblems.add(account);
154 }
155 }
156 NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
157 if (accountsWproblems.size() == 0) {
158 mNotificationManager.cancel(1111);
159 return;
160 } else if (accountsWproblems.size() == 1) {
161 mBuilder.setContentTitle(context.getString(R.string.problem_connecting_to_account));
162 mBuilder.setContentText(accountsWproblems.get(0).getJid());
163 } else {
164 mBuilder.setContentTitle(context.getString(R.string.problem_connecting_to_accounts));
165 mBuilder.setContentText(context.getString(R.string.touch_to_fix));
166 }
167 mBuilder.setOngoing(true);
168 mBuilder.setLights(0xffffffff, 2000, 4000);
169 mBuilder.setSmallIcon(R.drawable.notification);
170 TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
171 stackBuilder.addParentStack(ConversationActivity.class);
172
173 Intent manageAccountsIntent = new Intent(context,
174 ManageAccountActivity.class);
175 stackBuilder.addNextIntent(manageAccountsIntent);
176
177 PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
178 0, PendingIntent.FLAG_UPDATE_CURRENT);
179
180 mBuilder.setContentIntent(resultPendingIntent);
181 Notification notification = mBuilder.build();
182 mNotificationManager.notify(1111, notification);
183 }
184
185 public static void updateNotification(Context context,
186 List<Conversation> conversations, Conversation currentCon, boolean notify) {
187 NotificationManager mNotificationManager = (NotificationManager) context
188 .getSystemService(Context.NOTIFICATION_SERVICE);
189
190 SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
191 boolean useSubject = preferences.getBoolean("use_subject_in_muc", true);
192 boolean showNofifications = preferences.getBoolean("show_notification",true);
193 boolean vibrate = preferences.getBoolean("vibrate_on_notification", true);
194 boolean alwaysNotify = preferences.getBoolean("notify_in_conversation_when_highlighted", false);
195
196 if (!showNofifications) {
197 mNotificationManager.cancel(2342);
198 return;
199 }
200
201 String targetUuid = "";
202
203 if ((currentCon != null) &&(currentCon.getMode() == Conversation.MODE_MULTI)&&(!alwaysNotify)) {
204 String nick = currentCon.getMucOptions().getNick();
205 notify = currentCon.getLatestMessage().getBody().contains(nick);
206 }
207
208 List<Conversation> unread = new ArrayList<Conversation>();
209 for (Conversation conversation : conversations) {
210 if (conversation.getMode() == Conversation.MODE_MULTI) {
211 if ((!conversation.isRead())&&((wasHighlighted(conversation)||(alwaysNotify)))) {
212 unread.add(conversation);
213 }
214 } else {
215 if (!conversation.isRead()) {
216 unread.add(conversation);
217 }
218 }
219 }
220 String ringtone = preferences.getString("notification_ringtone", null);
221
222 Resources res = context.getResources();
223 NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
224 context);
225 if (unread.size() == 0) {
226 mNotificationManager.cancel(2342);
227 return;
228 } else if (unread.size() == 1) {
229 Conversation conversation = unread.get(0);
230 targetUuid = conversation.getUuid();
231 mBuilder.setLargeIcon(UIHelper.getContactPicture(conversation, (int) res
232 .getDimension(android.R.dimen.notification_large_icon_width), context));
233 mBuilder.setContentTitle(conversation.getName(useSubject));
234 if (notify) {
235 mBuilder.setTicker(conversation.getLatestMessage().getBody().trim());
236 }
237 StringBuilder bigText = new StringBuilder();
238 List<Message> messages = conversation.getMessages();
239 String firstLine = "";
240 for (int i = messages.size() - 1; i >= 0; --i) {
241 if (!messages.get(i).isRead()) {
242 if (i == messages.size() - 1) {
243 firstLine = messages.get(i).getBody().trim();
244 bigText.append(firstLine);
245 } else {
246 firstLine = messages.get(i).getBody().trim();
247 bigText.insert(0, firstLine + "\n");
248 }
249 } else {
250 break;
251 }
252 }
253 mBuilder.setContentText(firstLine);
254 mBuilder.setStyle(new NotificationCompat.BigTextStyle()
255 .bigText(bigText.toString()));
256 } else {
257 NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
258 style.setBigContentTitle(unread.size() + " unread Conversations");
259 StringBuilder names = new StringBuilder();
260 for (int i = 0; i < unread.size(); ++i) {
261 targetUuid = unread.get(i).getUuid();
262 if (i < unread.size() - 1) {
263 names.append(unread.get(i).getName(useSubject) + ", ");
264 } else {
265 names.append(unread.get(i).getName(useSubject));
266 }
267 style.addLine(Html.fromHtml("<b>" + unread.get(i).getName(useSubject)
268 + "</b> " + unread.get(i).getLatestMessage().getBody().trim()));
269 }
270 mBuilder.setContentTitle(unread.size() + " unread Conversations");
271 mBuilder.setContentText(names.toString());
272 mBuilder.setStyle(style);
273 }
274 if (unread.size() != 0) {
275 mBuilder.setSmallIcon(R.drawable.notification);
276 if (notify) {
277 if (vibrate) {
278 int dat = 70;
279 long[] pattern = {0,3*dat,dat,dat};
280 mBuilder.setVibrate(pattern);
281 }
282 mBuilder.setLights(0xffffffff, 2000, 4000);
283 if (ringtone != null) {
284 mBuilder.setSound(Uri.parse(ringtone));
285 }
286 }
287
288 TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
289 stackBuilder.addParentStack(ConversationActivity.class);
290
291 Intent viewConversationIntent = new Intent(context,
292 ConversationActivity.class);
293 viewConversationIntent.setAction(Intent.ACTION_VIEW);
294 viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
295 targetUuid);
296 viewConversationIntent
297 .setType(ConversationActivity.VIEW_CONVERSATION);
298
299 stackBuilder.addNextIntent(viewConversationIntent);
300
301 PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
302 0, PendingIntent.FLAG_UPDATE_CURRENT);
303
304 mBuilder.setContentIntent(resultPendingIntent);
305 Notification notification = mBuilder.build();
306 mNotificationManager.notify(2342, notification);
307 }
308 }
309
310 private static boolean wasHighlighted(Conversation conversation) {
311 List<Message> messages = conversation.getMessages();
312 String nick = conversation.getMucOptions().getNick();
313 for(int i = messages.size() - 1; i >= 0; --i) {
314 if (messages.get(i).isRead()) {
315 break;
316 } else {
317 if (messages.get(i).getBody().contains(nick)) {
318 return true;
319 }
320 }
321 }
322 return false;
323 }
324
325 public static void prepareContactBadge(final Activity activity,
326 QuickContactBadge badge, final Contact contact, Context context) {
327 if (contact.getSystemAccount() != null) {
328 String[] systemAccount = contact.getSystemAccount().split("#");
329 long id = Long.parseLong(systemAccount[0]);
330 badge.assignContactUri(Contacts.getLookupUri(id, systemAccount[1]));
331 }
332 badge.setImageBitmap(UIHelper.getContactPicture(contact, 400, context));
333 }
334
335 public static AlertDialog getVerifyFingerprintDialog(
336 final ConversationActivity activity,
337 final Conversation conversation, final LinearLayout msg) {
338 final Contact contact = conversation.getContact();
339 final Account account = conversation.getAccount();
340
341 AlertDialog.Builder builder = new AlertDialog.Builder(activity);
342 builder.setTitle("Verify fingerprint");
343 LayoutInflater inflater = activity.getLayoutInflater();
344 View view = inflater.inflate(R.layout.dialog_verify_otr, null);
345 TextView jid = (TextView) view.findViewById(R.id.verify_otr_jid);
346 TextView fingerprint = (TextView) view
347 .findViewById(R.id.verify_otr_fingerprint);
348 TextView yourprint = (TextView) view
349 .findViewById(R.id.verify_otr_yourprint);
350
351 jid.setText(contact.getJid());
352 fingerprint.setText(conversation.getOtrFingerprint());
353 yourprint.setText(account.getOtrFingerprint());
354 builder.setNegativeButton("Cancel", null);
355 builder.setPositiveButton("Verify", new OnClickListener() {
356
357 @Override
358 public void onClick(DialogInterface dialog, int which) {
359 contact.addOtrFingerprint(conversation.getOtrFingerprint());
360 msg.setVisibility(View.GONE);
361 activity.xmppConnectionService.updateContact(contact);
362 }
363 });
364 builder.setView(view);
365 return builder.create();
366 }
367
368 public static Bitmap getSelfContactPicture(Account account, int size, boolean showPhoneSelfContactPicture, Activity activity) {
369 if (showPhoneSelfContactPicture) {
370 Uri selfiUri = PhoneHelper.getSefliUri(activity);
371 if (selfiUri != null) {
372 try {
373 return BitmapFactory.decodeStream(activity
374 .getContentResolver().openInputStream(selfiUri));
375 } catch (FileNotFoundException e) {
376 return getContactPicture(account.getJid(), size);
377 }
378 }
379 return getContactPicture(account.getJid(), size);
380 } else {
381 return getContactPicture(account.getJid(), size);
382 }
383 }
384}