5 #include <jsoncpp/json/json.h>
8 #include <vdr/videodir.h>
9 #include <vdr/recording.h>
11 #include <vdr/timers.h>
15 int jsonserver_request_handler(struct mg_connection *conn)
17 Log* log = Log::getInstance();
18 const struct mg_request_info *request_info = mg_get_request_info(conn);
20 if (strcmp(request_info->uri, "/jsonserver")) return 0; // not for us
23 int wvrl = mg_get_var(request_info->query_string, strlen(request_info->query_string), "req", wvrequest, 20);
26 log->log("JSONServer", Log::ERR, "Could not decode req");
31 if (!strcmp(request_info->request_method, "OPTIONS"))
33 mg_printf(conn, "%s", "HTTP/1.0 200 OK\r\n");
34 mg_printf(conn, "%s", "Access-Control-Allow-Origin: *\r\n");
35 mg_printf(conn, "%s", "Content-Type: text/plain\r\n\r\n");
43 if (!strcmp(request_info->request_method, "POST"))
45 const char* contentLength = mg_get_header(conn, "Content-Length");
46 int contentLengthI = atoi(contentLength);
47 log->log("JSONServer", Log::DEBUG, "POST data content length: %i", contentLengthI);
48 if (contentLengthI > 10000)
50 log->log("JSONServer", Log::DEBUG, "Length > 10000, rejecting");
54 if (contentLengthI > 0)
56 // FIXME - assume for now that all post data will be small enough to have arrived immediately
57 int bytesRead = mg_read(conn, postData, contentLengthI);
58 if (bytesRead != contentLengthI)
60 log->log("JSONServer", Log::DEBUG, "Could not read up to contentLength");
69 if (!strcmp(wvrequest, "reclist")) success = jsonserver_reclist(js);
70 else if (!strcmp(wvrequest, "recinfo")) success = jsonserver_recinfo(js, postData);
71 else if (!strcmp(wvrequest, "recdel")) success = jsonserver_recdel(js, postData);
72 else if (!strcmp(wvrequest, "recmove")) success = jsonserver_recmove(js, postData);
73 else if (!strcmp(wvrequest, "channellist")) success = jsonserver_channellist(js);
74 else if (!strcmp(wvrequest, "channelschedule")) success = jsonserver_channelschedule(js, postData);
75 else if (!strcmp(wvrequest, "timerlist")) success = jsonserver_timerlist(js);
76 else if (!strcmp(wvrequest, "timerdel")) success = jsonserver_timerdel(js, postData);
77 else if (!strcmp(wvrequest, "timerset")) success = jsonserver_timerset(js, postData);
79 if (!success) return 0; // the specific handler failed badly
81 // Now js will be filled
83 Json::StyledWriter sw;
84 std::string jsonout = sw.write(js);
85 mg_printf(conn, "%s", "HTTP/1.0 200 OK\r\n");
86 mg_printf(conn, "%s", "Content-Type: text/plain\r\n\r\n");
87 mg_write(conn, jsonout.c_str(), jsonout.length());
92 else if (event == MG_EVENT_LOG)
94 if (request_info->status_code == 400) // bad request
96 log->log("Mongoose", Log::DEBUG, "400 BAD REQUEST:");
97 log->log("Mongoose", Log::DEBUG, request_info->request_method);
98 log->log("Mongoose", Log::DEBUG, request_info->uri);
99 log->log("Mongoose", Log::DEBUG, request_info->http_version);
100 log->log("Mongoose", Log::DEBUG, request_info->query_string);
101 log->log("Mongoose", Log::DEBUG, request_info->log_message);
102 for (int i = 0; i < request_info->num_headers; i++)
104 log->log("Mongoose", Log::DEBUG, "%s: %s", request_info->http_headers[i].name, request_info->http_headers[i].value);
109 log->log("Mongoose", Log::DEBUG, request_info->log_message);
110 log->log("Mongoose", Log::DEBUG, request_info->uri);
115 // other events not handled:
116 // MG_HTTP_ERROR, MG_INIT_SSL
117 // Let mongoose do something with those
125 bool jsonserver_reclist(Json::Value& js)
127 Log* log = Log::getInstance();
128 log->log("JSONServer", Log::DEBUG, "reclist");
131 int Percent = VideoDiskSpace(&FreeMB);
132 int Total = (FreeMB / (100 - Percent)) * 100;
134 js["MBFree"] = FreeMB;
135 js["Percent"] = Percent;
138 Json::Value jsrecordings;
139 cRecordings Recordings;
141 for (cRecording *recording = Recordings.First(); recording; recording = Recordings.Next(recording))
144 oneRec["StartTime"] = (Json::UInt)recording->Start();
145 oneRec["Name"] = recording->Name();
146 oneRec["Filename"] = recording->FileName();
147 jsrecordings.append(oneRec);
149 js["Recordings"] = jsrecordings;
154 bool jsonserver_recinfo(Json::Value& js, const char* postData)
156 // For now this returns just the string summary of the recording
158 Log* log = Log::getInstance();
159 log->log("JSONServer", Log::DEBUG, "recinfo");
161 char reqfilename[1000];
162 int mgv1 = mg_get_var(postData, strlen(postData), "filename", reqfilename, 1000);
165 log->log("JSONServer", Log::ERR, "Could not decode filename");
166 js["Result"] = false;
167 js["Error"] = "Could not decode filename";
171 log->log("JSONServer", Log::DEBUG, "%s", reqfilename);
173 cRecordings Recordings;
174 Recordings.Load(); // probably have to do this
175 cRecording *recording = Recordings.GetByName(reqfilename);
179 const cRecordingInfo *Info = recording->Info();
180 char* summary = (char*)Info->ShortText();
181 if (isempty(summary)) summary = (char*)Info->Description();
183 js["Summary"] = summary;
187 log->log("JSONServer", Log::ERR, "recinfo found no recording");
188 js["Result"] = false;
195 bool jsonserver_recdel(Json::Value& js, const char* postData)
197 Log* log = Log::getInstance();
198 log->log("JSONServer", Log::DEBUG, "recdel");
200 char reqfilename[1000];
201 int mgv1 = mg_get_var(postData, strlen(postData), "filename", reqfilename, 1000);
204 log->log("JSONServer", Log::ERR, "Could not decode filename");
205 js["Result"] = false;
206 js["Error"] = "Could not decode filename";
210 log->log("JSONServer", Log::DEBUG, "%s", reqfilename);
212 cRecordings Recordings;
213 Recordings.Load(); // probably have to do this
214 cRecording *recording = Recordings.GetByName(reqfilename);
218 js["Result"] = false;
219 js["Error"] = "Could not find recording to delete";
223 log->log("JSONServer", Log::DEBUG, "Deleting recording: %s", recording->Name());
224 cRecordControl *rc = cRecordControls::GetRecordControl(recording->FileName());
227 js["Result"] = false;
228 js["Error"] = "This recording is still recording.. ho ho";
232 if (recording->Delete())
234 ::Recordings.DelByName(recording->FileName());
239 js["Result"] = false;
240 js["Error"] = "Failed to delete recording";
246 bool jsonserver_recmove(Json::Value& js, const char* postData)
248 Log* log = Log::getInstance();
249 log->log("JSONServer", Log::DEBUG, "recmove");
251 char sFileName[1000]; int mgv1 = mg_get_var(postData, strlen(postData), "filename", sFileName, 1000);
252 char sNewPath[1000]; int mgv2 = mg_get_var(postData, strlen(postData), "newpath", sNewPath, 1000);
254 if ( (mgv1 == -1) || (mgv2 == -1) || !strlen(sFileName) || !strlen(sNewPath) )
256 log->log("JSONServer", Log::ERR, "request mgvs: %i %i", mgv1, mgv2);
257 js["Result"] = false;
258 js["Error"] = "Bad request parameters";
262 cRecordings Recordings;
263 Recordings.Load(); // probably have to do this
264 cRecording* recording = Recordings.GetByName(sFileName);
268 log->log("JSONServer", Log::ERR, "Could not find recording to move");
269 js["Result"] = false;
270 js["Error"] = "Bad filename";
274 cRecordControl *rc = cRecordControls::GetRecordControl(recording->FileName());
277 log->log("JSONServer", Log::ERR, "Could not move recording, it is still recording");
278 js["Result"] = false;
279 js["Error"] = "Cannot move recording in progress";
283 log->log("JSONServer", Log::DEBUG, "moving recording: %s", recording->Name());
284 log->log("JSONServer", Log::DEBUG, "moving recording: %s", recording->FileName());
285 log->log("JSONServer", Log::DEBUG, "to: %s", sNewPath);
287 const char* t = recording->FileName();
289 char* dateDirName = NULL; int k;
290 char* titleDirName = NULL; int j;
291 char* newContainer = NULL;
293 // Find the datedirname
294 for(k = strlen(t) - 1; k >= 0; k--)
298 log->log("JSONServer", Log::DEBUG, "l1: %i", strlen(&t[k+1]) + 1);
299 dateDirName = new char[strlen(&t[k+1]) + 1];
300 strcpy(dateDirName, &t[k+1]);
305 // Find the titledirname
307 for(j = k-1; j >= 0; j--)
311 log->log("JSONServer", Log::DEBUG, "l2: %i", (k - j - 1) + 1);
312 titleDirName = new char[(k - j - 1) + 1];
313 memcpy(titleDirName, &t[j+1], k - j - 1);
314 titleDirName[k - j - 1] = '\0';
319 log->log("JSONServer", Log::DEBUG, "datedirname: %s", dateDirName);
320 log->log("JSONServer", Log::DEBUG, "titledirname: %s", titleDirName);
321 log->log("JSONServer", Log::DEBUG, "viddir: %s", VideoDirectory);
323 ExchangeChars(sNewPath, true);
324 log->log("JSONServer", Log::DEBUG, "EC: %s", sNewPath);
326 newContainer = new char[strlen(VideoDirectory) + strlen(sNewPath) + strlen(titleDirName) + 1];
327 log->log("JSONServer", Log::DEBUG, "l10: %i", strlen(VideoDirectory) + strlen(sNewPath) + strlen(titleDirName) + 1);
328 sprintf(newContainer, "%s%s%s", VideoDirectory, sNewPath, titleDirName);
329 log->log("JSONServer", Log::DEBUG, "%s", newContainer);
332 int statret = stat(newContainer, &dstat);
333 if ((statret == -1) && (errno == ENOENT)) // Dir does not exist
335 log->log("JSONServer", Log::DEBUG, "new dir does not exist");
336 int mkdirret = mkdir(newContainer, 0755);
339 delete[] dateDirName;
340 delete[] titleDirName;
341 delete[] newContainer;
343 log->log("JSONServer", Log::ERR, "Failed to make new dir");
344 js["Result"] = false;
345 js["Error"] = "Failed to create new directory";
349 else if ((statret == 0) && (! (dstat.st_mode && S_IFDIR))) // Something exists but it's not a dir
351 delete[] dateDirName;
352 delete[] titleDirName;
353 delete[] newContainer;
355 log->log("JSONServer", Log::ERR, "Something already exists?");
356 js["Result"] = false;
357 js["Error"] = "Something already exists at the new path";
361 // Ok, the directory container has been made, or it pre-existed.
363 char* newDir = new char[strlen(newContainer) + 1 + strlen(dateDirName) + 1];
364 sprintf(newDir, "%s/%s", newContainer, dateDirName);
366 log->log("JSONServer", Log::DEBUG, "doing rename '%s' '%s'", t, newDir);
367 int renameret = rename(t, newDir);
370 // Success. Test for remove old dir containter
371 char* oldTitleDir = new char[k+1];
372 memcpy(oldTitleDir, t, k);
373 oldTitleDir[k] = '\0';
374 log->log("JSONServer", Log::DEBUG, "len: %i, cp: %i, strlen: %i, oldtitledir: %s", k+1, k, strlen(oldTitleDir), oldTitleDir);
375 rmdir(oldTitleDir); // can't do anything about a fail result at this point.
376 delete[] oldTitleDir;
378 ::Recordings.Update();
383 log->log("JSONServer", Log::ERR, "Rename failed");
384 js["Result"] = false;
385 js["Error"] = "Move failed";
388 delete[] dateDirName;
389 delete[] titleDirName;
390 delete[] newContainer;
396 bool jsonserver_channellist(Json::Value& js)
398 Log* log = Log::getInstance();
399 log->log("JSONServer", Log::DEBUG, "channellist");
401 Json::Value jschannels;
404 for (cChannel *channel = Channels.First(); channel; channel = Channels.Next(channel))
406 if (!channel->GroupSep())
408 log->log("JSONServer", Log::DEBUG, "name: '%s'", channel->Name());
410 if (channel->Vpid()) type = 1;
411 else if (channel->Apid(0)) type = 2;
414 Json::Value oneChannel;
415 oneChannel["Number"] = channel->Number();
416 oneChannel["Type"] = type;
417 oneChannel["Name"] = channel->Name();
418 #if VDRVERSNUM < 10703
419 oneChannel["VType"] = 2;
421 oneChannel["VType"] = channel->Vtype();
423 jschannels.append(oneChannel);
426 js["Channels"] = jschannels;
431 bool jsonserver_channelschedule(Json::Value& js, const char* postData)
433 Log* log = Log::getInstance();
434 log->log("JSONServer", Log::DEBUG, "channelschedule '%s'", postData);
436 char sChannelNumber[15]; int mgv1 = mg_get_var(postData, strlen(postData), "channelnumber", sChannelNumber, 15);
437 char sStartTime[15]; int mgv2 = mg_get_var(postData, strlen(postData), "starttime", sStartTime, 15);
438 char sDuration[15]; int mgv3 = mg_get_var(postData, strlen(postData), "duration", sDuration, 15);
440 if ( (mgv1 == -1) || (mgv2 == -1) || (mgv3 == -1) )
442 log->log("JSONServer", Log::ERR, "request mgvs: %i %i %i", mgv1, mgv2, mgv3);
443 js["Result"] = false;
444 js["Error"] = "Bad request parameters";
448 int channelNumber = atoi(sChannelNumber);
449 int startTime = atoi(sStartTime);
450 int duration = atoi(sDuration);
452 cChannel* channel = NULL;
453 for (channel = Channels.First(); channel; channel = Channels.Next(channel))
455 if (channel->GroupSep()) continue;
456 if (channel->Number() == channelNumber) break;
461 log->log("JSONServer", Log::ERR, "Could not find requested channel: %i", channelNumber);
462 js["Result"] = false;
463 js["Error"] = "Could not find channel";
467 cSchedulesLock MutexLock;
468 const cSchedules *Schedules = cSchedules::Schedules(MutexLock);
471 log->log("JSONServer", Log::ERR, "Could not find requested channel: %i", channelNumber);
472 js["Result"] = false;
473 js["Error"] = "Internal schedules error (1)";
476 const cSchedule *Schedule = Schedules->GetSchedule(channel->GetChannelID());
479 log->log("JSONServer", Log::ERR, "Could not find requested channel: %i", channelNumber);
480 js["Result"] = false;
481 js["Error"] = "Internal schedules error (2)";
485 Json::Value jsevents;
487 for (const cEvent* event = Schedule->Events()->First(); event; event = Schedule->Events()->Next(event))
490 if ((event->StartTime() + event->Duration()) < time(NULL)) continue;
492 if ((event->StartTime() + event->Duration()) <= startTime) continue;
494 if (event->StartTime() >= (startTime + duration)) continue;
496 Json::Value oneEvent;
497 oneEvent["ID"] = event->EventID();
498 oneEvent["Time"] = (Json::UInt)event->StartTime();
499 oneEvent["Duration"] = event->Duration();
500 oneEvent["Title"] = event->Title() ? event->Title() : "";
501 oneEvent["Description"] = event->Description() ? event->Description() : "";
502 jsevents.append(oneEvent);
505 js["Events"] = jsevents;
509 bool jsonserver_timerlist(Json::Value& js)
511 Log* log = Log::getInstance();
512 log->log("JSONServer", Log::DEBUG, "timerlist");
514 Json::Value jstimers;
517 int numTimers = Timers.Count();
519 for (int i = 0; i < numTimers; i++)
521 timer = Timers.Get(i);
522 Json::Value oneTimer;
523 oneTimer["Active"] = timer->HasFlags(tfActive);
524 oneTimer["Recording"] = timer->Recording();
525 oneTimer["Pending"] = timer->Pending();
526 oneTimer["Priority"] = timer->Priority();
527 oneTimer["Lifetime"] = timer->Lifetime();
528 oneTimer["ChannelNumber"] = timer->Channel()->Number();
529 oneTimer["StartTime"] = (int)timer->StartTime();
530 oneTimer["StopTime"] = (int)timer->StopTime();
531 oneTimer["Day"] = (int)timer->Day();
532 oneTimer["WeekDays"] = timer->WeekDays();
533 oneTimer["Name"] = timer->File();
534 jstimers.append(oneTimer);
537 js["Timers"] = jstimers;
541 bool jsonserver_timerdel(Json::Value& js, const char* postData)
543 Log* log = Log::getInstance();
544 log->log("JSONServer", Log::DEBUG, "timerdel");
546 char sdelChannel[15]; int mgv1 = mg_get_var(postData, strlen(postData), "delchannel", sdelChannel, 15);
547 char sdelWeekdays[15]; int mgv2 = mg_get_var(postData, strlen(postData), "delweekdays", sdelWeekdays, 15);
548 char sdelDay[15]; int mgv3 = mg_get_var(postData, strlen(postData), "delday", sdelDay, 15);
549 char sdelStart[15]; int mgv4 = mg_get_var(postData, strlen(postData), "delstart", sdelStart, 15);
550 char sdelStop[15]; int mgv5 = mg_get_var(postData, strlen(postData), "delstop", sdelStop, 15);
552 if ( (mgv1 == -1) || (mgv2 == -1) || (mgv3 == -1) || (mgv4 == -1) || (mgv5 == -1) )
554 log->log("JSONServer", Log::ERR, "request mgvs: %i %i %i %i %i", mgv1, mgv2, mgv3, mgv4, mgv5);
555 js["Result"] = false;
556 js["Error"] = "Bad request parameters";
560 int delChannel = atoi(sdelChannel);
561 int delWeekdays = atoi(sdelWeekdays);
562 int delDay = atoi(sdelDay);
563 int delStart = atoi(sdelStart);
564 int delStop = atoi(sdelStop);
567 for (ti = Timers.First(); ti; ti = Timers.Next(ti))
569 if ( (ti->Channel()->Number() == delChannel)
570 && ((ti->WeekDays() && (ti->WeekDays() == delWeekdays)) || (!ti->WeekDays() && (ti->Day() == delDay)))
571 && (ti->StartTime() == delStart)
572 && (ti->StopTime() == delStop) )
578 log->log("JSONServer", Log::ERR, "Could not find timer");
579 js["Result"] = false;
580 js["Error"] = "Could not find timer";
584 if (Timers.BeingEdited())
586 log->log("JSONServer", Log::ERR, "Unable to delete timer - timers being edited at VDR");
587 js["Result"] = false;
588 js["Error"] = "Timers being edited at VDR";
594 log->log("JSONServer", Log::ERR, "Unable to delete timer - timer is running");
595 js["Result"] = false;
596 js["Error"] = "Timer is running";
601 Timers.SetModified();
607 bool jsonserver_timerset(Json::Value& js, const char* postData)
609 Log* log = Log::getInstance();
610 log->log("JSONServer", Log::DEBUG, "timerset");
612 char sTimerString[1024]; int mgv1 = mg_get_var(postData, strlen(postData), "timerstring", sTimerString, 1024);
616 log->log("JSONServer", Log::ERR, "Could not get timerstring");
617 js["Result"] = false;
618 js["Error"] = "Bad request parameters";
622 log->log("JSONServer", Log::DEBUG, "'%s'", sTimerString);
623 cTimer *timer = new cTimer;
624 if (!timer->Parse(sTimerString))
627 js["Result"] = false;
628 js["Error"] = "Failed to parse timer request details";
632 cTimer *t = Timers.GetTimer(timer);
636 js["Result"] = false;
637 js["Error"] = "Timer already exists";
642 Timers.SetModified();