MessageArchiveService.java

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