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 long startCatchup = getLastMessageTransmitted(account);
49 long endCatchup = account.getXmppConnection().getLastSessionEstablished();
50 if (startCatchup == 0) {
51 return;
52 } else if (endCatchup - startCatchup >= Config.MAM_MAX_CATCHUP) {
53 startCatchup = endCatchup - Config.MAM_MAX_CATCHUP;
54 List<Conversation> conversations = mXmppConnectionService.getConversations();
55 for (Conversation conversation : conversations) {
56 if (conversation.getMode() == Conversation.MODE_SINGLE && conversation.getAccount() == account && startCatchup > conversation.getLastMessageTransmitted()) {
57 this.query(conversation,startCatchup);
58 }
59 }
60 }
61 final Query query = new Query(account, startCatchup, endCatchup);
62 this.queries.add(query);
63 this.execute(query);
64 }
65
66 public void catchupMUC(final Conversation conversation) {
67 if (conversation.getLastMessageTransmitted() < 0 && conversation.countMessages() == 0) {
68 query(conversation,
69 0,
70 System.currentTimeMillis());
71 } else {
72 query(conversation,
73 conversation.getLastMessageTransmitted(),
74 System.currentTimeMillis());
75 }
76 }
77
78 private long getLastMessageTransmitted(final Account account) {
79 Pair<Long,String> pair = mXmppConnectionService.databaseBackend.getLastMessageReceived(account);
80 return pair == null ? 0 : pair.first;
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.remove(query);
231 this.queries.add(nextQuery);
232 }
233 }
234 }
235
236 public Query findQuery(String id) {
237 if (id == null) {
238 return null;
239 }
240 synchronized (this.queries) {
241 for(Query query : this.queries) {
242 if (query.getQueryId().equals(id)) {
243 return query;
244 }
245 }
246 return null;
247 }
248 }
249
250 @Override
251 public void onAdvancedStreamFeaturesAvailable(Account account) {
252 if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().mam()) {
253 this.catchup(account);
254 }
255 }
256
257 public class Query {
258 private int totalCount = 0;
259 private int messageCount = 0;
260 private long start;
261 private long end;
262 private String queryId;
263 private String reference = null;
264 private Account account;
265 private Conversation conversation;
266 private PagingOrder pagingOrder = PagingOrder.NORMAL;
267 private XmppConnectionService.OnMoreMessagesLoaded callback = null;
268
269
270 public Query(Conversation conversation, long start, long end) {
271 this(conversation.getAccount(), start, end);
272 this.conversation = conversation;
273 }
274
275 public Query(Conversation conversation, long start, long end, PagingOrder order) {
276 this(conversation,start,end);
277 this.pagingOrder = order;
278 }
279
280 public Query(Account account, long start, long end) {
281 this.account = account;
282 this.start = start;
283 this.end = end;
284 this.queryId = new BigInteger(50, mXmppConnectionService.getRNG()).toString(32);
285 }
286
287 private Query page(String reference) {
288 Query query = new Query(this.account,this.start,this.end);
289 query.reference = reference;
290 query.conversation = conversation;
291 query.totalCount = totalCount;
292 query.callback = callback;
293 return query;
294 }
295
296 public Query next(String reference) {
297 Query query = page(reference);
298 query.pagingOrder = PagingOrder.NORMAL;
299 return query;
300 }
301
302 public Query prev(String reference) {
303 Query query = page(reference);
304 query.pagingOrder = PagingOrder.REVERSE;
305 return query;
306 }
307
308 public String getReference() {
309 return reference;
310 }
311
312 public PagingOrder getPagingOrder() {
313 return this.pagingOrder;
314 }
315
316 public String getQueryId() {
317 return queryId;
318 }
319
320 public Jid getWith() {
321 return conversation == null ? null : conversation.getJid().toBareJid();
322 }
323
324 public boolean muc() {
325 return conversation != null && conversation.getMode() == Conversation.MODE_MULTI;
326 }
327
328 public long getStart() {
329 return start;
330 }
331
332 public void setCallback(XmppConnectionService.OnMoreMessagesLoaded callback) {
333 this.callback = callback;
334 }
335
336 public void callback(boolean done) {
337 if (this.callback != null) {
338 this.callback.onMoreMessagesLoaded(messageCount,conversation);
339 if (done) {
340 this.callback.informUser(R.string.no_more_history_on_server);
341 }
342 }
343 }
344
345 public long getEnd() {
346 return end;
347 }
348
349 public Conversation getConversation() {
350 return conversation;
351 }
352
353 public Account getAccount() {
354 return this.account;
355 }
356
357 public void incrementMessageCount() {
358 this.messageCount++;
359 this.totalCount++;
360 }
361
362 public int getTotalCount() {
363 return this.totalCount;
364 }
365
366 public int getMessageCount() {
367 return this.messageCount;
368 }
369
370 public boolean validFrom(Jid from) {
371 if (muc()) {
372 return getWith().equals(from);
373 } else {
374 return (from == null) || account.getJid().toBareJid().equals(from.toBareJid());
375 }
376 }
377
378 @Override
379 public String toString() {
380 StringBuilder builder = new StringBuilder();
381 if (this.muc()) {
382 builder.append("to=");
383 builder.append(this.getWith().toString());
384 } else {
385 builder.append("with=");
386 if (this.getWith() == null) {
387 builder.append("*");
388 } else {
389 builder.append(getWith().toString());
390 }
391 }
392 builder.append(", start=");
393 builder.append(AbstractGenerator.getTimestamp(this.start));
394 builder.append(", end=");
395 builder.append(AbstractGenerator.getTimestamp(this.end));
396 if (this.reference!=null) {
397 if (this.pagingOrder == PagingOrder.NORMAL) {
398 builder.append(", after=");
399 } else {
400 builder.append(", before=");
401 }
402 builder.append(this.reference);
403 }
404 return builder.toString();
405 }
406
407 public boolean hasCallback() {
408 return this.callback != null;
409 }
410 }
411}