summaryrefslogtreecommitdiff
path: root/commands.cpp
blob: 240169032d10718a0340634e7f7e464b08cb21a0 (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
#include "commands.h"
#include "music.h"

#include <boost/cast.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string/join.hpp>

#include <iostream>

static std::vector<std::string> ls(const std::vector<std::string>& args) {
	if(args.size() != 2) {
		throw commands::CommandException("usage: ls DIR");
	}

	MusicListing::p ml = music::get(args[1]);
	if(!ml || !fs::is_directory(ml->path)) {
		throw commands::CommandException("no such directory");
	}
	std::vector<std::string> result;
	MusicDirectory *dir = boost::polymorphic_downcast<MusicDirectory*>(&(*ml));
	for(MusicDirectory::PathListings::iterator it = dir->directories.begin(); it != dir->directories.end(); it++) {
		std::string rel_path = it->string().substr(music::root_directory.string().size());
		result.push_back(rel_path);
	}
	for(MusicDirectory::PathListings::iterator it = dir->tracks.begin(); it != dir->tracks.end(); it++) {
		std::string rel_path = it->string().substr(music::root_directory.string().size());
		result.push_back(rel_path);
	}

	return result;
}

typedef boost::function<std::vector<MusicListing::p> (const std::string artist)> FindFunction;
std::map<std::string, FindFunction> find_handlers;

static std::vector<std::string> find(const std::vector<std::string>& args) {
	if(args.size() != 3) {
		throw commands::CommandException("usage: find TYPE SEARCH");
	}

	FindFunction ff;
	if(find_handlers.find(args[1]) != find_handlers.end()) {
		ff = find_handlers[args[1]];
	} else {
		std::vector<std::string> types;
		for(std::map<std::string, FindFunction>::iterator it = find_handlers.begin(); it != find_handlers.end(); it++) {
			types.push_back(it->first);
		}
		std::string s = boost::str(boost::format("unknown search type, must be one of %s") % boost::algorithm::join(types, ", "));
		throw commands::CommandException(s.c_str());
	}

	std::vector<MusicListing::p> ml = ff(args[2]);
	if(!ml.size()) {
		throw commands::CommandException("no results");
	}

	std::vector<std::string> result;
	for(std::vector<MusicListing::p>::iterator it = ml.begin(); it != ml.end(); it++) {
		result.push_back((*it)->path.string());
	}


	return result;
}

std::map<std::string, commands::Handler> commands::handlers;

void commands::init() {
	handlers["ls"] = ls;
	handlers["find"] = find;
	find_handlers["artist"] = music::find_artist;
}

std::vector<std::string> commands::execute(const std::vector<std::string>& args) {
	assert(args.size());
	Handler h = commands::handlers[args[0]];
	if(!h) {
		throw CommandException("unknown command");
	}

	return h(args);
}