1package eu.siacs.conversations.services;
2
3import android.app.Notification;
4import android.app.PendingIntent;
5import android.content.Intent;
6import android.content.SharedPreferences;
7import android.graphics.Bitmap;
8import android.graphics.Typeface;
9import android.net.Uri;
10import android.os.Build;
11import android.os.SystemClock;
12import android.support.v4.app.NotificationCompat;
13import android.support.v4.app.NotificationCompat.BigPictureStyle;
14import android.support.v4.app.NotificationCompat.Builder;
15import android.support.v4.app.NotificationManagerCompat;
16import android.support.v4.app.NotificationCompat.CarExtender.UnreadConversation;
17import android.support.v4.app.RemoteInput;
18import android.support.v4.content.ContextCompat;
19import android.text.SpannableString;
20import android.text.style.StyleSpan;
21import android.util.DisplayMetrics;
22import android.util.Log;
23import android.util.Pair;
24
25import java.io.File;
26import java.io.FileNotFoundException;
27import java.util.ArrayList;
28import java.util.Calendar;
29import java.util.HashMap;
30import java.util.Iterator;
31import java.util.LinkedHashMap;
32import java.util.List;
33import java.util.Map;
34import java.util.concurrent.atomic.AtomicInteger;
35import java.util.regex.Matcher;
36import java.util.regex.Pattern;
37
38import eu.siacs.conversations.Config;
39import eu.siacs.conversations.R;
40import eu.siacs.conversations.entities.Account;
41import eu.siacs.conversations.entities.Contact;
42import eu.siacs.conversations.entities.Conversation;
43import eu.siacs.conversations.entities.Message;
44import eu.siacs.conversations.persistance.FileBackend;
45import eu.siacs.conversations.ui.ConversationActivity;
46import eu.siacs.conversations.ui.ManageAccountActivity;
47import eu.siacs.conversations.ui.SettingsActivity;
48import eu.siacs.conversations.ui.TimePreference;
49import eu.siacs.conversations.utils.GeoHelper;
50import eu.siacs.conversations.utils.UIHelper;
51import eu.siacs.conversations.xmpp.XmppConnection;
52
53public class NotificationService {
54
55 public static final Object CATCHUP_LOCK = new Object();
56
57 private static final String CONVERSATIONS_GROUP = "eu.siacs.conversations";
58 private final XmppConnectionService mXmppConnectionService;
59
60 private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
61
62 private static final int NOTIFICATION_ID_MULTIPLIER = 1024 * 1024;
63
64 public static final int NOTIFICATION_ID = 2 * NOTIFICATION_ID_MULTIPLIER;
65 public static final int FOREGROUND_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 4;
66 public static final int ERROR_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 6;
67
68 private Conversation mOpenConversation;
69 private boolean mIsInForeground;
70 private long mLastNotification;
71
72 private final HashMap<Conversation,AtomicInteger> mBacklogMessageCounter = new HashMap<>();
73
74 public NotificationService(final XmppConnectionService service) {
75 this.mXmppConnectionService = service;
76 }
77
78 public boolean notify(final Message message) {
79 return message.getStatus() == Message.STATUS_RECEIVED
80 && notificationsEnabled()
81 && !message.getConversation().isMuted()
82 && (message.getConversation().alwaysNotify() || wasHighlightedOrPrivate(message))
83 && (!message.getConversation().isWithStranger() || notificationsFromStrangers())
84 ;
85 }
86
87 public boolean notificationsEnabled() {
88 return mXmppConnectionService.getPreferences().getBoolean("show_notification", true);
89 }
90
91 private boolean notificationsFromStrangers() {
92 return mXmppConnectionService.getPreferences().getBoolean("notifications_from_strangers",
93 mXmppConnectionService.getResources().getBoolean(R.bool.notifications_from_strangers));
94 }
95
96 public boolean isQuietHours() {
97 if (!mXmppConnectionService.getPreferences().getBoolean("enable_quiet_hours", false)) {
98 return false;
99 }
100 final long startTime = mXmppConnectionService.getPreferences().getLong("quiet_hours_start", TimePreference.DEFAULT_VALUE) % Config.MILLISECONDS_IN_DAY;
101 final long endTime = mXmppConnectionService.getPreferences().getLong("quiet_hours_end", TimePreference.DEFAULT_VALUE) % Config.MILLISECONDS_IN_DAY;
102 final long nowTime = Calendar.getInstance().getTimeInMillis() % Config.MILLISECONDS_IN_DAY;
103
104 if (endTime < startTime) {
105 return nowTime > startTime || nowTime < endTime;
106 } else {
107 return nowTime > startTime && nowTime < endTime;
108 }
109 }
110
111 public void pushFromBacklog(final Message message) {
112 if (notify(message)) {
113 synchronized (notifications) {
114 getBacklogMessageCounter(message.getConversation()).incrementAndGet();
115 pushToStack(message);
116 }
117 }
118 }
119
120 private AtomicInteger getBacklogMessageCounter(Conversation conversation) {
121 synchronized (mBacklogMessageCounter) {
122 if (!mBacklogMessageCounter.containsKey(conversation)) {
123 mBacklogMessageCounter.put(conversation,new AtomicInteger(0));
124 }
125 return mBacklogMessageCounter.get(conversation);
126 }
127 }
128
129 public void pushFromDirectReply(final Message message) {
130 synchronized (notifications) {
131 pushToStack(message);
132 updateNotification(false);
133 }
134 }
135
136 public void finishBacklog(boolean notify, Account account) {
137 synchronized (notifications) {
138 mXmppConnectionService.updateUnreadCountBadge();
139 if (account == null || !notify) {
140 updateNotification(notify);
141 } else {
142 updateNotification(getBacklogMessageCount(account) > 0);
143 }
144 }
145 }
146
147 private int getBacklogMessageCount(Account account) {
148 int count = 0;
149 synchronized (this.mBacklogMessageCounter) {
150 for(Iterator<Map.Entry<Conversation, AtomicInteger>> it = mBacklogMessageCounter.entrySet().iterator(); it.hasNext(); ) {
151 Map.Entry<Conversation, AtomicInteger> entry = it.next();
152 if (entry.getKey().getAccount() == account) {
153 count += entry.getValue().get();
154 it.remove();
155 }
156 }
157 }
158 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": backlog message count="+count);
159 return count;
160 }
161
162 public void finishBacklog(boolean notify) {
163 finishBacklog(notify,null);
164 }
165
166 private void pushToStack(final Message message) {
167 final String conversationUuid = message.getConversationUuid();
168 if (notifications.containsKey(conversationUuid)) {
169 notifications.get(conversationUuid).add(message);
170 } else {
171 final ArrayList<Message> mList = new ArrayList<>();
172 mList.add(message);
173 notifications.put(conversationUuid, mList);
174 }
175 }
176
177 public void push(final Message message) {
178 synchronized (CATCHUP_LOCK) {
179 final XmppConnection connection = message.getConversation().getAccount().getXmppConnection();
180 if (connection.isWaitingForSmCatchup()) {
181 connection.incrementSmCatchupMessageCounter();
182 pushFromBacklog(message);
183 } else {
184 pushNow(message);
185 }
186 }
187 }
188
189 private void pushNow(final Message message) {
190 mXmppConnectionService.updateUnreadCountBadge();
191 if (!notify(message)) {
192 Log.d(Config.LOGTAG,message.getConversation().getAccount().getJid().toBareJid()+": suppressing notification because turned off");
193 return;
194 }
195 final boolean isScreenOn = mXmppConnectionService.isInteractive();
196 if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
197 Log.d(Config.LOGTAG,message.getConversation().getAccount().getJid().toBareJid()+": suppressing notification because conversation is open");
198 return;
199 }
200 synchronized (notifications) {
201 pushToStack(message);
202 final Account account = message.getConversation().getAccount();
203 final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
204 && !account.inGracePeriod()
205 && !this.inMiniGracePeriod(account);
206 updateNotification(doNotify);
207 }
208 }
209
210 public void clear() {
211 synchronized (notifications) {
212 for(ArrayList<Message> messages : notifications.values()) {
213 markAsReadIfHasDirectReply(messages);
214 }
215 notifications.clear();
216 updateNotification(false);
217 }
218 }
219
220 public void clear(final Conversation conversation) {
221 synchronized (this.mBacklogMessageCounter) {
222 this.mBacklogMessageCounter.remove(conversation);
223 }
224 synchronized (notifications) {
225 markAsReadIfHasDirectReply(conversation);
226 notifications.remove(conversation.getUuid());
227 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
228 notificationManager.cancel(conversation.getUuid(), NOTIFICATION_ID);
229 updateNotification(false);
230 }
231 }
232
233 private void markAsReadIfHasDirectReply(final Conversation conversation) {
234 markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
235 }
236
237 private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
238 if (messages != null && messages.size() > 0) {
239 Message last = messages.get(messages.size() - 1);
240 if (last.getStatus() != Message.STATUS_RECEIVED) {
241 if (mXmppConnectionService.markRead(last.getConversation(), false)) {
242 mXmppConnectionService.updateConversationUi();
243 }
244 }
245 }
246 }
247
248 private void setNotificationColor(final Builder mBuilder) {
249 mBuilder.setColor(ContextCompat.getColor(mXmppConnectionService, R.color.primary500));
250 }
251
252 public void updateNotification(final boolean notify) {
253 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
254 final SharedPreferences preferences = mXmppConnectionService.getPreferences();
255
256 if (notifications.size() == 0) {
257 notificationManager.cancel(NOTIFICATION_ID);
258 } else {
259 if (notify) {
260 this.markLastNotification();
261 }
262 final Builder mBuilder;
263 if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
264 mBuilder = buildSingleConversations(notifications.values().iterator().next());
265 modifyForSoundVibrationAndLight(mBuilder, notify, preferences);
266 notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
267 } else {
268 mBuilder = buildMultipleConversation();
269 modifyForSoundVibrationAndLight(mBuilder, notify, preferences);
270 for(Map.Entry<String,ArrayList<Message>> entry : notifications.entrySet()) {
271 Builder singleBuilder = buildSingleConversations(entry.getValue());
272 singleBuilder.setGroup(CONVERSATIONS_GROUP);
273 modifyForSoundVibrationAndLight(singleBuilder,notify,preferences);
274 notificationManager.notify(entry.getKey(), NOTIFICATION_ID ,singleBuilder.build());
275 }
276 notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
277 }
278 }
279 }
280
281
282 private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, SharedPreferences preferences) {
283 final String ringtone = preferences.getString("notification_ringtone", null);
284 final boolean vibrate = preferences.getBoolean("vibrate_on_notification", true);
285 final boolean led = preferences.getBoolean("led", true);
286 if (notify && !isQuietHours()) {
287 if (vibrate) {
288 final int dat = 70;
289 final long[] pattern = {0, 3 * dat, dat, dat};
290 mBuilder.setVibrate(pattern);
291 } else {
292 mBuilder.setVibrate(new long[]{0});
293 }
294 if (ringtone != null) {
295 Uri uri = Uri.parse(ringtone);
296 try {
297 mBuilder.setSound(fixRingtoneUri(uri));
298 } catch (SecurityException e) {
299 Log.d(Config.LOGTAG,"unable to use custom notification sound "+uri.toString());
300 }
301 }
302 }
303 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
304 mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
305 }
306 mBuilder.setPriority(notify ? NotificationCompat.PRIORITY_DEFAULT : NotificationCompat.PRIORITY_LOW);
307 setNotificationColor(mBuilder);
308 mBuilder.setDefaults(0);
309 if (led) {
310 mBuilder.setLights(0xff00FF00, 2000, 3000);
311 }
312 }
313
314 private Uri fixRingtoneUri(Uri uri) {
315 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && "file".equals(uri.getScheme())) {
316 return FileBackend.getUriForFile(mXmppConnectionService,new File(uri.getPath()));
317 } else {
318 return uri;
319 }
320 }
321
322 private Builder buildMultipleConversation() {
323 final Builder mBuilder = new NotificationCompat.Builder(
324 mXmppConnectionService);
325 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
326 style.setBigContentTitle(notifications.size()
327 + " "
328 + mXmppConnectionService
329 .getString(R.string.unread_conversations));
330 final StringBuilder names = new StringBuilder();
331 Conversation conversation = null;
332 for (final ArrayList<Message> messages : notifications.values()) {
333 if (messages.size() > 0) {
334 conversation = messages.get(0).getConversation();
335 final String name = conversation.getName();
336 SpannableString styledString;
337 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
338 int count = messages.size();
339 styledString = new SpannableString(name + ": " + mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count));
340 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
341 style.addLine(styledString);
342 } else {
343 styledString = new SpannableString(name + ": " + UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
344 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
345 style.addLine(styledString);
346 }
347 names.append(name);
348 names.append(", ");
349 }
350 }
351 if (names.length() >= 2) {
352 names.delete(names.length() - 2, names.length());
353 }
354 mBuilder.setContentTitle(notifications.size()
355 + " "
356 + mXmppConnectionService
357 .getString(R.string.unread_conversations));
358 mBuilder.setContentText(names.toString());
359 mBuilder.setStyle(style);
360 if (conversation != null) {
361 mBuilder.setContentIntent(createContentIntent(conversation));
362 }
363 mBuilder.setGroupSummary(true);
364 mBuilder.setGroup(CONVERSATIONS_GROUP);
365 mBuilder.setDeleteIntent(createDeleteIntent(null));
366 mBuilder.setSmallIcon(R.drawable.ic_notification);
367 return mBuilder;
368 }
369
370 private Builder buildSingleConversations(final ArrayList<Message> messages) {
371 final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
372 if (messages.size() >= 1) {
373 final Conversation conversation = messages.get(0).getConversation();
374 final UnreadConversation.Builder mUnreadBuilder = new UnreadConversation.Builder(conversation.getName());
375 mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
376 .get(conversation, getPixel(64)));
377 mBuilder.setContentTitle(conversation.getName());
378 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
379 int count = messages.size();
380 mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count));
381 } else {
382 Message message;
383 if ((message = getImage(messages)) != null) {
384 modifyForImage(mBuilder, mUnreadBuilder, message, messages);
385 } else {
386 modifyForTextOnly(mBuilder, mUnreadBuilder, messages);
387 }
388 RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
389 NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(R.drawable.ic_send_text_offline, "Reply", createReplyIntent(conversation, false)).addRemoteInput(remoteInput).build();
390 NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_wear_reply, "Reply", createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
391 mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
392 mUnreadBuilder.setReplyAction(createReplyIntent(conversation, true), remoteInput);
393 mUnreadBuilder.setReadPendingIntent(createReadPendingIntent(conversation));
394 mBuilder.extend(new NotificationCompat.CarExtender().setUnreadConversation(mUnreadBuilder.build()));
395 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
396 mBuilder.addAction(replyAction);
397 }
398 if ((message = getFirstDownloadableMessage(messages)) != null) {
399 mBuilder.addAction(
400 Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ?
401 R.drawable.ic_file_download_white_24dp : R.drawable.ic_action_download,
402 mXmppConnectionService.getResources().getString(R.string.download_x_file,
403 UIHelper.getFileDescriptionString(mXmppConnectionService, message)),
404 createDownloadIntent(message)
405 );
406 }
407 if ((message = getFirstLocationMessage(messages)) != null) {
408 mBuilder.addAction(R.drawable.ic_room_white_24dp,
409 mXmppConnectionService.getString(R.string.show_location),
410 createShowLocationIntent(message));
411 }
412 }
413 if (conversation.getMode() == Conversation.MODE_SINGLE) {
414 Contact contact = conversation.getContact();
415 Uri systemAccount = contact.getSystemAccount();
416 if (systemAccount != null) {
417 mBuilder.addPerson(systemAccount.toString());
418 }
419 }
420 mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
421 mBuilder.setSmallIcon(R.drawable.ic_notification);
422 mBuilder.setDeleteIntent(createDeleteIntent(conversation));
423 mBuilder.setContentIntent(createContentIntent(conversation));
424 }
425 return mBuilder;
426 }
427
428 private void modifyForImage(final Builder builder, final UnreadConversation.Builder uBuilder,
429 final Message message, final ArrayList<Message> messages) {
430 try {
431 final Bitmap bitmap = mXmppConnectionService.getFileBackend()
432 .getThumbnail(message, getPixel(288), false);
433 final ArrayList<Message> tmp = new ArrayList<>();
434 for (final Message msg : messages) {
435 if (msg.getType() == Message.TYPE_TEXT
436 && msg.getTransferable() == null) {
437 tmp.add(msg);
438 }
439 }
440 final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
441 bigPictureStyle.bigPicture(bitmap);
442 if (tmp.size() > 0) {
443 CharSequence text = getMergedBodies(tmp);
444 bigPictureStyle.setSummaryText(text);
445 builder.setContentText(text);
446 } else {
447 builder.setContentText(mXmppConnectionService.getString(
448 R.string.received_x_file,
449 UIHelper.getFileDescriptionString(mXmppConnectionService, message)));
450 }
451 builder.setStyle(bigPictureStyle);
452 } catch (final FileNotFoundException e) {
453 modifyForTextOnly(builder, uBuilder, messages);
454 }
455 }
456
457 private void modifyForTextOnly(final Builder builder, final UnreadConversation.Builder uBuilder, final ArrayList<Message> messages) {
458 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
459 NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(mXmppConnectionService.getString(R.string.me));
460 Conversation conversation = messages.get(0).getConversation();
461 if (conversation.getMode() == Conversation.MODE_MULTI) {
462 messagingStyle.setConversationTitle(conversation.getName());
463 }
464 for (Message message : messages) {
465 String sender = message.getStatus() == Message.STATUS_RECEIVED ? UIHelper.getMessageDisplayName(message) : null;
466 messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService,message).first, message.getTimeSent(), sender);
467 }
468 builder.setStyle(messagingStyle);
469 } else {
470 if(messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE) {
471 builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
472 builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
473 } else {
474 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
475 SpannableString styledString;
476 for (Message message : messages) {
477 final String name = UIHelper.getMessageDisplayName(message);
478 styledString = new SpannableString(name + ": " + message.getBody());
479 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
480 style.addLine(styledString);
481 }
482 builder.setStyle(style);
483 int count = messages.size();
484 if(count == 1) {
485 final String name = UIHelper.getMessageDisplayName(messages.get(0));
486 styledString = new SpannableString(name + ": " + messages.get(0).getBody());
487 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
488 builder.setContentText(styledString);
489 } else {
490 builder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count));
491 }
492 }
493 }
494 /** message preview for Android Auto **/
495 for (Message message : messages) {
496 Pair<String,Boolean> preview = UIHelper.getMessagePreview(mXmppConnectionService, message);
497 // only show user written text
498 if (preview.second == false) {
499 uBuilder.addMessage(preview.first);
500 uBuilder.setLatestTimestamp(message.getTimeSent());
501 }
502 }
503 }
504
505 private Message getImage(final Iterable<Message> messages) {
506 Message image = null;
507 for (final Message message : messages) {
508 if (message.getStatus() != Message.STATUS_RECEIVED) {
509 return null;
510 }
511 if (message.getType() != Message.TYPE_TEXT
512 && message.getTransferable() == null
513 && message.getEncryption() != Message.ENCRYPTION_PGP
514 && message.getFileParams().height > 0) {
515 image = message;
516 }
517 }
518 return image;
519 }
520
521 private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
522 for (final Message message : messages) {
523 if (message.getTransferable() != null || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
524 return message;
525 }
526 }
527 return null;
528 }
529
530 private Message getFirstLocationMessage(final Iterable<Message> messages) {
531 for (final Message message : messages) {
532 if (GeoHelper.isGeoUri(message.getBody())) {
533 return message;
534 }
535 }
536 return null;
537 }
538
539 private CharSequence getMergedBodies(final ArrayList<Message> messages) {
540 final StringBuilder text = new StringBuilder();
541 for(Message message : messages) {
542 if (text.length() != 0) {
543 text.append("\n");
544 }
545 text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
546 }
547 return text.toString();
548 }
549
550 private PendingIntent createShowLocationIntent(final Message message) {
551 Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(message);
552 for (Intent intent : intents) {
553 if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
554 return PendingIntent.getActivity(mXmppConnectionService, 18, intent, PendingIntent.FLAG_UPDATE_CURRENT);
555 }
556 }
557 return createOpenConversationsIntent();
558 }
559
560 private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
561 final Intent viewConversationIntent = new Intent(mXmppConnectionService,ConversationActivity.class);
562 viewConversationIntent.setAction(ConversationActivity.ACTION_VIEW_CONVERSATION);
563 viewConversationIntent.putExtra(ConversationActivity.CONVERSATION, conversationUuid);
564 if (downloadMessageUuid != null) {
565 viewConversationIntent.putExtra(ConversationActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
566 return PendingIntent.getActivity(mXmppConnectionService,
567 (conversationUuid.hashCode() % NOTIFICATION_ID_MULTIPLIER) + 8 * NOTIFICATION_ID_MULTIPLIER,
568 viewConversationIntent,
569 PendingIntent.FLAG_UPDATE_CURRENT);
570 } else {
571 return PendingIntent.getActivity(mXmppConnectionService,
572 (conversationUuid.hashCode() % NOTIFICATION_ID_MULTIPLIER) + 10 * NOTIFICATION_ID_MULTIPLIER,
573 viewConversationIntent,
574 PendingIntent.FLAG_UPDATE_CURRENT);
575 }
576 }
577
578 private PendingIntent createDownloadIntent(final Message message) {
579 return createContentIntent(message.getConversationUuid(), message.getUuid());
580 }
581
582 private PendingIntent createContentIntent(final Conversation conversation) {
583 return createContentIntent(conversation.getUuid(), null);
584 }
585
586 private PendingIntent createDeleteIntent(Conversation conversation) {
587 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
588 intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
589 if (conversation != null) {
590 intent.putExtra("uuid", conversation.getUuid());
591 return PendingIntent.getService(mXmppConnectionService, (conversation.getUuid().hashCode() % NOTIFICATION_ID_MULTIPLIER) + 12 * NOTIFICATION_ID_MULTIPLIER, intent, 0);
592 }
593 return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
594 }
595
596 private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
597 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
598 intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
599 intent.putExtra("uuid",conversation.getUuid());
600 intent.putExtra("dismiss_notification",dismissAfterReply);
601 int id = (conversation.getUuid().hashCode() % NOTIFICATION_ID_MULTIPLIER) + (dismissAfterReply ? 12 : 14) * NOTIFICATION_ID_MULTIPLIER;
602 return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
603 }
604
605 private PendingIntent createReadPendingIntent(Conversation conversation) {
606 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
607 intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
608 intent.putExtra("uuid", conversation.getUuid());
609 intent.setPackage(mXmppConnectionService.getPackageName());
610 return PendingIntent.getService(mXmppConnectionService, (conversation.getUuid().hashCode() % NOTIFICATION_ID_MULTIPLIER) + 16 * NOTIFICATION_ID_MULTIPLIER, intent, PendingIntent.FLAG_UPDATE_CURRENT);
611 }
612
613 private PendingIntent createDisableForeground() {
614 final Intent intent = new Intent(mXmppConnectionService,
615 XmppConnectionService.class);
616 intent.setAction(XmppConnectionService.ACTION_DISABLE_FOREGROUND);
617 return PendingIntent.getService(mXmppConnectionService, 34, intent, 0);
618 }
619
620 private PendingIntent createTryAgainIntent() {
621 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
622 intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
623 return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
624 }
625
626 private PendingIntent createDismissErrorIntent() {
627 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
628 intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
629 return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
630 }
631
632 private boolean wasHighlightedOrPrivate(final Message message) {
633 final String nick = message.getConversation().getMucOptions().getActualNick();
634 final Pattern highlight = generateNickHighlightPattern(nick);
635 if (message.getBody() == null || nick == null) {
636 return false;
637 }
638 final Matcher m = highlight.matcher(message.getBody());
639 return (m.find() || message.getType() == Message.TYPE_PRIVATE);
640 }
641
642 public static Pattern generateNickHighlightPattern(final String nick) {
643 // We expect a word boundary, i.e. space or start of string, followed by
644 // the
645 // nick (matched in case-insensitive manner), followed by optional
646 // punctuation (for example "bob: i disagree" or "how are you alice?"),
647 // followed by another word boundary.
648 return Pattern.compile("\\b" + Pattern.quote(nick) + "\\p{Punct}?\\b",
649 Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
650 }
651
652 public void setOpenConversation(final Conversation conversation) {
653 this.mOpenConversation = conversation;
654 }
655
656 public void setIsInForeground(final boolean foreground) {
657 this.mIsInForeground = foreground;
658 }
659
660 private int getPixel(final int dp) {
661 final DisplayMetrics metrics = mXmppConnectionService.getResources()
662 .getDisplayMetrics();
663 return ((int) (dp * metrics.density));
664 }
665
666 private void markLastNotification() {
667 this.mLastNotification = SystemClock.elapsedRealtime();
668 }
669
670 private boolean inMiniGracePeriod(final Account account) {
671 final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
672 : Config.MINI_GRACE_PERIOD * 2;
673 return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
674 }
675
676 public Notification createForegroundNotification() {
677 final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
678
679 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
680 if (Config.SHOW_CONNECTED_ACCOUNTS) {
681 List<Account> accounts = mXmppConnectionService.getAccounts();
682 int enabled = 0;
683 int connected = 0;
684 for (Account account : accounts) {
685 if (account.isOnlineAndConnected()) {
686 connected++;
687 enabled++;
688 } else if (!account.isOptionSet(Account.OPTION_DISABLED)) {
689 enabled++;
690 }
691 }
692 mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
693 } else {
694 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_open_conversations));
695 }
696 mBuilder.setContentIntent(createOpenConversationsIntent());
697 mBuilder.setWhen(0);
698 mBuilder.setPriority(Config.SHOW_CONNECTED_ACCOUNTS ? NotificationCompat.PRIORITY_DEFAULT : NotificationCompat.PRIORITY_MIN);
699 mBuilder.setSmallIcon(R.drawable.ic_link_white_24dp);
700 if (Config.SHOW_DISABLE_FOREGROUND) {
701 final int cancelIcon;
702 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
703 mBuilder.setCategory(Notification.CATEGORY_SERVICE);
704 cancelIcon = R.drawable.ic_cancel_white_24dp;
705 } else {
706 cancelIcon = R.drawable.ic_action_cancel;
707 }
708 mBuilder.addAction(cancelIcon,
709 mXmppConnectionService.getString(R.string.disable_foreground_service),
710 createDisableForeground());
711 }
712 return mBuilder.build();
713 }
714
715 private PendingIntent createOpenConversationsIntent() {
716 return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationActivity.class), 0);
717 }
718
719 public void updateErrorNotification() {
720 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
721 final List<Account> errors = new ArrayList<>();
722 for (final Account account : mXmppConnectionService.getAccounts()) {
723 if (account.hasErrorStatus() && account.showErrorNotification()) {
724 errors.add(account);
725 }
726 }
727 if (mXmppConnectionService.getPreferences().getBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE, false)) {
728 notificationManager.notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
729 }
730 final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
731 if (errors.size() == 0) {
732 notificationManager.cancel(ERROR_NOTIFICATION_ID);
733 return;
734 } else if (errors.size() == 1) {
735 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
736 mBuilder.setContentText(errors.get(0).getJid().toBareJid().toString());
737 } else {
738 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
739 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
740 }
741 mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
742 mXmppConnectionService.getString(R.string.try_again),
743 createTryAgainIntent());
744 mBuilder.setDeleteIntent(createDismissErrorIntent());
745 mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
746 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
747 mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
748 } else {
749 mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
750 }
751 mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService,
752 145,
753 new Intent(mXmppConnectionService,ManageAccountActivity.class),
754 PendingIntent.FLAG_UPDATE_CURRENT));
755 notificationManager.notify(ERROR_NOTIFICATION_ID, mBuilder.build());
756 }
757}