1package eu.siacs.conversations.services;
2
3import java.util.ArrayList;
4import java.util.Iterator;
5import java.util.LinkedHashMap;
6import java.util.Map.Entry;
7import java.util.regex.Matcher;
8import java.util.regex.Pattern;
9
10import android.app.Notification;
11import android.app.NotificationManager;
12import android.app.PendingIntent;
13import android.content.Context;
14import android.content.Intent;
15import android.content.SharedPreferences;
16import android.net.Uri;
17import android.os.PowerManager;
18import android.support.v4.app.NotificationCompat;
19import android.support.v4.app.TaskStackBuilder;
20import android.text.Html;
21import android.util.DisplayMetrics;
22
23import eu.siacs.conversations.R;
24import eu.siacs.conversations.entities.Account;
25import eu.siacs.conversations.entities.Conversation;
26import eu.siacs.conversations.entities.Message;
27import eu.siacs.conversations.ui.ConversationActivity;
28
29public class NotificationService {
30
31 private XmppConnectionService mXmppConnectionService;
32
33 private LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<String, ArrayList<Message>>();
34
35 public int NOTIFICATION_ID = 0x2342;
36 private Conversation mOpenConversation;
37 private boolean mIsInForeground;
38
39 public NotificationService(XmppConnectionService service) {
40 this.mXmppConnectionService = service;
41 }
42
43 public void push(Message message) {
44 PowerManager pm = (PowerManager) mXmppConnectionService
45 .getSystemService(Context.POWER_SERVICE);
46 boolean isScreenOn = pm.isScreenOn();
47
48 if (this.mIsInForeground && isScreenOn
49 && this.mOpenConversation == message.getConversation()) {
50 return;
51 }
52 synchronized (notifications) {
53 String conversationUuid = message.getConversationUuid();
54 if (notifications.containsKey(conversationUuid)) {
55 notifications.get(conversationUuid).add(message);
56 } else {
57 ArrayList<Message> mList = new ArrayList<Message>();
58 mList.add(message);
59 notifications.put(conversationUuid, mList);
60 }
61 }
62 Account account = message.getConversation().getAccount();
63 updateNotification((!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
64 && !account.inGracePeriod());
65 }
66
67 public void clear() {
68 synchronized (notifications) {
69 notifications.clear();
70 }
71 updateNotification(false);
72 }
73
74 public void clear(Conversation conversation) {
75 synchronized (notifications) {
76 notifications.remove(conversation.getUuid());
77 }
78 updateNotification(false);
79 }
80
81 private void updateNotification(boolean notify) {
82 NotificationManager notificationManager = (NotificationManager) mXmppConnectionService
83 .getSystemService(Context.NOTIFICATION_SERVICE);
84 SharedPreferences preferences = mXmppConnectionService.getPreferences();
85
86 String ringtone = preferences.getString("notification_ringtone", null);
87 boolean vibrate = preferences.getBoolean("vibrate_on_notification",
88 true);
89
90 if (notifications.size() == 0) {
91 notificationManager.cancel(NOTIFICATION_ID);
92 } else {
93 NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
94 mXmppConnectionService);
95 mBuilder.setSmallIcon(R.drawable.ic_notification);
96 if (notifications.size() == 1) {
97 ArrayList<Message> messages = notifications.values().iterator()
98 .next();
99 if (messages.size() >= 1) {
100 Conversation conversation = messages.get(0)
101 .getConversation();
102 mBuilder.setLargeIcon(mXmppConnectionService
103 .getAvatarService().get(conversation, getPixel(64)));
104 mBuilder.setContentTitle(conversation.getName());
105 StringBuilder text = new StringBuilder();
106 for (int i = 0; i < messages.size(); ++i) {
107 text.append(messages.get(i).getReadableBody(
108 mXmppConnectionService));
109 if (i != messages.size() - 1) {
110 text.append("\n");
111 }
112 }
113 mBuilder.setStyle(new NotificationCompat.BigTextStyle()
114 .bigText(text.toString()));
115 mBuilder.setContentText(messages.get(0).getReadableBody(
116 mXmppConnectionService));
117 if (notify) {
118 mBuilder.setTicker(messages.get(messages.size() - 1)
119 .getReadableBody(mXmppConnectionService));
120 }
121 mBuilder.setContentIntent(createContentIntent(conversation
122 .getUuid()));
123 } else {
124 notificationManager.cancel(NOTIFICATION_ID);
125 return;
126 }
127 } else {
128 NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
129 style.setBigContentTitle(notifications.size()
130 + " "
131 + mXmppConnectionService
132 .getString(R.string.unread_conversations));
133 StringBuilder names = new StringBuilder();
134 Conversation conversation = null;
135 Iterator<Entry<String, ArrayList<Message>>> it = notifications
136 .entrySet().iterator();
137 while (it.hasNext()) {
138 Entry<String, ArrayList<Message>> entry = it.next();
139 ArrayList<Message> messages = entry.getValue();
140 if (messages.size() > 0) {
141 conversation = messages.get(0).getConversation();
142 String name = conversation.getName();
143 style.addLine(Html.fromHtml("<b>"
144 + name
145 + "</b> "
146 + messages.get(0).getReadableBody(
147 mXmppConnectionService)));
148 names.append(name);
149 names.append(", ");
150 }
151 it.remove();
152 }
153 if (names.length() >= 2) {
154 names.delete(names.length() - 2, names.length());
155 }
156 mBuilder.setContentTitle(notifications.size()
157 + " "
158 + mXmppConnectionService
159 .getString(R.string.unread_conversations));
160 mBuilder.setContentText(names.toString());
161 mBuilder.setStyle(style);
162 if (conversation != null) {
163 mBuilder.setContentIntent(createContentIntent(conversation
164 .getUuid()));
165 }
166 }
167 if (notify) {
168 if (vibrate) {
169 int dat = 70;
170 long[] pattern = { 0, 3 * dat, dat, dat };
171 mBuilder.setVibrate(pattern);
172 }
173 if (ringtone != null) {
174 mBuilder.setSound(Uri.parse(ringtone));
175 }
176 }
177 mBuilder.setDeleteIntent(createDeleteIntent());
178 mBuilder.setLights(0xffffffff, 2000, 4000);
179 Notification notification = mBuilder.build();
180 notificationManager.notify(NOTIFICATION_ID, notification);
181 }
182 }
183
184 private PendingIntent createContentIntent(String conversationUuid) {
185 TaskStackBuilder stackBuilder = TaskStackBuilder
186 .create(mXmppConnectionService);
187 stackBuilder.addParentStack(ConversationActivity.class);
188
189 Intent viewConversationIntent = new Intent(mXmppConnectionService,
190 ConversationActivity.class);
191 viewConversationIntent.setAction(Intent.ACTION_VIEW);
192 viewConversationIntent.putExtra(ConversationActivity.CONVERSATION,
193 conversationUuid);
194 viewConversationIntent.setType(ConversationActivity.VIEW_CONVERSATION);
195
196 stackBuilder.addNextIntent(viewConversationIntent);
197
198 PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
199 PendingIntent.FLAG_UPDATE_CURRENT);
200 return resultPendingIntent;
201 }
202
203 private PendingIntent createDeleteIntent() {
204 Intent intent = new Intent(mXmppConnectionService,
205 XmppConnectionService.class);
206 intent.setAction("clear_notification");
207 return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
208 }
209
210 public static boolean wasHighlightedOrPrivate(Message message) {
211 String nick = message.getConversation().getMucOptions().getActualNick();
212 Pattern highlight = generateNickHighlightPattern(nick);
213 if (message.getBody() == null || nick == null) {
214 return false;
215 }
216 Matcher m = highlight.matcher(message.getBody());
217 return (m.find() || message.getType() == Message.TYPE_PRIVATE);
218 }
219
220 private static Pattern generateNickHighlightPattern(String nick) {
221 // We expect a word boundary, i.e. space or start of string, followed by
222 // the
223 // nick (matched in case-insensitive manner), followed by optional
224 // punctuation (for example "bob: i disagree" or "how are you alice?"),
225 // followed by another word boundary.
226 return Pattern.compile("\\b" + nick + "\\p{Punct}?\\b",
227 Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
228 }
229
230 public void setOpenConversation(Conversation conversation) {
231 this.mOpenConversation = conversation;
232 }
233
234 public void setIsInForeground(boolean foreground) {
235 this.mIsInForeground = foreground;
236 }
237
238 private int getPixel(int dp) {
239 DisplayMetrics metrics = mXmppConnectionService.getResources()
240 .getDisplayMetrics();
241 return ((int) (dp * metrics.density));
242 }
243}