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.entities.Account;
 13import eu.siacs.conversations.entities.Conversation;
 14import eu.siacs.conversations.generator.AbstractGenerator;
 15import eu.siacs.conversations.parser.AbstractParser;
 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.MAX_CATCHUP) {
 44			startCatchup = endCatchup - Config.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 void query(final Conversation conversation) {
 71		query(conversation,conversation.getAccount().getXmppConnection().getLastSessionEstablished());
 72	}
 73
 74	public void query(final Conversation conversation, long end) {
 75		synchronized (this.queries) {
 76			final Account account = conversation.getAccount();
 77			long start = conversation.getLastMessageTransmitted();
 78			if (start > end) {
 79				return;
 80			} else if (end - start >= Config.MAX_HISTORY_AGE) {
 81				start = end - Config.MAX_HISTORY_AGE;
 82			}
 83			final Query query = new Query(conversation, start, end,PagingOrder.REVERSE);
 84			this.queries.add(query);
 85			this.execute(query);
 86		}
 87	}
 88
 89	public void executePendingQueries(final Account account) {
 90		List<Query> pending = new ArrayList<>();
 91		synchronized(this.pendingQueries) {
 92			for(Iterator<Query> iterator = this.pendingQueries.iterator(); iterator.hasNext();) {
 93				Query query = iterator.next();
 94				if (query.getAccount() == account) {
 95					pending.add(query);
 96					iterator.remove();
 97				}
 98			}
 99		}
100		for(Query query : pending) {
101			this.execute(query);
102		}
103	}
104
105	private void execute(final Query query) {
106		final Account account=  query.getAccount();
107		if (account.getStatus() == Account.State.ONLINE) {
108			Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": running mam query " + query.toString());
109			IqPacket packet = this.mXmppConnectionService.getIqGenerator().queryMessageArchiveManagement(query);
110			this.mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
111				@Override
112				public void onIqPacketReceived(Account account, IqPacket packet) {
113					if (packet.getType() == IqPacket.TYPE_ERROR) {
114						Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": error executing mam: " + packet.toString());
115						finalizeQuery(query);
116					}
117				}
118			});
119		} else {
120			synchronized (this.pendingQueries) {
121				this.pendingQueries.add(query);
122			}
123		}
124	}
125
126	private void finalizeQuery(Query query) {
127		synchronized (this.queries) {
128			this.queries.remove(query);
129		}
130		final Conversation conversation = query.getConversation();
131		if (conversation != null) {
132			conversation.sort();
133			if (conversation.setLastMessageTransmitted(query.getEnd())) {
134				this.mXmppConnectionService.databaseBackend.updateConversation(conversation);
135			}
136			this.mXmppConnectionService.updateConversationUi();
137		} else {
138			for(Conversation tmp : this.mXmppConnectionService.getConversations()) {
139				if (tmp.getAccount() == query.getAccount()) {
140					tmp.sort();
141					if (tmp.setLastMessageTransmitted(query.getEnd())) {
142						this.mXmppConnectionService.databaseBackend.updateConversation(tmp);
143					}
144				}
145			}
146		}
147	}
148
149	public boolean queryInProgress(Conversation conversation) {
150		synchronized (this.queries) {
151			for(Query query : queries) {
152				if (query.conversation == conversation) {
153					return true;
154				}
155			}
156			return false;
157		}
158	}
159
160	public void processFin(Element fin) {
161		if (fin == null) {
162			return;
163		}
164		Query query = findQuery(fin.getAttribute("queryid"));
165		if (query == null) {
166			return;
167		}
168		boolean complete = fin.getAttributeAsBoolean("complete");
169		Element set = fin.findChild("set","http://jabber.org/protocol/rsm");
170		Element last = set == null ? null : set.findChild("last");
171		Element first = set == null ? null : set.findChild("first");
172		Element relevant = query.getPagingOrder() == PagingOrder.NORMAL ? last : first;
173		if (complete || relevant == null) {
174			this.finalizeQuery(query);
175		} else {
176			final Query nextQuery;
177			if (query.getPagingOrder() == PagingOrder.NORMAL) {
178				nextQuery = query.next(last == null ? null : last.getContent());
179			} else {
180				nextQuery = query.prev(first == null ? null : first.getContent());
181			}
182			this.execute(nextQuery);
183			this.finalizeQuery(query);
184			synchronized (this.queries) {
185				this.queries.remove(query);
186				this.queries.add(nextQuery);
187			}
188		}
189	}
190
191	public Query findQuery(String id) {
192		if (id == null) {
193			return null;
194		}
195		synchronized (this.queries) {
196			for(Query query : this.queries) {
197				if (query.getQueryId().equals(id)) {
198					return query;
199				}
200			}
201			return null;
202		}
203	}
204
205	@Override
206	public void onAdvancedStreamFeaturesAvailable(Account account) {
207		if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().mam()) {
208			this.catchup(account);
209		}
210	}
211
212	public class Query {
213		private long start;
214		private long end;
215		private Jid with = null;
216		private String queryId;
217		private String reference = null;
218		private Account account;
219		private Conversation conversation;
220		private PagingOrder pagingOrder = PagingOrder.NORMAL;
221
222
223		public Query(Conversation conversation, long start, long end) {
224			this(conversation.getAccount(), start, end);
225			this.conversation = conversation;
226			this.with = conversation.getContactJid().toBareJid();
227		}
228
229		public Query(Conversation conversation, long start, long end, PagingOrder order) {
230			this(conversation,start,end);
231			this.pagingOrder = order;
232		}
233
234		public Query(Account account, long start, long end) {
235			this.account = account;
236			this.start = start;
237			this.end = end;
238			this.queryId = new BigInteger(50, mXmppConnectionService.getRNG()).toString(32);
239		}
240
241		private Query page(String reference) {
242			Query query = new Query(this.account,this.start,this.end);
243			query.reference = reference;
244			query.conversation = conversation;
245			query.with = with;
246			return query;
247		}
248
249		public Query next(String reference) {
250			Query query = page(reference);
251			query.pagingOrder = PagingOrder.NORMAL;
252			return query;
253		}
254
255		public Query prev(String reference) {
256			Query query = page(reference);
257			query.pagingOrder = PagingOrder.REVERSE;
258			return query;
259		}
260
261		public String getReference() {
262			return reference;
263		}
264
265		public PagingOrder getPagingOrder() {
266			return this.pagingOrder;
267		}
268
269		public String getQueryId() {
270			return queryId;
271		}
272
273		public Jid getWith() {
274			return with;
275		}
276
277		public long getStart() {
278			return start;
279		}
280
281		public long getEnd() {
282			return end;
283		}
284
285		public Conversation getConversation() {
286			return conversation;
287		}
288
289		public Account getAccount() {
290			return this.account;
291		}
292
293		@Override
294		public String toString() {
295			StringBuilder builder = new StringBuilder();
296			builder.append("with=");
297			if (this.with==null) {
298				builder.append("*");
299			} else {
300				builder.append(with.toString());
301			}
302			builder.append(", start=");
303			builder.append(AbstractGenerator.getTimestamp(this.start));
304			builder.append(", end=");
305			builder.append(AbstractGenerator.getTimestamp(this.end));
306			if (this.reference!=null) {
307				if (this.pagingOrder == PagingOrder.NORMAL) {
308					builder.append(", after=");
309				} else {
310					builder.append(", before=");
311				}
312				builder.append(this.reference);
313			}
314			return builder.toString();
315		}
316	}
317}