2 Copyright (C) 2014-2015 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/>.
21 #include "json_server.h"
22 #include "job_manager.h"
26 #include "transcode_job.h"
27 #include <dcp/raw_convert.h>
28 #include <boost/asio.hpp>
29 #include <boost/bind.hpp>
30 #include <boost/thread.hpp>
38 using boost::shared_ptr;
39 using boost::dynamic_pointer_cast;
40 using boost::asio::ip::tcp;
41 using dcp::raw_convert;
43 #define MAX_LENGTH 512
53 JSONServer::JSONServer (int port)
55 new thread (boost::bind (&JSONServer::run, this, port));
59 JSONServer::run (int port)
62 boost::asio::io_service io_service;
63 tcp::acceptor a (io_service, tcp::endpoint (tcp::v4 (), port));
66 shared_ptr<tcp::socket> s (new tcp::socket (io_service));
81 JSONServer::handle (shared_ptr<tcp::socket> socket)
84 State state = AWAITING_G;
87 char data[MAX_LENGTH];
88 boost::system::error_code error;
89 size_t len = socket->read_some (boost::asio::buffer (data), error);
99 State old_state = state;
113 state = AWAITING_SPACE;
123 request (url, socket);
132 if (state == old_state && state != READING_URL) {
142 JSONServer::request (string url, shared_ptr<tcp::socket> socket)
144 cout << "request: " << url << "\n";
146 map<string, string> r = split_get_request (url);
147 for (map<string, string>::iterator i = r.begin(); i != r.end(); ++i) {
148 cout << i->first << " => " << i->second << "\n";
152 if (r.find ("action") != r.end ()) {
153 action = r["action"];
157 if (action == "status") {
159 list<shared_ptr<Job> > jobs = JobManager::instance()->get ();
161 json += "{ \"jobs\": [";
162 for (list<shared_ptr<Job> >::iterator i = jobs.begin(); i != jobs.end(); ++i) {
167 json += "\"dcp\": \"" + (*i)->film()->dcp_name() + "\", ";
170 json += "\"name\": \"" + (*i)->json_name() + "\", ";
171 if ((*i)->progress ()) {
172 json += "\"progress\": " + raw_convert<string>((*i)->progress().get()) + ", ";
174 json += "\"progress\": unknown, ";
176 json += "\"status\": \"" + (*i)->json_status() + "\"";
179 list<shared_ptr<Job> >::iterator j = i;
181 if (j != jobs.end ()) {
188 string reply = "HTTP/1.1 200 OK\r\n"
189 "Content-Length: " + raw_convert<string>(json.length()) + "\r\n"
190 "Content-Type: application/json\r\n"
193 cout << "reply: " << json << "\n";
194 boost::asio::write (*socket, boost::asio::buffer (reply.c_str(), reply.length()));