2 Copyright (C) 2014-2021 Carl Hetherington <cth@carlh.net>
4 This file is part of DCP-o-matic.
6 DCP-o-matic is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 DCP-o-matic is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with DCP-o-matic. If not, see <http://www.gnu.org/licenses/>.
24 #include "job_manager.h"
25 #include "json_server.h"
26 #include "transcode_job.h"
28 #include <dcp/raw_convert.h>
29 #include <boost/asio.hpp>
30 #include <boost/bind/bind.hpp>
31 #include <boost/thread.hpp>
36 using std::dynamic_pointer_cast;
38 using std::make_shared;
40 using std::shared_ptr;
42 using boost::asio::ip::tcp;
44 using dcp::raw_convert;
47 #define MAX_LENGTH 512
59 JSONServer::JSONServer (int port)
61 #ifdef DCPOMATIC_LINUX
62 auto t = new thread (boost::bind (&JSONServer::run, this, port));
63 pthread_setname_np (t->native_handle(), "json-server");
65 new thread (boost::bind (&JSONServer::run, this, port));
71 JSONServer::run (int port)
74 boost::asio::io_service io_service;
75 tcp::acceptor a (io_service, tcp::endpoint (tcp::v4 (), port));
78 auto s = make_shared<tcp::socket>(io_service);
94 JSONServer::handle (shared_ptr<tcp::socket> socket)
97 State state = AWAITING_G;
100 char data[MAX_LENGTH];
101 boost::system::error_code error;
102 size_t len = socket->read_some (boost::asio::buffer (data), error);
112 auto old_state = state;
126 state = AWAITING_SPACE;
136 request (url, socket);
145 if (state == old_state && state != READING_URL) {
156 JSONServer::request (string url, shared_ptr<tcp::socket> socket)
158 cout << "request: " << url << "\n";
160 auto r = split_get_request (url);
161 for (auto const& i: r) {
162 cout << i.first << " => " << i.second << "\n";
166 if (r.find ("action") != r.end ()) {
167 action = r["action"];
171 if (action == "status") {
173 auto jobs = JobManager::instance()->get();
175 json += "{ \"jobs\": [";
176 for (auto i = jobs.cbegin(); i != jobs.cend(); ++i) {
180 json += "\"dcp\": \"" + (*i)->film()->dcp_name() + "\", ";
183 json += "\"name\": \"" + (*i)->json_name() + "\", ";
184 if ((*i)->progress()) {
185 json += "\"progress\": " + raw_convert<string>((*i)->progress().get()) + ", ";
187 json += "\"progress\": unknown, ";
189 json += "\"status\": \"" + (*i)->json_status() + "\"";
194 if (j != jobs.end ()) {
201 string reply = "HTTP/1.1 200 OK\r\n"
202 "Content-Length: " + raw_convert<string>(json.length()) + "\r\n"
203 "Content-Type: application/json\r\n"
206 cout << "reply: " << json << "\n";
207 boost::asio::write (*socket, boost::asio::buffer(reply.c_str(), reply.length()));