comparison irccdctl/cli.cpp @ 344:4665fffff6f2

Irccdctl: new cli interface
author David Demelier <markand@malikania.fr>
date Sat, 12 Nov 2016 22:58:48 +0100
parents
children 006452e4a997
comparison
equal deleted inserted replaced
343:3d927ba4af75 344:4665fffff6f2
1 /*
2 * cli.cpp -- command line for irccdctl
3 *
4 * Copyright (c) 2013-2016 David Demelier <markand@malikania.fr>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 #include <json.hpp>
20
21 #include "cli.hpp"
22 #include "irccdctl.hpp"
23 #include "util.hpp"
24 #include "elapsed-timer.hpp"
25
26 namespace irccd {
27
28 void Cli::check(const nlohmann::json &response)
29 {
30 if (!util::json::getBool(response, "status", false)) {
31 auto error = util::json::getString(response, "error");
32
33 if (error.empty())
34 throw std::runtime_error("command failed with an unknown error");
35
36 throw std::runtime_error(error);
37 }
38 }
39
40 nlohmann::json Cli::request(Irccdctl &irccdctl, nlohmann::json args)
41 {
42 auto msg = nlohmann::json();
43
44 if (!args.is_object())
45 args = nlohmann::json::object();
46
47 args.push_back({"command", m_name});
48 irccdctl.client().request(args);
49
50 auto id = irccdctl.client().onMessage.connect([&] (auto input) {
51 msg = std::move(input);
52 });
53
54 try {
55 ElapsedTimer timer;
56
57 while (!msg.is_object() && timer.elapsed() < 3000)
58 util::poller::poll(3000 - timer.elapsed(), irccdctl);
59 } catch (const std::exception &) {
60 irccdctl.client().onMessage.disconnect(id);
61 throw;
62 }
63
64 irccdctl.client().onMessage.disconnect(id);
65
66 std::cout << msg << std::endl;
67
68 if (!msg.is_object())
69 throw std::runtime_error("no response received");
70 if (util::json::getString(msg, "command") != m_name)
71 throw std::runtime_error("unexpected command result received");
72
73 check(msg);
74
75 return msg;
76 }
77
78 void Cli::call(Irccdctl &irccdctl, nlohmann::json args)
79 {
80 check(request(irccdctl, args));
81 }
82
83 } // !irccd