ClientSubscribe.cxx 2 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
#include "ClientInternal.hxx"
Max Kellermann's avatar
Max Kellermann committed
22
#include "Idle.hxx"
23

24
#include <assert.h>
25 26 27

Client::SubscribeResult
Client::Subscribe(const char *channel)
28
{
29
	assert(channel != nullptr);
30 31

	if (!client_message_valid_channel_name(channel))
32
		return Client::SubscribeResult::INVALID;
33

34 35
	if (num_subscriptions >= CLIENT_MAX_SUBSCRIPTIONS)
		return Client::SubscribeResult::FULL;
36

37
	auto r = subscriptions.insert(channel);
38
	if (!r.second)
39
		return Client::SubscribeResult::ALREADY;
40

41
	++num_subscriptions;
42 43 44

	idle_add(IDLE_SUBSCRIPTION);

45
	return Client::SubscribeResult::OK;
46 47 48
}

bool
49
Client::Unsubscribe(const char *channel)
50
{
51 52
	const auto i = subscriptions.find(channel);
	if (i == subscriptions.end())
53 54
		return false;

55
	assert(num_subscriptions > 0);
56

57 58
	subscriptions.erase(i);
	--num_subscriptions;
59 60 61

	idle_add(IDLE_SUBSCRIPTION);

62 63
	assert((num_subscriptions == 0) ==
	       subscriptions.empty());
64 65 66 67 68

	return true;
}

void
69
Client::UnsubscribeAll()
70
{
71 72
	subscriptions.clear();
	num_subscriptions = 0;
73 74 75
}

bool
76
Client::PushMessage(const ClientMessage &msg)
77
{
78 79
	if (messages.size() >= CLIENT_MAX_MESSAGES ||
	    !IsSubscribed(msg.GetChannel()))
80 81
		return false;

82 83
	if (messages.empty())
		IdleAdd(IDLE_MESSAGE);
84

85
	messages.push_back(msg);
86 87
	return true;
}