1package eu.siacs.conversations.services;
2
3import java.io.FileNotFoundException;
4import java.util.ArrayList;
5import java.util.LinkedHashMap;
6import java.util.regex.Matcher;
7import java.util.regex.Pattern;
8
9import android.app.Notification;
10import android.app.NotificationManager;
11import android.app.PendingIntent;
12import android.content.Context;
13import android.content.Intent;
14import android.content.SharedPreferences;
15import android.graphics.Bitmap;
16import android.net.Uri;
17import android.os.PowerManager;
18import android.os.SystemClock;
19import android.support.v4.app.NotificationCompat;
20import android.support.v4.app.NotificationCompat.BigPictureStyle;
21import android.support.v4.app.NotificationCompat.Builder;
22import android.support.v4.app.TaskStackBuilder;
23import android.text.Html;
24import android.util.DisplayMetrics;
25
26import eu.siacs.conversations.Config;
27import eu.siacs.conversations.R;
28import eu.siacs.conversations.entities.Account;
29import eu.siacs.conversations.entities.Conversation;
30import eu.siacs.conversations.entities.Downloadable;
31import eu.siacs.conversations.entities.Message;
32import eu.siacs.conversations.ui.ConversationActivity;
33
34public class NotificationService {
35
36 private XmppConnectionService mXmppConnectionService;
37
38 private LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<String, ArrayList<Message>>();
39
40 public static int NOTIFICATION_ID = 0x2342;
41 private Conversation mOpenConversation;
42 private boolean mIsInForeground;
43 private long mLastNotification;
44
45 public NotificationService(XmppConnectionService service) {
46 this.mXmppConnectionService = service;
47 }
48
49 public void push(Message message) {
50 PowerManager pm = (PowerManager) mXmppConnectionService
51 .getSystemService(Context.POWER_SERVICE);
52 boolean isScreenOn = pm.isScreenOn();
53
54 if (this.mIsInForeground && isScreenOn
55 && this.mOpenConversation == message.getConversation()) {
56 return;
57 }
58 synchronized (notifications) {
59 String conversationUuid = message.getConversationUuid();
60 if (notifications.containsKey(conversationUuid)) {
61 notifications.get(conversationUuid).add(message);
62 } else {
63 ArrayList<Message> mList = new ArrayList<Message>();
64 mList.add(message);
65 notifications.put(conversationUuid, mList);
66 }
67 Account account = message.getConversation().getAccount();
68 updateNotification((!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
69 && !account.inGracePeriod()
70 && !this.inMiniGracePeriod(account));
71 }
72
73 }
74
75 public void clear() {
76 synchronized (notifications) {
77 notifications.clear();
78 updateNotification(false);
79 }
80 }
81
82 public void clear(Conversation conversation) {
83 synchronized (notifications) {
84 notifications.remove(conversation.getUuid());
85 updateNotification(false);
86 }
87 }
88
89 private void updateNotification(boolean notify) {
90 NotificationManager notificationManager = (NotificationManager) mXmppConnectionService
91 .getSystemService(Context.NOTIFICATION_SERVICE);
92 SharedPreferences preferences = mXmppConnectionService.getPreferences();
93
94 String ringtone = preferences.getString("notification_ringtone", null);
95 boolean vibrate = preferences.getBoolean("vibrate_on_notification",
96 true);
97
98 if (notifications.size() == 0) {
99 notificationManager.cancel(NOTIFICATION_ID);
100 } else {
101 if (notify) {
102 this.markLastNotification();
103 }
104 Builder mBuilder;
105 if (notifications.size() == 1) {
106 mBuilder = buildSingleConversations(notify);
107 } else {
108 mBuilder = buildMultipleConversation();
109 }
110 if (notify) {
111 if (vibrate) {
112 int dat = 70;
113 long[] pattern = { 0, 3 * dat, dat, dat };
114 mBuilder.setVibrate(pattern);
115 }
116 if (ringtone != null) {
117 mBuilder.setSound(Uri.parse(ringtone));
118 }
119 }
120 mBuilder.setSmallIcon(R.drawable.ic_notification);
121 mBuilder.setDeleteIntent(createDeleteIntent());
122 mBuilder.setLights(0xffffffff, 2000, 4000);
123 Notification notification = mBuilder.build();
124 notificationManager.notify(NOTIFICATION_ID, notification);
125 }
126 }
127
128 private Builder buildMultipleConversation() {
129 Builder mBuilder = new NotificationCompat.Builder(
130 mXmppConnectionService);
131 NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
132 style.setBigContentTitle(notifications.size()
133 + " "
134 + mXmppConnectionService
135 .getString(R.string.unread_conversations));
136 StringBuilder names = new StringBuilder();
137 Conversation conversation = null;
138 for (ArrayList<Message> messages : notifications.values()) {
139 if (messages.size() > 0) {
140 conversation = messages.get(0).getConversation();
141 String name = conversation.getName();
142 style.addLine(Html.fromHtml("<b>" + name + "</b> "
143 + getReadableBody(messages.get(0))));
144 names.append(name);
145 names.append(", ");
146 }
147 }
148 if (names.length() >= 2) {
149 names.delete(names.length() - 2, names.length());
150 }
151 mBuilder.setContentTitle(notifications.size()
152 + " "
153 + mXmppConnectionService
154 .getString(R.string.unread_conversations));
155 mBuilder.setContentText(names.toString());
156 mBuilder.setStyle(style);
157 if (conversation != null) {
158 mBuilder.setContentIntent(createContentIntent(conversation
159 .getUuid()));
160 }
161 return mBuilder;
162 }
163
164 private Builder buildSingleConversations(boolean notify) {
165 Builder mBuilder = new NotificationCompat.Builder(
166 mXmppConnectionService);
167 ArrayList<Message> messages = notifications.values().iterator().next();
168 if (messages.size() >= 1) {
169 Conversation conversation = messages.get(0).getConversation();
170 mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
171 .get(conversation, getPixel(64)));
172 mBuilder.setContentTitle(conversation.getName());
173 Message message;
174 if ((message = getImage(messages)) != null) {
175 modifyForImage(mBuilder, message, messages, notify);
176 } else {
177 modifyForTextOnly(mBuilder, messages, notify);
178 }
179 mBuilder.setContentIntent(createContentIntent(conversation
180 .getUuid()));
181 }
182 return mBuilder;
183
184 }
185
186 private void modifyForImage(Builder builder, Message message,
187 ArrayList<Message> messages, boolean notify) {
188 try {
189 Bitmap bitmap = mXmppConnectionService.getFileBackend()
190 .getThumbnail(message, getPixel(288), false);
191 ArrayList<Message> tmp = new ArrayList<Message>();
192 for (Message msg : messages) {
193 if (msg.getType() == Message.TYPE_TEXT
194 && msg.getDownloadable() == null) {
195 tmp.add(msg);
196 }
197 }
198 BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
199 bigPictureStyle.bigPicture(bitmap);
200 if (tmp.size() > 0) {
201 bigPictureStyle.setSummaryText(getMergedBodies(tmp));
202 builder.setContentText(getReadableBody(tmp.get(0)));
203 } else {
204 builder.setContentText(mXmppConnectionService.getString(R.string.image_file));
205 }
206 builder.setStyle(bigPictureStyle);
207 } catch (FileNotFoundException e) {
208 modifyForTextOnly(builder, messages, notify);
209 }
210 }
211
212 private void modifyForTextOnly(Builder builder,
213 ArrayList<Message> messages, boolean notify) {
214 builder.setStyle(new NotificationCompat.BigTextStyle()
215 .bigText(getMergedBodies(messages)));
216 builder.setContentText(getReadableBody(messages.get(0)));
217 if (notify) {
218 builder.setTicker(getReadableBody(messages.get(messages.size() - 1)));
219 }
220 }
221
222 private Message getImage(ArrayList<Message> messages) {
223 for (Message message : messages) {
224 if (message.getType() == Message.TYPE_IMAGE
225 && message.getDownloadable() == null
226 && message.getEncryption() != Message.ENCRYPTION_PGP) {
227 return message;
228 }
229 }
230 return null;
231 }
232
233 private String getMergedBodies(ArrayList<Message> messages) {
234 StringBuilder text = new StringBuilder();
235 for (int i = 0; i < messages.size(); ++i) {
236 text.append(getReadableBody(messages.get(i)));
237 if (i != messages.size() - 1) {
238 text.append("\n");
239 }
240 }
241 return text.toString();
242 }
243
244 private String getReadableBody(Message message) {
245 if (message.getDownloadable() != null
246 && (message.getDownloadable().getStatus() == Downloadable.STATUS_OFFER || message
247 .getDownloadable().getStatus() == Downloadable.STATUS_OFFER_CHECK_FILESIZE)) {
248 return mXmppConnectionService.getText(
249 R.string.image_offered_for_download).toString();
250 } else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
251 return mXmppConnectionService.getText(
252 R.string.encrypted_message_received).toString();
253 } else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) {
254 return mXmppConnectionService.getText(R.string.decryption_failed)
255 .toString();
256 } else if (message.getType() == Message.TYPE_IMAGE) {
257 return mXmppConnectionService.getText(R.string.image_file)
258 .toString();
259 } else {
260 return message.getBody().trim();
261 }
262 }
263
264 private PendingIntent createContentIntent(String conversationUuid) {
265 TaskStackBuilder stackBuilder = TaskStackBuilder
266 .create(mXmppConnectionService);
267 stackBuilder.addParentStack(ConversationActivity.class);
268
269 Intent viewConversationIntent = new Intent(mXmppConnectionService,
270 ConversationActivity.class);
271 viewConversationIntent.setAction(Intent.ACTION_VIEW);
272 viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
273 conversationUuid);
274 viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
275
276 stackBuilder.addNextIntent(viewConversationIntent);
277
278 PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
279 PendingIntent.FLAG_UPDATE_CURRENT);
280 return resultPendingIntent;
281 }
282
283 private PendingIntent createDeleteIntent() {
284 Intent intent = new Intent(mXmppConnectionService,
285 XmppConnectionService.class);
286 intent.setAction("clear_notification");
287 return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
288 }
289
290 public static boolean wasHighlightedOrPrivate(Message message) {
291 String nick = message.getConversation().getMucOptions().getActualNick();
292 Pattern highlight = generateNickHighlightPattern(nick);
293 if (message.getBody() == null || nick == null) {
294 return false;
295 }
296 Matcher m = highlight.matcher(message.getBody());
297 return (m.find() || message.getType() == Message.TYPE_PRIVATE);
298 }
299
300 private static Pattern generateNickHighlightPattern(String nick) {
301 // We expect a word boundary, i.e. space or start of string, followed by
302 // the
303 // nick (matched in case-insensitive manner), followed by optional
304 // punctuation (for example "bob: i disagree" or "how are you alice?"),
305 // followed by another word boundary.
306 return Pattern.compile("\\b" + nick + "\\p{Punct}?\\b",
307 Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
308 }
309
310 public void setOpenConversation(Conversation conversation) {
311 this.mOpenConversation = conversation;
312 }
313
314 public void setIsInForeground(boolean foreground) {
315 this.mIsInForeground = foreground;
316 }
317
318 private int getPixel(int dp) {
319 DisplayMetrics metrics = mXmppConnectionService.getResources()
320 .getDisplayMetrics();
321 return ((int) (dp * metrics.density));
322 }
323
324 private void markLastNotification() {
325 this.mLastNotification = SystemClock.elapsedRealtime();
326 }
327
328 private boolean inMiniGracePeriod(Account account) {
329 int miniGrace = account.getStatus() == Account.STATUS_ONLINE ? Config.MINI_GRACE_PERIOD
330 : Config.MINI_GRACE_PERIOD * 2;
331 return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
332 }
333}