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