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 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_ERROR) {
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			if (query.hasCallback()) {
138				query.callback();
139			} else {
140				this.mXmppConnectionService.updateConversationUi();
141			}
142		} else {
143			for(Conversation tmp : this.mXmppConnectionService.getConversations()) {
144				if (tmp.getAccount() == query.getAccount()) {
145					tmp.sort();
146					if (tmp.setLastMessageTransmitted(query.getEnd())) {
147						this.mXmppConnectionService.databaseBackend.updateConversation(tmp);
148					}
149				}
150			}
151		}
152	}
153
154	public boolean queryInProgress(Conversation conversation, XmppConnectionService.OnMoreMessagesLoaded callback) {
155		synchronized (this.queries) {
156			for(Query query : queries) {
157				if (query.conversation == conversation) {
158					if (!query.hasCallback() && callback != null) {
159						query.setCallback(callback);
160					}
161					return true;
162				}
163			}
164			return false;
165		}
166	}
167
168	public void processFin(Element fin) {
169		if (fin == null) {
170			return;
171		}
172		Query query = findQuery(fin.getAttribute("queryid"));
173		if (query == null) {
174			return;
175		}
176		boolean complete = fin.getAttributeAsBoolean("complete");
177		Element set = fin.findChild("set","http://jabber.org/protocol/rsm");
178		Element last = set == null ? null : set.findChild("last");
179		Element first = set == null ? null : set.findChild("first");
180		Element relevant = query.getPagingOrder() == PagingOrder.NORMAL ? last : first;
181		boolean abort = (query.getStart() == 0 && query.getTotalCount() >= Config.PAGE_SIZE) || query.getTotalCount() >= Config.MAM_MAX_MESSAGES;
182		if (complete || relevant == null || abort) {
183			this.finalizeQuery(query);
184			Log.d(Config.LOGTAG,query.getAccount().getJid().toBareJid().toString()+": finished mam after "+query.getTotalCount()+" messages");
185		} else {
186			final Query nextQuery;
187			if (query.getPagingOrder() == PagingOrder.NORMAL) {
188				nextQuery = query.next(last == null ? null : last.getContent());
189			} else {
190				nextQuery = query.prev(first == null ? null : first.getContent());
191			}
192			this.execute(nextQuery);
193			this.finalizeQuery(query);
194			synchronized (this.queries) {
195				this.queries.remove(query);
196				this.queries.add(nextQuery);
197			}
198		}
199	}
200
201	public Query findQuery(String id) {
202		if (id == null) {
203			return null;
204		}
205		synchronized (this.queries) {
206			for(Query query : this.queries) {
207				if (query.getQueryId().equals(id)) {
208					return query;
209				}
210			}
211			return null;
212		}
213	}
214
215	@Override
216	public void onAdvancedStreamFeaturesAvailable(Account account) {
217		if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().mam()) {
218			this.catchup(account);
219		}
220	}
221
222	public class Query {
223		private int totalCount = 0;
224		private int messageCount = 0;
225		private long start;
226		private long end;
227		private Jid with = null;
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			this.with = conversation.getContactJid().toBareJid();
240		}
241
242		public Query(Conversation conversation, long start, long end, PagingOrder order) {
243			this(conversation,start,end);
244			this.pagingOrder = order;
245		}
246
247		public Query(Account account, long start, long end) {
248			this.account = account;
249			this.start = start;
250			this.end = end;
251			this.queryId = new BigInteger(50, mXmppConnectionService.getRNG()).toString(32);
252		}
253
254		private Query page(String reference) {
255			Query query = new Query(this.account,this.start,this.end);
256			query.reference = reference;
257			query.conversation = conversation;
258			query.with = with;
259			query.totalCount = totalCount;
260			query.callback = callback;
261			return query;
262		}
263
264		public Query next(String reference) {
265			Query query = page(reference);
266			query.pagingOrder = PagingOrder.NORMAL;
267			return query;
268		}
269
270		public Query prev(String reference) {
271			Query query = page(reference);
272			query.pagingOrder = PagingOrder.REVERSE;
273			return query;
274		}
275
276		public String getReference() {
277			return reference;
278		}
279
280		public PagingOrder getPagingOrder() {
281			return this.pagingOrder;
282		}
283
284		public String getQueryId() {
285			return queryId;
286		}
287
288		public Jid getWith() {
289			return with;
290		}
291
292		public long getStart() {
293			return start;
294		}
295
296		public void setCallback(XmppConnectionService.OnMoreMessagesLoaded callback) {
297			this.callback = callback;
298		}
299
300		public void callback() {
301			if (this.callback != null) {
302				this.callback.onMoreMessagesLoaded(messageCount,conversation);
303				if (messageCount==0) {
304					this.callback.informUser(R.string.no_more_history_on_server);
305				}
306			}
307		}
308
309		public long getEnd() {
310			return end;
311		}
312
313		public Conversation getConversation() {
314			return conversation;
315		}
316
317		public Account getAccount() {
318			return this.account;
319		}
320
321		public void incrementTotalCount() {
322			this.totalCount++;
323		}
324
325		public void incrementMessageCount() {
326			this.messageCount++;
327		}
328
329		public int getTotalCount() {
330			return this.totalCount;
331		}
332
333		@Override
334		public String toString() {
335			StringBuilder builder = new StringBuilder();
336			builder.append("with=");
337			if (this.with==null) {
338				builder.append("*");
339			} else {
340				builder.append(with.toString());
341			}
342			builder.append(", start=");
343			builder.append(AbstractGenerator.getTimestamp(this.start));
344			builder.append(", end=");
345			builder.append(AbstractGenerator.getTimestamp(this.end));
346			if (this.reference!=null) {
347				if (this.pagingOrder == PagingOrder.NORMAL) {
348					builder.append(", after=");
349				} else {
350					builder.append(", before=");
351				}
352				builder.append(this.reference);
353			}
354			return builder.toString();
355		}
356
357		public boolean hasCallback() {
358			return this.callback != null;
359		}
360	}
361}