summaryrefslogtreecommitdiff
path: root/control_commands.c
blob: 0e5658a7bc04374f408e801c079dc27cef5c2777 (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
#include "control_commands.h"
#include "servers.h"
#include "music.h"
#include "server_communication.h"

#include <glib.h>
#include <string.h>

static void list_servers(GSocketConnection *connection, const gchar *cmd) {
	GSocket *socket = g_socket_connection_get_socket(connection);

	for(GSList *node = servers; node; node = g_slist_next(node)) {
		struct server *s = node->data;
		gchar *buffer = g_strdup_printf("%s:%d\n", s->host, s->port);
		g_socket_send(socket, buffer, strlen(buffer), NULL, NULL);
	}
}

static void commands_find(GSocketConnection *connection, const gchar *cmd) {
	GError *error = NULL;
	gchar **data = g_strsplit(cmd, " ", 3);

	if(g_strv_length(data) != 3) {
		const gchar *buf = "syntax: find (artist) search\n";
		GSocket *socket = g_socket_connection_get_socket(connection);
		g_socket_send(socket, buf, strlen(buf), NULL, NULL);
		return;
	}

	GSList *list = NULL;
	g_debug("strlen(%s) == %d", data[1], strlen(data[1]));
	if(g_ascii_strcasecmp(data[1], "artist") == 0) {
		g_debug("artist search");
		list = music_find_artist(data[2]);
	} else {
		g_debug("unknown search");
	}

	GString *string = g_string_new(NULL);
	for(GSList *node = list; node; node = g_slist_next(node)) {
		struct file *f = node->data;
		gchar *relpath = g_build_filename(f->parent->path +
				strlen(music_root->path), f->name, NULL);
		g_string_append_printf(string, "%s\n", relpath);
		g_free(relpath);
	}
	g_slist_free(list);

	for(GSList *node = servers; node; node = g_slist_next(node)) {
		struct server *server = node->data;
		g_debug("fetching data from server %s", server->host);
		gchar **temp = server_find(server, data[1], data[2]);
		if(temp == NULL) {
			continue;
		}
		for(gint i = 0; i < g_strv_length(temp); i++) {
			if(strlen(temp[i]) == 0) {
				break;
			}
			g_string_append_printf(string, "%s:%s\n", server->host, temp[i]);
		}
		g_strfreev(temp);
	}

	GOutputStream *os = g_io_stream_get_output_stream((GIOStream*)connection);
	if(g_output_stream_write_all(os, string->str, string->len, NULL, NULL,
				&error) == FALSE) {
		g_warning(error->message);
		g_error_free(error);
	}
	g_string_free(string, TRUE);
}

void control_commands_handle(GSocketConnection *connection, const gchar *cmd) {
	if(g_strcmp0(cmd, "servers") == 0) {
		list_servers(connection, cmd);
	} else if(g_strncasecmp(cmd, "find", 4) == 0) {
		commands_find(connection, cmd);
	} else {
		g_debug("unknown command");
		gchar *buf = g_strdup_printf("error: unknown command %s\n", cmd);
		GSocket *socket = g_socket_connection_get_socket(connection);
		g_socket_send(socket, buf, strlen(buf), NULL, NULL);
		g_free(buf);
	}
}