IQMUCSearchHandler.java 11.7 KB
Newer Older
1 2 3 4
/**
 * $Revision: $
 * $Date: $
 *
5
 * Copyright (C) 2005-2008 Jive Software. All rights reserved.
6
 *
7 8 9 10 11 12 13 14 15 16 17
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
18 19 20 21 22 23 24
 */
package org.jivesoftware.openfire.muc.spi;

import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;
import org.jivesoftware.openfire.muc.MUCRoom;
25
import org.jivesoftware.openfire.muc.MultiUserChatService;
26 27
import org.xmpp.forms.DataForm;
import org.xmpp.forms.FormField;
28 29 30
import org.xmpp.packet.IQ;
import org.xmpp.packet.PacketError;
import org.xmpp.packet.PacketError.Condition;
31 32
import org.xmpp.resultsetmanagement.ResultSet;
import org.xmpp.resultsetmanagement.ResultSetImpl;
33 34 35 36 37 38 39

import java.util.*;

/**
 * This class adds jabber:iq:search combined with 'result set management'
 * functionality to the MUC service of Openfire.
 * 
40 41
 * @author Guus der Kinderen - Nimbuzz B.V. <guus@nimbuzz.com>
 * @author Giancarlo Frison - Nimbuzz B.V. <giancarlo@nimbuzz.com>
42 43 44 45 46 47
 */
public class IQMUCSearchHandler
{
	/**
	 * The MUC-server to extend with jabber:iq:search functionality.
	 */
48
	private final MultiUserChatService mucService;
49 50 51 52

	/**
	 * Creates a new instance of the search provider.
	 * 
53
	 * @param mucService
54 55
	 *            The server for which to return search results.
	 */
56
	public IQMUCSearchHandler(MultiUserChatService mucService)
57
	{
58
		this.mucService = mucService;
59 60 61 62 63 64 65 66 67 68 69
	}

	/**
	 * Utility method that returns a 'jabber:iq:search' child element filled
	 * with a blank dataform.
	 * 
	 * @return Element, named 'query', escaped by the 'jabber:iq:search'
	 *         namespace, filled with a blank dataform.
	 */
	private static Element getDataElement()
	{
70
		final DataForm searchForm = new DataForm(DataForm.Type.form);
71
		searchForm.setTitle("Chat Rooms Search");
Gaston Dombiak's avatar
Gaston Dombiak committed
72
		searchForm.addInstruction("Instructions");
73

74 75 76
		final FormField typeFF = searchForm.addField();
		typeFF.setVariable("FORM_TYPE");
		typeFF.setType(FormField.Type.hidden);
77 78
		typeFF.addValue("jabber:iq:search");

79 80 81
		final FormField nameFF = searchForm.addField();
		nameFF.setVariable("name");
		nameFF.setType(FormField.Type.text_single);
82 83 84
		nameFF.setLabel("Name");
		nameFF.setRequired(false);

85 86 87
		final FormField matchFF = searchForm.addField();
		matchFF.setVariable("name_is_exact_match");
		matchFF.setType(FormField.Type.boolean_type);
88 89 90
		matchFF.setLabel("Name must match exactly");
		matchFF.setRequired(false);

91 92 93
		final FormField subjectFF = searchForm.addField();
		subjectFF.setVariable("subject");
		subjectFF.setType(FormField.Type.text_single);
94 95 96
		subjectFF.setLabel("Subject");
		subjectFF.setRequired(false);

97 98 99
		final FormField userAmountFF = searchForm.addField();
		userAmountFF.setVariable("num_users");
		userAmountFF.setType(FormField.Type.text_single);
100 101 102
		userAmountFF.setLabel("Number of users");
		userAmountFF.setRequired(false);

103 104 105
		final FormField maxUsersFF = searchForm.addField();
		maxUsersFF.setVariable("num_max_users");
		maxUsersFF.setType(FormField.Type.text_single);
106 107 108
		maxUsersFF.setLabel("Max number allowed of users");
		maxUsersFF.setRequired(false);

109 110 111
		final FormField includePasswordProtectedFF = searchForm.addField();
		includePasswordProtectedFF.setVariable("include_password_protected");
		includePasswordProtectedFF.setType(FormField.Type.boolean_type);
112 113 114 115 116
		includePasswordProtectedFF.setLabel("Include password protected rooms");
		includePasswordProtectedFF.setRequired(false);

		final Element probeResult = DocumentHelper.createElement(QName.get(
			"query", "jabber:iq:search"));
117
		probeResult.add(searchForm.getElement());
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
		return probeResult;
	}

	/**
	 * Constructs an answer on a IQ stanza that contains a search request. The
	 * answer will be an IQ stanza of type 'result' or 'error'.
	 * 
	 * @param iq
	 *            The IQ stanza that is the search request.
	 * @return An answer to the provided request.
	 */
	public IQ handleIQ(IQ iq)
	{
		final IQ reply = IQ.createResultIQ(iq);
		final Element formElement = iq.getChildElement().element(
			QName.get("x", "jabber:x:data"));
		if (formElement == null)
		{
			reply.setChildElement(getDataElement());
			return reply;
		}

		// parse params from request.
141
		final DataForm df = new DataForm(formElement);
142 143 144 145 146 147
		boolean name_is_exact_match = false;
		String subject = null;
		int numusers = -1;
		int numaxusers = -1;
		boolean includePasswordProtectedRooms = true;

148
		final Set<String> names = new HashSet<>();
149
		for (final FormField field : df.getFields()) 
150 151 152
		{
			if (field.getVariable().equals("name"))
			{
153
				names.add(field.getFirstValue());
154 155 156 157 158 159
			}
		}

		final FormField matchFF = df.getField("name_is_exact_match");
		if (matchFF != null)
		{
160
			final String b = matchFF.getFirstValue();
161 162 163 164 165 166 167 168 169 170 171
			if (b != null)
			{
				name_is_exact_match = b.equals("1")
						|| b.equalsIgnoreCase("true")
						|| b.equalsIgnoreCase("yes");
			}
		}

		final FormField subjectFF = df.getField("subject");
		if (subjectFF != null)
		{
172
			subject = subjectFF.getFirstValue();
173 174 175 176 177 178 179
		}

		try
		{
			final FormField userAmountFF = df.getField("num_users");
			if (userAmountFF != null)
			{
180
                String value = userAmountFF.getFirstValue();
181 182 183
                if (value != null && !"".equals(value)) {
                    numusers = Integer.parseInt(value);
                }
184 185 186 187 188
			}

			final FormField maxUsersFF = df.getField("num_max_users");
			if (maxUsersFF != null)
			{
189
                String value = maxUsersFF.getFirstValue();
190 191 192 193
                if (value != null && !"".equals(value)) {
                    numaxusers = Integer.parseInt(value);
                }
            }
194 195 196 197 198 199 200 201 202 203
		}
		catch (NumberFormatException e)
		{
			reply.setError(PacketError.Condition.bad_request);
			return reply;
		}

		final FormField includePasswordProtectedRoomsFF = df.getField("include_password_protected");
		if (includePasswordProtectedRoomsFF != null)
		{
204
			final String b = includePasswordProtectedRoomsFF.getFirstValue();
205 206 207 208 209 210 211 212 213 214 215
			if (b != null)
			{
				if (b.equals("0") || b.equalsIgnoreCase("false")
						|| b.equalsIgnoreCase("no"))
				{
					includePasswordProtectedRooms = false;
				}
			}
		}

		// search for chatrooms matching the request params.
216
		final List<MUCRoom> mucs = new ArrayList<>();
217
		for (MUCRoom room : mucService.getChatRooms())
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
		{
			boolean find = false;

			if (names.size() > 0)
			{
				for (final String name : names)
				{
					if (name_is_exact_match)
					{
						if (name.equalsIgnoreCase(room.getNaturalLanguageName()))
						{
							find = true;
							break;
						}
					}
					else
					{
						if (room.getNaturalLanguageName().toLowerCase().indexOf(
							name.toLowerCase()) != -1)
						{
							find = true;
							break;
						}
					}
				}
			}

			if (subject != null
					&& room.getSubject().toLowerCase().indexOf(
						subject.toLowerCase()) != -1)
			{
				find = true;
			}

			if (numusers > -1 && room.getParticipants().size() < numusers)
			{
				find = false;
			}

			if (numaxusers > -1 && room.getMaxUsers() < numaxusers)
			{
				find = false;
			}

			if (!includePasswordProtectedRooms && room.isPasswordProtected())
			{
				find = false;
			}

			if (find && canBeIncludedInResult(room))
			{
				mucs.add(room);
			}
		}

273
		final ResultSet<MUCRoom> searchResults = new ResultSetImpl<>(
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
			sortByUserAmount(mucs));

		// See if the requesting entity would like to apply 'result set
		// management'
		final Element set = iq.getChildElement().element(
			QName.get("set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT));
		final List<MUCRoom> mucrsm;

		// apply RSM only if the element exists, and the (total) results
		// set is not empty.
		final boolean applyRSM = set != null && !mucs.isEmpty();

		if (applyRSM)
		{
			if (!ResultSet.isValidRSMRequest(set))
			{
				reply.setError(Condition.bad_request);
				return reply;
			}

			try
			{
				mucrsm = searchResults.applyRSMDirectives(set);
			}
			catch (NullPointerException e)
			{
				final IQ itemNotFound = IQ.createResultIQ(iq);
				itemNotFound.setError(Condition.item_not_found);
				return itemNotFound;
			}
		}
		else
		{
			// if no rsm, all found rooms are part of the result.
308
			mucrsm = new ArrayList<>(searchResults);
309 310 311 312 313
		}

		final Element res = DocumentHelper.createElement(QName.get("query",
			"jabber:iq:search"));

314
		final DataForm resultform = new DataForm(DataForm.Type.result);
315 316 317
		boolean atLeastoneResult = false;
		for (MUCRoom room : mucrsm)
		{
318
			final Map<String, Object> fields = new HashMap<>();
319 320 321 322 323 324 325
			fields.put("name", room.getNaturalLanguageName());
			fields.put("subject", room.getSubject());
			fields.put("num_users", room.getOccupantsCount());
			fields.put("num_max_users", room.getMaxUsers());
			fields.put("is_password_protected", room.isPasswordProtected());
			fields.put("is_member_only", room.isMembersOnly());
			fields.put("jid", room.getRole().getRoleAddress().toString());
326
            resultform.addItemFields(fields);
327 328 329 330
			atLeastoneResult = true;
		}
		if (atLeastoneResult)
		{
331 332 333 334 335 336
			resultform.addReportedField("name", "Name", FormField.Type.text_single);
			resultform.addReportedField("subject", "Subject", FormField.Type.text_single);
			resultform.addReportedField("num_users", "Number of users", FormField.Type.text_single);
			resultform.addReportedField("num_max_users", "Max number allowed of users", FormField.Type.text_single);
			resultform.addReportedField("is_password_protected", "Is a password protected room.", FormField.Type.boolean_type);
			resultform.addReportedField("is_member_only", "Is a member only room.", FormField.Type.boolean_type);
337
			resultform.addReportedField("jid", "JID", FormField.Type.jid_single);
338
		}
339
                res.add(resultform.getElement());
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
		if (applyRSM)
		{
			res.add(searchResults.generateSetElementFromResults(mucrsm));
		}

		reply.setChildElement(res);

		return reply;
	}

	/**
	 * Sorts the provided list in such a way that the MUC with the most users
	 * will be the first one in the list.
	 * 
	 * @param mucs
	 *            The unordered list that will be sorted.
356
     * @return The sorted list of MUC rooms.
357 358 359 360 361
	 */
	private static List<MUCRoom> sortByUserAmount(List<MUCRoom> mucs)
	{
		Collections.sort(mucs, new Comparator<MUCRoom>()
		{
362
			@Override
363 364 365 366 367 368 369 370 371 372 373
			public int compare(MUCRoom o1, MUCRoom o2)
			{
				return o2.getOccupantsCount() - o1.getOccupantsCount();
			}
		});

		return mucs;
	}

	/**
	 * Checks if the room may be included in search results. This is almost
374
	 * identical to {@link MultiUserChatServiceImpl#canDiscoverRoom(org.jivesoftware.openfire.muc.MUCRoom, org.xmpp.packet.JID)},
375 376 377 378 379 380 381 382 383 384
	 * but that method is private and cannot be re-used here.
	 * 
	 * @param room
	 *            The room to check
	 * @return ''true'' if the room may be included in search results, ''false''
	 *         otherwise.
	 */
	private static boolean canBeIncludedInResult(MUCRoom room)
	{
		// Check if locked rooms may be discovered
385
		final boolean discoverLocked = MUCPersistenceManager.getBooleanProperty(room.getMUCService().getServiceName(), "discover.locked", true);
386 387 388 389 390 391 392 393

		if (!discoverLocked && room.isLocked())
		{
			return false;
		}
		return room.isPublicRoom();
	}
}