Changeset - 144ccb07e8e2
[Not reviewed]
0 2 0
Jan Kaluza - 10 years ago 2016-01-28 09:23:41
jkaluza@redhat.com
Web interface: Fix missing ',' in app.js
2 files changed with 5 insertions and 1 deletions:
0 comments (0 inline, 0 general)
spectrum_manager/src/APIServer.cpp
Show inline comments
 
#include "APIServer.h"
 
#include "methods.h"
 

	
 
#include <stdio.h>
 
#include <stdlib.h>
 
#include <assert.h>
 
#include <string.h>
 
#include <time.h>
 
#include <stdarg.h>
 
#include <pthread.h>
 
#include <fstream>
 
#include <string>
 
#include <cerrno>
 

	
 
#include "rapidjson/rapidjson.h"
 
#include "rapidjson/stringbuffer.h"
 
#include "rapidjson/writer.h"
 

	
 
#define ALLOW_ONLY_ADMIN() 	if (!session->admin) { \
 
		send_ack(conn, true, "Only administrators can do this API call."); \
 
		return; \
 
	}
 

	
 
static std::string get_http_var(const struct http_message *hm, const char *name) {
 
	char data[4096];
 
	data[0] = '\0';
 

	
 
	mg_get_http_var(&hm->body, name, data, sizeof(data));
 
	if (data[0] != '\0') {
 
		return data;
 
	}
 

	
 
	mg_get_http_var(&hm->query_string, name, data, sizeof(data));
 
	if (data[0] != '\0') {
 
		return data;
 
	}
 

	
 
	return "";
 
}
 

	
 
static int has_prefix(const struct mg_str *uri, const char *prefix) {
 
	size_t prefix_len = strlen(prefix);
 
	return uri->len >= prefix_len && memcmp(uri->p, prefix, prefix_len) == 0;
 
}
 

	
 
APIServer::APIServer(ManagerConfig *config, StorageBackend *storage) {
 
	m_config = config;
 
	m_storage = storage;
 
}
 

	
 
APIServer::~APIServer() {
 
}
 

	
 
void APIServer::send_json(struct mg_connection *conn, const Document &d) {
 
	StringBuffer buffer;
 
	Writer<StringBuffer> writer(buffer);
 
	d.Accept(writer);
 
	std::string json(buffer.GetString());
 

	
 
	std::cout << "Sending JSON:\n";
 
	std::cout << json << "\n";
 
	mg_printf(conn,
 
			"HTTP/1.1 200 OK\r\n"
 
			"Content-Type: text/json\r\n"
 
			"Content-Length: %d\r\n"
 
			"\r\n"
 
			"%s",
 
			(int) json.size(), json.c_str());
 
}
 

	
 
void APIServer::send_ack(struct mg_connection *conn, bool error, const std::string &message) {
 
	Document json;
 
	json.SetObject();
 
	json.AddMember("error", error, json.GetAllocator());
 
	json.AddMember("message", message.c_str(), json.GetAllocator());
 

	
 
	send_json(conn, json);
 
}
 

	
 
void APIServer::serve_instances(Server *server, Server::session *session, struct mg_connection *conn, struct http_message *hm) {
 
	// rapidjson stores const char* pointer to status, so we have to keep
 
	// the std::string stored out of BOOST_FOREACH scope, otherwise the
 
	// const char * returned by c_str() would be invalid during send_json.
 
	std::vector<std::string> statuses;
 
	std::vector<std::string> usernames;
 
	std::vector<std::string> list = show_list(m_config, false);
 

	
 
	Document json;
 
	json.SetObject();
 
	json.AddMember("error", 0, json.GetAllocator());
 

	
 
	Value instances(kArrayType);
 
	BOOST_FOREACH(std::string &id, list) {
 
		Value instance;
 
		instance.SetObject();
 
		instance.AddMember("id", id.c_str(), json.GetAllocator());
 
		instance.AddMember("name", id.c_str(), json.GetAllocator());
 

	
 
		std::string status = server->send_command(id, "status");
 
		if (status.empty()) {
 
			status = "Cannot get the instance status.";
 
		}
 

	
 
		statuses.push_back(status);
 
		instance.AddMember("status", statuses.back().c_str(), json.GetAllocator());
 

	
 
		bool running = true;
 
		if (status.find("Running") == std::string::npos) {
 
			running = false;
 
		}
 
		instance.AddMember("running", running, json.GetAllocator());
 

	
 
		UserInfo info;
 
		m_storage->getUser(session->user, info);
 
		std::string username = "";
 
		int type = (int) TYPE_STRING;
 
		m_storage->getUserSetting(info.id, id, type, username);
 

	
 
		usernames.push_back(username);
 
		instance.AddMember("registered", !username.empty(), json.GetAllocator());
 
		instance.AddMember("username", usernames.back().c_str(), json.GetAllocator());
 
		instance.AddMember("frontend", is_slack(m_config, id) ? "slack" : "xmpp", json.GetAllocator());
 

	
 
		instances.PushBack(instance, json.GetAllocator());
 
	}
 

	
 
	json.AddMember("instances", instances, json.GetAllocator());
 
	send_json(conn, json);
 
}
 

	
 
void APIServer::serve_instances_list_rooms(Server *server, Server::session *session, struct mg_connection *conn, struct http_message *hm) {
 
	std::string uri(hm->uri.p, hm->uri.len);
 
	std::string instance = uri.substr(uri.rfind("/") + 1);
 

	
 
	UserInfo info;
 
	m_storage->getUser(session->user, info);
 

	
 
	std::string username = "";
 
	int type = (int) TYPE_STRING;
 
	m_storage->getUserSetting(info.id, instance, type, username);
 

	
 
	if (username.empty()) {
 
		send_ack(conn, true, "You are not registered to this Spectrum 2 instance.");
 
		return;
 
	}
 

	
 
	std::string response = server->send_command(instance, "list_rooms " + username);
 

	
 
	std::vector<std::string> commands;
 
	boost::split(commands, response, boost::is_any_of("\n"));
 

	
 
	Document json;
 
	json.SetObject();
 
	json.AddMember("error", 0, json.GetAllocator());
 
	json.AddMember("name_label", "Nickname in 3rd-party room", json.GetAllocator());
 
	json.AddMember("legacy_room_label", "3rd-party room name", json.GetAllocator());
 
	json.AddMember("legacy_server_label", "3rd-party server", json.GetAllocator());
 
	json.AddMember("frontend_room_label", "Slack channel", json.GetAllocator());
 

	
 
	std::vector<std::vector<std::string> > tmp;
 
	Value rooms(kArrayType);
 
	BOOST_FOREACH(const std::string &command, commands) {
 
		if (command.size() > 5) {
 
			std::vector<std::string> args2;
 
			boost::split(args2, command, boost::is_any_of(" "));
 
			if (args2.size() == 6) {
 
				tmp.push_back(args2);
 
				Value room;
 
				room.SetObject();
 
				room.AddMember("name", tmp.back()[2].c_str(), json.GetAllocator());
 
				room.AddMember("legacy_room", tmp.back()[3].c_str(), json.GetAllocator());
 
				room.AddMember("legacy_server", tmp.back()[4].c_str(), json.GetAllocator());
 
				room.AddMember("frontend_room", tmp.back()[5].c_str(), json.GetAllocator());
 
				rooms.PushBack(room, json.GetAllocator());
 
			}
 
		}
 
	}
 

	
 
	json.AddMember("rooms", rooms, json.GetAllocator());
 
	send_json(conn, json);
 
}
 

	
 
void APIServer::serve_instances_start(Server *server, Server::session *session, struct mg_connection *conn, struct http_message *hm) {
 
	ALLOW_ONLY_ADMIN();
 

	
 
	std::string uri(hm->uri.p, hm->uri.len);
 
	std::string instance = uri.substr(uri.rfind("/") + 1);
 
	start_instances(m_config, instance);
 
	std::string response = get_response();
 

	
 
	// TODO: So far it needs some time to reload Spectrum 2, so just sleep here.
 
	sleep(1);
 

	
 
	send_ack(conn, response.find("OK") == std::string::npos, response);
 
}
 

	
 
void APIServer::serve_instances_stop(Server *server, Server::session *session, struct mg_connection *conn, struct http_message *hm) {
 
	ALLOW_ONLY_ADMIN();
 

	
 
	std::string uri(hm->uri.p, hm->uri.len);
 
	std::string instance = uri.substr(uri.rfind("/") + 1);
 
	stop_instances(m_config, instance);
 
	std::string response = get_response();
 
	send_ack(conn, response.find("OK") == std::string::npos, response);
 
}
 

	
 
void APIServer::serve_instances_unregister(Server *server, Server::session *session, struct mg_connection *conn, struct http_message *hm) {
 
	std::string uri(hm->uri.p, hm->uri.len);
 
	std::string instance = uri.substr(uri.rfind("/") + 1);
 

	
 
	UserInfo info;
 
	m_storage->getUser(session->user, info);
 

	
 
	std::string username = "";
 
	int type = (int) TYPE_STRING;
 
	m_storage->getUserSetting(info.id, instance, type, username);
 

	
 
	if (!username.empty()) {
 
		std::string response = server->send_command(instance, "unregister " + username);
 
		if (!response.empty()) {
 
			username = "";
 
			m_storage->updateUserSetting(info.id, instance, username);
 
			send_ack(conn, false, response);
 
		}
 
		else {
 
			send_ack(conn, true, "Unknown error.");
 
		}
 
	}
 
	else {
 
		send_ack(conn, true, "You are not registered to this Spectrum 2 instance.");
 
	}
 
}
 

	
 
void APIServer::serve_instances_register(Server *server, Server::session *session, struct mg_connection *conn, struct http_message *hm) {
 
	std::string uri(hm->uri.p, hm->uri.len);
 
	std::string instance = uri.substr(uri.rfind("/") + 1);
 

	
 
	UserInfo info;
 
	m_storage->getUser(session->user, info);
 

	
 
	std::string username = "";
 
	int type = (int) TYPE_STRING;
 
	m_storage->getUserSetting(info.id, instance, type, username);
 

	
 
	std::string jid = get_http_var(hm, "jid");
 
	std::string uin = get_http_var(hm, "uin");
 
	std::string password = get_http_var(hm, "password");
 

	
 
	if (jid.empty() || uin.empty() || password.empty()) {
 
		send_ack(conn, true, "Insufficient data.");
 
	}
 
	else {
 
		// Check if the frontend wants to use OAuth2 (Slack for example).
 
		std::string response = server->send_command(instance, "get_oauth2_url " + jid + " " + uin + " " + password);
 
		if (!response.empty()) {
 
			Document json;
 
			json.SetObject();
 
			json.AddMember("error", false, json.GetAllocator());
 
			json.AddMember("oauth2_url", response.c_str(), json.GetAllocator());
 
			send_json(conn, json);
 
		}
 
		else {
 
			response = server->send_command(instance, "register " + jid + " " + uin + " " + password);
 
			if (!response.empty()) {
 
				std::string value = jid;
 
				int type = (int) TYPE_STRING;
 
				m_storage->updateUserSetting(info.id, instance, value);
 
			}
 
			else {
 
				send_ack(conn, true, response);
 
				return;
 
			}
 
		}
 
	}
 
}
 

	
 
void APIServer::serve_instances_join_room(Server *server, Server::session *session, struct mg_connection *conn, struct http_message *hm) {
 
	std::string uri(hm->uri.p, hm->uri.len);
 
	std::string instance = uri.substr(uri.rfind("/") + 1);
 

	
 
	UserInfo info;
 
	m_storage->getUser(session->user, info);
 

	
 
	std::string username = "";
 
	int type = (int) TYPE_STRING;
 
	m_storage->getUserSetting(info.id, instance, type, username);
 

	
 
	if (username.empty()) {
 
		send_ack(conn, true, "You are not registered to this Spectrum 2 instance.");
 
		return;
 
	}
 

	
 
	std::string name = get_http_var(hm, "name");
 
	std::string legacy_room = get_http_var(hm, "legacy_room");
 
	std::string legacy_server = get_http_var(hm, "legacy_server");
 
	std::string frontend_room = get_http_var(hm, "frontend_room");
 

	
 
	std::string response = server->send_command(instance, "join_room " +
 
		username + " " + name + " " + legacy_room + " " + legacy_server + " " + frontend_room);
 

	
 
	if (response.find("Joined the room") == std::string::npos) {
 
		send_ack(conn, true, response);
 
	}
 
	else {
 
		send_ack(conn, false, response);
 
	}
 
}
 

	
 
void APIServer::serve_instances_join_room_form(Server *server, Server::session *session, struct mg_connection *conn, struct http_message *hm) {
 
	// So far we support just Slack here. For XMPP, it is up to user to initiate the join room request.
 
	Document json;
 
	json.SetObject();
 
	json.AddMember("error", 0, json.GetAllocator());
 
	json.AddMember("name_label", "Nickname in 3rd-party room", json.GetAllocator());
 
	json.AddMember("legacy_room_label", "3rd-party room name", json.GetAllocator());
 
	json.AddMember("legacy_server_label", "3rd-party server", json.GetAllocator());
 
	json.AddMember("frontend_room_label", "Slack channel", json.GetAllocator());
 
	send_json(conn, json);
 
}
 

	
 
void APIServer::serve_instances_register_form(Server *server, Server::session *session, struct mg_connection *conn, struct http_message *hm) {
 
	std::string uri(hm->uri.p, hm->uri.len);
 
	std::string instance = uri.substr(uri.rfind("/") + 1);
 

	
 
	std::string response = server->send_command(instance, "registration_fields");
 
	std::vector<std::string> fields;
 
	boost::split(fields, response, boost::is_any_of("\n"));
 

	
 
	if (fields.size() < 3) {
 
		fields.clear();
 
		fields.push_back("Jabber ID");
 
		fields.push_back("3rd-party network username");
 
		fields.push_back("3rd-party network password");
 
	}
 

	
 
	Document json;
 
	json.SetObject();
 
	json.AddMember("error", 0, json.GetAllocator());
 
	json.AddMember("username_label", fields[0].c_str(), json.GetAllocator());
 
	json.AddMember("legacy_username_label", fields[1].c_str(), json.GetAllocator());
 
	json.AddMember("password_label", fields[2].c_str(), json.GetAllocator());
 
	send_json(conn, json);
 
}
 

	
 
void APIServer::serve_users(Server *server, Server::session *session, struct mg_connection *conn, struct http_message *hm) {
 
	ALLOW_ONLY_ADMIN();
 

	
 
	Document json;
 
	json.SetObject();
 
	json.AddMember("error", 0, json.GetAllocator());
spectrum_manager/src/html/js/app.js
Show inline comments
 
function getQueryParams(qs) {
 
	qs = qs.split('+').join(' ');
 

	
 
	var params = {},
 
		tokens,
 
		re = /[?&]?([^=]+)=([^&]*)/g;
 

	
 
	while (tokens = re.exec(qs)) {
 
		params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
 
	}
 

	
 
	return params;
 
}
 

	
 
function show_instances() {
 
	$.get($.cookie("base_location") + "api/v1/instances", function(data) {
 
		$("#main_content").html("<h2>List of Spectrum 2 instances</h2><table id='main_result'><tr><th>Name<th>Status</th><th>Actions</th></tr>");
 

	
 
		var admin = $.cookie("admin") == "1";
 
		$.each(data.instances, function(i, instance) {
 
			if (instance.running) {
 
				if (admin) {
 
					var command = instance.running ? "stop" : "start";
 
				}
 
				else {
 
					var command = instance.registered ? "unregister" : "register";
 
					if (instance.registered) {
 
						instance.status += "<br/>Registered as " + instance.username;
 
					}
 
				}
 
			}
 
			else if (admin) {
 
				var command = "start";
 
			}
 
			else {
 
				var command = "";
 
			}
 
			var row = '<tr>'
 
			row += '<td>' + instance.name + '</td>'
 
			row += '<td>' + instance.status + '</td>'
 

	
 
			if (command == 'register') {
 
				row += '<td><a class="button_command" href="' + $.cookie("base_location") + 'instances/register.shtml?id=' + instance.id + '">' + command + '</a>' + '</td></tr>';
 
				$("#main_result  > tbody:last-child").append(row);
 
			}
 
			else if (command == "") {
 
				row += '<td></td></tr>';
 
				$("#main_result  > tbody:last-child").append(row);
 
			}
 
			else {
 
				row += '<td>';
 
				if (command == 'unregister' && instance.frontend == "slack") {
 
					row += '<a href="' + $.cookie("base_location") + 'instances/join_room.shtml?id=' + instance.id + '">Join room</a> | ';
 
					row += '<a href="' + $.cookie("base_location") + 'instances/list_rooms.shtml?id=' + instance.id + '">List joined rooms</a> | ';
 
				}
 
				row += '<a class="button_command" href="' + $.cookie("base_location") +  'api/v1/instances/' + command + '/' + instance.id + '">' + command + '</a>';
 
				row += '</td></tr>';
 
				$("#main_result  > tbody:last-child").append(row);
 
				$(".button_command").click(function(e) {
 
					e.preventDefault();
 
					$(this).parent().empty().progressbar( {value: false} ).css('height', '1em');
 

	
 
					var url = $(this).attr('href');
 
					$.get(url, function(data) {
 
						show_instances();
 
					});
 
				})
 
			}
 
		});
 
	});
 
}
 

	
 
function show_list_rooms() {
 
	var query = getQueryParams(document.location.search);
 
	$.get($.cookie("base_location") + "api/v1/instances/list_rooms/" + query.id, function(data) {
 
		$("#main_content").html("<h2>Joined rooms</h2><table id='main_result'><tr><th>" + data.frontend_room_label + "</th><th>" + data.legacy_room_label + "</th><th>" + data.legacy_server_label + "</th><th>" + data.name_label + "</th><th>Actions</th></tr>");
 

	
 
		$.each(data.room, function(i, instance) {
 
			var row = '<tr>';
 
			row += '<td>' + room.frontend_room + '</td>';
 
			row += '<td>' + room.legacy_room + '</td>';
 
			row += '<td>' + room.legacy_server + '</td>';
 
			row += '<td>' + room.name + '</td>';
 
			row += '<td><a class="button_command" href="' + $.cookie("base_location") +  'api/v1/instances/leave_room/' + instance.id + '?frontend_room=' + room.frontend_room + '">Leave</a></td>';
 
			row += '</tr>';
 

	
 
			$("#main_result  > tbody:last-child").append(row);
 
			$(".button_command").click(function(e) {
 
				e.preventDefault();
 
				$(this).parent().empty().progressbar( {value: false} ).css('height', '1em');
 

	
 
				var url = $(this).attr('href');
 
				$.get(url, function(data) {
 
					show_instances();
 
				});
 
			})
 
		});
 
	});
 
}
 

	
 
function show_users() {
 
	var admin = $.cookie("admin") == "1";
 
	if (!admin) {
 
		$("#main_content").html("<h2>List of Spectrum 2 users</h2><p>Only administrator can list the users.</p>");
 
		return;
 
	}
 

	
 
	$.get($.cookie("base_location") + "api/v1/users", function(data) {
 
		$("#main_content").html("<h2>List of Spectrum 2 users</h2><p>You can add new users <a href=\"register.shtml?back_to_list=1\">here</a>.</p><table id='main_result'><tr><th>Name<th>Actions</th></tr>");
 

	
 
		$.each(data.users, function(i, user) {
 
			var row = '<tr>'
 
			row += '<td>' + user.username + '</td>'
 
			row += '<td><a class="button_command" href="' + $.cookie("base_location") +  'api/v1/users/remove/' + user.username + '">remove</a></td></tr>';
 
			$("#main_result  > tbody:last-child").append(row);
 
			$(".button_command").click(function(e) {
 
				e.preventDefault();
 
				$(this).parent().empty().progressbar( {value: false} ).css('height', '1em');
 

	
 
				var url = $(this).attr('href');
 
				$.get(url, function(data) {
 
					show_users();
 
				});
 
			})
 
		});
 
	});
 
}
 

	
 
function fill_instances_join_room_form() {
 
	var query = getQueryParams(document.location.search);
 
	$("#instance").attr("value", query.id);
 

	
 
	$(".button_command").click(function(e) {
 
		e.preventDefault();
 
		$(this).parent().empty().progressbar( {value: false} ).css('height', '1em');
 

	
 
		var postdata ={
 
			"name": $("#name").val(),
 
			"legacy_room": $("#legacy_room").val(),
 
			"legacy_server": $("#legacy_server").val()
 
			"legacy_server": $("#legacy_server").val(),
 
			"frontend_room": $("#frontend_room").val()
 
		};
 

	
 
		$.post($.cookie("base_location") + "api/v1/instances/join_room/" + $("#instance").val(), postdata, function(data) {
 
			window.location.replace("index.shtml");
 
		});
 
	})
 
	
 
	$.get($.cookie("base_location") + "api/v1/instances/join_room_form/" + query.id, function(data) {
 
		$("#name_desc").html(data.name_label + ":");
 
		$("#legacy_room_desc").html(data.legacy_room_label + ":");
 
		$("#legacy_server_desc").html(data.legacy_server_label + ":");
 
		$("#frontend_room_desc").html(data.frontend_room_label + ":");
 

	
 
		$("#name").attr("placeholder", data.name_label + ":");
 
		$("#legacy_room").attr("placeholder", data.legacy_room_label + ":");
 
		$("#legacy_server").attr("placeholder", data.legacy_server_label + ":");
 
		$("#frontend_room").attr("placeholder", data.frontend_room_label + ":");
 
	});
 
}
 

	
 
function fill_instances_register_form() {
 
	var query = getQueryParams(document.location.search);
 
	$("#instance").attr("value", query.id);
 

	
 
	$(".button_command").click(function(e) {
 
		e.preventDefault();
 
		$(this).parent().empty().progressbar( {value: false} ).css('height', '1em');
 

	
 
		var postdata ={
 
			"jid": $("#jid").val(),
 
			"uin": $("#uin").val(),
 
			"password": $("#password").val()
 
		};
 

	
 
		$.post($.cookie("base_location") + "api/v1/instances/register/" + $("#instance").val(), postdata, function(data) {
 
			if (data.oauth2_url) {
 
				window.location.replace(data.oauth2_url);
 
			}
 
			else {
 
				window.location.replace("index.shtml");
 
			}
 
		});
 
	})
 
	
 
	$.get($.cookie("base_location") + "api/v1/instances/register_form/" + query.id, function(data) {
 
		$("#jid_desc").html(data.username_label + ":");
 
		$("#uin_desc").html(data.legacy_username_label + ":");
 
		$("#password_desc").html(data.password_label + ":");
 

	
 
		$("#jid").attr("placeholder", data.username_label);
 
		$("#uin").attr("placeholder", data.legacy_username_label);
 
		$("#password").attr("placeholder", data.password_label);
 
	});
 
}
 

	
 
function fill_users_register_form() {
 
	$(".button").click(function(e) {
 
		e.preventDefault();
 
		$(this).parent().empty().progressbar( {value: false} ).css('height', '1em');
 

	
 
		var postdata ={
 
			"username": $("#username").val(),
 
			"password": $("#password").val()
 
		};
 

	
 
		$.post($.cookie("base_location") + "api/v1/users/add", postdata, function(data) {
 
			var query = getQueryParams(document.location.search);
 
			if (query.back_to_list == "1") {
 
				window.location.replace("list.shtml");
 
			}
 
			else {
 
				window.location.replace("../login/");
 
			}
 
		});
 
	})
 
}
 

	
0 comments (0 inline, 0 general)