Changeset - 00c5273fbb13
[Not reviewed]
0 6 0
Jan Kaluza - 9 years ago 2016-02-20 07:23:07
jkaluza@redhat.com
Slack: Handle channels starting with hash, do not reconnect to Slack RTM when URL expired
6 files changed with 43 insertions and 3 deletions:
0 comments (0 inline, 0 general)
backends/libpurple/main.cpp
Show inline comments
 
@@ -2041,99 +2041,102 @@ static bool initPurple() {
 
		purple_signal_connect_wrapped(purple_blist_get_handle_wrapped(), "buddy-privacy-changed", &conversation_handle, PURPLE_CALLBACK(buddyPrivacyChanged), NULL);
 
		purple_signal_connect_wrapped(purple_conversations_get_handle_wrapped(), "got-attention", &conversation_handle, PURPLE_CALLBACK(gotAttention), NULL);
 
		purple_signal_connect_wrapped(purple_connections_get_handle_wrapped(), "signed-on", &blist_handle,PURPLE_CALLBACK(signed_on), NULL);
 
// 		purple_signal_connect_wrapped(purple_blist_get_handle_wrapped(), "buddy-removed", &blist_handle,PURPLE_CALLBACK(buddyRemoved), NULL);
 
// 		purple_signal_connect_wrapped(purple_blist_get_handle_wrapped(), "buddy-signed-on", &blist_handle,PURPLE_CALLBACK(buddySignedOn), NULL);
 
// 		purple_signal_connect_wrapped(purple_blist_get_handle_wrapped(), "buddy-signed-off", &blist_handle,PURPLE_CALLBACK(buddySignedOff), NULL);
 
// 		purple_signal_connect_wrapped(purple_blist_get_handle_wrapped(), "buddy-status-changed", &blist_handle,PURPLE_CALLBACK(buddyStatusChanged), NULL);
 
		purple_signal_connect_wrapped(purple_blist_get_handle_wrapped(), "blist-node-removed", &blist_handle,PURPLE_CALLBACK(NodeRemoved), NULL);
 
		purple_signal_connect_wrapped(purple_conversations_get_handle_wrapped(), "chat-topic-changed", &conversation_handle, PURPLE_CALLBACK(conv_chat_topic_changed), NULL);
 
		static int xfer_handle;
 
		purple_signal_connect_wrapped(purple_xfers_get_handle_wrapped(), "file-send-start", &xfer_handle, PURPLE_CALLBACK(fileSendStart), NULL);
 
		purple_signal_connect_wrapped(purple_xfers_get_handle_wrapped(), "file-recv-start", &xfer_handle, PURPLE_CALLBACK(fileRecvStart), NULL);
 
		purple_signal_connect_wrapped(purple_xfers_get_handle_wrapped(), "file-recv-request", &xfer_handle, PURPLE_CALLBACK(newXfer), NULL);
 
		purple_signal_connect_wrapped(purple_xfers_get_handle_wrapped(), "file-recv-complete", &xfer_handle, PURPLE_CALLBACK(XferReceiveComplete), NULL);
 
		purple_signal_connect_wrapped(purple_xfers_get_handle_wrapped(), "file-send-complete", &xfer_handle, PURPLE_CALLBACK(XferSendComplete), NULL);
 
// 
 
// 		purple_commands_init();
 

	
 
	}
 
	return ret;
 
}
 

	
 

	
 
static void transportDataReceived(gpointer data, gint source, PurpleInputCondition cond) {
 
	if (cond & PURPLE_INPUT_READ) {
 
		char buffer[65535];
 
		char *ptr = buffer;
 
#ifdef WIN32
 
		ssize_t n = recv(source, ptr, sizeof(buffer), 0);
 
#else
 
		ssize_t n = read(source, ptr, sizeof(buffer));
 
#endif
 
		if (n <= 0) {
 
			if (errno == EAGAIN) {
 
				return;
 
			}
 
			LOG4CXX_INFO(logger, "Diconnecting from spectrum2 server");
 
			exit(errno);
 
		}
 
		std::string d = std::string(buffer, n);
 

	
 
		if (firstPing) {
 
			firstPing = false;
 
			NetworkPlugin::PluginConfig cfg;			
 
			cfg.setSupportMUC(true);
 
			if (CONFIG_STRING(config, "service.protocol") == "prpl-telegram") {
 
				cfg.setNeedPassword(false);
 
			}
 
			if (CONFIG_STRING(config, "service.protocol") != "prpl-irc") {
 
			if (CONFIG_STRING(config, "service.protocol") == "prpl-irc") {
 
				cfg.setNeedRegistration(false);
 
			}
 
			else {
 
				cfg.setNeedRegistration(true);
 
			}
 
			np->sendConfig(cfg);
 
		}
 

	
 
		np->handleDataRead(d);
 
	}
 
	else {
 
		if (writeInput != 0) {
 
			purple_input_remove_wrapped(writeInput);
 
			writeInput = 0;
 
		}
 
		np->readyForData();
 
	}
 
}
 

	
 
int main(int argc, char **argv) {
 
#ifndef WIN32
 
#if !defined(__FreeBSD__) && !defined(__APPLE__)
 
		mallopt(M_CHECK_ACTION, 2);
 
		mallopt(M_PERTURB, 0xb);
 
#endif
 

	
 
		signal(SIGPIPE, SIG_IGN);
 

	
 
		if (signal(SIGCHLD, spectrum_sigchld_handler) == SIG_ERR) {
 
			std::cout << "SIGCHLD handler can't be set\n";
 
			return -1;
 
		}
 
#endif
 

	
 
	std::string error;
 
	Config *cfg = Config::createFromArgs(argc, argv, error, host, port);
 
	if (cfg == NULL) {
 
		std::cerr << error;
 
		return 1;
 
	}
 

	
 
	config = boost::shared_ptr<Config>(cfg);
 
 
 
	Logging::initBackendLogging(config.get());
 
	initPurple();
 
 
 
	main_socket = create_socket(host.c_str(), port);
 
	purple_input_add_wrapped(main_socket, PURPLE_INPUT_READ, &transportDataReceived, NULL);
 
	purple_timeout_add_seconds_wrapped(30, pingTimeout, NULL);
 
 
 
	np = new SpectrumNetworkPlugin();
 
	bool libev = CONFIG_STRING_DEFAULTED(config, "service.eventloop", "") == "libev";
 

	
include/transport/WebSocketClient.h
Show inline comments
 
@@ -10,79 +10,80 @@
 
 *
 
 * 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  02111-1301  USA
 
 */
 

	
 
#pragma once
 

	
 
#include <Swiften/Network/TLSConnectionFactory.h>
 
#include <Swiften/Network/HostAddressPort.h>
 
#include <Swiften/TLS/PlatformTLSFactories.h>
 
#include <Swiften/Network/DomainNameResolveError.h>
 
#include <Swiften/Network/DomainNameAddressQuery.h>
 
#include <Swiften/Network/DomainNameResolver.h>
 
#include <Swiften/Network/HostAddress.h>
 
#include <Swiften/Network/Connection.h>
 
#include <Swiften/Base/SafeByteArray.h>
 
#include "Swiften/Version.h"
 
#include "Swiften/Network/Timer.h"
 

	
 
#define HAVE_SWIFTEN_3  (SWIFTEN_VERSION >= 0x030000)
 

	
 
#if HAVE_SWIFTEN_3
 
#include <Swiften/TLS/TLSOptions.h>
 
#endif
 

	
 
#include <string>
 
#include <algorithm>
 
#include <map>
 

	
 
#include <boost/signal.hpp>
 

	
 
namespace Transport {
 

	
 
class Component;
 

	
 
class WebSocketClient {
 
	public:
 
		WebSocketClient(Component *component, const std::string &user);
 

	
 
		virtual ~WebSocketClient();
 

	
 
		void connectServer(const std::string &u);
 
		void disconnectServer();
 

	
 
		void write(const std::string &data);
 

	
 
		boost::signal<void (const std::string &payload)> onPayloadReceived;
 

	
 
		boost::signal<void ()> onWebSocketConnected;
 
		boost::signal<void (const boost::optional<Swift::Connection::Error> &error)> onWebSocketDisconnected;
 

	
 
	private:
 
		void handleDNSResult(const std::vector<Swift::HostAddress>&, boost::optional<Swift::DomainNameResolveError>);
 
		void handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data);
 
		void handleConnected(bool error);
 
		void handleDisconnected(const boost::optional<Swift::Connection::Error> &error);
 

	
 
		void connectServer();
 

	
 
	private:
 
		Component *m_component;
 
		boost::shared_ptr<Swift::DomainNameAddressQuery> m_dnsQuery;
 
		boost::shared_ptr<Swift::Connection> m_conn;
 
		Swift::TLSConnectionFactory *m_tlsConnectionFactory;
 
		Swift::PlatformTLSFactories *m_tlsFactory;
 
		std::string m_host;
 
		std::string m_path;
 
		std::string m_buffer;
 
		bool m_upgraded;
 
		Swift::Timer::ref m_reconnectTimer;
 
		std::string m_user;
 
};
 

	
 
}
libtransport/WebSocketClient.cpp
Show inline comments
 
@@ -37,96 +37,103 @@ DEFINE_LOGGER(logger, "WebSocketClient");
 
WebSocketClient::WebSocketClient(Component *component, const std::string &user) {
 
	m_component = component;
 
	m_upgraded = false;
 
	m_user = user;
 

	
 
#if HAVE_SWIFTEN_3
 
	Swift::TLSOptions o;
 
#endif
 
	m_tlsFactory = new Swift::PlatformTLSFactories();
 
#if HAVE_SWIFTEN_3
 
	m_tlsConnectionFactory = new Swift::TLSConnectionFactory(m_tlsFactory->getTLSContextFactory(), component->getNetworkFactories()->getConnectionFactory(), o);
 
#else
 
	m_tlsConnectionFactory = new Swift::TLSConnectionFactory(m_tlsFactory->getTLSContextFactory(), component->getNetworkFactories()->getConnectionFactory());
 
#endif
 

	
 
	m_reconnectTimer = m_component->getNetworkFactories()->getTimerFactory()->createTimer(1000);
 
	m_reconnectTimer->onTick.connect(boost::bind(&WebSocketClient::connectServer, this));
 
}
 

	
 
WebSocketClient::~WebSocketClient() {
 
	if (m_conn) {
 
		m_conn->onDataRead.disconnect(boost::bind(&WebSocketClient::handleDataRead, this, _1));
 
		m_conn->disconnect();
 
	}
 

	
 
	delete m_tlsFactory;
 
	delete m_tlsConnectionFactory;
 
}
 

	
 
void WebSocketClient::connectServer() {
 
	LOG4CXX_INFO(logger, m_user << ": Starting DNS query for " << m_host << " " << m_path);
 

	
 
	m_upgraded = false;
 
	m_buffer.clear();
 

	
 
	m_dnsQuery = m_component->getNetworkFactories()->getDomainNameResolver()->createAddressQuery(m_host);
 
	m_dnsQuery->onResult.connect(boost::bind(&WebSocketClient::handleDNSResult, this, _1, _2));
 
	m_dnsQuery->run();
 
	m_reconnectTimer->stop();
 
}
 

	
 
void WebSocketClient::connectServer(const std::string &url) {
 
	std::string u = url.substr(6);
 
	m_host = u.substr(0, u.find("/"));
 
	m_path = u.substr(u.find("/"));
 
	connectServer();
 
}
 

	
 
void WebSocketClient::disconnectServer() {
 
	if (m_conn) {
 
		m_conn->onDataRead.disconnect(boost::bind(&WebSocketClient::handleDataRead, this, _1));
 
		m_conn->disconnect();
 
	}
 
}
 

	
 
void WebSocketClient::write(const std::string &data) {
 
	if (!m_conn) {
 
		return;
 
	}
 

	
 
	uint8_t opcode = 129; // UTF8
 
	if (data.empty()) {
 
		opcode = 138; // PONG
 
	}
 

	
 
	// Mask the payload
 
	char mask_bits[4] = {0x11, 0x22, 0x33, 0x44};
 
	std::string payload = data;
 
	for (size_t i = 0; i < data.size(); i++ ) {
 
		payload[i] = payload[i] ^ mask_bits[i&3];
 
	}
 

	
 
	if (data.size() <= 125) {
 
		uint8_t size7 = data.size() + 128; // Mask bit
 
		m_conn->write(Swift::createSafeByteArray(std::string((char *) &opcode, 1)
 
			+ std::string((char *) &size7, 1)
 
			+ std::string((char *) &mask_bits[0], 4)
 
			+ payload));
 
	}
 
	else {
 
		uint8_t size7 = 126 + 128; // Mask bit
 
		uint16_t size16 = data.size();
 
		size16 = htons(size16);
 
		m_conn->write(Swift::createSafeByteArray(std::string((char *) &opcode, 1)
 
			+ std::string((char *) &size7, 1)
 
			+ std::string((char *) &size16, 2)
 
			+ std::string((char *) &mask_bits[0], 4)
 
			+ payload));
 
	}
 

	
 
	LOG4CXX_INFO(logger, m_user << ": > " << data);
 
}
 

	
 
void WebSocketClient::handleDataRead(boost::shared_ptr<Swift::SafeByteArray> data) {
 
	std::string d = Swift::safeByteArrayToString(*data);
 
	m_buffer += d;
 

	
 
	if (!m_upgraded) {
 
		if (m_buffer.find("\r\n\r\n") != std::string::npos) {
 
			m_buffer.erase(0, m_buffer.find("\r\n\r\n") + 4);
 
			m_upgraded = true;
 
			onWebSocketConnected();
 
		}
spectrum/src/frontends/slack/SlackRTM.cpp
Show inline comments
 
@@ -47,148 +47,167 @@ SlackRTM::SlackRTM(Component *component, StorageBackend *storageBackend, SlackId
 
	m_idManager = idManager;
 
	m_client = new WebSocketClient(component, m_uinfo.jid);
 
	m_client->onPayloadReceived.connect(boost::bind(&SlackRTM::handlePayloadReceived, this, _1));
 
	m_client->onWebSocketConnected.connect(boost::bind(&SlackRTM::handleWebSocketConnected, this));
 

	
 
	m_pingTimer = m_component->getNetworkFactories()->getTimerFactory()->createTimer(20000);
 
	m_pingTimer->onTick.connect(boost::bind(&SlackRTM::sendPing, this));
 

	
 
	int type = (int) TYPE_STRING;
 
	m_storageBackend->getUserSetting(m_uinfo.id, "bot_token", type, m_token);
 

	
 
	m_api = new SlackAPI(component, m_idManager, m_token, m_uinfo.jid);
 
}
 

	
 
SlackRTM::~SlackRTM() {
 
	delete m_client;
 
	delete m_api;
 
	m_pingTimer->stop();
 
}
 

	
 
void SlackRTM::start() {
 
	std::string url = "https://slack.com/api/rtm.start?";
 
	url += "token=" + Util::urlencode(m_token);
 

	
 
	HTTPRequest *req = new HTTPRequest(THREAD_POOL(m_component), HTTPRequest::Get, url, boost::bind(&SlackRTM::handleRTMStart, this, _1, _2, _3, _4));
 
	req->execute();
 
}
 

	
 
#define STORE_STRING(FROM, NAME) rapidjson::Value &NAME##_tmp = FROM[#NAME]; \
 
	if (!NAME##_tmp.IsString()) {  \
 
		LOG4CXX_ERROR(logger, "No '" << #NAME << "' string in the reply."); \
 
		LOG4CXX_ERROR(logger, payload); \
 
		return; \
 
	} \
 
	std::string NAME = NAME##_tmp.GetString();
 

	
 
#define STORE_STRING_OPTIONAL(FROM, NAME) rapidjson::Value &NAME##_tmp = FROM[#NAME]; \
 
	std::string NAME; \
 
	if (NAME##_tmp.IsString()) {  \
 
		 NAME = NAME##_tmp.GetString(); \
 
	}
 

	
 
#define GET_OBJECT(FROM, NAME) rapidjson::Value &NAME = FROM[#NAME]; \
 
	if (!NAME.IsObject()) { \
 
		LOG4CXX_ERROR(logger, "No '" << #NAME << "' object in the reply."); \
 
		return; \
 
	}
 

	
 
#define STORE_INT(FROM, NAME) rapidjson::Value &NAME##_tmp = FROM[#NAME]; \
 
	if (!NAME##_tmp.IsInt()) {  \
 
		LOG4CXX_ERROR(logger, "No '" << #NAME << "' number in the reply."); \
 
		LOG4CXX_ERROR(logger, payload); \
 
		return; \
 
	} \
 
	int NAME = NAME##_tmp.GetInt();
 

	
 
void SlackRTM::handlePayloadReceived(const std::string &payload) {
 
	rapidjson::Document d;
 
	if (d.Parse<0>(payload.c_str()).HasParseError()) {
 
		LOG4CXX_ERROR(logger, "Error while parsing JSON");
 
		LOG4CXX_ERROR(logger, payload);
 
		return;
 
	}
 

	
 
	STORE_STRING(d, type);
 

	
 
	if (type == "message") {
 
		STORE_STRING(d, channel);
 
		STORE_STRING(d, text);
 
		STORE_STRING(d, ts);
 
		STORE_STRING_OPTIONAL(d, subtype);
 
		STORE_STRING_OPTIONAL(d, purpose);
 

	
 
		rapidjson::Value &attachments = d["attachments"];
 
		if (attachments.IsArray()) {
 
			for (int i = 0; i < attachments.Size(); i++) {
 
				STORE_STRING_OPTIONAL(attachments[i], fallback);
 
				if (!fallback.empty()) {
 
					text += fallback;
 
				}
 
			}
 
		}
 

	
 
		if (subtype == "bot_message") {
 
			STORE_STRING(d, bot_id);
 
			onMessageReceived(channel, bot_id, text, ts);
 
		}
 
		else if (subtype == "me_message") {
 
			text = "/me " + text;
 
			STORE_STRING(d, user);
 
			onMessageReceived(channel, user, text, ts);
 
		}
 
		else if (subtype == "channel_join") {
 
			
 
		}
 
		else if (!purpose.empty()) {
 
			
 
		}
 
		else {
 
			STORE_STRING(d, user);
 
			onMessageReceived(channel, user, text, ts);
 
		}
 
	}
 
	else if (type == "channel_joined"
 
		  || type == "channel_created") {
 
		std::map<std::string, SlackChannelInfo> &channels = m_idManager->getChannels();
 
		SlackAPI::getSlackChannelInfo(NULL, true, d, payload, channels);
 
	}
 
	else if (type == "error") {
 
		GET_OBJECT(d, error);
 
		STORE_INT(error, code);
 

	
 
		if (code == 1) {
 
			LOG4CXX_INFO(logger, "Reconnecting to Slack network");
 
			m_pingTimer->stop();
 
			m_client->disconnectServer();
 
			start();
 
		}
 
	}
 
}
 

	
 
void SlackRTM::sendMessage(const std::string &channel, const std::string &message) {
 
	m_counter++;
 

	
 
	std::string m = message;
 
	boost::replace_all(m, "\"", "\\\"");
 
	std::string msg = "{\"id\": " + boost::lexical_cast<std::string>(m_counter) + ", \"type\": \"message\", \"channel\":\"" + channel + "\", \"text\":\"" + m + "\"}";
 
	m_client->write(msg);
 
}
 

	
 
void SlackRTM::sendPing() {
 
	m_counter++;
 
	std::string msg = "{\"id\": " + boost::lexical_cast<std::string>(m_counter) + ", \"type\": \"ping\"}";
 
	m_client->write(msg);
 
	m_pingTimer->start();
 
}
 

	
 
void SlackRTM::handleRTMStart(HTTPRequest *req, bool ok, rapidjson::Document &resp, const std::string &data) {
 
	if (!ok) {
 
		LOG4CXX_ERROR(logger, req->getError());
 
		LOG4CXX_ERROR(logger, data);
 
		return;
 
	}
 

	
 
	rapidjson::Value &url = resp["url"];
 
	if (!url.IsString()) {
 
		LOG4CXX_ERROR(logger, "No 'url' object in the reply.");
 
		LOG4CXX_ERROR(logger, data);
 
		return;
 
	}
 

	
 
	rapidjson::Value &self = resp["self"];
 
	if (!self.IsObject()) {
 
		LOG4CXX_ERROR(logger, "No 'self' object in the reply.");
 
		LOG4CXX_ERROR(logger, data);
 
		return;
 
	}
 

	
 
	rapidjson::Value &selfName = self["name"];
 
	if (!selfName.IsString()) {
 
		LOG4CXX_ERROR(logger, "No 'name' string in the reply.");
 
		LOG4CXX_ERROR(logger, data);
 
		return;
 
	}
 

	
 
	m_idManager->setSelfName(selfName.GetString());
 

	
spectrum/src/frontends/slack/SlackSession.cpp
Show inline comments
 
@@ -155,113 +155,120 @@ void SlackSession::sendMessage(boost::shared_ptr<Swift::Message> message) {
 
#else
 
	std::string body = message->getBody();
 
#endif
 
	m_rtm->getAPI()->sendMessage(from, channel, body);
 
}
 

	
 
void SlackSession::setPurpose(const std::string &purpose, const std::string &channel) {
 
	std::string ch = channel;
 
	if (ch.empty()) {
 
		ch = m_slackChannel;
 
	}
 
	if (ch.empty()) {
 
		return;
 
	}
 

	
 
	LOG4CXX_INFO(logger, m_uinfo.jid << ": Setting channel purppose: " << ch << " " << purpose);
 
	m_api->setPurpose(ch, purpose);
 
}
 

	
 
void SlackSession::handleJoinRoomCreated(const std::string &channelId, std::vector<std::string> args) {
 
	args[5] = channelId;
 
	std::string &name = args[2];
 
	std::string &legacyRoom = args[3];
 
	std::string &legacyServer = args[4];
 
	std::string &slackChannel = args[5];
 

	
 
	std::string to = legacyRoom + "%" + legacyServer + "@" + m_component->getJID().toString();
 
// 	if (!CONFIG_BOOL_DEFAULTED(m_component->getConfig(), "registration.needRegistration", true)) {
 
// 		m_uinfo.uin = name;
 
// 		m_storageBackend->setUser(m_uinfo);
 
// 	}
 

	
 
	LOG4CXX_INFO(logger, m_uinfo.jid << ": Channel " << args[5] << " is created. Joining the room on legacy network.");
 

	
 
	m_jid2channel[to] = slackChannel;
 
	m_channel2jid[slackChannel] = to;
 

	
 
	Swift::Presence::ref presence = Swift::Presence::create();
 
	presence->setFrom(Swift::JID(m_uinfo.jid + "/default"));
 
	presence->setTo(Swift::JID(to + "/" + name));
 
	presence->setType(Swift::Presence::Available);
 
	presence->addPayload(boost::shared_ptr<Swift::Payload>(new Swift::MUCPayload()));
 
	m_component->getFrontend()->onPresenceReceived(presence);
 

	
 
	m_onlineBuddiesTimer->start();
 
}
 

	
 
void SlackSession::handleJoinMessage(const std::string &message, std::vector<std::string> &args, bool quiet) {
 
	if (args[5][0] == '#') {
 
		args[5].erase(0, 1);
 
	}
 
	LOG4CXX_INFO(logger, m_uinfo.jid << ": Going to join the room " << args[3] << "@" << args[4] << ", transporting it to channel " << args[5]);
 
	m_api->createChannel(args[5], m_idManager->getSelfId(), boost::bind(&SlackSession::handleJoinRoomCreated, this, _1, args));
 
}
 

	
 
void SlackSession::handleSlackChannelCreated(const std::string &channelId) {
 
	m_slackChannel = channelId;
 

	
 
	LOG4CXX_INFO(logger, m_uinfo.jid << ": Main Slack Channel created, connecting the legacy network");
 
	Swift::Presence::ref presence = Swift::Presence::create();
 
	presence->setFrom(Swift::JID(m_uinfo.jid + "/default"));
 
	presence->setTo(m_component->getJID());
 
	presence->setType(Swift::Presence::Available);
 
	presence->addPayload(boost::shared_ptr<Swift::Payload>(new Swift::MUCPayload()));
 
	m_component->getFrontend()->onPresenceReceived(presence);
 
}
 

	
 
void SlackSession::leaveRoom(const std::string &channel) {
 
void SlackSession::leaveRoom(const std::string &channel_) {
 
	std::string channel = channel_;
 
	if (channel[0] == '#') {
 
		channel.erase(0, 1);
 
	}
 
	std::string channelId = m_idManager->getId(channel);
 
	std::string to = m_channel2jid[channelId];
 
	if (to.empty()) {
 
		LOG4CXX_ERROR(logger, "Spectrum 2 is not configured to transport this Slack channel.")
 
		return;
 
	}
 

	
 
	LOG4CXX_INFO(logger, m_uinfo.jid << ": Leaving the legacy network room " << to);
 

	
 
	Swift::Presence::ref presence = Swift::Presence::create();
 
	presence->setFrom(Swift::JID(m_uinfo.jid + "/default"));
 
	presence->setTo(Swift::JID(to + "/" + m_uinfo.uin));
 
	presence->setType(Swift::Presence::Unavailable);
 
	presence->addPayload(boost::shared_ptr<Swift::Payload>(new Swift::MUCPayload()));
 
	m_component->getFrontend()->onPresenceReceived(presence);
 
}
 

	
 
void SlackSession::handleMessageReceived(const std::string &channel, const std::string &user, const std::string &message, const std::string &ts, bool quiet) {
 
	std::string to = m_channel2jid[channel];
 
	if (m_idManager->getName(user) == m_idManager->getSelfName()) {
 
		return;
 
	}
 

	
 
	if (!to.empty()) {
 
		boost::shared_ptr<Swift::Message> msg(new Swift::Message());
 
		msg->setType(Swift::Message::Groupchat);
 
		msg->setTo(to);
 
		msg->setFrom(Swift::JID(m_uinfo.jid + "/default"));
 
		msg->setBody("<" + m_idManager->getName(user) + "> " + message);
 
		m_component->getFrontend()->onMessageReceived(msg);
 
	}
 
	else {
 
		// When changing the purpose, we do not want to spam to room with the info,
 
		// so remove the purpose message.
 
// 			if (message.find("set the channel purpose") != std::string::npos) {
 
// 				m_rtm->getAPI()->deleteMessage(channel, ts);
 
// 			}
 
		// TODO: MAP `user` to JID somehow and send the message to proper JID.
 
		// So far send to all online contacts
 

	
 
		if (!m_user || !m_user->getRosterManager()) {
 
			return;
 
		}
 

	
 
		Swift::StatusShow s;
 
		std::string statusMessage;
 
		const RosterManager::BuddiesMap &roster = m_user->getRosterManager()->getBuddies();
 
		for(RosterManager::BuddiesMap::const_iterator bt = roster.begin(); bt != roster.end(); bt++) {
spectrum/src/frontends/slack/SlackUserRegistration.cpp
Show inline comments
 
@@ -30,97 +30,97 @@
 
#include "transport/Logging.h"
 
#include "transport/Buddy.h"
 
#include "transport/Config.h"
 
#include "transport/OAuth2.h"
 
#include "transport/Util.h"
 
#include "transport/HTTPRequest.h"
 

	
 
#include "rapidjson/document.h"
 

	
 
#include <boost/shared_ptr.hpp>
 
#include <boost/thread.hpp>
 
#include <boost/date_time/posix_time/posix_time.hpp>
 
#include <boost/regex.hpp> 
 

	
 
using namespace Swift;
 

	
 
namespace Transport {
 

	
 
DEFINE_LOGGER(logger, "SlackUserRegistration");
 

	
 
SlackUserRegistration::SlackUserRegistration(Component *component, UserManager *userManager,
 
								   StorageBackend *storageBackend)
 
: UserRegistration(component, userManager, storageBackend) {
 
	m_component = component;
 
	m_config = m_component->getConfig();
 
	m_storageBackend = storageBackend;
 
	m_userManager = userManager;
 

	
 
}
 

	
 
SlackUserRegistration::~SlackUserRegistration(){
 
	
 
}
 

	
 
std::string SlackUserRegistration::createOAuth2URL(const std::vector<std::string> &args) {
 
	std::string redirect_url = "https://slack.spectrum.im/oauth2/" + CONFIG_STRING(m_config, "service.jid");
 
	OAuth2 *oauth2 = new OAuth2(CONFIG_STRING_DEFAULTED(m_config, "service.client_id",""),
 
						  CONFIG_STRING_DEFAULTED(m_config, "service.client_secret",""),
 
						  "https://slack.com/oauth/authorize",
 
						  "https://slack.com/api/oauth.access",
 
						  redirect_url,
 
						  "channels:read channels:write team:read im:read im:write chat:write:bot bot");
 
	std::string url = oauth2->generateAuthURL();
 

	
 
	m_auths[oauth2->getState()] = oauth2;
 
	m_authsData[oauth2->getState()] = args;
 

	
 
	if (args.size() >= 3) {
 
		LOG4CXX_INFO(logger, "Generating OAUth2 URL with slack_channel=" << args[0] << ", 3rd_party_account=" << args[1]);
 
		LOG4CXX_INFO(logger, "Generating OAUth2 URL with slack_channel=" << args[1] << ", 3rd_party_account=" << args[2]);
 
	}
 
	else {
 
		LOG4CXX_WARN(logger, "Generating OAUth2 URL with too few arguments");
 
	}
 

	
 
	return url;
 
}
 

	
 
std::string SlackUserRegistration::getTeamDomain(const std::string &token) {
 
	std::string url = "https://slack.com/api/team.info?token=" + Util::urlencode(token);
 

	
 
	rapidjson::Document resp;
 
	HTTPRequest req(HTTPRequest::Get, url);
 
	if (!req.execute(resp)) {
 
		LOG4CXX_ERROR(logger, url);
 
		LOG4CXX_ERROR(logger, req.getError());
 
		return "";
 
	}
 

	
 
	rapidjson::Value &team = resp["team"];
 
	if (!team.IsObject()) {
 
		LOG4CXX_ERROR(logger, "No 'team' object in the reply.");
 
		LOG4CXX_ERROR(logger, url);
 
		LOG4CXX_ERROR(logger, req.getRawData());
 
		return "";
 
	}
 

	
 
	rapidjson::Value &domain = team["domain"];
 
	if (!domain.IsString()) {
 
		LOG4CXX_ERROR(logger, "No 'domain' string in the reply.");
 
		LOG4CXX_ERROR(logger, url);
 
		LOG4CXX_ERROR(logger, req.getRawData());
 
		return "";
 
	}
 

	
 
	return domain.GetString();
 
}
 

	
 
std::string SlackUserRegistration::handleOAuth2Code(const std::string &code, const std::string &state) {
 
	OAuth2 *oauth2 = NULL;
 
	std::string token;
 
	std::string access_token;
 
	std::vector<std::string> data;
 
	std::string value;
 
	int type = (int) TYPE_STRING;
 

	
 
	if (state == "use_bot_token") {
 
		token = code;
 
@@ -135,82 +135,85 @@ std::string SlackUserRegistration::handleOAuth2Code(const std::string &code, con
 
			return "Received state code '" + state + "' not found in state codes list.";
 
		}
 

	
 
		std::string error = oauth2->requestToken(code, access_token, token);
 
		if (!error.empty())  {
 
			return error;
 
		}
 

	
 
		if (token.empty()) {
 
			LOG4CXX_INFO(logger, "Using 'token' as 'bot_access_token'");
 
			token = access_token;
 
		}
 
	}
 

	
 
	std::string domain = getTeamDomain(access_token);
 
	if (domain.empty()) {
 
		return "The token you have provided is invalid";
 
	}
 

	
 
	std::string slackChannel;
 
	std::string uin;
 
	std::string password;
 
	if (data.size() >= 3) {
 
		slackChannel = data[1];
 
		uin = data[2];
 
	}
 
	if (data.size() == 4) {
 
		password = data[3];
 
	}
 

	
 
	UserInfo user;
 
	user.uin = "";
 
	user.password = "";
 
	user.id = 0;
 
	m_storageBackend->getUser(domain, user);
 

	
 
	user.jid = domain;
 
	user.uin = uin;
 
	user.password = password;
 
	user.language = "en";
 
	user.encoding = "";
 
	user.vip = 0;
 

	
 
	registerUser(user, true);
 

	
 
	m_storageBackend->getUser(user.jid, user);
 

	
 
	if (!slackChannel.empty()) {
 
		if (slackChannel[0] == '#') {
 
			slackChannel.erase(0, 1);
 
		}
 
		m_storageBackend->getUserSetting(user.id, "slack_channel", type, slackChannel);
 
	}
 

	
 
	value = token;
 
	m_storageBackend->getUserSetting(user.id, "bot_token", type, value);
 

	
 
	value = access_token;
 
	m_storageBackend->getUserSetting(user.id, "access_token", type, value);
 

	
 
	LOG4CXX_INFO(logger, "Registered Slack user " << user.jid << ", slack_channel=" << slackChannel);
 

	
 
	if (oauth2) {
 
		m_auths.erase(state);
 
		delete oauth2;
 

	
 
		m_authsData.erase(state);
 
	}
 

	
 
	m_component->getFrontend()->reconnectUser(user.jid);
 

	
 
	return "Registered as " + domain;
 
}
 

	
 
bool SlackUserRegistration::doUserRegistration(const UserInfo &row) {
 
	return true;
 
}
 

	
 
bool SlackUserRegistration::doUserUnregistration(const UserInfo &row) {
 
	return true;
 
}
 

	
 

	
 

	
 
}
0 comments (0 inline, 0 general)