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