1/*
  2 * Copyright (c) 2018, Daniel Gultsch All rights reserved.
  3 *
  4 * Redistribution and use in source and binary forms, with or without modification,
  5 * are permitted provided that the following conditions are met:
  6 *
  7 * 1. Redistributions of source code must retain the above copyright notice, this
  8 * list of conditions and the following disclaimer.
  9 *
 10 * 2. Redistributions in binary form must reproduce the above copyright notice,
 11 * this list of conditions and the following disclaimer in the documentation and/or
 12 * other materials provided with the distribution.
 13 *
 14 * 3. Neither the name of the copyright holder nor the names of its contributors
 15 * may be used to endorse or promote products derived from this software without
 16 * specific prior written permission.
 17 *
 18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 21 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 22 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 25 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 27 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 28 */
 29
 30package eu.siacs.conversations.services;
 31
 32import android.database.Cursor;
 33import android.os.SystemClock;
 34import android.util.Log;
 35
 36import java.util.ArrayList;
 37import java.util.HashMap;
 38import java.util.List;
 39
 40import eu.siacs.conversations.Config;
 41import eu.siacs.conversations.entities.Account;
 42import eu.siacs.conversations.entities.Conversation;
 43import eu.siacs.conversations.entities.Conversational;
 44import eu.siacs.conversations.entities.IndividualMessage;
 45import eu.siacs.conversations.entities.Message;
 46import eu.siacs.conversations.entities.StubConversation;
 47import eu.siacs.conversations.ui.interfaces.OnSearchResultsAvailable;
 48import eu.siacs.conversations.utils.Cancellable;
 49import eu.siacs.conversations.utils.MessageUtils;
 50import eu.siacs.conversations.utils.ReplacingSerialSingleThreadExecutor;
 51import eu.siacs.conversations.xmpp.Jid;
 52
 53public class MessageSearchTask implements Runnable, Cancellable {
 54
 55	private static final ReplacingSerialSingleThreadExecutor EXECUTOR = new ReplacingSerialSingleThreadExecutor(MessageSearchTask.class.getName());
 56
 57	private final XmppConnectionService xmppConnectionService;
 58	private final List<String> term;
 59	private final String uuid;
 60	private final OnSearchResultsAvailable onSearchResultsAvailable;
 61
 62	private boolean isCancelled = false;
 63
 64	private MessageSearchTask(XmppConnectionService xmppConnectionService, List<String> term, final String uuid, OnSearchResultsAvailable onSearchResultsAvailable) {
 65		this.xmppConnectionService = xmppConnectionService;
 66		this.term = term;
 67		this.uuid = uuid;
 68		this.onSearchResultsAvailable = onSearchResultsAvailable;
 69	}
 70
 71	public static void search(XmppConnectionService xmppConnectionService, List<String> term, final String uuid, OnSearchResultsAvailable onSearchResultsAvailable) {
 72		new MessageSearchTask(xmppConnectionService, term, uuid, onSearchResultsAvailable).executeInBackground();
 73	}
 74
 75	public static void cancelRunningTasks() {
 76		EXECUTOR.cancelRunningTasks();
 77	}
 78
 79	@Override
 80	public void cancel() {
 81		this.isCancelled = true;
 82	}
 83
 84	@Override
 85	public void run() {
 86		long startTimestamp = SystemClock.elapsedRealtime();
 87		Cursor cursor = null;
 88		try {
 89			final HashMap<String, Conversational> conversationCache = new HashMap<>();
 90			final List<Message> result = new ArrayList<>();
 91			cursor = xmppConnectionService.databaseBackend.getMessageSearchCursor(term, uuid);
 92			long dbTimer = SystemClock.elapsedRealtime();
 93			if (isCancelled) {
 94				Log.d(Config.LOGTAG, "canceled search task");
 95				return;
 96			}
 97			if (cursor != null && cursor.getCount() > 0) {
 98				cursor.moveToLast();
 99				final int indexBody = cursor.getColumnIndex(Message.BODY);
100				final int indexOob = cursor.getColumnIndex(Message.OOB);
101				final int indexConversation = cursor.getColumnIndex(Message.CONVERSATION);
102				final int indexAccount = cursor.getColumnIndex(Conversation.ACCOUNT);
103				final int indexContact = cursor.getColumnIndex(Conversation.CONTACTJID);
104				final int indexMode = cursor.getColumnIndex(Conversation.MODE);
105				do {
106					if (isCancelled) {
107						Log.d(Config.LOGTAG, "canceled search task");
108						return;
109					}
110					final String body = cursor.getString(indexBody);
111					final boolean oob = cursor.getInt(indexOob) > 0;
112					if (MessageUtils.treatAsDownloadable(body,oob,false)) {
113						continue;
114					}
115					final String conversationUuid = cursor.getString(indexConversation);
116					Conversational conversation = conversationCache.get(conversationUuid);
117					if (conversation == null) {
118						String accountUuid = cursor.getString(indexAccount);
119						String contactJid = cursor.getString(indexContact);
120						int mode = cursor.getInt(indexMode);
121						conversation = findOrGenerateStub(conversationUuid, accountUuid, contactJid, mode);
122						conversationCache.put(conversationUuid, conversation);
123					}
124					Message message = IndividualMessage.fromCursor(cursor, conversation);
125					result.add(message);
126				} while (cursor.moveToPrevious());
127			}
128			long stopTimestamp = SystemClock.elapsedRealtime();
129			Log.d(Config.LOGTAG, "found " + result.size() + " messages in " + (stopTimestamp - startTimestamp) + "ms"+ " (db was "+(dbTimer - startTimestamp)+"ms)");
130			onSearchResultsAvailable.onSearchResultsAvailable(term, result);
131		} catch (Exception e) {
132			Log.d(Config.LOGTAG, "exception while searching ", e);
133		} finally {
134			if (cursor != null) {
135				cursor.close();
136			}
137		}
138	}
139
140	private Conversational findOrGenerateStub(String conversationUuid, String accountUuid, String contactJid, int mode) throws Exception {
141		Conversation conversation = xmppConnectionService.findConversationByUuid(conversationUuid);
142		if (conversation != null) {
143			return conversation;
144		}
145		Account account = xmppConnectionService.findAccountByUuid(accountUuid);
146		Jid jid = Jid.of(contactJid);
147		if (account != null && jid != null) {
148			return new StubConversation(account, conversationUuid, jid.asBareJid(), mode);
149		}
150		throw new Exception("Unable to generate stub for " + contactJid);
151	}
152
153	private void executeInBackground() {
154		EXECUTOR.execute(this);
155	}
156}