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