summaryrefslogtreecommitdiff
path: root/rotord/src/rotord.cpp
blob: e7c68cfe7783bdc5b0d5e1138d50445382f33a4e (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
#include "rotord.h"

using namespace Rotor;

RenderContextHandler::RenderContextHandler(const std::string _content,const HTTPServerResponse::HTTPStatus _status){
	content=_content;
	status=_status;
}


void RenderContextHandler::handleRequest(HTTPServerRequest& request,HTTPServerResponse& response) {

    response.setChunkedTransferEncoding(true);
    response.setContentType("text/html");
	response.setStatus(status);

    std::ostream& ostr = response.send();

	ostr << content;

}


HTTPRequestHandler* RotorRequestHandlerFactory::createRequestHandler(const HTTPServerRequest& request){


	Poco::URI theuri=Poco::URI(request.getURI());
	std::vector <std::string> command;
	theuri.getPathSegments(command);

	Logger& logger = Logger::get("Rotor");
	logger.information(request.clientAddress().toString()+" "+request.getMethod());

	HTTPResponse::HTTPStatus status=HTTPResponse::HTTP_BAD_REQUEST; //by default

	std::string body;
	std::ostringstream os;
	os<<request.stream().rdbuf();
	body=os.str();

	xmlIO XML; //xml object handles the servers responses
	XML.addTag("rotor");

	//can we create a tinyxml object here and pass a pointer to it to the render context?
	//can tinyxml output to a string? is there any reason to use poco instead?

	if (command.size()) {
		if (command[0]=="thumbnail") {
			XML.pushTag("rotor");
			if (request.getMethod()=="POST") {
				if (body.size()){
					int w=320;
					int h=180;
					if (command.size()>1){
						Poco::StringTokenizer t1(command[1],",");
						if (t1.count()>1){
							int _w=toInt(t1[0]);
							int _h=toInt(t1[1]);
							if (_h>16&&_w>16){
								w=_w;
								h=_h;
							}
						}
					}
					Thumbnailer thumb;
					Poco::StringTokenizer t1(body,".");
					if (t1.count()>1){
						if (thumb.make(media_dir+body,w,h,thumbnail_dir+t1[0]+".jpg")){
							status=HTTPResponse::HTTP_OK;
							XML.addValue("thumbnail",t1[0]+".jpg");
						}
						else {
							status=HTTPResponse::HTTP_INTERNAL_SERVER_ERROR;
							logger.error("ERROR: could not create thumbnail for "+media_dir+body);
							XML.addValue("error","could not create thumbnail for "+media_dir+body);
						}
					}					
					else {
						if (thumb.make(media_dir+body,w,h,thumbnail_dir+body+".jpg")){
							status=HTTPResponse::HTTP_OK;
							XML.addValue("thumbnail",body+".jpg");
						}
						else {
							status=HTTPResponse::HTTP_INTERNAL_SERVER_ERROR;
							logger.error("ERROR: could not create thumbnail for "+media_dir+body);
							XML.addValue("error","could not create thumbnail for "+media_dir+body);
						}
					}
				}
				else {
					status=HTTPResponse::HTTP_BAD_REQUEST;
					logger.error("ERROR: Body missing");
					XML.addValue("error","Body missing");
			    }
			}
			else {
				status=HTTPResponse::HTTP_BAD_REQUEST;
				logger.error("ERROR: Invalid command combination");
				XML.addValue("error","Invalid command combination");
		    }
		}
		else if (command[0]=="new") {
			XML.pushTag("rotor");
			if (request.getMethod()=="GET") {
				string sID=idGen.createOne().toString();    	//create() seems to cause problems
													//Creates a new time-based UUID, using the MAC address of one of the system's ethernet adapters.
													//Throws a SystemException if no MAC address can be obtained.
													//
													//seems to hang, to me
				logger.information("starting thread "+sID);
				manager.start(new Rotor::Render_context(sID));
				//XML.addTag("sID");
				XML.addValue("sID",sID);
				status=HTTPResponse::HTTP_OK;
			}
			else if (request.getMethod()=="PUT") {		//unofficial manual thread name
				if (body.size()) {
					string sID=body;
					bool found=false;
					for (auto& task: manager.taskList()) {
						if(task->name()==sID) {
							logger.error("ERROR: tried to create thread with existing name "+sID);
							XML.addValue("error","Render context /"+sID+"/ exists already");
							found=true;
						}
					}
					if (!found){
						logger.information("starting thread "+sID);
						manager.start(new Rotor::Render_context(sID));
						XML.addValue("sID",sID);
						status=HTTPResponse::HTTP_OK;
					}
				}
			}
			else {
				status=HTTPResponse::HTTP_BAD_REQUEST;
				logger.error("ERROR: Body missing");
				XML.addValue("error","Body missing");
		    }
		}
		else if (command[0]=="list") {
			XML.pushTag("rotor");
			if (request.getMethod()=="GET") {
				logger.information("sending tasklist");
												//std::list < Poco::AutoPtr < Poco::Task > >::iterator it;
												//it=manager.taskList().begin();
												//for (it=manager.taskList().begin();it !=manager.taskList().end();++it) {
													//content+="<sID>"+(*it)->name()+"</sID>\n";
												//}

												//massive problems making an iterator for the tasklist, the above crashes
												//solution: auto type range-based for-loop
												//this is c++11 specific but works

				for (auto& task: manager.taskList()) { //c++11
					 XML.addValue("sID",task->name());
				}
				status=HTTPResponse::HTTP_OK;
			}
			else {
				status=HTTPResponse::HTTP_BAD_REQUEST;
				logger.error("ERROR: Invalid command combination");
				XML.addValue("error","Invalid command combination");
		    }
		}
		else if (command[0]=="listnodes") {
			if (command.size()>1){
				if (command[1]=="json") {
	        		Json::Value root;
	        		Json::StyledWriter writer;
	        		//root["title"]="Lights Down @Rotor";
	        		//root["audio"]="filename";
	        		
	        		Node_factory factory;
	        		factory.list_nodes(root);
					string content = writer.write(root);
					status=HTTPResponse::HTTP_OK;
	                return new RenderContextHandler(content, status);
				}
			}
			else {
				XML.pushTag("rotor");
				if (request.getMethod()=="GET") {
					Node_factory factory;
					factory.list_nodes(XML);
					status=HTTPResponse::HTTP_OK;
				}
			}
		}
		else if (command[0]=="listnode") {
			XML.pushTag("rotor");
			if (request.getMethod()=="GET") {
				Node_factory factory;
				if (factory.list_node(body,XML)) status=HTTPResponse::HTTP_OK;
			}
			else {
				status=HTTPResponse::HTTP_BAD_REQUEST;
				logger.error("ERROR: Invalid command combination");
				XML.addValue("error","Invalid command combination");
		    }
		}
		else if (command[0]=="listrenders") {
			XML.pushTag("rotor");
			if (request.getMethod()=="GET") {
				int i=0;
				for (auto r: renders){
					XML.addTag("render");
					XML.addAttribute("render","ID",r.first,i);
					bool context_found=false;
					for (auto& task: manager.taskList()) {
						if(task->name()==r.second) {
							Render_status status=((Poco::AutoPtr<Rotor::Render_context>)task)->get_render_status(r.first);
							//cerr<<"render "<<r.first<<" found, context "<<r.second<<", status: "<<status.status<<endl;
							switch (status.status) {
								case RENDERING:
									XML.addAttribute("render","status","rendering",i);
									XML.addAttribute("render","progress",status.progress,i);
									break;
								case RENDER_READY:
									XML.addAttribute("render","status","complete",i);
									break;
								case FAILED:
									XML.addAttribute("render","status","failed",i);
									break;
								case NOT_FOUND:
									XML.addAttribute("render","error","not found",i);
									break;
								case CANCELLED:
									XML.addAttribute("render","status","cancelled",i);
									break;
							}
							context_found=true;
						}
					}
					if (!context_found) XML.addAttribute("render","status","context unavailable",i);
					i++;
				}
				status=HTTPResponse::HTTP_OK;
			}
			else {
				status=HTTPResponse::HTTP_BAD_REQUEST;
				logger.error("ERROR: Invalid command combination");
				XML.addValue("error","Invalid command combination");
		    }
		}
		else if (command[0]=="exit") {
			logger.information("exiting");
			exit(0);
		}
		else {
			bool found=false;
			for (auto& task: manager.taskList()) { //c++11
				 if(task->name()==command[0]) {
					//valid session command
					found=true;
					XML.addAttribute("rotor","context",task->name(),0);
					XML.pushTag("rotor");
					if (command.size()==1) {
						//just invoking sID
						if (request.getMethod()=="DELETE") {
							task->cancel();
							status=HTTPResponse::HTTP_OK;
							logger.information("deleted context "+command[0]);
							XML.addValue("status","context deleted successfully");
						}
						else {
							logger.error("ERROR: Render context invoked with no command: "+command[0]);
							XML.addValue("error","Render context invoked with no command");
					   	}
				    }
				    else {                                                  		//session modifier command- to be passed to render context
													    //some commands need to return error codes
													    //ie where the audio file isn't found
													    //on the other hand, some commands need to know state of the renderer?


						Session_command SC;
						vector<string> sc;      //uid,method,id,command1,{command2,}{body}
						SC.uid=idGen.createOne().toString();
						sc.push_back(request.getMethod());
						SC.method=request.getMethod();
						for (auto& i: command){
						    sc.push_back(i);
						    SC.commands.push_back(i);
						}
						sc.push_back(body);
						SC.body=body;

						((Poco::AutoPtr<Rotor::Render_context>)task)->session_command(SC,XML,status);
						if (XML.tagExists("render_id")){
							//cerr<<"render started: "<<SC.uid<<" in context: "<<command[0]<<endl;
							renders[SC.uid]=command[0];
						}
				    }
				 }
			}
			if (!found) {
				status=HTTPResponse::HTTP_NOT_FOUND;
				logger.error("ERROR: context not found: "+command[0]);
				XML.pushTag("rotor");
				XML.addValue("error","Render context not found");
			}
		}
	}
	else {
		logger.error("ERROR: Empty request");
		XML.addValue("error","Empty request");
	}
	string header="<?xml version='1.0' encoding='ISO-8859-1'?>\n";
	string content;
	XML.copyXmlToString(content);
	header+=content;
	return new RenderContextHandler(header, status);
}


RotorServer::RotorServer(): _helpRequested(false)
{
}

RotorServer::~RotorServer()
{
}

void RotorServer::initialize(Application& self){
	loadConfiguration();
	ServerApplication::initialize(self);
}

void RotorServer::uninitialize(){
	ServerApplication::uninitialize();
}

void RotorServer::defineOptions(OptionSet& options) {
	ServerApplication::defineOptions(options);
	options.addOption(
		Option("help", "h", "display argument help information")
		    .required(false)
		    .repeatable(false)
		    .callback(OptionCallback<RotorServer>(this, &RotorServer::handleHelp)
		)
	);
}

void RotorServer::handleHelp(const std::string& name, const std::string& value){
	HelpFormatter helpFormatter(options());
	helpFormatter.setCommand(commandName());
	helpFormatter.setUsage("OPTIONS");
	helpFormatter.setHeader(
	    "Rotor");
	helpFormatter.format(std::cout);
	stopOptionsProcessing();
	_helpRequested = true;
}

int RotorServer::main(const std::vector<std::string>& args){
	if (!_helpRequested) {

		unsigned short port;

		static Logger& logger = Logger::get("Rotor");

		xmlIO xml;
		if(xml.loadFile("settings.xml") ){
			port=xml.getAttribute("Rotor","port",9000,0);
		}
		else logger.information("settings.xml not found, using defaults");

		logger.information("rotord running on port "+toString(port));

		port = (unsigned short) config().getInt("port", port); //override from command line

		std::string format(config().getString("format", DateTimeFormat::SORTABLE_FORMAT));



		ServerSocket svs(port);
		HTTPServer srv(new RotorRequestHandlerFactory(),svs, new HTTPServerParams);
		srv.start();
		waitForTerminationRequest();
		srv.stop();
	}
	return Application::EXIT_OK;
}