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