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.getMessageCount() >= Config.PAGE_SIZE) || query.getMessageCount() >= 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.getMessageCount()+" 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 messageCount = 0;
250		private long start;
251		private long end;
252		private String queryId;
253		private String reference = null;
254		private Account account;
255		private Conversation conversation;
256		private PagingOrder pagingOrder = PagingOrder.NORMAL;
257		private XmppConnectionService.OnMoreMessagesLoaded callback = null;
258
259
260		public Query(Conversation conversation, long start, long end) {
261			this(conversation.getAccount(), start, end);
262			this.conversation = conversation;
263		}
264
265		public Query(Conversation conversation, long start, long end, PagingOrder order) {
266			this(conversation,start,end);
267			this.pagingOrder = order;
268		}
269
270		public Query(Account account, long start, long end) {
271			this.account = account;
272			this.start = start;
273			this.end = end;
274			this.queryId = new BigInteger(50, mXmppConnectionService.getRNG()).toString(32);
275		}
276
277		private Query page(String reference) {
278			Query query = new Query(this.account,this.start,this.end);
279			query.reference = reference;
280			query.conversation = conversation;
281			query.callback = callback;
282			return query;
283		}
284
285		public Query next(String reference) {
286			Query query = page(reference);
287			query.pagingOrder = PagingOrder.NORMAL;
288			return query;
289		}
290
291		public Query prev(String reference) {
292			Query query = page(reference);
293			query.pagingOrder = PagingOrder.REVERSE;
294			return query;
295		}
296
297		public String getReference() {
298			return reference;
299		}
300
301		public PagingOrder getPagingOrder() {
302			return this.pagingOrder;
303		}
304
305		public String getQueryId() {
306			return queryId;
307		}
308
309		public Jid getWith() {
310			return conversation == null ? null : conversation.getJid().toBareJid();
311		}
312
313		public boolean muc() {
314			return conversation != null && conversation.getMode() == Conversation.MODE_MULTI;
315		}
316
317		public long getStart() {
318			return start;
319		}
320
321		public void setCallback(XmppConnectionService.OnMoreMessagesLoaded callback) {
322			this.callback = callback;
323		}
324
325		public void callback() {
326			if (this.callback != null) {
327				this.callback.onMoreMessagesLoaded(messageCount,conversation);
328				if (messageCount == 0) {
329					this.callback.informUser(R.string.no_more_history_on_server);
330				}
331			}
332		}
333
334		public long getEnd() {
335			return end;
336		}
337
338		public Conversation getConversation() {
339			return conversation;
340		}
341
342		public Account getAccount() {
343			return this.account;
344		}
345
346		public void incrementMessageCount() {
347			this.messageCount++;
348		}
349
350		public int getMessageCount() {
351			return this.messageCount;
352		}
353
354		public boolean validFrom(Jid from) {
355			if (muc()) {
356				return getWith().equals(from);
357			} else {
358				return (from == null) || account.getJid().toBareJid().equals(from.toBareJid());
359			}
360		}
361
362		@Override
363		public String toString() {
364			StringBuilder builder = new StringBuilder();
365			if (this.muc()) {
366				builder.append("to="+this.getWith().toString());
367			} else {
368				builder.append("with=");
369				if (this.getWith() == null) {
370					builder.append("*");
371				} else {
372					builder.append(getWith().toString());
373				}
374			}
375			builder.append(", start=");
376			builder.append(AbstractGenerator.getTimestamp(this.start));
377			builder.append(", end=");
378			builder.append(AbstractGenerator.getTimestamp(this.end));
379			if (this.reference!=null) {
380				if (this.pagingOrder == PagingOrder.NORMAL) {
381					builder.append(", after=");
382				} else {
383					builder.append(", before=");
384				}
385				builder.append(this.reference);
386			}
387			return builder.toString();
388		}
389
390		public boolean hasCallback() {
391			return this.callback != null;
392		}
393	}
394}