1package eu.siacs.conversations.services;
2
3import android.app.Notification;
4import android.app.NotificationChannel;
5import android.app.NotificationChannelGroup;
6import android.app.NotificationManager;
7import android.app.PendingIntent;
8import android.content.Context;
9import android.content.Intent;
10import android.content.SharedPreferences;
11import android.content.res.Resources;
12import android.graphics.Bitmap;
13import android.graphics.Typeface;
14import android.media.AudioAttributes;
15import android.media.Ringtone;
16import android.media.RingtoneManager;
17import android.net.Uri;
18import android.os.Build;
19import android.os.SystemClock;
20import android.os.Vibrator;
21import android.preference.PreferenceManager;
22import android.text.SpannableString;
23import android.text.style.StyleSpan;
24import android.util.DisplayMetrics;
25import android.util.Log;
26
27import androidx.annotation.RequiresApi;
28import androidx.core.app.NotificationCompat;
29import androidx.core.app.NotificationCompat.BigPictureStyle;
30import androidx.core.app.NotificationCompat.Builder;
31import androidx.core.app.NotificationManagerCompat;
32import androidx.core.app.Person;
33import androidx.core.app.RemoteInput;
34import androidx.core.content.ContextCompat;
35import androidx.core.graphics.drawable.IconCompat;
36
37import java.io.File;
38import java.io.IOException;
39import java.util.ArrayList;
40import java.util.Calendar;
41import java.util.Collections;
42import java.util.HashMap;
43import java.util.Iterator;
44import java.util.LinkedHashMap;
45import java.util.List;
46import java.util.Map;
47import java.util.Set;
48import java.util.concurrent.Executors;
49import java.util.concurrent.ScheduledExecutorService;
50import java.util.concurrent.ScheduledFuture;
51import java.util.concurrent.TimeUnit;
52import java.util.concurrent.atomic.AtomicInteger;
53import java.util.regex.Matcher;
54import java.util.regex.Pattern;
55
56import eu.siacs.conversations.Config;
57import eu.siacs.conversations.R;
58import eu.siacs.conversations.entities.Account;
59import eu.siacs.conversations.entities.Contact;
60import eu.siacs.conversations.entities.Conversation;
61import eu.siacs.conversations.entities.Conversational;
62import eu.siacs.conversations.entities.Message;
63import eu.siacs.conversations.persistance.FileBackend;
64import eu.siacs.conversations.ui.ConversationsActivity;
65import eu.siacs.conversations.ui.EditAccountActivity;
66import eu.siacs.conversations.ui.RtpSessionActivity;
67import eu.siacs.conversations.ui.TimePreference;
68import eu.siacs.conversations.utils.AccountUtils;
69import eu.siacs.conversations.utils.Compatibility;
70import eu.siacs.conversations.utils.GeoHelper;
71import eu.siacs.conversations.utils.TorServiceUtils;
72import eu.siacs.conversations.utils.UIHelper;
73import eu.siacs.conversations.xmpp.XmppConnection;
74import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
75import eu.siacs.conversations.xmpp.jingle.Media;
76
77public class NotificationService {
78
79 private static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE = Executors.newSingleThreadScheduledExecutor();
80
81 public static final Object CATCHUP_LOCK = new Object();
82
83 private static final int LED_COLOR = 0xff00ff00;
84
85 private static final long[] CALL_PATTERN = {0, 500, 300, 600};
86
87 private static final String CONVERSATIONS_GROUP = "eu.siacs.conversations";
88 private static final int NOTIFICATION_ID_MULTIPLIER = 1024 * 1024;
89 static final int FOREGROUND_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 4;
90 private static final int NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 2;
91 private static final int ERROR_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 6;
92 private static final int INCOMING_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 8;
93 public static final int ONGOING_CALL_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 10;
94 private static final int DELIVERY_FAILED_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 12;
95 private final XmppConnectionService mXmppConnectionService;
96 private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
97 private final HashMap<Conversation, AtomicInteger> mBacklogMessageCounter = new HashMap<>();
98 private Conversation mOpenConversation;
99 private boolean mIsInForeground;
100 private long mLastNotification;
101
102 private static final String INCOMING_CALLS_NOTIFICATION_CHANNEL = "incoming_calls_channel";
103 private Ringtone currentlyPlayingRingtone = null;
104 private ScheduledFuture<?> vibrationFuture;
105
106 NotificationService(final XmppConnectionService service) {
107 this.mXmppConnectionService = service;
108 }
109
110 private static boolean displaySnoozeAction(List<Message> messages) {
111 int numberOfMessagesWithoutReply = 0;
112 for (Message message : messages) {
113 if (message.getStatus() == Message.STATUS_RECEIVED) {
114 ++numberOfMessagesWithoutReply;
115 } else {
116 return false;
117 }
118 }
119 return numberOfMessagesWithoutReply >= 3;
120 }
121
122 public static Pattern generateNickHighlightPattern(final String nick) {
123 return Pattern.compile("(?<=(^|\\s))" + Pattern.quote(nick) + "(?=\\s|$|\\p{Punct})");
124 }
125
126 private static boolean isImageMessage(Message message) {
127 return message.getType() != Message.TYPE_TEXT
128 && message.getTransferable() == null
129 && !message.isDeleted()
130 && message.getEncryption() != Message.ENCRYPTION_PGP
131 && message.getFileParams().height > 0;
132 }
133
134 @RequiresApi(api = Build.VERSION_CODES.O)
135 void initializeChannels() {
136 final Context c = mXmppConnectionService;
137 final NotificationManager notificationManager = c.getSystemService(NotificationManager.class);
138 if (notificationManager == null) {
139 return;
140 }
141
142 notificationManager.deleteNotificationChannel("export");
143 notificationManager.deleteNotificationChannel("incoming_calls");
144
145 notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("status", c.getString(R.string.notification_group_status_information)));
146 notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("chats", c.getString(R.string.notification_group_messages)));
147 notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("calls", c.getString(R.string.notification_group_calls)));
148 final NotificationChannel foregroundServiceChannel = new NotificationChannel("foreground",
149 c.getString(R.string.foreground_service_channel_name),
150 NotificationManager.IMPORTANCE_MIN);
151 foregroundServiceChannel.setDescription(c.getString(R.string.foreground_service_channel_description, c.getString(R.string.app_name)));
152 foregroundServiceChannel.setShowBadge(false);
153 foregroundServiceChannel.setGroup("status");
154 notificationManager.createNotificationChannel(foregroundServiceChannel);
155 final NotificationChannel errorChannel = new NotificationChannel("error",
156 c.getString(R.string.error_channel_name),
157 NotificationManager.IMPORTANCE_LOW);
158 errorChannel.setDescription(c.getString(R.string.error_channel_description));
159 errorChannel.setShowBadge(false);
160 errorChannel.setGroup("status");
161 notificationManager.createNotificationChannel(errorChannel);
162
163 final NotificationChannel videoCompressionChannel = new NotificationChannel("compression",
164 c.getString(R.string.video_compression_channel_name),
165 NotificationManager.IMPORTANCE_LOW);
166 videoCompressionChannel.setShowBadge(false);
167 videoCompressionChannel.setGroup("status");
168 notificationManager.createNotificationChannel(videoCompressionChannel);
169
170 final NotificationChannel exportChannel = new NotificationChannel("backup",
171 c.getString(R.string.backup_channel_name),
172 NotificationManager.IMPORTANCE_LOW);
173 exportChannel.setShowBadge(false);
174 exportChannel.setGroup("status");
175 notificationManager.createNotificationChannel(exportChannel);
176
177 final NotificationChannel incomingCallsChannel = new NotificationChannel(INCOMING_CALLS_NOTIFICATION_CHANNEL,
178 c.getString(R.string.incoming_calls_channel_name),
179 NotificationManager.IMPORTANCE_HIGH);
180 incomingCallsChannel.setSound(null, null);
181 incomingCallsChannel.setShowBadge(false);
182 incomingCallsChannel.setLightColor(LED_COLOR);
183 incomingCallsChannel.enableLights(true);
184 incomingCallsChannel.setGroup("calls");
185 incomingCallsChannel.setBypassDnd(true);
186 incomingCallsChannel.enableVibration(false);
187 notificationManager.createNotificationChannel(incomingCallsChannel);
188
189 final NotificationChannel ongoingCallsChannel = new NotificationChannel("ongoing_calls",
190 c.getString(R.string.ongoing_calls_channel_name),
191 NotificationManager.IMPORTANCE_LOW);
192 ongoingCallsChannel.setShowBadge(false);
193 ongoingCallsChannel.setGroup("calls");
194 notificationManager.createNotificationChannel(ongoingCallsChannel);
195
196
197 final NotificationChannel messagesChannel = new NotificationChannel("messages",
198 c.getString(R.string.messages_channel_name),
199 NotificationManager.IMPORTANCE_HIGH);
200 messagesChannel.setShowBadge(true);
201 messagesChannel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), new AudioAttributes.Builder()
202 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
203 .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT)
204 .build());
205 messagesChannel.setLightColor(LED_COLOR);
206 final int dat = 70;
207 final long[] pattern = {0, 3 * dat, dat, dat};
208 messagesChannel.setVibrationPattern(pattern);
209 messagesChannel.enableVibration(true);
210 messagesChannel.enableLights(true);
211 messagesChannel.setGroup("chats");
212 notificationManager.createNotificationChannel(messagesChannel);
213 final NotificationChannel silentMessagesChannel = new NotificationChannel("silent_messages",
214 c.getString(R.string.silent_messages_channel_name),
215 NotificationManager.IMPORTANCE_LOW);
216 silentMessagesChannel.setDescription(c.getString(R.string.silent_messages_channel_description));
217 silentMessagesChannel.setShowBadge(true);
218 silentMessagesChannel.setLightColor(LED_COLOR);
219 silentMessagesChannel.enableLights(true);
220 silentMessagesChannel.setGroup("chats");
221 notificationManager.createNotificationChannel(silentMessagesChannel);
222
223 final NotificationChannel quietHoursChannel = new NotificationChannel("quiet_hours",
224 c.getString(R.string.title_pref_quiet_hours),
225 NotificationManager.IMPORTANCE_LOW);
226 quietHoursChannel.setShowBadge(true);
227 quietHoursChannel.setLightColor(LED_COLOR);
228 quietHoursChannel.enableLights(true);
229 quietHoursChannel.setGroup("chats");
230 quietHoursChannel.enableVibration(false);
231 quietHoursChannel.setSound(null, null);
232
233 notificationManager.createNotificationChannel(quietHoursChannel);
234
235 final NotificationChannel deliveryFailedChannel = new NotificationChannel("delivery_failed",
236 c.getString(R.string.delivery_failed_channel_name),
237 NotificationManager.IMPORTANCE_DEFAULT);
238 deliveryFailedChannel.setShowBadge(false);
239 deliveryFailedChannel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), new AudioAttributes.Builder()
240 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
241 .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT)
242 .build());
243 deliveryFailedChannel.setGroup("chats");
244 notificationManager.createNotificationChannel(deliveryFailedChannel);
245 }
246
247 private boolean notify(final Message message) {
248 final Conversation conversation = (Conversation) message.getConversation();
249 return message.getStatus() == Message.STATUS_RECEIVED
250 && !conversation.isMuted()
251 && (conversation.alwaysNotify() || wasHighlightedOrPrivate(message))
252 && (!conversation.isWithStranger() || notificationsFromStrangers());
253 }
254
255 public boolean notificationsFromStrangers() {
256 return mXmppConnectionService.getBooleanPreference("notifications_from_strangers", R.bool.notifications_from_strangers);
257 }
258
259 private boolean isQuietHours() {
260 if (!mXmppConnectionService.getBooleanPreference("enable_quiet_hours", R.bool.enable_quiet_hours)) {
261 return false;
262 }
263 final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
264 final long startTime = TimePreference.minutesToTimestamp(preferences.getLong("quiet_hours_start", TimePreference.DEFAULT_VALUE));
265 final long endTime = TimePreference.minutesToTimestamp(preferences.getLong("quiet_hours_end", TimePreference.DEFAULT_VALUE));
266 final long nowTime = Calendar.getInstance().getTimeInMillis();
267
268 if (endTime < startTime) {
269 return nowTime > startTime || nowTime < endTime;
270 } else {
271 return nowTime > startTime && nowTime < endTime;
272 }
273 }
274
275 public void pushFromBacklog(final Message message) {
276 if (notify(message)) {
277 synchronized (notifications) {
278 getBacklogMessageCounter((Conversation) message.getConversation()).incrementAndGet();
279 pushToStack(message);
280 }
281 }
282 }
283
284 private AtomicInteger getBacklogMessageCounter(Conversation conversation) {
285 synchronized (mBacklogMessageCounter) {
286 if (!mBacklogMessageCounter.containsKey(conversation)) {
287 mBacklogMessageCounter.put(conversation, new AtomicInteger(0));
288 }
289 return mBacklogMessageCounter.get(conversation);
290 }
291 }
292
293 void pushFromDirectReply(final Message message) {
294 synchronized (notifications) {
295 pushToStack(message);
296 updateNotification(false);
297 }
298 }
299
300 public void finishBacklog(boolean notify, Account account) {
301 synchronized (notifications) {
302 mXmppConnectionService.updateUnreadCountBadge();
303 if (account == null || !notify) {
304 updateNotification(notify);
305 } else {
306 final int count;
307 final List<String> conversations;
308 synchronized (this.mBacklogMessageCounter) {
309 conversations = getBacklogConversations(account);
310 count = getBacklogMessageCount(account);
311 }
312 updateNotification(count > 0, conversations);
313 }
314 }
315 }
316
317 private List<String> getBacklogConversations(Account account) {
318 final List<String> conversations = new ArrayList<>();
319 for (Map.Entry<Conversation, AtomicInteger> entry : mBacklogMessageCounter.entrySet()) {
320 if (entry.getKey().getAccount() == account) {
321 conversations.add(entry.getKey().getUuid());
322 }
323 }
324 return conversations;
325 }
326
327 private int getBacklogMessageCount(Account account) {
328 int count = 0;
329 for (Iterator<Map.Entry<Conversation, AtomicInteger>> it = mBacklogMessageCounter.entrySet().iterator(); it.hasNext(); ) {
330 Map.Entry<Conversation, AtomicInteger> entry = it.next();
331 if (entry.getKey().getAccount() == account) {
332 count += entry.getValue().get();
333 it.remove();
334 }
335 }
336 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": backlog message count=" + count);
337 return count;
338 }
339
340 void finishBacklog(boolean notify) {
341 finishBacklog(notify, null);
342 }
343
344 private void pushToStack(final Message message) {
345 final String conversationUuid = message.getConversationUuid();
346 if (notifications.containsKey(conversationUuid)) {
347 notifications.get(conversationUuid).add(message);
348 } else {
349 final ArrayList<Message> mList = new ArrayList<>();
350 mList.add(message);
351 notifications.put(conversationUuid, mList);
352 }
353 }
354
355 public void push(final Message message) {
356 synchronized (CATCHUP_LOCK) {
357 final XmppConnection connection = message.getConversation().getAccount().getXmppConnection();
358 if (connection != null && connection.isWaitingForSmCatchup()) {
359 connection.incrementSmCatchupMessageCounter();
360 pushFromBacklog(message);
361 } else {
362 pushNow(message);
363 }
364 }
365 }
366
367 public void pushFailedDelivery(final Message message) {
368 final Conversation conversation = (Conversation) message.getConversation();
369 final boolean isScreenOn = mXmppConnectionService.isInteractive();
370 if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
371 Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing failed delivery notification because conversation is open");
372 return;
373 }
374 final PendingIntent pendingIntent = createContentIntent(conversation);
375 final int notificationId = generateRequestCode(conversation, 0) + DELIVERY_FAILED_NOTIFICATION_ID;
376 final int failedDeliveries = conversation.countFailedDeliveries();
377 final Notification notification =
378 new Builder(mXmppConnectionService, "delivery_failed")
379 .setContentTitle(conversation.getName())
380 .setAutoCancel(true)
381 .setSmallIcon(R.drawable.ic_error_white_24dp)
382 .setContentText(mXmppConnectionService.getResources().getQuantityText(R.plurals.some_messages_could_not_be_delivered, failedDeliveries))
383 .setGroup("delivery_failed")
384 .setContentIntent(pendingIntent).build();
385 final Notification summaryNotification =
386 new Builder(mXmppConnectionService, "delivery_failed")
387 .setContentTitle(mXmppConnectionService.getString(R.string.failed_deliveries))
388 .setContentText(mXmppConnectionService.getResources().getQuantityText(R.plurals.some_messages_could_not_be_delivered, 1024))
389 .setSmallIcon(R.drawable.ic_error_white_24dp)
390 .setGroup("delivery_failed")
391 .setGroupSummary(true)
392 .setAutoCancel(true)
393 .build();
394 notify(notificationId, notification);
395 notify(DELIVERY_FAILED_NOTIFICATION_ID, summaryNotification);
396 }
397
398 public void startRinging(final AbstractJingleConnection.Id id, final Set<Media> media) {
399 showIncomingCallNotification(id, media);
400 final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
401 final Resources resources = mXmppConnectionService.getResources();
402 final Uri uri = Uri.parse(preferences.getString("call_ringtone", resources.getString(R.string.incoming_call_ringtone)));
403 this.currentlyPlayingRingtone = RingtoneManager.getRingtone(mXmppConnectionService, uri);
404 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
405 this.currentlyPlayingRingtone.setLooping(true);
406 }
407 this.currentlyPlayingRingtone.play();
408 this.vibrationFuture = SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(
409 new VibrationRunnable(),
410 0,
411 3,
412 TimeUnit.SECONDS
413 );
414 }
415
416 private void showIncomingCallNotification(final AbstractJingleConnection.Id id, final Set<Media> media) {
417 final Intent fullScreenIntent = new Intent(mXmppConnectionService, RtpSessionActivity.class);
418 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.account.getJid().asBareJid().toEscapedString());
419 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
420 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
421 fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
422 fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
423 final NotificationCompat.Builder builder = new NotificationCompat.Builder(mXmppConnectionService, INCOMING_CALLS_NOTIFICATION_CHANNEL);
424 if (media.contains(Media.VIDEO)) {
425 builder.setSmallIcon(R.drawable.ic_videocam_white_24dp);
426 builder.setContentTitle(mXmppConnectionService.getString(R.string.rtp_state_incoming_video_call));
427 } else {
428 builder.setSmallIcon(R.drawable.ic_call_white_24dp);
429 builder.setContentTitle(mXmppConnectionService.getString(R.string.rtp_state_incoming_call));
430 }
431 final Contact contact = id.getContact();
432 builder.setLargeIcon(mXmppConnectionService.getAvatarService().get(
433 contact,
434 AvatarService.getSystemUiAvatarSize(mXmppConnectionService))
435 );
436 final Uri systemAccount = contact.getSystemAccount();
437 if (systemAccount != null) {
438 builder.addPerson(systemAccount.toString());
439 }
440 builder.setContentText(id.account.getRoster().getContact(id.with).getDisplayName());
441 builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
442 builder.setPriority(NotificationCompat.PRIORITY_HIGH);
443 builder.setCategory(NotificationCompat.CATEGORY_CALL);
444 PendingIntent pendingIntent = createPendingRtpSession(id, Intent.ACTION_VIEW, 101);
445 builder.setFullScreenIntent(pendingIntent, true);
446 builder.setContentIntent(pendingIntent); //old androids need this?
447 builder.setOngoing(true);
448 builder.addAction(new NotificationCompat.Action.Builder(
449 R.drawable.ic_call_end_white_48dp,
450 mXmppConnectionService.getString(R.string.dismiss_call),
451 createCallAction(id.sessionId, XmppConnectionService.ACTION_DISMISS_CALL, 102))
452 .build());
453 builder.addAction(new NotificationCompat.Action.Builder(
454 R.drawable.ic_call_white_24dp,
455 mXmppConnectionService.getString(R.string.answer_call),
456 createPendingRtpSession(id, RtpSessionActivity.ACTION_ACCEPT_CALL, 103))
457 .build());
458 modifyIncomingCall(builder);
459 final Notification notification = builder.build();
460 notification.flags = notification.flags | Notification.FLAG_INSISTENT;
461 notify(INCOMING_CALL_NOTIFICATION_ID, notification);
462 }
463
464 public Notification getOngoingCallNotification(final AbstractJingleConnection.Id id, final Set<Media> media) {
465 final NotificationCompat.Builder builder = new NotificationCompat.Builder(mXmppConnectionService, "ongoing_calls");
466 if (media.contains(Media.VIDEO)) {
467 builder.setSmallIcon(R.drawable.ic_videocam_white_24dp);
468 builder.setContentTitle(mXmppConnectionService.getString(R.string.ongoing_video_call));
469 } else {
470 builder.setSmallIcon(R.drawable.ic_call_white_24dp);
471 builder.setContentTitle(mXmppConnectionService.getString(R.string.ongoing_call));
472 }
473 builder.setContentText(id.account.getRoster().getContact(id.with).getDisplayName());
474 builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
475 builder.setPriority(NotificationCompat.PRIORITY_HIGH);
476 builder.setCategory(NotificationCompat.CATEGORY_CALL);
477 builder.setContentIntent(createPendingRtpSession(id, Intent.ACTION_VIEW, 101));
478 builder.setOngoing(true);
479 builder.addAction(new NotificationCompat.Action.Builder(
480 R.drawable.ic_call_end_white_48dp,
481 mXmppConnectionService.getString(R.string.hang_up),
482 createCallAction(id.sessionId, XmppConnectionService.ACTION_END_CALL, 104))
483 .build());
484 return builder.build();
485 }
486
487 private PendingIntent createPendingRtpSession(final AbstractJingleConnection.Id id, final String action, final int requestCode) {
488 final Intent fullScreenIntent = new Intent(mXmppConnectionService, RtpSessionActivity.class);
489 fullScreenIntent.setAction(action);
490 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.account.getJid().asBareJid().toEscapedString());
491 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
492 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
493 return PendingIntent.getActivity(mXmppConnectionService, requestCode, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);
494 }
495
496 public void cancelIncomingCallNotification() {
497 stopSoundAndVibration();
498 cancel(INCOMING_CALL_NOTIFICATION_ID);
499 }
500
501 public boolean stopSoundAndVibration() {
502 int stopped = 0;
503 if (this.currentlyPlayingRingtone != null) {
504 if (this.currentlyPlayingRingtone.isPlaying()) {
505 Log.d(Config.LOGTAG, "stop playing ring tone");
506 ++stopped;
507 }
508 this.currentlyPlayingRingtone.stop();
509 }
510 if (this.vibrationFuture != null && !this.vibrationFuture.isCancelled()) {
511 Log.d(Config.LOGTAG, "stop vibration");
512 this.vibrationFuture.cancel(true);
513 ++stopped;
514 }
515 return stopped > 0;
516 }
517
518 public static void cancelIncomingCallNotification(final Context context) {
519 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
520 try {
521 notificationManager.cancel(INCOMING_CALL_NOTIFICATION_ID);
522 } catch (RuntimeException e) {
523 Log.d(Config.LOGTAG, "unable to cancel incoming call notification after crash", e);
524 }
525 }
526
527 private void pushNow(final Message message) {
528 mXmppConnectionService.updateUnreadCountBadge();
529 if (!notify(message)) {
530 Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because turned off");
531 return;
532 }
533 final boolean isScreenOn = mXmppConnectionService.isInteractive();
534 if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
535 Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because conversation is open");
536 return;
537 }
538 synchronized (notifications) {
539 pushToStack(message);
540 final Conversational conversation = message.getConversation();
541 final Account account = conversation.getAccount();
542 final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
543 && !account.inGracePeriod()
544 && !this.inMiniGracePeriod(account);
545 updateNotification(doNotify, Collections.singletonList(conversation.getUuid()));
546 }
547 }
548
549 public void clear() {
550 synchronized (notifications) {
551 for (ArrayList<Message> messages : notifications.values()) {
552 markAsReadIfHasDirectReply(messages);
553 }
554 notifications.clear();
555 updateNotification(false);
556 }
557 }
558
559 public void clear(final Conversation conversation) {
560 synchronized (this.mBacklogMessageCounter) {
561 this.mBacklogMessageCounter.remove(conversation);
562 }
563 synchronized (notifications) {
564 markAsReadIfHasDirectReply(conversation);
565 if (notifications.remove(conversation.getUuid()) != null) {
566 cancel(conversation.getUuid(), NOTIFICATION_ID);
567 updateNotification(false, null, true);
568 }
569 }
570 }
571
572 private void markAsReadIfHasDirectReply(final Conversation conversation) {
573 markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
574 }
575
576 private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
577 if (messages != null && messages.size() > 0) {
578 Message last = messages.get(messages.size() - 1);
579 if (last.getStatus() != Message.STATUS_RECEIVED) {
580 if (mXmppConnectionService.markRead((Conversation) last.getConversation(), false)) {
581 mXmppConnectionService.updateConversationUi();
582 }
583 }
584 }
585 }
586
587 private void setNotificationColor(final Builder mBuilder) {
588 mBuilder.setColor(ContextCompat.getColor(mXmppConnectionService, R.color.green600));
589 }
590
591 public void updateNotification() {
592 synchronized (notifications) {
593 updateNotification(false);
594 }
595 }
596
597 private void updateNotification(final boolean notify) {
598 updateNotification(notify, null, false);
599 }
600
601 private void updateNotification(final boolean notify, final List<String> conversations) {
602 updateNotification(notify, conversations, false);
603 }
604
605 private void updateNotification(final boolean notify, final List<String> conversations, final boolean summaryOnly) {
606 final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
607
608 final boolean quiteHours = isQuietHours();
609
610 final boolean notifyOnlyOneChild = notify && conversations != null && conversations.size() == 1; //if this check is changed to > 0 catchup messages will create one notification per conversation
611
612
613 if (notifications.size() == 0) {
614 cancel(NOTIFICATION_ID);
615 } else {
616 if (notify) {
617 this.markLastNotification();
618 }
619 final Builder mBuilder;
620 if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
621 mBuilder = buildSingleConversations(notifications.values().iterator().next(), notify, quiteHours);
622 modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
623 notify(NOTIFICATION_ID, mBuilder.build());
624 } else {
625 mBuilder = buildMultipleConversation(notify, quiteHours);
626 if (notifyOnlyOneChild) {
627 mBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
628 }
629 modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
630 if (!summaryOnly) {
631 for (Map.Entry<String, ArrayList<Message>> entry : notifications.entrySet()) {
632 String uuid = entry.getKey();
633 final boolean notifyThis = notifyOnlyOneChild ? conversations.contains(uuid) : notify;
634 Builder singleBuilder = buildSingleConversations(entry.getValue(), notifyThis, quiteHours);
635 if (!notifyOnlyOneChild) {
636 singleBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY);
637 }
638 modifyForSoundVibrationAndLight(singleBuilder, notifyThis, quiteHours, preferences);
639 singleBuilder.setGroup(CONVERSATIONS_GROUP);
640 setNotificationColor(singleBuilder);
641 notify(entry.getKey(), NOTIFICATION_ID, singleBuilder.build());
642 }
643 }
644 notify(NOTIFICATION_ID, mBuilder.build());
645 }
646 }
647 }
648
649 private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, boolean quietHours, SharedPreferences preferences) {
650 final Resources resources = mXmppConnectionService.getResources();
651 final String ringtone = preferences.getString("notification_ringtone", resources.getString(R.string.notification_ringtone));
652 final boolean vibrate = preferences.getBoolean("vibrate_on_notification", resources.getBoolean(R.bool.vibrate_on_notification));
653 final boolean led = preferences.getBoolean("led", resources.getBoolean(R.bool.led));
654 final boolean headsup = preferences.getBoolean("notification_headsup", resources.getBoolean(R.bool.headsup_notifications));
655 if (notify && !quietHours) {
656 if (vibrate) {
657 final int dat = 70;
658 final long[] pattern = {0, 3 * dat, dat, dat};
659 mBuilder.setVibrate(pattern);
660 } else {
661 mBuilder.setVibrate(new long[]{0});
662 }
663 Uri uri = Uri.parse(ringtone);
664 try {
665 mBuilder.setSound(fixRingtoneUri(uri));
666 } catch (SecurityException e) {
667 Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
668 }
669 } else {
670 mBuilder.setLocalOnly(true);
671 }
672 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
673 mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
674 }
675 mBuilder.setPriority(notify ? (headsup ? NotificationCompat.PRIORITY_HIGH : NotificationCompat.PRIORITY_DEFAULT) : NotificationCompat.PRIORITY_LOW);
676 setNotificationColor(mBuilder);
677 mBuilder.setDefaults(0);
678 if (led) {
679 mBuilder.setLights(LED_COLOR, 2000, 3000);
680 }
681 }
682
683 private void modifyIncomingCall(final Builder mBuilder) {
684 mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
685 setNotificationColor(mBuilder);
686 mBuilder.setLights(LED_COLOR, 2000, 3000);
687 }
688
689 private Uri fixRingtoneUri(Uri uri) {
690 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && "file".equals(uri.getScheme())) {
691 return FileBackend.getUriForFile(mXmppConnectionService, new File(uri.getPath()));
692 } else {
693 return uri;
694 }
695 }
696
697 private Builder buildMultipleConversation(final boolean notify, final boolean quietHours) {
698 final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
699 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
700 style.setBigContentTitle(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_unread_conversations, notifications.size(), notifications.size()));
701 final StringBuilder names = new StringBuilder();
702 Conversation conversation = null;
703 for (final ArrayList<Message> messages : notifications.values()) {
704 if (messages.size() > 0) {
705 conversation = (Conversation) messages.get(0).getConversation();
706 final String name = conversation.getName().toString();
707 SpannableString styledString;
708 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
709 int count = messages.size();
710 styledString = new SpannableString(name + ": " + mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
711 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
712 style.addLine(styledString);
713 } else {
714 styledString = new SpannableString(name + ": " + UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
715 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
716 style.addLine(styledString);
717 }
718 names.append(name);
719 names.append(", ");
720 }
721 }
722 if (names.length() >= 2) {
723 names.delete(names.length() - 2, names.length());
724 }
725 final String contentTitle = mXmppConnectionService.getResources().getQuantityString(R.plurals.x_unread_conversations, notifications.size(), notifications.size());
726 mBuilder.setContentTitle(contentTitle);
727 mBuilder.setTicker(contentTitle);
728 mBuilder.setContentText(names.toString());
729 mBuilder.setStyle(style);
730 if (conversation != null) {
731 mBuilder.setContentIntent(createContentIntent(conversation));
732 }
733 mBuilder.setGroupSummary(true);
734 mBuilder.setGroup(CONVERSATIONS_GROUP);
735 mBuilder.setDeleteIntent(createDeleteIntent(null));
736 mBuilder.setSmallIcon(R.drawable.ic_notification);
737 return mBuilder;
738 }
739
740 private Builder buildSingleConversations(final ArrayList<Message> messages, final boolean notify, final boolean quietHours) {
741 final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
742 if (messages.size() >= 1) {
743 final Conversation conversation = (Conversation) messages.get(0).getConversation();
744 mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
745 .get(conversation, AvatarService.getSystemUiAvatarSize(mXmppConnectionService)));
746 mBuilder.setContentTitle(conversation.getName());
747 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
748 int count = messages.size();
749 mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
750 } else {
751 Message message;
752 //TODO starting with Android 9 we might want to put images in MessageStyle
753 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P && (message = getImage(messages)) != null) {
754 modifyForImage(mBuilder, message, messages);
755 } else {
756 modifyForTextOnly(mBuilder, messages);
757 }
758 RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
759 PendingIntent markAsReadPendingIntent = createReadPendingIntent(conversation);
760 NotificationCompat.Action markReadAction = new NotificationCompat.Action.Builder(
761 R.drawable.ic_drafts_white_24dp,
762 mXmppConnectionService.getString(R.string.mark_as_read),
763 markAsReadPendingIntent)
764 .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
765 .setShowsUserInterface(false)
766 .build();
767 String replyLabel = mXmppConnectionService.getString(R.string.reply);
768 NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
769 R.drawable.ic_send_text_offline,
770 replyLabel,
771 createReplyIntent(conversation, false))
772 .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
773 .setShowsUserInterface(false)
774 .addRemoteInput(remoteInput).build();
775 NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_wear_reply,
776 replyLabel,
777 createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
778 mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
779 int addedActionsCount = 1;
780 mBuilder.addAction(markReadAction);
781 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
782 mBuilder.addAction(replyAction);
783 ++addedActionsCount;
784 }
785
786 if (displaySnoozeAction(messages)) {
787 String label = mXmppConnectionService.getString(R.string.snooze);
788 PendingIntent pendingSnoozeIntent = createSnoozeIntent(conversation);
789 NotificationCompat.Action snoozeAction = new NotificationCompat.Action.Builder(
790 R.drawable.ic_notifications_paused_white_24dp,
791 label,
792 pendingSnoozeIntent).build();
793 mBuilder.addAction(snoozeAction);
794 ++addedActionsCount;
795 }
796 if (addedActionsCount < 3) {
797 final Message firstLocationMessage = getFirstLocationMessage(messages);
798 if (firstLocationMessage != null) {
799 final PendingIntent pendingShowLocationIntent = createShowLocationIntent(firstLocationMessage);
800 if (pendingShowLocationIntent != null) {
801 final String label = mXmppConnectionService.getResources().getString(R.string.show_location);
802 NotificationCompat.Action locationAction = new NotificationCompat.Action.Builder(
803 R.drawable.ic_room_white_24dp,
804 label,
805 pendingShowLocationIntent).build();
806 mBuilder.addAction(locationAction);
807 ++addedActionsCount;
808 }
809 }
810 }
811 if (addedActionsCount < 3) {
812 Message firstDownloadableMessage = getFirstDownloadableMessage(messages);
813 if (firstDownloadableMessage != null) {
814 String label = mXmppConnectionService.getResources().getString(R.string.download_x_file, UIHelper.getFileDescriptionString(mXmppConnectionService, firstDownloadableMessage));
815 PendingIntent pendingDownloadIntent = createDownloadIntent(firstDownloadableMessage);
816 NotificationCompat.Action downloadAction = new NotificationCompat.Action.Builder(
817 R.drawable.ic_file_download_white_24dp,
818 label,
819 pendingDownloadIntent).build();
820 mBuilder.addAction(downloadAction);
821 ++addedActionsCount;
822 }
823 }
824 }
825 if (conversation.getMode() == Conversation.MODE_SINGLE) {
826 Contact contact = conversation.getContact();
827 Uri systemAccount = contact.getSystemAccount();
828 if (systemAccount != null) {
829 mBuilder.addPerson(systemAccount.toString());
830 }
831 }
832 mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
833 mBuilder.setSmallIcon(R.drawable.ic_notification);
834 mBuilder.setDeleteIntent(createDeleteIntent(conversation));
835 mBuilder.setContentIntent(createContentIntent(conversation));
836 }
837 return mBuilder;
838 }
839
840 private void modifyForImage(final Builder builder, final Message message, final ArrayList<Message> messages) {
841 try {
842 final Bitmap bitmap = mXmppConnectionService.getFileBackend().getThumbnail(message, getPixel(288), false);
843 final ArrayList<Message> tmp = new ArrayList<>();
844 for (final Message msg : messages) {
845 if (msg.getType() == Message.TYPE_TEXT
846 && msg.getTransferable() == null) {
847 tmp.add(msg);
848 }
849 }
850 final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
851 bigPictureStyle.bigPicture(bitmap);
852 if (tmp.size() > 0) {
853 CharSequence text = getMergedBodies(tmp);
854 bigPictureStyle.setSummaryText(text);
855 builder.setContentText(text);
856 builder.setTicker(text);
857 } else {
858 final String description = UIHelper.getFileDescriptionString(mXmppConnectionService, message);
859 builder.setContentText(description);
860 builder.setTicker(description);
861 }
862 builder.setStyle(bigPictureStyle);
863 } catch (final IOException e) {
864 modifyForTextOnly(builder, messages);
865 }
866 }
867
868 private Person getPerson(Message message) {
869 final Contact contact = message.getContact();
870 final Person.Builder builder = new Person.Builder();
871 if (contact != null) {
872 builder.setName(contact.getDisplayName());
873 final Uri uri = contact.getSystemAccount();
874 if (uri != null) {
875 builder.setUri(uri.toString());
876 }
877 } else {
878 builder.setName(UIHelper.getMessageDisplayName(message));
879 }
880 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
881 builder.setIcon(IconCompat.createWithBitmap(mXmppConnectionService.getAvatarService().get(message, AvatarService.getSystemUiAvatarSize(mXmppConnectionService), false)));
882 }
883 return builder.build();
884 }
885
886 private void modifyForTextOnly(final Builder builder, final ArrayList<Message> messages) {
887 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
888 final Conversation conversation = (Conversation) messages.get(0).getConversation();
889 final Person.Builder meBuilder = new Person.Builder().setName(mXmppConnectionService.getString(R.string.me));
890 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
891 meBuilder.setIcon(IconCompat.createWithBitmap(mXmppConnectionService.getAvatarService().get(conversation.getAccount(), AvatarService.getSystemUiAvatarSize(mXmppConnectionService))));
892 }
893 final Person me = meBuilder.build();
894 NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(me);
895 final boolean multiple = conversation.getMode() == Conversation.MODE_MULTI;
896 if (multiple) {
897 messagingStyle.setConversationTitle(conversation.getName());
898 }
899 for (Message message : messages) {
900 final Person sender = message.getStatus() == Message.STATUS_RECEIVED ? getPerson(message) : null;
901 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && isImageMessage(message)) {
902 final Uri dataUri = FileBackend.getMediaUri(mXmppConnectionService, mXmppConnectionService.getFileBackend().getFile(message));
903 NotificationCompat.MessagingStyle.Message imageMessage = new NotificationCompat.MessagingStyle.Message(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
904 if (dataUri != null) {
905 imageMessage.setData(message.getMimeType(), dataUri);
906 }
907 messagingStyle.addMessage(imageMessage);
908 } else {
909 messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
910 }
911 }
912 messagingStyle.setGroupConversation(multiple);
913 builder.setStyle(messagingStyle);
914 } else {
915 if (messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE) {
916 builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
917 final CharSequence preview = UIHelper.getMessagePreview(mXmppConnectionService, messages.get(messages.size() - 1)).first;
918 builder.setContentText(preview);
919 builder.setTicker(preview);
920 builder.setNumber(messages.size());
921 } else {
922 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
923 SpannableString styledString;
924 for (Message message : messages) {
925 final String name = UIHelper.getMessageDisplayName(message);
926 styledString = new SpannableString(name + ": " + message.getBody());
927 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
928 style.addLine(styledString);
929 }
930 builder.setStyle(style);
931 int count = messages.size();
932 if (count == 1) {
933 final String name = UIHelper.getMessageDisplayName(messages.get(0));
934 styledString = new SpannableString(name + ": " + messages.get(0).getBody());
935 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
936 builder.setContentText(styledString);
937 builder.setTicker(styledString);
938 } else {
939 final String text = mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count);
940 builder.setContentText(text);
941 builder.setTicker(text);
942 }
943 }
944 }
945 }
946
947 private Message getImage(final Iterable<Message> messages) {
948 Message image = null;
949 for (final Message message : messages) {
950 if (message.getStatus() != Message.STATUS_RECEIVED) {
951 return null;
952 }
953 if (isImageMessage(message)) {
954 image = message;
955 }
956 }
957 return image;
958 }
959
960 private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
961 for (final Message message : messages) {
962 if (message.getTransferable() != null || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
963 return message;
964 }
965 }
966 return null;
967 }
968
969 private Message getFirstLocationMessage(final Iterable<Message> messages) {
970 for (final Message message : messages) {
971 if (message.isGeoUri()) {
972 return message;
973 }
974 }
975 return null;
976 }
977
978 private CharSequence getMergedBodies(final ArrayList<Message> messages) {
979 final StringBuilder text = new StringBuilder();
980 for (Message message : messages) {
981 if (text.length() != 0) {
982 text.append("\n");
983 }
984 text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
985 }
986 return text.toString();
987 }
988
989 private PendingIntent createShowLocationIntent(final Message message) {
990 Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(mXmppConnectionService, message);
991 for (Intent intent : intents) {
992 if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
993 return PendingIntent.getActivity(mXmppConnectionService, generateRequestCode(message.getConversation(), 18), intent, PendingIntent.FLAG_UPDATE_CURRENT);
994 }
995 }
996 return null;
997 }
998
999 private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
1000 final Intent viewConversationIntent = new Intent(mXmppConnectionService, ConversationsActivity.class);
1001 viewConversationIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
1002 viewConversationIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversationUuid);
1003 if (downloadMessageUuid != null) {
1004 viewConversationIntent.putExtra(ConversationsActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
1005 return PendingIntent.getActivity(mXmppConnectionService,
1006 generateRequestCode(conversationUuid, 8),
1007 viewConversationIntent,
1008 PendingIntent.FLAG_UPDATE_CURRENT);
1009 } else {
1010 return PendingIntent.getActivity(mXmppConnectionService,
1011 generateRequestCode(conversationUuid, 10),
1012 viewConversationIntent,
1013 PendingIntent.FLAG_UPDATE_CURRENT);
1014 }
1015 }
1016
1017 private int generateRequestCode(String uuid, int actionId) {
1018 return (actionId * NOTIFICATION_ID_MULTIPLIER) + (uuid.hashCode() % NOTIFICATION_ID_MULTIPLIER);
1019 }
1020
1021 private int generateRequestCode(Conversational conversation, int actionId) {
1022 return generateRequestCode(conversation.getUuid(), actionId);
1023 }
1024
1025 private PendingIntent createDownloadIntent(final Message message) {
1026 return createContentIntent(message.getConversationUuid(), message.getUuid());
1027 }
1028
1029 private PendingIntent createContentIntent(final Conversational conversation) {
1030 return createContentIntent(conversation.getUuid(), null);
1031 }
1032
1033 private PendingIntent createDeleteIntent(Conversation conversation) {
1034 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1035 intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
1036 if (conversation != null) {
1037 intent.putExtra("uuid", conversation.getUuid());
1038 return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 20), intent, 0);
1039 }
1040 return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
1041 }
1042
1043 private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
1044 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1045 intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
1046 intent.putExtra("uuid", conversation.getUuid());
1047 intent.putExtra("dismiss_notification", dismissAfterReply);
1048 final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14);
1049 return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
1050 }
1051
1052 private PendingIntent createReadPendingIntent(Conversation conversation) {
1053 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1054 intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
1055 intent.putExtra("uuid", conversation.getUuid());
1056 intent.setPackage(mXmppConnectionService.getPackageName());
1057 return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 16), intent, PendingIntent.FLAG_UPDATE_CURRENT);
1058 }
1059
1060 private PendingIntent createCallAction(String sessionId, final String action, int requestCode) {
1061 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1062 intent.setAction(action);
1063 intent.setPackage(mXmppConnectionService.getPackageName());
1064 intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, sessionId);
1065 return PendingIntent.getService(mXmppConnectionService, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
1066 }
1067
1068 private PendingIntent createSnoozeIntent(Conversation conversation) {
1069 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1070 intent.setAction(XmppConnectionService.ACTION_SNOOZE);
1071 intent.putExtra("uuid", conversation.getUuid());
1072 intent.setPackage(mXmppConnectionService.getPackageName());
1073 return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 22), intent, PendingIntent.FLAG_UPDATE_CURRENT);
1074 }
1075
1076 private PendingIntent createTryAgainIntent() {
1077 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1078 intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
1079 return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
1080 }
1081
1082 private PendingIntent createDismissErrorIntent() {
1083 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1084 intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
1085 return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
1086 }
1087
1088 private boolean wasHighlightedOrPrivate(final Message message) {
1089 if (message.getConversation() instanceof Conversation) {
1090 Conversation conversation = (Conversation) message.getConversation();
1091 final String nick = conversation.getMucOptions().getActualNick();
1092 final Pattern highlight = generateNickHighlightPattern(nick);
1093 if (message.getBody() == null || nick == null) {
1094 return false;
1095 }
1096 final Matcher m = highlight.matcher(message.getBody());
1097 return (m.find() || message.isPrivateMessage());
1098 } else {
1099 return false;
1100 }
1101 }
1102
1103 public void setOpenConversation(final Conversation conversation) {
1104 this.mOpenConversation = conversation;
1105 }
1106
1107 public void setIsInForeground(final boolean foreground) {
1108 this.mIsInForeground = foreground;
1109 }
1110
1111 private int getPixel(final int dp) {
1112 final DisplayMetrics metrics = mXmppConnectionService.getResources()
1113 .getDisplayMetrics();
1114 return ((int) (dp * metrics.density));
1115 }
1116
1117 private void markLastNotification() {
1118 this.mLastNotification = SystemClock.elapsedRealtime();
1119 }
1120
1121 private boolean inMiniGracePeriod(final Account account) {
1122 final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
1123 : Config.MINI_GRACE_PERIOD * 2;
1124 return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
1125 }
1126
1127 Notification createForegroundNotification() {
1128 final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1129 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.app_name));
1130 final List<Account> accounts = mXmppConnectionService.getAccounts();
1131 int enabled = 0;
1132 int connected = 0;
1133 if (accounts != null) {
1134 for (Account account : accounts) {
1135 if (account.isOnlineAndConnected()) {
1136 connected++;
1137 enabled++;
1138 } else if (account.isEnabled()) {
1139 enabled++;
1140 }
1141 }
1142 }
1143 mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
1144 final PendingIntent openIntent = createOpenConversationsIntent();
1145 if (openIntent != null) {
1146 mBuilder.setContentIntent(openIntent);
1147 }
1148 mBuilder.setWhen(0);
1149 mBuilder.setPriority(Notification.PRIORITY_MIN);
1150 mBuilder.setSmallIcon(connected > 0 ? R.drawable.ic_link_white_24dp : R.drawable.ic_link_off_white_24dp);
1151
1152 if (Compatibility.runsTwentySix()) {
1153 mBuilder.setChannelId("foreground");
1154 }
1155
1156
1157 return mBuilder.build();
1158 }
1159
1160 private PendingIntent createOpenConversationsIntent() {
1161 try {
1162 return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationsActivity.class), 0);
1163 } catch (RuntimeException e) {
1164 return null;
1165 }
1166 }
1167
1168 void updateErrorNotification() {
1169 if (Config.SUPPRESS_ERROR_NOTIFICATION) {
1170 cancel(ERROR_NOTIFICATION_ID);
1171 return;
1172 }
1173 final boolean showAllErrors = QuickConversationsService.isConversations();
1174 final List<Account> errors = new ArrayList<>();
1175 boolean torNotAvailable = false;
1176 for (final Account account : mXmppConnectionService.getAccounts()) {
1177 if (account.hasErrorStatus() && account.showErrorNotification() && (showAllErrors || account.getLastErrorStatus() == Account.State.UNAUTHORIZED)) {
1178 errors.add(account);
1179 torNotAvailable |= account.getStatus() == Account.State.TOR_NOT_AVAILABLE;
1180 }
1181 }
1182 if (mXmppConnectionService.foregroundNotificationNeedsUpdatingWhenErrorStateChanges()) {
1183 notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
1184 }
1185 final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1186 if (errors.size() == 0) {
1187 cancel(ERROR_NOTIFICATION_ID);
1188 return;
1189 } else if (errors.size() == 1) {
1190 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
1191 mBuilder.setContentText(errors.get(0).getJid().asBareJid().toEscapedString());
1192 } else {
1193 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
1194 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
1195 }
1196 mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
1197 mXmppConnectionService.getString(R.string.try_again),
1198 createTryAgainIntent()
1199 );
1200 if (torNotAvailable) {
1201 if (TorServiceUtils.isOrbotInstalled(mXmppConnectionService)) {
1202 mBuilder.addAction(
1203 R.drawable.ic_play_circle_filled_white_48dp,
1204 mXmppConnectionService.getString(R.string.start_orbot),
1205 PendingIntent.getActivity(mXmppConnectionService, 147, TorServiceUtils.LAUNCH_INTENT, 0)
1206 );
1207 } else {
1208 mBuilder.addAction(
1209 R.drawable.ic_file_download_white_24dp,
1210 mXmppConnectionService.getString(R.string.install_orbot),
1211 PendingIntent.getActivity(mXmppConnectionService, 146, TorServiceUtils.INSTALL_INTENT, 0)
1212 );
1213 }
1214 }
1215 mBuilder.setDeleteIntent(createDismissErrorIntent());
1216 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
1217 mBuilder.setVisibility(Notification.VISIBILITY_PRIVATE);
1218 mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
1219 } else {
1220 mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
1221 }
1222 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
1223 mBuilder.setLocalOnly(true);
1224 }
1225 mBuilder.setPriority(Notification.PRIORITY_LOW);
1226 final Intent intent;
1227 if (AccountUtils.MANAGE_ACCOUNT_ACTIVITY != null) {
1228 intent = new Intent(mXmppConnectionService, AccountUtils.MANAGE_ACCOUNT_ACTIVITY);
1229 } else {
1230 intent = new Intent(mXmppConnectionService, EditAccountActivity.class);
1231 intent.putExtra("jid", errors.get(0).getJid().asBareJid().toEscapedString());
1232 intent.putExtra(EditAccountActivity.EXTRA_OPENED_FROM_NOTIFICATION, true);
1233 }
1234 mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService, 145, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1235 if (Compatibility.runsTwentySix()) {
1236 mBuilder.setChannelId("error");
1237 }
1238 notify(ERROR_NOTIFICATION_ID, mBuilder.build());
1239 }
1240
1241 void updateFileAddingNotification(int current, Message message) {
1242 Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1243 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video));
1244 mBuilder.setProgress(100, current, false);
1245 mBuilder.setSmallIcon(R.drawable.ic_hourglass_empty_white_24dp);
1246 mBuilder.setContentIntent(createContentIntent(message.getConversation()));
1247 mBuilder.setOngoing(true);
1248 if (Compatibility.runsTwentySix()) {
1249 mBuilder.setChannelId("compression");
1250 }
1251 Notification notification = mBuilder.build();
1252 notify(FOREGROUND_NOTIFICATION_ID, notification);
1253 }
1254
1255 private void notify(String tag, int id, Notification notification) {
1256 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1257 try {
1258 notificationManager.notify(tag, id, notification);
1259 } catch (RuntimeException e) {
1260 Log.d(Config.LOGTAG, "unable to make notification", e);
1261 }
1262 }
1263
1264 public void notify(int id, Notification notification) {
1265 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1266 try {
1267 notificationManager.notify(id, notification);
1268 } catch (RuntimeException e) {
1269 Log.d(Config.LOGTAG, "unable to make notification", e);
1270 }
1271 }
1272
1273 public void cancel(int id) {
1274 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1275 try {
1276 notificationManager.cancel(id);
1277 } catch (RuntimeException e) {
1278 Log.d(Config.LOGTAG, "unable to cancel notification", e);
1279 }
1280 }
1281
1282 private void cancel(String tag, int id) {
1283 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1284 try {
1285 notificationManager.cancel(tag, id);
1286 } catch (RuntimeException e) {
1287 Log.d(Config.LOGTAG, "unable to cancel notification", e);
1288 }
1289 }
1290
1291 private class VibrationRunnable implements Runnable {
1292
1293 @Override
1294 public void run() {
1295 final Vibrator vibrator = (Vibrator) mXmppConnectionService.getSystemService(Context.VIBRATOR_SERVICE);
1296 vibrator.vibrate(CALL_PATTERN, -1);
1297 }
1298 }
1299}