ClientSubscribe.cxx 2.26 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2013 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 * http://www.musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

20
#include "config.h"
Max Kellermann's avatar
Max Kellermann committed
21 22
#include "ClientSubscribe.hxx"
#include "ClientInternal.hxx"
Max Kellermann's avatar
Max Kellermann committed
23
#include "Idle.hxx"
24

25
#include <assert.h>
26 27 28
#include <string.h>

enum client_subscribe_result
29
client_subscribe(Client *client, const char *channel)
30 31 32 33 34 35 36 37 38 39
{
	assert(client != NULL);
	assert(channel != NULL);

	if (!client_message_valid_channel_name(channel))
		return CLIENT_SUBSCRIBE_INVALID;

	if (client->num_subscriptions >= CLIENT_MAX_SUBSCRIPTIONS)
		return CLIENT_SUBSCRIBE_FULL;

40 41 42 43
	auto r = client->subscriptions.insert(channel);
	if (!r.second)
		return CLIENT_SUBSCRIBE_ALREADY;

44 45 46 47 48 49 50 51
	++client->num_subscriptions;

	idle_add(IDLE_SUBSCRIPTION);

	return CLIENT_SUBSCRIBE_OK;
}

bool
52
client_unsubscribe(Client *client, const char *channel)
53
{
54 55
	const auto i = client->subscriptions.find(channel);
	if (i == client->subscriptions.end())
56 57 58 59
		return false;

	assert(client->num_subscriptions > 0);

60
	client->subscriptions.erase(i);
61 62 63 64 65
	--client->num_subscriptions;

	idle_add(IDLE_SUBSCRIPTION);

	assert((client->num_subscriptions == 0) ==
66
	       client->subscriptions.empty());
67 68 69 70 71

	return true;
}

void
72
client_unsubscribe_all(Client *client)
73
{
74
	client->subscriptions.clear();
75 76 77 78
	client->num_subscriptions = 0;
}

bool
79
client_push_message(Client *client, const ClientMessage &msg)
80 81 82
{
	assert(client != NULL);

83
	if (client->messages.size() >= CLIENT_MAX_MESSAGES ||
84
	    !client->IsSubscribed(msg.GetChannel()))
85 86
		return false;

87
	if (client->messages.empty())
88
		client->IdleAdd(IDLE_MESSAGE);
89

90
	client->messages.push_back(msg);
91 92
	return true;
}