summaryrefslogtreecommitdiffstats
blob: 1bfff706667adbcb9fdf906e6fb224826528ddb0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
 * Copyright (c) 2010 Remko Tronçon
 * Licensed under the GNU General Public License v3.
 * See Documentation/Licenses/GPLv3.txt for more information.
 */

#include "Swiften/Queries/IQRouter.h"

#include <algorithm>
#include <boost/bind.hpp>

#include "Swiften/Base/foreach.h"
#include "Swiften/Queries/IQHandler.h"
#include "Swiften/Queries/IQChannel.h"
#include "Swiften/Elements/ErrorPayload.h"

namespace Swift {

static void noop(IQHandler*) {}

IQRouter::IQRouter(IQChannel* channel) : channel_(channel), queueRemoves_(false) {
	channel->onIQReceived.connect(boost::bind(&IQRouter::handleIQ, this, _1));
}

IQRouter::~IQRouter() {
	channel_->onIQReceived.disconnect(boost::bind(&IQRouter::handleIQ, this, _1));
}

bool IQRouter::isAvailable() {
	return channel_->isAvailable();
}

void IQRouter::handleIQ(boost::shared_ptr<IQ> iq) {
	queueRemoves_ = true;

	bool handled = false;
	// Go through the handlers in reverse order, to give precedence to the last added handler
	std::vector<boost::shared_ptr<IQHandler> >::const_reverse_iterator i = handlers_.rbegin();
	std::vector<boost::shared_ptr<IQHandler> >::const_reverse_iterator rend = handlers_.rend();
	for (; i != rend; ++i) {
		handled |= (*i)->handleIQ(iq);
		if (handled) {
			break;
		}
	}
	if (!handled && (iq->getType() == IQ::Get || iq->getType() == IQ::Set) ) {
		sendIQ(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::FeatureNotImplemented, ErrorPayload::Cancel));
	}

	processPendingRemoves();

	queueRemoves_ = false;
}

void IQRouter::processPendingRemoves() {
	foreach(boost::shared_ptr<IQHandler> handler, queuedRemoves_) {
		handlers_.erase(std::remove(handlers_.begin(), handlers_.end(), handler), handlers_.end());
	}
	queuedRemoves_.clear();
}

void IQRouter::addHandler(IQHandler* handler) {
	addHandler(boost::shared_ptr<IQHandler>(handler, noop));
}

void IQRouter::removeHandler(IQHandler* handler) {
	removeHandler(boost::shared_ptr<IQHandler>(handler, noop));
}

void IQRouter::addHandler(boost::shared_ptr<IQHandler> handler) {
	handlers_.push_back(handler);
}

void IQRouter::removeHandler(boost::shared_ptr<IQHandler> handler) {
	if (queueRemoves_) {
		queuedRemoves_.push_back(handler);
	}
	else {
		handlers_.erase(std::remove(handlers_.begin(), handlers_.end(), handler), handlers_.end());
	}
}

void IQRouter::sendIQ(boost::shared_ptr<IQ> iq) {
	if (from_.isValid()) {
		iq->setFrom(from_);
	}
	channel_->sendIQ(iq);
}

std::string IQRouter::getNewIQID() {
	return channel_->getNewIQID();
}

}