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