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