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 isScreenLocked = !mXmppConnectionService.isScreenLocked();
372 if (this.mIsInForeground && isScreenLocked && 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 final NotificationManager notificationManager = (NotificationManager) mXmppConnectionService.getSystemService(Context.NOTIFICATION_SERVICE);
403 final int currentInterruptionFilter;
404 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && notificationManager != null) {
405 currentInterruptionFilter = notificationManager.getCurrentInterruptionFilter();
406 } else {
407 currentInterruptionFilter = 1; //INTERRUPTION_FILTER_ALL
408 }
409 if (currentInterruptionFilter != 1) {
410 Log.d(Config.LOGTAG,"do not ring or vibrate because interruption filter has been set to "+currentInterruptionFilter);
411 return;
412 }
413 this.vibrationFuture = SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(
414 new VibrationRunnable(),
415 0,
416 3,
417 TimeUnit.SECONDS
418 );
419 final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
420 final Resources resources = mXmppConnectionService.getResources();
421 final String ringtonePreference = preferences.getString("call_ringtone", resources.getString(R.string.incoming_call_ringtone));
422 if (Strings.isNullOrEmpty(ringtonePreference)) {
423 Log.d(Config.LOGTAG,"ringtone has been set to none");
424 return;
425 }
426 final Uri uri = Uri.parse(ringtonePreference);
427 this.currentlyPlayingRingtone = RingtoneManager.getRingtone(mXmppConnectionService, uri);
428 if (this.currentlyPlayingRingtone == null) {
429 Log.d(Config.LOGTAG,"unable to find ringtone for uri "+uri);
430 return;
431 }
432 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
433 this.currentlyPlayingRingtone.setLooping(true);
434 }
435 this.currentlyPlayingRingtone.play();
436 }
437
438 private void showIncomingCallNotification(final AbstractJingleConnection.Id id, final Set<Media> media) {
439 final Intent fullScreenIntent = new Intent(mXmppConnectionService, RtpSessionActivity.class);
440 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.account.getJid().asBareJid().toEscapedString());
441 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
442 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
443 fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
444 fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
445 final NotificationCompat.Builder builder = new NotificationCompat.Builder(mXmppConnectionService, INCOMING_CALLS_NOTIFICATION_CHANNEL);
446 if (media.contains(Media.VIDEO)) {
447 builder.setSmallIcon(R.drawable.ic_videocam_white_24dp);
448 builder.setContentTitle(mXmppConnectionService.getString(R.string.rtp_state_incoming_video_call));
449 } else {
450 builder.setSmallIcon(R.drawable.ic_call_white_24dp);
451 builder.setContentTitle(mXmppConnectionService.getString(R.string.rtp_state_incoming_call));
452 }
453 final Contact contact = id.getContact();
454 builder.setLargeIcon(mXmppConnectionService.getAvatarService().get(
455 contact,
456 AvatarService.getSystemUiAvatarSize(mXmppConnectionService))
457 );
458 final Uri systemAccount = contact.getSystemAccount();
459 if (systemAccount != null) {
460 builder.addPerson(systemAccount.toString());
461 }
462 builder.setContentText(id.account.getRoster().getContact(id.with).getDisplayName());
463 builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
464 builder.setPriority(NotificationCompat.PRIORITY_HIGH);
465 builder.setCategory(NotificationCompat.CATEGORY_CALL);
466 PendingIntent pendingIntent = createPendingRtpSession(id, Intent.ACTION_VIEW, 101);
467 builder.setFullScreenIntent(pendingIntent, true);
468 builder.setContentIntent(pendingIntent); //old androids need this?
469 builder.setOngoing(true);
470 builder.addAction(new NotificationCompat.Action.Builder(
471 R.drawable.ic_call_end_white_48dp,
472 mXmppConnectionService.getString(R.string.dismiss_call),
473 createCallAction(id.sessionId, XmppConnectionService.ACTION_DISMISS_CALL, 102))
474 .build());
475 builder.addAction(new NotificationCompat.Action.Builder(
476 R.drawable.ic_call_white_24dp,
477 mXmppConnectionService.getString(R.string.answer_call),
478 createPendingRtpSession(id, RtpSessionActivity.ACTION_ACCEPT_CALL, 103))
479 .build());
480 modifyIncomingCall(builder);
481 final Notification notification = builder.build();
482 notification.flags = notification.flags | Notification.FLAG_INSISTENT;
483 notify(INCOMING_CALL_NOTIFICATION_ID, notification);
484 }
485
486 public Notification getOngoingCallNotification(final AbstractJingleConnection.Id id, final Set<Media> media) {
487 final NotificationCompat.Builder builder = new NotificationCompat.Builder(mXmppConnectionService, "ongoing_calls");
488 if (media.contains(Media.VIDEO)) {
489 builder.setSmallIcon(R.drawable.ic_videocam_white_24dp);
490 builder.setContentTitle(mXmppConnectionService.getString(R.string.ongoing_video_call));
491 } else {
492 builder.setSmallIcon(R.drawable.ic_call_white_24dp);
493 builder.setContentTitle(mXmppConnectionService.getString(R.string.ongoing_call));
494 }
495 builder.setContentText(id.account.getRoster().getContact(id.with).getDisplayName());
496 builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
497 builder.setPriority(NotificationCompat.PRIORITY_HIGH);
498 builder.setCategory(NotificationCompat.CATEGORY_CALL);
499 builder.setContentIntent(createPendingRtpSession(id, Intent.ACTION_VIEW, 101));
500 builder.setOngoing(true);
501 builder.addAction(new NotificationCompat.Action.Builder(
502 R.drawable.ic_call_end_white_48dp,
503 mXmppConnectionService.getString(R.string.hang_up),
504 createCallAction(id.sessionId, XmppConnectionService.ACTION_END_CALL, 104))
505 .build());
506 return builder.build();
507 }
508
509 private PendingIntent createPendingRtpSession(final AbstractJingleConnection.Id id, final String action, final int requestCode) {
510 final Intent fullScreenIntent = new Intent(mXmppConnectionService, RtpSessionActivity.class);
511 fullScreenIntent.setAction(action);
512 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.account.getJid().asBareJid().toEscapedString());
513 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
514 fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
515 return PendingIntent.getActivity(mXmppConnectionService, requestCode, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);
516 }
517
518 public void cancelIncomingCallNotification() {
519 stopSoundAndVibration();
520 cancel(INCOMING_CALL_NOTIFICATION_ID);
521 }
522
523 public boolean stopSoundAndVibration() {
524 int stopped = 0;
525 if (this.currentlyPlayingRingtone != null) {
526 if (this.currentlyPlayingRingtone.isPlaying()) {
527 Log.d(Config.LOGTAG, "stop playing ring tone");
528 ++stopped;
529 }
530 this.currentlyPlayingRingtone.stop();
531 }
532 if (this.vibrationFuture != null && !this.vibrationFuture.isCancelled()) {
533 Log.d(Config.LOGTAG, "stop vibration");
534 this.vibrationFuture.cancel(true);
535 ++stopped;
536 }
537 return stopped > 0;
538 }
539
540 public static void cancelIncomingCallNotification(final Context context) {
541 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
542 try {
543 notificationManager.cancel(INCOMING_CALL_NOTIFICATION_ID);
544 } catch (RuntimeException e) {
545 Log.d(Config.LOGTAG, "unable to cancel incoming call notification after crash", e);
546 }
547 }
548
549 private void pushNow(final Message message) {
550 mXmppConnectionService.updateUnreadCountBadge();
551 if (!notify(message)) {
552 Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because turned off");
553 return;
554 }
555 final boolean isScreenLocked = mXmppConnectionService.isScreenLocked();
556 if (this.mIsInForeground && !isScreenLocked && this.mOpenConversation == message.getConversation()) {
557 Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because conversation is open");
558 return;
559 }
560 synchronized (notifications) {
561 pushToStack(message);
562 final Conversational conversation = message.getConversation();
563 final Account account = conversation.getAccount();
564 final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || isScreenLocked)
565 && !account.inGracePeriod()
566 && !this.inMiniGracePeriod(account);
567 updateNotification(doNotify, Collections.singletonList(conversation.getUuid()));
568 }
569 }
570
571 public void clear() {
572 synchronized (notifications) {
573 for (ArrayList<Message> messages : notifications.values()) {
574 markAsReadIfHasDirectReply(messages);
575 }
576 notifications.clear();
577 updateNotification(false);
578 }
579 }
580
581 public void clear(final Conversation conversation) {
582 synchronized (this.mBacklogMessageCounter) {
583 this.mBacklogMessageCounter.remove(conversation);
584 }
585 synchronized (notifications) {
586 markAsReadIfHasDirectReply(conversation);
587 if (notifications.remove(conversation.getUuid()) != null) {
588 cancel(conversation.getUuid(), NOTIFICATION_ID);
589 updateNotification(false, null, true);
590 }
591 }
592 }
593
594 private void markAsReadIfHasDirectReply(final Conversation conversation) {
595 markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
596 }
597
598 private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
599 if (messages != null && messages.size() > 0) {
600 Message last = messages.get(messages.size() - 1);
601 if (last.getStatus() != Message.STATUS_RECEIVED) {
602 if (mXmppConnectionService.markRead((Conversation) last.getConversation(), false)) {
603 mXmppConnectionService.updateConversationUi();
604 }
605 }
606 }
607 }
608
609 private void setNotificationColor(final Builder mBuilder) {
610 mBuilder.setColor(ContextCompat.getColor(mXmppConnectionService, R.color.green600));
611 }
612
613 public void updateNotification() {
614 synchronized (notifications) {
615 updateNotification(false);
616 }
617 }
618
619 private void updateNotification(final boolean notify) {
620 updateNotification(notify, null, false);
621 }
622
623 private void updateNotification(final boolean notify, final List<String> conversations) {
624 updateNotification(notify, conversations, false);
625 }
626
627 private void updateNotification(final boolean notify, final List<String> conversations, final boolean summaryOnly) {
628 final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
629
630 final boolean quiteHours = isQuietHours();
631
632 final boolean notifyOnlyOneChild = notify && conversations != null && conversations.size() == 1; //if this check is changed to > 0 catchup messages will create one notification per conversation
633
634
635 if (notifications.size() == 0) {
636 cancel(NOTIFICATION_ID);
637 } else {
638 if (notify) {
639 this.markLastNotification();
640 }
641 final Builder mBuilder;
642 if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
643 mBuilder = buildSingleConversations(notifications.values().iterator().next(), notify, quiteHours);
644 modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
645 notify(NOTIFICATION_ID, mBuilder.build());
646 } else {
647 mBuilder = buildMultipleConversation(notify, quiteHours);
648 if (notifyOnlyOneChild) {
649 mBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
650 }
651 modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
652 if (!summaryOnly) {
653 for (Map.Entry<String, ArrayList<Message>> entry : notifications.entrySet()) {
654 String uuid = entry.getKey();
655 final boolean notifyThis = notifyOnlyOneChild ? conversations.contains(uuid) : notify;
656 Builder singleBuilder = buildSingleConversations(entry.getValue(), notifyThis, quiteHours);
657 if (!notifyOnlyOneChild) {
658 singleBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY);
659 }
660 modifyForSoundVibrationAndLight(singleBuilder, notifyThis, quiteHours, preferences);
661 singleBuilder.setGroup(CONVERSATIONS_GROUP);
662 setNotificationColor(singleBuilder);
663 notify(entry.getKey(), NOTIFICATION_ID, singleBuilder.build());
664 }
665 }
666 notify(NOTIFICATION_ID, mBuilder.build());
667 }
668 }
669 }
670
671 private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, boolean quietHours, SharedPreferences preferences) {
672 final Resources resources = mXmppConnectionService.getResources();
673 final String ringtone = preferences.getString("notification_ringtone", resources.getString(R.string.notification_ringtone));
674 final boolean vibrate = preferences.getBoolean("vibrate_on_notification", resources.getBoolean(R.bool.vibrate_on_notification));
675 final boolean led = preferences.getBoolean("led", resources.getBoolean(R.bool.led));
676 final boolean headsup = preferences.getBoolean("notification_headsup", resources.getBoolean(R.bool.headsup_notifications));
677 if (notify && !quietHours) {
678 if (vibrate) {
679 final int dat = 70;
680 final long[] pattern = {0, 3 * dat, dat, dat};
681 mBuilder.setVibrate(pattern);
682 } else {
683 mBuilder.setVibrate(new long[]{0});
684 }
685 Uri uri = Uri.parse(ringtone);
686 try {
687 mBuilder.setSound(fixRingtoneUri(uri));
688 } catch (SecurityException e) {
689 Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
690 }
691 } else {
692 mBuilder.setLocalOnly(true);
693 }
694 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
695 mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
696 }
697 mBuilder.setPriority(notify ? (headsup ? NotificationCompat.PRIORITY_HIGH : NotificationCompat.PRIORITY_DEFAULT) : NotificationCompat.PRIORITY_LOW);
698 setNotificationColor(mBuilder);
699 mBuilder.setDefaults(0);
700 if (led) {
701 mBuilder.setLights(LED_COLOR, 2000, 3000);
702 }
703 }
704
705 private void modifyIncomingCall(final Builder mBuilder) {
706 mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
707 setNotificationColor(mBuilder);
708 mBuilder.setLights(LED_COLOR, 2000, 3000);
709 }
710
711 private Uri fixRingtoneUri(Uri uri) {
712 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && "file".equals(uri.getScheme())) {
713 return FileBackend.getUriForFile(mXmppConnectionService, new File(uri.getPath()));
714 } else {
715 return uri;
716 }
717 }
718
719 private Builder buildMultipleConversation(final boolean notify, final boolean quietHours) {
720 final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
721 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
722 style.setBigContentTitle(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_unread_conversations, notifications.size(), notifications.size()));
723 final StringBuilder names = new StringBuilder();
724 Conversation conversation = null;
725 for (final ArrayList<Message> messages : notifications.values()) {
726 if (messages.size() > 0) {
727 conversation = (Conversation) messages.get(0).getConversation();
728 final String name = conversation.getName().toString();
729 SpannableString styledString;
730 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
731 int count = messages.size();
732 styledString = new SpannableString(name + ": " + mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
733 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
734 style.addLine(styledString);
735 } else {
736 styledString = new SpannableString(name + ": " + UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
737 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
738 style.addLine(styledString);
739 }
740 names.append(name);
741 names.append(", ");
742 }
743 }
744 if (names.length() >= 2) {
745 names.delete(names.length() - 2, names.length());
746 }
747 final String contentTitle = mXmppConnectionService.getResources().getQuantityString(R.plurals.x_unread_conversations, notifications.size(), notifications.size());
748 mBuilder.setContentTitle(contentTitle);
749 mBuilder.setTicker(contentTitle);
750 mBuilder.setContentText(names.toString());
751 mBuilder.setStyle(style);
752 if (conversation != null) {
753 mBuilder.setContentIntent(createContentIntent(conversation));
754 }
755 mBuilder.setGroupSummary(true);
756 mBuilder.setGroup(CONVERSATIONS_GROUP);
757 mBuilder.setDeleteIntent(createDeleteIntent(null));
758 mBuilder.setSmallIcon(R.drawable.ic_notification);
759 return mBuilder;
760 }
761
762 private Builder buildSingleConversations(final ArrayList<Message> messages, final boolean notify, final boolean quietHours) {
763 final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
764 if (messages.size() >= 1) {
765 final Conversation conversation = (Conversation) messages.get(0).getConversation();
766 mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
767 .get(conversation, AvatarService.getSystemUiAvatarSize(mXmppConnectionService)));
768 mBuilder.setContentTitle(conversation.getName());
769 if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
770 int count = messages.size();
771 mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
772 } else {
773 Message message;
774 //TODO starting with Android 9 we might want to put images in MessageStyle
775 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P && (message = getImage(messages)) != null) {
776 modifyForImage(mBuilder, message, messages);
777 } else {
778 modifyForTextOnly(mBuilder, messages);
779 }
780 RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
781 PendingIntent markAsReadPendingIntent = createReadPendingIntent(conversation);
782 NotificationCompat.Action markReadAction = new NotificationCompat.Action.Builder(
783 R.drawable.ic_drafts_white_24dp,
784 mXmppConnectionService.getString(R.string.mark_as_read),
785 markAsReadPendingIntent)
786 .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
787 .setShowsUserInterface(false)
788 .build();
789 String replyLabel = mXmppConnectionService.getString(R.string.reply);
790 NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
791 R.drawable.ic_send_text_offline,
792 replyLabel,
793 createReplyIntent(conversation, false))
794 .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
795 .setShowsUserInterface(false)
796 .addRemoteInput(remoteInput).build();
797 NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_wear_reply,
798 replyLabel,
799 createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
800 mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
801 int addedActionsCount = 1;
802 mBuilder.addAction(markReadAction);
803 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
804 mBuilder.addAction(replyAction);
805 ++addedActionsCount;
806 }
807
808 if (displaySnoozeAction(messages)) {
809 String label = mXmppConnectionService.getString(R.string.snooze);
810 PendingIntent pendingSnoozeIntent = createSnoozeIntent(conversation);
811 NotificationCompat.Action snoozeAction = new NotificationCompat.Action.Builder(
812 R.drawable.ic_notifications_paused_white_24dp,
813 label,
814 pendingSnoozeIntent).build();
815 mBuilder.addAction(snoozeAction);
816 ++addedActionsCount;
817 }
818 if (addedActionsCount < 3) {
819 final Message firstLocationMessage = getFirstLocationMessage(messages);
820 if (firstLocationMessage != null) {
821 final PendingIntent pendingShowLocationIntent = createShowLocationIntent(firstLocationMessage);
822 if (pendingShowLocationIntent != null) {
823 final String label = mXmppConnectionService.getResources().getString(R.string.show_location);
824 NotificationCompat.Action locationAction = new NotificationCompat.Action.Builder(
825 R.drawable.ic_room_white_24dp,
826 label,
827 pendingShowLocationIntent).build();
828 mBuilder.addAction(locationAction);
829 ++addedActionsCount;
830 }
831 }
832 }
833 if (addedActionsCount < 3) {
834 Message firstDownloadableMessage = getFirstDownloadableMessage(messages);
835 if (firstDownloadableMessage != null) {
836 String label = mXmppConnectionService.getResources().getString(R.string.download_x_file, UIHelper.getFileDescriptionString(mXmppConnectionService, firstDownloadableMessage));
837 PendingIntent pendingDownloadIntent = createDownloadIntent(firstDownloadableMessage);
838 NotificationCompat.Action downloadAction = new NotificationCompat.Action.Builder(
839 R.drawable.ic_file_download_white_24dp,
840 label,
841 pendingDownloadIntent).build();
842 mBuilder.addAction(downloadAction);
843 ++addedActionsCount;
844 }
845 }
846 }
847 if (conversation.getMode() == Conversation.MODE_SINGLE) {
848 Contact contact = conversation.getContact();
849 Uri systemAccount = contact.getSystemAccount();
850 if (systemAccount != null) {
851 mBuilder.addPerson(systemAccount.toString());
852 }
853 }
854 mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
855 mBuilder.setSmallIcon(R.drawable.ic_notification);
856 mBuilder.setDeleteIntent(createDeleteIntent(conversation));
857 mBuilder.setContentIntent(createContentIntent(conversation));
858 }
859 return mBuilder;
860 }
861
862 private void modifyForImage(final Builder builder, final Message message, final ArrayList<Message> messages) {
863 try {
864 final Bitmap bitmap = mXmppConnectionService.getFileBackend().getThumbnail(message, getPixel(288), false);
865 final ArrayList<Message> tmp = new ArrayList<>();
866 for (final Message msg : messages) {
867 if (msg.getType() == Message.TYPE_TEXT
868 && msg.getTransferable() == null) {
869 tmp.add(msg);
870 }
871 }
872 final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
873 bigPictureStyle.bigPicture(bitmap);
874 if (tmp.size() > 0) {
875 CharSequence text = getMergedBodies(tmp);
876 bigPictureStyle.setSummaryText(text);
877 builder.setContentText(text);
878 builder.setTicker(text);
879 } else {
880 final String description = UIHelper.getFileDescriptionString(mXmppConnectionService, message);
881 builder.setContentText(description);
882 builder.setTicker(description);
883 }
884 builder.setStyle(bigPictureStyle);
885 } catch (final IOException e) {
886 modifyForTextOnly(builder, messages);
887 }
888 }
889
890 private Person getPerson(Message message) {
891 final Contact contact = message.getContact();
892 final Person.Builder builder = new Person.Builder();
893 if (contact != null) {
894 builder.setName(contact.getDisplayName());
895 final Uri uri = contact.getSystemAccount();
896 if (uri != null) {
897 builder.setUri(uri.toString());
898 }
899 } else {
900 builder.setName(UIHelper.getMessageDisplayName(message));
901 }
902 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
903 builder.setIcon(IconCompat.createWithBitmap(mXmppConnectionService.getAvatarService().get(message, AvatarService.getSystemUiAvatarSize(mXmppConnectionService), false)));
904 }
905 return builder.build();
906 }
907
908 private void modifyForTextOnly(final Builder builder, final ArrayList<Message> messages) {
909 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
910 final Conversation conversation = (Conversation) messages.get(0).getConversation();
911 final Person.Builder meBuilder = new Person.Builder().setName(mXmppConnectionService.getString(R.string.me));
912 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
913 meBuilder.setIcon(IconCompat.createWithBitmap(mXmppConnectionService.getAvatarService().get(conversation.getAccount(), AvatarService.getSystemUiAvatarSize(mXmppConnectionService))));
914 }
915 final Person me = meBuilder.build();
916 NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(me);
917 final boolean multiple = conversation.getMode() == Conversation.MODE_MULTI;
918 if (multiple) {
919 messagingStyle.setConversationTitle(conversation.getName());
920 }
921 for (Message message : messages) {
922 final Person sender = message.getStatus() == Message.STATUS_RECEIVED ? getPerson(message) : null;
923 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && isImageMessage(message)) {
924 final Uri dataUri = FileBackend.getMediaUri(mXmppConnectionService, mXmppConnectionService.getFileBackend().getFile(message));
925 NotificationCompat.MessagingStyle.Message imageMessage = new NotificationCompat.MessagingStyle.Message(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
926 if (dataUri != null) {
927 imageMessage.setData(message.getMimeType(), dataUri);
928 }
929 messagingStyle.addMessage(imageMessage);
930 } else {
931 messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
932 }
933 }
934 messagingStyle.setGroupConversation(multiple);
935 builder.setStyle(messagingStyle);
936 } else {
937 if (messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE) {
938 builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
939 final CharSequence preview = UIHelper.getMessagePreview(mXmppConnectionService, messages.get(messages.size() - 1)).first;
940 builder.setContentText(preview);
941 builder.setTicker(preview);
942 builder.setNumber(messages.size());
943 } else {
944 final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
945 SpannableString styledString;
946 for (Message message : messages) {
947 final String name = UIHelper.getMessageDisplayName(message);
948 styledString = new SpannableString(name + ": " + message.getBody());
949 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
950 style.addLine(styledString);
951 }
952 builder.setStyle(style);
953 int count = messages.size();
954 if (count == 1) {
955 final String name = UIHelper.getMessageDisplayName(messages.get(0));
956 styledString = new SpannableString(name + ": " + messages.get(0).getBody());
957 styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
958 builder.setContentText(styledString);
959 builder.setTicker(styledString);
960 } else {
961 final String text = mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count);
962 builder.setContentText(text);
963 builder.setTicker(text);
964 }
965 }
966 }
967 }
968
969 private Message getImage(final Iterable<Message> messages) {
970 Message image = null;
971 for (final Message message : messages) {
972 if (message.getStatus() != Message.STATUS_RECEIVED) {
973 return null;
974 }
975 if (isImageMessage(message)) {
976 image = message;
977 }
978 }
979 return image;
980 }
981
982 private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
983 for (final Message message : messages) {
984 if (message.getTransferable() != null || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
985 return message;
986 }
987 }
988 return null;
989 }
990
991 private Message getFirstLocationMessage(final Iterable<Message> messages) {
992 for (final Message message : messages) {
993 if (message.isGeoUri()) {
994 return message;
995 }
996 }
997 return null;
998 }
999
1000 private CharSequence getMergedBodies(final ArrayList<Message> messages) {
1001 final StringBuilder text = new StringBuilder();
1002 for (Message message : messages) {
1003 if (text.length() != 0) {
1004 text.append("\n");
1005 }
1006 text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
1007 }
1008 return text.toString();
1009 }
1010
1011 private PendingIntent createShowLocationIntent(final Message message) {
1012 Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(mXmppConnectionService, message);
1013 for (Intent intent : intents) {
1014 if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
1015 return PendingIntent.getActivity(mXmppConnectionService, generateRequestCode(message.getConversation(), 18), intent, PendingIntent.FLAG_UPDATE_CURRENT);
1016 }
1017 }
1018 return null;
1019 }
1020
1021 private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
1022 final Intent viewConversationIntent = new Intent(mXmppConnectionService, ConversationsActivity.class);
1023 viewConversationIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
1024 viewConversationIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversationUuid);
1025 if (downloadMessageUuid != null) {
1026 viewConversationIntent.putExtra(ConversationsActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
1027 return PendingIntent.getActivity(mXmppConnectionService,
1028 generateRequestCode(conversationUuid, 8),
1029 viewConversationIntent,
1030 PendingIntent.FLAG_UPDATE_CURRENT);
1031 } else {
1032 return PendingIntent.getActivity(mXmppConnectionService,
1033 generateRequestCode(conversationUuid, 10),
1034 viewConversationIntent,
1035 PendingIntent.FLAG_UPDATE_CURRENT);
1036 }
1037 }
1038
1039 private int generateRequestCode(String uuid, int actionId) {
1040 return (actionId * NOTIFICATION_ID_MULTIPLIER) + (uuid.hashCode() % NOTIFICATION_ID_MULTIPLIER);
1041 }
1042
1043 private int generateRequestCode(Conversational conversation, int actionId) {
1044 return generateRequestCode(conversation.getUuid(), actionId);
1045 }
1046
1047 private PendingIntent createDownloadIntent(final Message message) {
1048 return createContentIntent(message.getConversationUuid(), message.getUuid());
1049 }
1050
1051 private PendingIntent createContentIntent(final Conversational conversation) {
1052 return createContentIntent(conversation.getUuid(), null);
1053 }
1054
1055 private PendingIntent createDeleteIntent(Conversation conversation) {
1056 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1057 intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
1058 if (conversation != null) {
1059 intent.putExtra("uuid", conversation.getUuid());
1060 return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 20), intent, 0);
1061 }
1062 return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
1063 }
1064
1065 private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
1066 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1067 intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
1068 intent.putExtra("uuid", conversation.getUuid());
1069 intent.putExtra("dismiss_notification", dismissAfterReply);
1070 final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14);
1071 return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
1072 }
1073
1074 private PendingIntent createReadPendingIntent(Conversation conversation) {
1075 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1076 intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
1077 intent.putExtra("uuid", conversation.getUuid());
1078 intent.setPackage(mXmppConnectionService.getPackageName());
1079 return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 16), intent, PendingIntent.FLAG_UPDATE_CURRENT);
1080 }
1081
1082 private PendingIntent createCallAction(String sessionId, final String action, int requestCode) {
1083 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1084 intent.setAction(action);
1085 intent.setPackage(mXmppConnectionService.getPackageName());
1086 intent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, sessionId);
1087 return PendingIntent.getService(mXmppConnectionService, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
1088 }
1089
1090 private PendingIntent createSnoozeIntent(Conversation conversation) {
1091 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1092 intent.setAction(XmppConnectionService.ACTION_SNOOZE);
1093 intent.putExtra("uuid", conversation.getUuid());
1094 intent.setPackage(mXmppConnectionService.getPackageName());
1095 return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 22), intent, PendingIntent.FLAG_UPDATE_CURRENT);
1096 }
1097
1098 private PendingIntent createTryAgainIntent() {
1099 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1100 intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
1101 return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
1102 }
1103
1104 private PendingIntent createDismissErrorIntent() {
1105 final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
1106 intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
1107 return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
1108 }
1109
1110 private boolean wasHighlightedOrPrivate(final Message message) {
1111 if (message.getConversation() instanceof Conversation) {
1112 Conversation conversation = (Conversation) message.getConversation();
1113 final String nick = conversation.getMucOptions().getActualNick();
1114 final Pattern highlight = generateNickHighlightPattern(nick);
1115 if (message.getBody() == null || nick == null) {
1116 return false;
1117 }
1118 final Matcher m = highlight.matcher(message.getBody());
1119 return (m.find() || message.isPrivateMessage());
1120 } else {
1121 return false;
1122 }
1123 }
1124
1125 public void setOpenConversation(final Conversation conversation) {
1126 this.mOpenConversation = conversation;
1127 }
1128
1129 public void setIsInForeground(final boolean foreground) {
1130 this.mIsInForeground = foreground;
1131 }
1132
1133 private int getPixel(final int dp) {
1134 final DisplayMetrics metrics = mXmppConnectionService.getResources()
1135 .getDisplayMetrics();
1136 return ((int) (dp * metrics.density));
1137 }
1138
1139 private void markLastNotification() {
1140 this.mLastNotification = SystemClock.elapsedRealtime();
1141 }
1142
1143 private boolean inMiniGracePeriod(final Account account) {
1144 final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
1145 : Config.MINI_GRACE_PERIOD * 2;
1146 return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
1147 }
1148
1149 Notification createForegroundNotification() {
1150 final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1151 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.app_name));
1152 final List<Account> accounts = mXmppConnectionService.getAccounts();
1153 int enabled = 0;
1154 int connected = 0;
1155 if (accounts != null) {
1156 for (Account account : accounts) {
1157 if (account.isOnlineAndConnected()) {
1158 connected++;
1159 enabled++;
1160 } else if (account.isEnabled()) {
1161 enabled++;
1162 }
1163 }
1164 }
1165 mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
1166 final PendingIntent openIntent = createOpenConversationsIntent();
1167 if (openIntent != null) {
1168 mBuilder.setContentIntent(openIntent);
1169 }
1170 mBuilder.setWhen(0);
1171 mBuilder.setPriority(Notification.PRIORITY_MIN);
1172 mBuilder.setSmallIcon(connected > 0 ? R.drawable.ic_link_white_24dp : R.drawable.ic_link_off_white_24dp);
1173
1174 if (Compatibility.runsTwentySix()) {
1175 mBuilder.setChannelId("foreground");
1176 }
1177
1178
1179 return mBuilder.build();
1180 }
1181
1182 private PendingIntent createOpenConversationsIntent() {
1183 try {
1184 return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationsActivity.class), 0);
1185 } catch (RuntimeException e) {
1186 return null;
1187 }
1188 }
1189
1190 void updateErrorNotification() {
1191 if (Config.SUPPRESS_ERROR_NOTIFICATION) {
1192 cancel(ERROR_NOTIFICATION_ID);
1193 return;
1194 }
1195 final boolean showAllErrors = QuickConversationsService.isConversations();
1196 final List<Account> errors = new ArrayList<>();
1197 boolean torNotAvailable = false;
1198 for (final Account account : mXmppConnectionService.getAccounts()) {
1199 if (account.hasErrorStatus() && account.showErrorNotification() && (showAllErrors || account.getLastErrorStatus() == Account.State.UNAUTHORIZED)) {
1200 errors.add(account);
1201 torNotAvailable |= account.getStatus() == Account.State.TOR_NOT_AVAILABLE;
1202 }
1203 }
1204 if (mXmppConnectionService.foregroundNotificationNeedsUpdatingWhenErrorStateChanges()) {
1205 notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
1206 }
1207 final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1208 if (errors.size() == 0) {
1209 cancel(ERROR_NOTIFICATION_ID);
1210 return;
1211 } else if (errors.size() == 1) {
1212 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
1213 mBuilder.setContentText(errors.get(0).getJid().asBareJid().toEscapedString());
1214 } else {
1215 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
1216 mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
1217 }
1218 mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
1219 mXmppConnectionService.getString(R.string.try_again),
1220 createTryAgainIntent()
1221 );
1222 if (torNotAvailable) {
1223 if (TorServiceUtils.isOrbotInstalled(mXmppConnectionService)) {
1224 mBuilder.addAction(
1225 R.drawable.ic_play_circle_filled_white_48dp,
1226 mXmppConnectionService.getString(R.string.start_orbot),
1227 PendingIntent.getActivity(mXmppConnectionService, 147, TorServiceUtils.LAUNCH_INTENT, 0)
1228 );
1229 } else {
1230 mBuilder.addAction(
1231 R.drawable.ic_file_download_white_24dp,
1232 mXmppConnectionService.getString(R.string.install_orbot),
1233 PendingIntent.getActivity(mXmppConnectionService, 146, TorServiceUtils.INSTALL_INTENT, 0)
1234 );
1235 }
1236 }
1237 mBuilder.setDeleteIntent(createDismissErrorIntent());
1238 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
1239 mBuilder.setVisibility(Notification.VISIBILITY_PRIVATE);
1240 mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
1241 } else {
1242 mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
1243 }
1244 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
1245 mBuilder.setLocalOnly(true);
1246 }
1247 mBuilder.setPriority(Notification.PRIORITY_LOW);
1248 final Intent intent;
1249 if (AccountUtils.MANAGE_ACCOUNT_ACTIVITY != null) {
1250 intent = new Intent(mXmppConnectionService, AccountUtils.MANAGE_ACCOUNT_ACTIVITY);
1251 } else {
1252 intent = new Intent(mXmppConnectionService, EditAccountActivity.class);
1253 intent.putExtra("jid", errors.get(0).getJid().asBareJid().toEscapedString());
1254 intent.putExtra(EditAccountActivity.EXTRA_OPENED_FROM_NOTIFICATION, true);
1255 }
1256 mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService, 145, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1257 if (Compatibility.runsTwentySix()) {
1258 mBuilder.setChannelId("error");
1259 }
1260 notify(ERROR_NOTIFICATION_ID, mBuilder.build());
1261 }
1262
1263 void updateFileAddingNotification(int current, Message message) {
1264 Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
1265 mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video));
1266 mBuilder.setProgress(100, current, false);
1267 mBuilder.setSmallIcon(R.drawable.ic_hourglass_empty_white_24dp);
1268 mBuilder.setContentIntent(createContentIntent(message.getConversation()));
1269 mBuilder.setOngoing(true);
1270 if (Compatibility.runsTwentySix()) {
1271 mBuilder.setChannelId("compression");
1272 }
1273 Notification notification = mBuilder.build();
1274 notify(FOREGROUND_NOTIFICATION_ID, notification);
1275 }
1276
1277 private void notify(String tag, int id, Notification notification) {
1278 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1279 try {
1280 notificationManager.notify(tag, id, notification);
1281 } catch (RuntimeException e) {
1282 Log.d(Config.LOGTAG, "unable to make notification", e);
1283 }
1284 }
1285
1286 public void notify(int id, Notification notification) {
1287 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1288 try {
1289 notificationManager.notify(id, notification);
1290 } catch (RuntimeException e) {
1291 Log.d(Config.LOGTAG, "unable to make notification", e);
1292 }
1293 }
1294
1295 public void cancel(int id) {
1296 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1297 try {
1298 notificationManager.cancel(id);
1299 } catch (RuntimeException e) {
1300 Log.d(Config.LOGTAG, "unable to cancel notification", e);
1301 }
1302 }
1303
1304 private void cancel(String tag, int id) {
1305 final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1306 try {
1307 notificationManager.cancel(tag, id);
1308 } catch (RuntimeException e) {
1309 Log.d(Config.LOGTAG, "unable to cancel notification", e);
1310 }
1311 }
1312
1313 private class VibrationRunnable implements Runnable {
1314
1315 @Override
1316 public void run() {
1317 final Vibrator vibrator = (Vibrator) mXmppConnectionService.getSystemService(Context.VIBRATOR_SERVICE);
1318 vibrator.vibrate(CALL_PATTERN, -1);
1319 }
1320 }
1321}