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