1package eu.siacs.conversations.services;
2
3import android.util.Log;
4
5import java.math.BigInteger;
6import java.util.ArrayList;
7import java.util.HashSet;
8import java.util.Iterator;
9import java.util.List;
10
11import eu.siacs.conversations.Config;
12import eu.siacs.conversations.R;
13import eu.siacs.conversations.entities.Account;
14import eu.siacs.conversations.entities.Conversation;
15import eu.siacs.conversations.generator.AbstractGenerator;
16import eu.siacs.conversations.xml.Element;
17import eu.siacs.conversations.xmpp.OnAdvancedStreamFeaturesLoaded;
18import eu.siacs.conversations.xmpp.OnIqPacketReceived;
19import eu.siacs.conversations.xmpp.jid.Jid;
20import eu.siacs.conversations.xmpp.stanzas.IqPacket;
21
22public class MessageArchiveService implements OnAdvancedStreamFeaturesLoaded {
23
24 private final XmppConnectionService mXmppConnectionService;
25
26 private final HashSet<Query> queries = new HashSet<Query>();
27 private final ArrayList<Query> pendingQueries = new ArrayList<Query>();
28
29 public enum PagingOrder {
30 NORMAL,
31 REVERSE
32 };
33
34 public MessageArchiveService(final XmppConnectionService service) {
35 this.mXmppConnectionService = service;
36 }
37
38 private void catchup(final Account account) {
39 synchronized (this.queries) {
40 for(Iterator<Query> iterator = this.queries.iterator(); iterator.hasNext();) {
41 Query query = iterator.next();
42 if (query.getAccount() == account) {
43 iterator.remove();
44 }
45 }
46 }
47 long startCatchup = getLastMessageTransmitted(account);
48 long endCatchup = account.getXmppConnection().getLastSessionEstablished();
49 if (startCatchup == 0) {
50 return;
51 } else if (endCatchup - startCatchup >= Config.MAM_MAX_CATCHUP) {
52 startCatchup = endCatchup - Config.MAM_MAX_CATCHUP;
53 List<Conversation> conversations = mXmppConnectionService.getConversations();
54 for (Conversation conversation : conversations) {
55 if (conversation.getMode() == Conversation.MODE_SINGLE && conversation.getAccount() == account && startCatchup > conversation.getLastMessageTransmitted()) {
56 this.query(conversation,startCatchup);
57 }
58 }
59 }
60 final Query query = new Query(account, startCatchup, endCatchup);
61 this.queries.add(query);
62 this.execute(query);
63 }
64
65 public void catchupMUC(final Conversation conversation) {
66 if (conversation.getLastMessageTransmitted() < 0 && conversation.countMessages() == 0) {
67 query(conversation,
68 0,
69 System.currentTimeMillis());
70 } else {
71 query(conversation,
72 conversation.getLastMessageTransmitted(),
73 System.currentTimeMillis());
74 }
75 }
76
77 private long getLastMessageTransmitted(final Account account) {
78 long timestamp = 0;
79 for(final Conversation conversation : mXmppConnectionService.getConversations()) {
80 if (conversation.getAccount() == account) {
81 long tmp = conversation.getLastMessageTransmitted();
82 if (tmp > timestamp) {
83 timestamp = tmp;
84 }
85 }
86 }
87 return timestamp;
88 }
89
90 public Query query(final Conversation conversation) {
91 if (conversation.getLastMessageTransmitted() < 0 && conversation.countMessages() == 0) {
92 return query(conversation,
93 0,
94 System.currentTimeMillis());
95 } else {
96 return query(conversation,
97 conversation.getLastMessageTransmitted(),
98 conversation.getAccount().getXmppConnection().getLastSessionEstablished());
99 }
100 }
101
102 public Query query(final Conversation conversation, long end) {
103 return this.query(conversation,conversation.getLastMessageTransmitted(),end);
104 }
105
106 public Query query(Conversation conversation, long start, long end) {
107 synchronized (this.queries) {
108 if (start > end) {
109 return null;
110 }
111 final Query query = new Query(conversation, start, end,PagingOrder.REVERSE);
112 this.queries.add(query);
113 this.execute(query);
114 return query;
115 }
116 }
117
118 public void executePendingQueries(final Account account) {
119 List<Query> pending = new ArrayList<>();
120 synchronized(this.pendingQueries) {
121 for(Iterator<Query> iterator = this.pendingQueries.iterator(); iterator.hasNext();) {
122 Query query = iterator.next();
123 if (query.getAccount() == account) {
124 pending.add(query);
125 iterator.remove();
126 }
127 }
128 }
129 for(Query query : pending) {
130 this.execute(query);
131 }
132 }
133
134 private void execute(final Query query) {
135 final Account account= query.getAccount();
136 if (account.getStatus() == Account.State.ONLINE) {
137 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": running mam query " + query.toString());
138 IqPacket packet = this.mXmppConnectionService.getIqGenerator().queryMessageArchiveManagement(query);
139 this.mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
140 @Override
141 public void onIqPacketReceived(Account account, IqPacket packet) {
142 if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
143 synchronized (MessageArchiveService.this.queries) {
144 MessageArchiveService.this.queries.remove(query);
145 if (query.hasCallback()) {
146 query.callback();
147 }
148 }
149 } else if (packet.getType() != IqPacket.TYPE.RESULT) {
150 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": error executing mam: " + packet.toString());
151 finalizeQuery(query);
152 }
153 }
154 });
155 } else {
156 synchronized (this.pendingQueries) {
157 this.pendingQueries.add(query);
158 }
159 }
160 }
161
162 private void finalizeQuery(Query query) {
163 synchronized (this.queries) {
164 this.queries.remove(query);
165 }
166 final Conversation conversation = query.getConversation();
167 if (conversation != null) {
168 conversation.sort();
169 if (conversation.setLastMessageTransmitted(query.getEnd())) {
170 this.mXmppConnectionService.databaseBackend.updateConversation(conversation);
171 }
172 conversation.setHasMessagesLeftOnServer(query.getMessageCount() > 0);
173 if (query.hasCallback()) {
174 query.callback();
175 } else {
176 this.mXmppConnectionService.updateConversationUi();
177 }
178 } else {
179 for(Conversation tmp : this.mXmppConnectionService.getConversations()) {
180 if (tmp.getAccount() == query.getAccount()) {
181 tmp.sort();
182 if (tmp.setLastMessageTransmitted(query.getEnd())) {
183 this.mXmppConnectionService.databaseBackend.updateConversation(tmp);
184 }
185 }
186 }
187 }
188 }
189
190 public boolean queryInProgress(Conversation conversation, XmppConnectionService.OnMoreMessagesLoaded callback) {
191 synchronized (this.queries) {
192 for(Query query : queries) {
193 if (query.conversation == conversation) {
194 if (!query.hasCallback() && callback != null) {
195 query.setCallback(callback);
196 }
197 return true;
198 }
199 }
200 return false;
201 }
202 }
203
204 public void processFin(Element fin, Jid from) {
205 if (fin == null) {
206 return;
207 }
208 Query query = findQuery(fin.getAttribute("queryid"));
209 if (query == null || !query.validFrom(from)) {
210 return;
211 }
212 boolean complete = fin.getAttributeAsBoolean("complete");
213 Element set = fin.findChild("set","http://jabber.org/protocol/rsm");
214 Element last = set == null ? null : set.findChild("last");
215 Element first = set == null ? null : set.findChild("first");
216 Element relevant = query.getPagingOrder() == PagingOrder.NORMAL ? last : first;
217 boolean abort = (query.getStart() == 0 && query.getTotalCount() >= Config.PAGE_SIZE) || query.getTotalCount() >= Config.MAM_MAX_MESSAGES;
218 if (complete || relevant == null || abort) {
219 this.finalizeQuery(query);
220 Log.d(Config.LOGTAG,query.getAccount().getJid().toBareJid().toString()+": finished mam after "+query.getTotalCount()+" messages");
221 if (query.getWith() == null && query.getTotalCount() > 0) {
222 mXmppConnectionService.getNotificationService().finishBacklog(true);
223 }
224 } else {
225 final Query nextQuery;
226 if (query.getPagingOrder() == PagingOrder.NORMAL) {
227 nextQuery = query.next(last == null ? null : last.getContent());
228 } else {
229 nextQuery = query.prev(first == null ? null : first.getContent());
230 }
231 this.execute(nextQuery);
232 this.finalizeQuery(query);
233 synchronized (this.queries) {
234 this.queries.remove(query);
235 this.queries.add(nextQuery);
236 }
237 }
238 }
239
240 public Query findQuery(String id) {
241 if (id == null) {
242 return null;
243 }
244 synchronized (this.queries) {
245 for(Query query : this.queries) {
246 if (query.getQueryId().equals(id)) {
247 return query;
248 }
249 }
250 return null;
251 }
252 }
253
254 @Override
255 public void onAdvancedStreamFeaturesAvailable(Account account) {
256 if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().mam()) {
257 this.catchup(account);
258 }
259 }
260
261 public class Query {
262 private int totalCount = 0;
263 private int messageCount = 0;
264 private long start;
265 private long end;
266 private String queryId;
267 private String reference = null;
268 private Account account;
269 private Conversation conversation;
270 private PagingOrder pagingOrder = PagingOrder.NORMAL;
271 private XmppConnectionService.OnMoreMessagesLoaded callback = null;
272
273
274 public Query(Conversation conversation, long start, long end) {
275 this(conversation.getAccount(), start, end);
276 this.conversation = conversation;
277 }
278
279 public Query(Conversation conversation, long start, long end, PagingOrder order) {
280 this(conversation,start,end);
281 this.pagingOrder = order;
282 }
283
284 public Query(Account account, long start, long end) {
285 this.account = account;
286 this.start = start;
287 this.end = end;
288 this.queryId = new BigInteger(50, mXmppConnectionService.getRNG()).toString(32);
289 }
290
291 private Query page(String reference) {
292 Query query = new Query(this.account,this.start,this.end);
293 query.reference = reference;
294 query.conversation = conversation;
295 query.totalCount = totalCount;
296 query.callback = callback;
297 return query;
298 }
299
300 public Query next(String reference) {
301 Query query = page(reference);
302 query.pagingOrder = PagingOrder.NORMAL;
303 return query;
304 }
305
306 public Query prev(String reference) {
307 Query query = page(reference);
308 query.pagingOrder = PagingOrder.REVERSE;
309 return query;
310 }
311
312 public String getReference() {
313 return reference;
314 }
315
316 public PagingOrder getPagingOrder() {
317 return this.pagingOrder;
318 }
319
320 public String getQueryId() {
321 return queryId;
322 }
323
324 public Jid getWith() {
325 return conversation == null ? null : conversation.getJid().toBareJid();
326 }
327
328 public boolean muc() {
329 return conversation != null && conversation.getMode() == Conversation.MODE_MULTI;
330 }
331
332 public long getStart() {
333 return start;
334 }
335
336 public void setCallback(XmppConnectionService.OnMoreMessagesLoaded callback) {
337 this.callback = callback;
338 }
339
340 public void callback() {
341 if (this.callback != null) {
342 this.callback.onMoreMessagesLoaded(messageCount,conversation);
343 if (messageCount == 0) {
344 this.callback.informUser(R.string.no_more_history_on_server);
345 }
346 }
347 }
348
349 public long getEnd() {
350 return end;
351 }
352
353 public Conversation getConversation() {
354 return conversation;
355 }
356
357 public Account getAccount() {
358 return this.account;
359 }
360
361 public void incrementTotalCount() {
362 this.totalCount++;
363 }
364
365 public void incrementMessageCount() {
366 this.messageCount++;
367 }
368
369 public int getTotalCount() {
370 return this.totalCount;
371 }
372
373 public int getMessageCount() {
374 return this.messageCount;
375 }
376
377 public boolean validFrom(Jid from) {
378 if (muc()) {
379 return getWith().equals(from);
380 } else {
381 return (from == null) || account.getJid().toBareJid().equals(from.toBareJid());
382 }
383 }
384
385 @Override
386 public String toString() {
387 StringBuilder builder = new StringBuilder();
388 if (this.muc()) {
389 builder.append("to="+this.getWith().toString());
390 } else {
391 builder.append("with=");
392 if (this.getWith() == null) {
393 builder.append("*");
394 } else {
395 builder.append(getWith().toString());
396 }
397 }
398 builder.append(", start=");
399 builder.append(AbstractGenerator.getTimestamp(this.start));
400 builder.append(", end=");
401 builder.append(AbstractGenerator.getTimestamp(this.end));
402 if (this.reference!=null) {
403 if (this.pagingOrder == PagingOrder.NORMAL) {
404 builder.append(", after=");
405 } else {
406 builder.append(", before=");
407 }
408 builder.append(this.reference);
409 }
410 return builder.toString();
411 }
412
413 public boolean hasCallback() {
414 return this.callback != null;
415 }
416 }
417}