MessageArchiveService.java

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