2 Copyright (C) 2014 Carl Hetherington <cth@carlh.net>
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 #include <boost/asio.hpp>
21 #include <boost/bind.hpp>
22 #include <boost/thread.hpp>
23 #include "json_server.h"
24 #include "job_manager.h"
28 #include "transcode_job.h"
31 using std::stringstream;
36 using boost::shared_ptr;
37 using boost::dynamic_pointer_cast;
38 using boost::asio::ip::tcp;
40 #define MAX_LENGTH 512
50 JSONServer::JSONServer (int port)
52 new thread (boost::bind (&JSONServer::run, this, port));
56 JSONServer::run (int port)
59 boost::asio::io_service io_service;
60 tcp::acceptor a (io_service, tcp::endpoint (tcp::v4 (), port));
63 shared_ptr<tcp::socket> s (new tcp::socket (io_service));
78 JSONServer::handle (shared_ptr<tcp::socket> socket)
81 State state = AWAITING_G;
84 char data[MAX_LENGTH];
85 boost::system::error_code error;
86 size_t len = socket->read_some (boost::asio::buffer (data), error);
96 State old_state = state;
110 state = AWAITING_SPACE;
120 request (url, socket);
129 if (state == old_state && state != READING_URL) {
139 JSONServer::request (string url, shared_ptr<tcp::socket> socket)
141 cout << "request: " << url << "\n";
143 map<string, string> r = split_get_request (url);
144 for (map<string, string>::iterator i = r.begin(); i != r.end(); ++i) {
145 cout << i->first << " => " << i->second << "\n";
149 if (r.find ("action") != r.end ()) {
150 action = r["action"];
154 if (action == "status") {
156 list<shared_ptr<Job> > jobs = JobManager::instance()->get ();
158 json << "{ \"jobs\": [";
159 for (list<shared_ptr<Job> >::iterator i = jobs.begin(); i != jobs.end(); ++i) {
164 json << "\"dcp\": \"" << (*i)->film()->dcp_name() << "\", ";
167 json << "\"name\": \"" << (*i)->json_name() << "\", "
168 << "\"progress\": " << (*i)->progress () << ", "
169 << "\"status\": \"" << (*i)->json_status() << "\"";
172 list<shared_ptr<Job> >::iterator j = i;
174 if (j != jobs.end ()) {
180 if (json.str().empty ()) {
186 reply << "HTTP/1.1 200 OK\r\n"
187 << "Content-Length: " << json.str().length() << "\r\n"
188 << "Content-Type: application/json\r\n"
190 << json.str () << "\r\n";
191 cout << "reply: " << json.str() << "\n";
192 boost::asio::write (*socket, boost::asio::buffer (reply.str().c_str(), reply.str().length()));