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");
63 postData[contentLengthI] = '\0';
70 if (!strcmp(wvrequest, "reclist")) success = jsonserver_reclist(js);
71 else if (!strcmp(wvrequest, "recinfo")) success = jsonserver_recinfo(js, postData);
72 else if (!strcmp(wvrequest, "recdel")) success = jsonserver_recdel(js, postData);
73 else if (!strcmp(wvrequest, "recmove")) success = jsonserver_recmove(js, postData);
74 else if (!strcmp(wvrequest, "channellist")) success = jsonserver_channellist(js);
75 else if (!strcmp(wvrequest, "channelschedule")) success = jsonserver_channelschedule(js, postData);
76 else if (!strcmp(wvrequest, "timerlist")) success = jsonserver_timerlist(js);
77 else if (!strcmp(wvrequest, "timerdel")) success = jsonserver_timerdel(js, postData);
78 else if (!strcmp(wvrequest, "timerset")) success = jsonserver_timerset(js, postData);
80 if (!success) return 0; // the specific handler failed badly
82 // Now js will be filled
84 Json::StyledWriter sw;
85 std::string jsonout = sw.write(js);
86 mg_printf(conn, "%s", "HTTP/1.0 200 OK\r\n");
87 mg_printf(conn, "%s", "Content-Type: text/plain\r\n\r\n");
88 mg_write(conn, jsonout.c_str(), jsonout.length());
93 else if (event == MG_EVENT_LOG)
95 if (request_info->status_code == 400) // bad request
97 log->log("Mongoose", Log::DEBUG, "400 BAD REQUEST:");
98 log->log("Mongoose", Log::DEBUG, request_info->request_method);
99 log->log("Mongoose", Log::DEBUG, request_info->uri);
100 log->log("Mongoose", Log::DEBUG, request_info->http_version);
101 log->log("Mongoose", Log::DEBUG, request_info->query_string);
102 log->log("Mongoose", Log::DEBUG, request_info->log_message);
103 for (int i = 0; i < request_info->num_headers; i++)
105 log->log("Mongoose", Log::DEBUG, "%s: %s", request_info->http_headers[i].name, request_info->http_headers[i].value);
110 log->log("Mongoose", Log::DEBUG, request_info->log_message);
111 log->log("Mongoose", Log::DEBUG, request_info->uri);
116 // other events not handled:
117 // MG_HTTP_ERROR, MG_INIT_SSL
118 // Let mongoose do something with those
126 bool jsonserver_reclist(Json::Value& js)
128 Log* log = Log::getInstance();
129 log->log("JSONServer", Log::DEBUG, "reclist");
132 int Percent = VideoDiskSpace(&FreeMB);
133 int Total = (FreeMB / (100 - Percent)) * 100;
135 js["MBFree"] = FreeMB;
136 js["Percent"] = Percent;
139 Json::Value jsrecordings;
140 cRecordings Recordings;
142 for (cRecording *recording = Recordings.First(); recording; recording = Recordings.Next(recording))
145 oneRec["StartTime"] = (Json::UInt)recording->Start();
146 oneRec["Length"] = (Json::UInt)recording->LengthInSeconds();
147 oneRec["IsNew"] = recording->IsNew();
148 oneRec["Name"] = recording->Name();
149 oneRec["Filename"] = recording->FileName();
150 jsrecordings.append(oneRec);
152 js["Recordings"] = jsrecordings;
157 bool jsonserver_recinfo(Json::Value& js, const char* postData)
159 Log* log = Log::getInstance();
160 log->log("JSONServer", Log::DEBUG, "recinfo");
162 char reqfilename[1000];
163 int mgv1 = mg_get_var(postData, strlen(postData), "filename", reqfilename, 1000);
166 log->log("JSONServer", Log::ERR, "Could not decode filename");
167 js["Result"] = false;
168 js["Error"] = "Could not decode filename";
172 log->log("JSONServer", Log::DEBUG, "%s", reqfilename);
174 cRecordings Recordings;
175 Recordings.Load(); // probably have to do this
176 cRecording *recording = Recordings.GetByName(reqfilename);
180 log->log("JSONServer", Log::ERR, "recinfo found no recording");
181 js["Result"] = false;
185 js["IsNew"] = recording->IsNew();
186 js["LengthInSeconds"] = recording->LengthInSeconds();
187 js["FileSizeMB"] = recording->FileSizeMB();
188 js["Name"] = recording->Name() ? recording->Name() : Json::Value::null;
189 js["Priority"] = recording->Priority();
190 js["LifeTime"] = recording->Lifetime();
191 js["Start"] = (Json::UInt)recording->Start();
193 js["ResumePoint"] = 0;
194 cResumeFile ResumeFile(recording->FileName(), recording->IsPesRecording());
195 if (ResumeFile.Read() >= 0) js["ResumePoint"] = ResumeFile.Read();
197 js["CurrentlyRecordingStart"] = 0;
198 js["CurrentlyRecordingStop"] = 0;
199 cRecordControl *rc = cRecordControls::GetRecordControl(recording->FileName());
202 js["CurrentlyRecordingStart"] = (Json::UInt)rc->Timer()->StartTime();
203 js["CurrentlyRecordingStop"] = (Json::UInt)rc->Timer()->StopTime();
206 const cRecordingInfo *info = recording->Info();
209 js["ChannelName"] = info->ChannelName() ? info->ChannelName() : Json::Value::null;
210 js["Title"] = info->Title() ? info->Title() : Json::Value::null;
211 js["ShortText"] = info->ShortText() ? info->ShortText() : Json::Value::null;
212 js["Description"] = info->Description() ? info->Description() : Json::Value::null;
214 const cComponents* components = info->Components();
217 js["Components"] = Json::Value::null;
221 Json::Value jscomponents;
223 tComponent* component;
224 for (int i = 0; i < components->NumComponents(); i++)
226 component = components->Component(i);
228 Json::Value oneComponent;
229 oneComponent["Stream"] = component->stream;
230 oneComponent["Type"] = component->type;
231 oneComponent["Language"] = component->language ? component->language : Json::Value::null;
232 oneComponent["Description"] = component->description ? component->description : Json::Value::null;
233 jscomponents.append(oneComponent);
236 js["Components"] = jscomponents;
244 bool jsonserver_recdel(Json::Value& js, const char* postData)
246 Log* log = Log::getInstance();
247 log->log("JSONServer", Log::DEBUG, "recdel");
249 char reqfilename[1000];
250 int mgv1 = mg_get_var(postData, strlen(postData), "filename", reqfilename, 1000);
253 log->log("JSONServer", Log::ERR, "Could not decode filename");
254 js["Result"] = false;
255 js["Error"] = "Could not decode filename";
259 log->log("JSONServer", Log::DEBUG, "%s", reqfilename);
261 cRecordings Recordings;
262 Recordings.Load(); // probably have to do this
263 cRecording *recording = Recordings.GetByName(reqfilename);
267 js["Result"] = false;
268 js["Error"] = "Could not find recording to delete";
272 log->log("JSONServer", Log::DEBUG, "Deleting recording: %s", recording->Name());
273 cRecordControl *rc = cRecordControls::GetRecordControl(recording->FileName());
276 js["Result"] = false;
277 js["Error"] = "This recording is still recording.. ho ho";
281 if (recording->Delete())
283 ::Recordings.DelByName(recording->FileName());
288 js["Result"] = false;
289 js["Error"] = "Failed to delete recording";
295 bool jsonserver_recmove(Json::Value& js, const char* postData)
297 Log* log = Log::getInstance();
298 log->log("JSONServer", Log::DEBUG, "recmove");
300 char sFileName[1000]; int mgv1 = mg_get_var(postData, strlen(postData), "filename", sFileName, 1000);
301 char sNewPath[1000]; int mgv2 = mg_get_var(postData, strlen(postData), "newpath", sNewPath, 1000);
303 if ( (mgv1 == -1) || (mgv2 == -1) || !strlen(sFileName) || !strlen(sNewPath) )
305 log->log("JSONServer", Log::ERR, "request mgvs: %i %i", mgv1, mgv2);
306 js["Result"] = false;
307 js["Error"] = "Bad request parameters";
311 cRecordings Recordings;
312 Recordings.Load(); // probably have to do this
313 cRecording* recording = Recordings.GetByName(sFileName);
317 log->log("JSONServer", Log::ERR, "Could not find recording to move");
318 js["Result"] = false;
319 js["Error"] = "Bad filename";
323 cRecordControl *rc = cRecordControls::GetRecordControl(recording->FileName());
326 log->log("JSONServer", Log::ERR, "Could not move recording, it is still recording");
327 js["Result"] = false;
328 js["Error"] = "Cannot move recording in progress";
332 log->log("JSONServer", Log::DEBUG, "moving recording: %s", recording->Name());
333 log->log("JSONServer", Log::DEBUG, "moving recording: %s", recording->FileName());
334 log->log("JSONServer", Log::DEBUG, "to: %s", sNewPath);
336 const char* t = recording->FileName();
338 char* dateDirName = NULL; int k;
339 char* titleDirName = NULL; int j;
340 char* newContainer = NULL;
342 // Find the datedirname
343 for(k = strlen(t) - 1; k >= 0; k--)
347 log->log("JSONServer", Log::DEBUG, "l1: %i", strlen(&t[k+1]) + 1);
348 dateDirName = new char[strlen(&t[k+1]) + 1];
349 strcpy(dateDirName, &t[k+1]);
354 // Find the titledirname
356 for(j = k-1; j >= 0; j--)
360 log->log("JSONServer", Log::DEBUG, "l2: %i", (k - j - 1) + 1);
361 titleDirName = new char[(k - j - 1) + 1];
362 memcpy(titleDirName, &t[j+1], k - j - 1);
363 titleDirName[k - j - 1] = '\0';
368 log->log("JSONServer", Log::DEBUG, "datedirname: %s", dateDirName);
369 log->log("JSONServer", Log::DEBUG, "titledirname: %s", titleDirName);
370 log->log("JSONServer", Log::DEBUG, "viddir: %s", VideoDirectory);
372 ExchangeChars(sNewPath, true);
373 log->log("JSONServer", Log::DEBUG, "EC: %s", sNewPath);
375 newContainer = new char[strlen(VideoDirectory) + strlen(sNewPath) + strlen(titleDirName) + 1];
376 log->log("JSONServer", Log::DEBUG, "l10: %i", strlen(VideoDirectory) + strlen(sNewPath) + strlen(titleDirName) + 1);
377 sprintf(newContainer, "%s%s%s", VideoDirectory, sNewPath, titleDirName);
378 log->log("JSONServer", Log::DEBUG, "%s", newContainer);
381 int statret = stat(newContainer, &dstat);
382 if ((statret == -1) && (errno == ENOENT)) // Dir does not exist
384 log->log("JSONServer", Log::DEBUG, "new dir does not exist");
385 int mkdirret = mkdir(newContainer, 0755);
388 delete[] dateDirName;
389 delete[] titleDirName;
390 delete[] newContainer;
392 log->log("JSONServer", Log::ERR, "Failed to make new dir");
393 js["Result"] = false;
394 js["Error"] = "Failed to create new directory";
398 else if ((statret == 0) && (! (dstat.st_mode && S_IFDIR))) // Something exists but it's not a dir
400 delete[] dateDirName;
401 delete[] titleDirName;
402 delete[] newContainer;
404 log->log("JSONServer", Log::ERR, "Something already exists?");
405 js["Result"] = false;
406 js["Error"] = "Something already exists at the new path";
410 // Ok, the directory container has been made, or it pre-existed.
412 char* newDir = new char[strlen(newContainer) + 1 + strlen(dateDirName) + 1];
413 sprintf(newDir, "%s/%s", newContainer, dateDirName);
415 log->log("JSONServer", Log::DEBUG, "doing rename '%s' '%s'", t, newDir);
416 int renameret = rename(t, newDir);
419 // Success. Test for remove old dir containter
420 char* oldTitleDir = new char[k+1];
421 memcpy(oldTitleDir, t, k);
422 oldTitleDir[k] = '\0';
423 log->log("JSONServer", Log::DEBUG, "len: %i, cp: %i, strlen: %i, oldtitledir: %s", k+1, k, strlen(oldTitleDir), oldTitleDir);
424 rmdir(oldTitleDir); // can't do anything about a fail result at this point.
425 delete[] oldTitleDir;
427 ::Recordings.Update();
429 js["NewRecordingFileName"] = newDir;
433 log->log("JSONServer", Log::ERR, "Rename failed");
434 js["Result"] = false;
435 js["Error"] = "Move failed";
438 delete[] dateDirName;
439 delete[] titleDirName;
440 delete[] newContainer;
446 bool jsonserver_channellist(Json::Value& js)
448 Log* log = Log::getInstance();
449 log->log("JSONServer", Log::DEBUG, "channellist");
451 Json::Value jschannels;
454 for (cChannel *channel = Channels.First(); channel; channel = Channels.Next(channel))
456 if (!channel->GroupSep())
458 log->log("JSONServer", Log::DEBUG, "name: '%s'", channel->Name());
460 if (channel->Vpid()) type = 1;
461 else if (channel->Apid(0)) type = 2;
464 Json::Value oneChannel;
465 oneChannel["Number"] = channel->Number();
466 oneChannel["Type"] = type;
467 oneChannel["Name"] = channel->Name();
468 #if VDRVERSNUM < 10703
469 oneChannel["VType"] = 2;
471 oneChannel["VType"] = channel->Vtype();
473 jschannels.append(oneChannel);
476 js["Channels"] = jschannels;
481 bool jsonserver_channelschedule(Json::Value& js, const char* postData)
483 Log* log = Log::getInstance();
484 log->log("JSONServer", Log::DEBUG, "channelschedule '%s'", postData);
486 char sChannelNumber[15]; int mgv1 = mg_get_var(postData, strlen(postData), "channelnumber", sChannelNumber, 15);
487 char sStartTime[15]; int mgv2 = mg_get_var(postData, strlen(postData), "starttime", sStartTime, 15);
488 char sDuration[15]; int mgv3 = mg_get_var(postData, strlen(postData), "duration", sDuration, 15);
490 if ( (mgv1 == -1) || (mgv2 == -1) || (mgv3 == -1) )
492 log->log("JSONServer", Log::ERR, "request mgvs: %i %i %i", mgv1, mgv2, mgv3);
493 js["Result"] = false;
494 js["Error"] = "Bad request parameters";
498 int channelNumber = atoi(sChannelNumber);
499 int startTime = atoi(sStartTime);
500 int duration = atoi(sDuration);
502 cChannel* channel = NULL;
503 for (channel = Channels.First(); channel; channel = Channels.Next(channel))
505 if (channel->GroupSep()) continue;
506 if (channel->Number() == channelNumber) break;
511 log->log("JSONServer", Log::ERR, "Could not find requested channel: %i", channelNumber);
512 js["Result"] = false;
513 js["Error"] = "Could not find channel";
517 cSchedulesLock MutexLock;
518 const cSchedules *Schedules = cSchedules::Schedules(MutexLock);
521 log->log("JSONServer", Log::ERR, "Could not find requested channel: %i", channelNumber);
522 js["Result"] = false;
523 js["Error"] = "Internal schedules error (1)";
526 const cSchedule *Schedule = Schedules->GetSchedule(channel->GetChannelID());
529 log->log("JSONServer", Log::ERR, "Could not find requested channel: %i", channelNumber);
530 js["Result"] = false;
531 js["Error"] = "Internal schedules error (2)";
535 Json::Value jsevents;
537 for (const cEvent* event = Schedule->Events()->First(); event; event = Schedule->Events()->Next(event))
540 if ((event->StartTime() + event->Duration()) < time(NULL)) continue;
542 if ((event->StartTime() + event->Duration()) <= startTime) continue;
544 if (event->StartTime() >= (startTime + duration)) continue;
546 Json::Value oneEvent;
547 oneEvent["ID"] = event->EventID();
548 oneEvent["Time"] = (Json::UInt)event->StartTime();
549 oneEvent["Duration"] = event->Duration();
550 oneEvent["Title"] = event->Title() ? event->Title() : "";
551 oneEvent["Description"] = event->Description() ? event->Description() : "";
552 jsevents.append(oneEvent);
555 js["Events"] = jsevents;
559 bool jsonserver_timerlist(Json::Value& js)
561 Log* log = Log::getInstance();
562 log->log("JSONServer", Log::DEBUG, "timerlist");
564 Json::Value jstimers;
567 int numTimers = Timers.Count();
569 for (int i = 0; i < numTimers; i++)
571 timer = Timers.Get(i);
572 Json::Value oneTimer;
573 oneTimer["Active"] = timer->HasFlags(tfActive);
574 oneTimer["Recording"] = timer->Recording();
575 oneTimer["Pending"] = timer->Pending();
576 oneTimer["Priority"] = timer->Priority();
577 oneTimer["Lifetime"] = timer->Lifetime();
578 oneTimer["ChannelNumber"] = timer->Channel()->Number();
579 oneTimer["StartTime"] = (int)timer->StartTime();
580 oneTimer["StopTime"] = (int)timer->StopTime();
581 oneTimer["Day"] = (int)timer->Day();
582 oneTimer["WeekDays"] = timer->WeekDays();
583 oneTimer["Name"] = timer->File();
584 jstimers.append(oneTimer);
587 js["Timers"] = jstimers;
591 bool jsonserver_timerdel(Json::Value& js, const char* postData)
593 Log* log = Log::getInstance();
594 log->log("JSONServer", Log::DEBUG, "timerdel");
596 char sdelChannel[15]; int mgv1 = mg_get_var(postData, strlen(postData), "delchannel", sdelChannel, 15);
597 char sdelWeekdays[15]; int mgv2 = mg_get_var(postData, strlen(postData), "delweekdays", sdelWeekdays, 15);
598 char sdelDay[15]; int mgv3 = mg_get_var(postData, strlen(postData), "delday", sdelDay, 15);
599 char sdelStart[15]; int mgv4 = mg_get_var(postData, strlen(postData), "delstart", sdelStart, 15);
600 char sdelStop[15]; int mgv5 = mg_get_var(postData, strlen(postData), "delstop", sdelStop, 15);
602 if ( (mgv1 == -1) || (mgv2 == -1) || (mgv3 == -1) || (mgv4 == -1) || (mgv5 == -1) )
604 log->log("JSONServer", Log::ERR, "request mgvs: %i %i %i %i %i", mgv1, mgv2, mgv3, mgv4, mgv5);
605 js["Result"] = false;
606 js["Error"] = "Bad request parameters";
610 int delChannel = atoi(sdelChannel);
611 int delWeekdays = atoi(sdelWeekdays);
612 int delDay = atoi(sdelDay);
613 int delStart = atoi(sdelStart);
614 int delStop = atoi(sdelStop);
617 for (ti = Timers.First(); ti; ti = Timers.Next(ti))
619 if ( (ti->Channel()->Number() == delChannel)
620 && ((ti->WeekDays() && (ti->WeekDays() == delWeekdays)) || (!ti->WeekDays() && (ti->Day() == delDay)))
621 && (ti->StartTime() == delStart)
622 && (ti->StopTime() == delStop) )
628 log->log("JSONServer", Log::ERR, "Could not find timer");
629 js["Result"] = false;
630 js["Error"] = "Could not find timer";
634 if (Timers.BeingEdited())
636 log->log("JSONServer", Log::ERR, "Unable to delete timer - timers being edited at VDR");
637 js["Result"] = false;
638 js["Error"] = "Timers being edited at VDR";
644 log->log("JSONServer", Log::ERR, "Unable to delete timer - timer is running");
645 js["Result"] = false;
646 js["Error"] = "Timer is running";
651 Timers.SetModified();
657 bool jsonserver_timerset(Json::Value& js, const char* postData)
659 Log* log = Log::getInstance();
660 log->log("JSONServer", Log::DEBUG, "timerset");
662 char sTimerString[1024]; int mgv1 = mg_get_var(postData, strlen(postData), "timerstring", sTimerString, 1024);
666 log->log("JSONServer", Log::ERR, "Could not get timerstring");
667 js["Result"] = false;
668 js["Error"] = "Bad request parameters";
672 log->log("JSONServer", Log::DEBUG, "'%s'", sTimerString);
673 cTimer *timer = new cTimer;
674 if (!timer->Parse(sTimerString))
677 js["Result"] = false;
678 js["Error"] = "Failed to parse timer request details";
682 cTimer *t = Timers.GetTimer(timer);
686 js["Result"] = false;
687 js["Error"] = "Timer already exists";
692 Timers.SetModified();