]> git.vomp.tv Git - jsonserver.git/blob - vdrclient.c
Fix httpd not accepting empty last post variable
[jsonserver.git] / vdrclient.c
1 #include "vdrclient.h"
2
3 /*
4 trace
5 debug
6 info
7 warn
8 error
9 critical
10 */
11
12 #include <string.h>
13 #include <stdlib.h>
14 #include <sys/time.h>
15 #include <string>
16
17 #include <vdr/plugin.h>
18 #include <vdr/videodir.h>
19 #include <vdr/recording.h>
20 #include <vdr/menu.h>
21 #include <vdr/timers.h>
22 #include <vdr/channels.h>
23
24 /* Locking information from VDR:
25 + If a plugin needs to access several of the global lists in parallel, locking must
26   always be done in the sequence Timers, Channels, Recordings, Schedules.
27 */
28
29 VDRClient::VDRClient(const std::string& _configDir)
30 : configDir(_configDir)
31 {
32   logger = spd::get("jsonserver_spdlog");
33 }
34
35 VDRClient::~VDRClient()
36 {
37   logger->debug("VDRClient destructor");
38 }
39
40 bool VDRClient::process(std::string& request, PFMap& postFields, std::string& returnString)
41 {
42   Json::Value returnJSON;
43   bool success = false;
44
45   try
46   {
47     if      (request == "gettime")           success = gettime(postFields, returnJSON);
48     else if (request == "diskstats")         success = diskstats(postFields, returnJSON);
49     else if (request == "channellist")       success = channellist(postFields, returnJSON);
50     else if (request == "reclist")           success = reclist(postFields, returnJSON);
51     else if (request == "timerlist")         success = timerlist(postFields, returnJSON);
52     else if (request == "epgdownload")       success = epgdownload(postFields, returnJSON);
53     else if (request == "tunersstatus")      success = tunersstatus(postFields, returnJSON);
54     else if (request == "epgfilterget")      success = epgfilterget(postFields, returnJSON);
55
56     else if (request == "channelschedule")   success = channelschedule(postFields, returnJSON);
57     else if (request == "getscheduleevent")  success = getscheduleevent(postFields, returnJSON);
58     else if (request == "epgsearch")         success = epgsearch(postFields, returnJSON);
59     else if (request == "epgsearchsame")     success = epgsearchsame(postFields, returnJSON);
60     else if (request == "epgsearchotherhalf")success = epgsearchotherhalf(postFields, returnJSON);
61     else if (request == "timerset")          success = timerset(postFields, returnJSON);
62     else if (request == "recinfo")           success = recinfo(postFields, returnJSON);
63     else if (request == "recstop")           success = recstop(postFields, returnJSON);
64     else if (request == "recdel")            success = recdel(postFields, returnJSON);
65     else if (request == "recrename")         success = recrename(postFields, returnJSON);
66     else if (request == "recmove")           success = recmove(postFields, returnJSON);
67     else if (request == "timersetactive")    success = timersetactive(postFields, returnJSON);
68     else if (request == "timerdel")          success = timerdel(postFields, returnJSON);
69     else if (request == "timerisrecording")  success = timerisrecording(postFields, returnJSON);
70     else if (request == "recresetresume")    success = recresetresume(postFields, returnJSON);
71     else if (request == "timeredit")         success = timeredit(postFields, returnJSON);
72     else if (request == "epgfilteradd")      success = epgfilteradd(postFields, returnJSON);
73     else if (request == "epgfilterdel")      success = epgfilterdel(postFields, returnJSON);
74   }
75   catch (const BadParamException& e)
76   {
77     logger->error("Bad parameter in call, paramName: {}", e.param);
78     returnJSON["Result"] = false;
79     returnJSON["Error"] = "Bad request parameter";
80     returnJSON["Detail"] = e.param;
81     success = true;
82   }
83
84   if (!success) return false;
85
86   Json::StyledWriter sw;
87   returnString = sw.write(returnJSON);
88   logger->debug("Done sw write");
89   return true;
90 }
91
92 bool VDRClient::gettime(PFMap& postFields, Json::Value& js)
93 {
94   logger->debug("get_time");
95
96   struct timeval tv;
97   gettimeofday(&tv, NULL);
98
99   js["Time"] = (Json::UInt64)tv.tv_sec;
100   js["MTime"] = (Json::UInt)(tv.tv_usec/1000);
101   js["Result"] = true;
102   return true;
103 }
104
105 bool VDRClient::diskstats(PFMap& postFields, Json::Value& js)
106 {
107   logger->debug("diskstats");
108
109   int FreeMB;
110   int UsedMB;
111   int Percent = cVideoDirectory::VideoDiskSpace(&FreeMB, &UsedMB);
112
113   js["FreeMiB"] = FreeMB;
114   js["UsedMiB"] = UsedMB;
115   js["Percent"] = Percent;
116   js["Result"] = true;
117   return true;
118 }
119
120 bool VDRClient::channellist(PFMap& postFields, Json::Value& js)
121 {
122   logger->debug("channellist");
123
124   Json::Value jschannels(Json::arrayValue);
125
126   LOCK_CHANNELS_READ;
127
128   for (const cChannel *channel = Channels->First(); channel; channel = Channels->Next(channel))
129   {
130     if (!channel->GroupSep())
131     {
132       Json::Value oneChannel;
133       oneChannel["ID"] = (const char *)channel->GetChannelID().ToString();
134       oneChannel["Number"] = channel->Number();
135       oneChannel["Name"] = channel->Name();
136       jschannels.append(oneChannel);
137     }
138   }
139   js["Channels"] = jschannels;
140
141   return true;
142 }
143
144 bool VDRClient::reclist(PFMap& postFields, Json::Value& js)
145 {
146   logger->debug("reclist");
147
148   Json::Value jsrecordings(Json::arrayValue);
149
150   LOCK_RECORDINGS_READ;
151
152   for (const cRecording *recording = Recordings->First(); recording; recording = Recordings->Next(recording))
153   {
154     Json::Value oneRec;
155     oneRec["StartTime"] = (Json::UInt)recording->Start();
156     oneRec["Length"] = (Json::UInt)recording->LengthInSeconds();
157     oneRec["IsNew"] = recording->IsNew();
158     oneRec["Name"] = recording->Name();
159     oneRec["Filename"] = recording->FileName();
160     oneRec["FileSizeMB"] = recording->FileSizeMB();
161
162     cRecordControl *rc = cRecordControls::GetRecordControl(recording->FileName());
163     if (rc) oneRec["CurrentlyRecording"] = true;
164     else    oneRec["CurrentlyRecording"] = false;
165
166     jsrecordings.append(oneRec);
167   }
168   js["Recordings"] = jsrecordings;
169
170   return true;
171 }
172
173 bool VDRClient::timerlist(PFMap& postFields, Json::Value& js)
174 {
175   logger->debug("timerlist");
176
177   Json::Value jstimers(Json::arrayValue);
178
179   const cTimer *timer;
180
181   LOCK_TIMERS_READ;
182   LOCK_CHANNELS_READ;
183   LOCK_SCHEDULES_READ;
184
185   int numTimers = Timers->Count();
186
187   for (int i = 0; i < numTimers; i++)
188   {
189     timer = Timers->Get(i);
190     Json::Value oneTimer;
191     oneTimer["Active"] = timer->HasFlags(tfActive);
192     oneTimer["Recording"] = timer->Recording();
193     oneTimer["Pending"] = timer->Pending();
194     oneTimer["Priority"] = timer->Priority();
195     oneTimer["Lifetime"] = timer->Lifetime();
196     oneTimer["ChannelNumber"] = timer->Channel()->Number();
197     oneTimer["ChannelID"] = (const char *)timer->Channel()->GetChannelID().ToString();
198     oneTimer["StartTime"] = (int)timer->StartTime();
199     oneTimer["StopTime"] = (int)timer->StopTime();
200     oneTimer["Day"] = (int)timer->Day();
201     oneTimer["WeekDays"] = timer->WeekDays();
202     oneTimer["Name"] = timer->File();
203
204     const cEvent* event = timer->Event();
205     if (event)
206     {
207       oneTimer["EventID"] = event->EventID();
208     }
209     else
210     {
211       int channelNumber = timer->Channel()->Number();
212       int aroundTime = timer->StartTime() + 1;
213       const cEvent* eventAround = getEvent(Channels, Schedules, js, channelNumber, 0, aroundTime);
214       if (eventAround)
215       {
216         oneTimer["EventID"] = eventAround->EventID();
217       }
218       else
219       {
220         oneTimer["EventID"] = 0;
221       }
222     }
223
224     jstimers.append(oneTimer);
225   }
226
227   js["Timers"] = jstimers;
228   js["NumTuners"] = cDevice::NumDevices();
229   js["Result"] = true;
230   return true;
231 }
232
233 bool VDRClient::channelschedule(PFMap& postFields, Json::Value& js) // RETHROWS
234 {
235   logger->debug("channelschedule");
236   int channelNumber = getVarInt(postFields, "channelnumber");
237   int startTime = getVarInt(postFields, "starttime");
238   int duration = getVarInt(postFields, "duration");
239
240   Json::Value jsevents(Json::arrayValue);
241
242   LOCK_CHANNELS_READ;
243
244   const cChannel* channel = NULL;
245   for (channel = Channels->First(); channel; channel = Channels->Next(channel))
246   {
247     if (channel->GroupSep()) continue;
248     if (channel->Number() == channelNumber) break;
249   }
250
251   if (!channel)
252   {
253     logger->error("channelschedule: Could not find requested channel: {}", channelNumber);
254     js["Result"] = false;
255     js["Error"] = "Could not find channel";
256     return true;
257   }
258
259   LOCK_SCHEDULES_READ;
260
261   const cSchedule *Schedule = Schedules->GetSchedule(channel->GetChannelID());
262   if (!Schedule)
263   {
264     logger->error("channelschedule: Could not find requested channel: {}", channelNumber);
265     js["Result"] = false;
266     js["Error"] = "Internal schedules error (2)";
267     return true;
268   }
269
270   for (const cEvent* event = Schedule->Events()->First(); event; event = Schedule->Events()->Next(event))
271   {
272     if ((event->StartTime() + event->Duration()) < time(NULL)) continue; //in the past filter
273     if ((event->StartTime() + event->Duration()) <= startTime) continue; //start time filter
274     if (event->StartTime() >= (startTime + duration)) continue;          //duration filter
275
276     Json::Value oneEvent;
277     oneEvent["ID"] = event->EventID();
278     oneEvent["Time"] = (Json::UInt)event->StartTime();
279     oneEvent["Duration"] = event->Duration();
280     oneEvent["Title"] = event->Title() ? event->Title() : "";
281     oneEvent["ShortText"] = event->ShortText() ? event->ShortText() : "";
282     oneEvent["HasTimer"] = event->HasTimer();
283     jsevents.append(oneEvent);
284   }
285
286   js["Result"] = true;
287   js["Events"] = jsevents;
288   return true;
289 }
290
291 bool VDRClient::getscheduleevent(PFMap& postFields, Json::Value& js) // RETHROWS
292 {
293   logger->debug("getscheduleevent");
294
295   int channelNumber = getVarInt(postFields, "channelnumber");
296   int eventID = getVarInt(postFields, "eventid");
297
298   LOCK_CHANNELS_READ;
299   LOCK_SCHEDULES_READ;
300
301   const cEvent* event = getEvent(Channels, Schedules, js, channelNumber, eventID, 0);
302   if (!event)
303   {
304     js["Result"] = false;
305     return true;
306   }
307
308   Json::Value oneEvent;
309   oneEvent["ID"] = event->EventID();
310   oneEvent["Time"] = (Json::UInt)event->StartTime();
311   oneEvent["Duration"] = event->Duration();
312   oneEvent["Title"] = event->Title() ? event->Title() : "";
313   oneEvent["ShortText"] = event->ShortText() ? event->ShortText() : "";
314   oneEvent["Description"] = event->Description() ? event->Description() : "";
315   oneEvent["HasTimer"] = event->HasTimer();
316   oneEvent["RunningStatus"] = event->RunningStatus();
317
318   js["Result"] = true;
319   js["Event"] = oneEvent;
320   return true;
321 }
322
323 bool VDRClient::epgdownload(PFMap& postFields, Json::Value& js)
324 {
325   logger->debug("epgdownload");
326   Json::Value jsevents(Json::arrayValue);
327
328   LOCK_CHANNELS_READ;
329   LOCK_SCHEDULES_READ;
330
331   for (const cChannel* channel = Channels->First(); channel; channel = Channels->Next(channel))
332   {
333     if (channel->GroupSep()) continue;
334
335     const cSchedule *Schedule = Schedules->GetSchedule(channel->GetChannelID());
336     if (!Schedule) continue;
337
338     for (const cEvent* event = Schedule->Events()->First(); event; event = Schedule->Events()->Next(event))
339     {
340       Json::Value oneEvent;
341       oneEvent["ChannelNumber"] = channel->Number();
342       oneEvent["ChannelID"] = (const char*)event->ChannelID().ToString();
343       oneEvent["ID"] = event->EventID();
344       oneEvent["Time"] = (Json::UInt)event->StartTime();
345       oneEvent["Duration"] = event->Duration();
346       oneEvent["Title"] = event->Title() ? event->Title() : "";
347       oneEvent["ShortText"] = event->ShortText() ? event->ShortText() : "";
348       oneEvent["HasTimer"] = event->HasTimer();
349       oneEvent["Description"] = event->Description() ? event->Description() : "";
350       jsevents.append(oneEvent);
351     }
352   }
353
354   js["Result"] = true;
355   js["Events"] = jsevents;
356   return true;
357 }
358
359 bool VDRClient::epgsearch(PFMap& postFields, Json::Value& js) // RETHROWS
360 {
361   logger->debug("epgsearch");
362
363   std::string searchfor = getVarString(postFields, "searchfor");
364   logger->debug("epgsearch: search for: {}", searchfor);
365
366   Json::Value jsevents(Json::arrayValue);
367
368   LOCK_CHANNELS_READ;
369   LOCK_SCHEDULES_READ;
370
371   for (const cChannel* channel = Channels->First(); channel; channel = Channels->Next(channel))
372   {
373     if (channel->GroupSep()) continue;
374
375     const cSchedule *Schedule = Schedules->GetSchedule(channel->GetChannelID());
376     if (!Schedule) continue;
377
378     bool foundtitle;
379     bool founddescription;
380     for (const cEvent* event = Schedule->Events()->First(); event; event = Schedule->Events()->Next(event))
381     {
382       foundtitle = false;
383       founddescription = false;
384
385       if (event->Title() && strcasestr(event->Title(), searchfor.c_str())) foundtitle = true;
386
387       if (!foundtitle && event->Description())
388         if (strcasestr(event->Description(), searchfor.c_str())) founddescription = true;
389
390       if (foundtitle || founddescription)
391       {
392         Json::Value oneEvent;
393         oneEvent["ChannelNumber"] = channel->Number();
394         oneEvent["ChannelID"] = (const char*)event->ChannelID().ToString();
395         oneEvent["ID"] = event->EventID();
396         oneEvent["Time"] = (Json::UInt)event->StartTime();
397         oneEvent["Duration"] = event->Duration();
398         oneEvent["Title"] = event->Title() ? event->Title() : "";
399         oneEvent["ShortText"] = event->ShortText() ? event->ShortText() : "";
400         oneEvent["HasTimer"] = event->HasTimer();
401         oneEvent["Description"] = event->Description() ? event->Description() : "";
402         if (founddescription)
403           oneEvent["FoundInDesc"] = true;
404         else
405           oneEvent["FoundInDesc"] = false;
406         jsevents.append(oneEvent);
407       }
408     }
409   }
410
411   js["Result"] = true;
412   js["Events"] = jsevents;
413
414   logger->debug("epgsearch: search for: {} done", searchfor);
415
416   return true;
417 }
418
419 bool VDRClient::epgsearchsame(PFMap& postFields, Json::Value& js) // RETHROWS
420 {
421   logger->debug("epgsearchsame");
422
423   int atTime = getVarInt(postFields, "time");
424   std::string sTitle = getVarString(postFields, "title");
425
426   logger->debug("epgsearchsame: request time: {}, title: {}", atTime, sTitle);
427
428   Json::Value jsevents(Json::arrayValue);
429   const cEvent *event;
430
431   LOCK_SCHEDULES_READ;
432
433   for (const cSchedule *schedule = Schedules->First(); (schedule != NULL); schedule = Schedules->Next(schedule))
434   {
435     event = schedule->GetEventAround(atTime);
436     if (!event) continue; // nothing found on this schedule(channel)
437
438     if (!strcmp(event->Title(), sTitle.c_str()))
439     {
440       Json::Value oneEvent;
441       oneEvent["ChannelID"] = (const char*)event->ChannelID().ToString();
442       oneEvent["ID"] = event->EventID();
443       oneEvent["Time"] = (Json::UInt)event->StartTime();
444       oneEvent["Duration"] = event->Duration();
445       oneEvent["Title"] = event->Title() ? event->Title() : "";
446       oneEvent["ShortText"] = event->ShortText() ? event->ShortText() : "";
447       oneEvent["HasTimer"] = event->HasTimer();
448       //oneEvent["Description"] = event->Description() ? event->Description() : "";
449       jsevents.append(oneEvent);
450     }
451   }
452
453   js["Events"] = jsevents;
454   js["Result"] = true;
455   return true;
456 }
457
458 bool VDRClient::epgsearchotherhalf(PFMap& postFields, Json::Value& js) // RETHROWS
459 {
460   logger->debug("epgsearchotherhalf");
461   int channelNumber = getVarInt(postFields, "channelnumber");
462   int eventID = getVarInt(postFields, "eventid");
463   const cChannel* channel = NULL;
464
465   LOCK_CHANNELS_READ;
466
467   for (channel = Channels->First(); channel; channel = Channels->Next(channel))
468   {
469     if (channel->GroupSep()) continue;
470     if (channel->Number() == channelNumber) break;
471   }
472
473   if (!channel)
474   {
475     logger->error("epgsearchotherhalf: Could not find requested channel: {}", channelNumber);
476     js["Result"] = false;
477     js["Error"] = "Could not find channel";
478     return true;
479   }
480
481   LOCK_SCHEDULES_READ;
482
483   const cSchedule *Schedule = Schedules->GetSchedule(channel->GetChannelID());
484   if (!Schedule)
485   {
486     logger->error("epgsearchotherhalf: Could not find requested channel: {}", channelNumber);
487     js["Result"] = false;
488     js["Error"] = "Internal schedules error (2)";
489     return true;
490   }
491
492   js["OtherEventFound"] = false;
493
494   const cEvent* eventM1 = NULL;
495   const cEvent* eventM2 = NULL;
496   const cEvent* otherEvent = NULL;
497
498   for (const cEvent* event = Schedule->Events()->First(); event; event = Schedule->Events()->Next(event))
499   {
500     if (event->EventID() == (unsigned long)eventID)
501     {
502       if ((eventM2 != NULL) && (!strcmp(eventM2->Title(), event->Title())))
503       {
504         otherEvent = eventM2;
505       }
506       else
507       {
508         const cEvent* eventP1 = Schedule->Events()->Next(event);
509         if (eventP1)
510         {
511           const cEvent* eventP2 = Schedule->Events()->Next(eventP1);
512
513           if (eventP2 && (!strcmp(eventP2->Title(), event->Title())))
514           {
515             otherEvent = eventP2;
516           }
517         }
518       }
519
520       if (otherEvent)
521       {
522         Json::Value oneEvent;
523         oneEvent["ID"] = otherEvent->EventID();
524         oneEvent["ChannelNumber"] = channel->Number();
525         oneEvent["Time"] = (Json::UInt)otherEvent->StartTime();
526         oneEvent["Duration"] = otherEvent->Duration();
527         oneEvent["Title"] = otherEvent->Title() ? otherEvent->Title() : "";
528         oneEvent["HasTimer"] = otherEvent->HasTimer();
529         js["Event"] = oneEvent;
530         js["OtherEventFound"] = true;
531       }
532
533       break;
534     }
535
536     eventM2 = eventM1;
537     eventM1 = event;
538   }
539
540   js["Result"] = true;
541   return true;
542 }
543
544 bool VDRClient::tunersstatus(PFMap& postFields, Json::Value& js)
545 {
546   logger->debug("tunerstatus");
547
548   js["NumDevices"] = cDevice::NumDevices();
549
550   Json::Value jsdevices(Json::arrayValue);
551
552   for (int i = 0; i < cDevice::NumDevices(); i++)
553   {
554     Json::Value oneDevice;
555     cDevice *d = cDevice::GetDevice(i);
556     oneDevice["Number"] = d->DeviceNumber();
557     oneDevice["Type"] = (const char*)d->DeviceType();
558     oneDevice["Name"] = (const char*)d->DeviceName();
559     oneDevice["IsPrimary"] = d->IsPrimaryDevice();
560
561     const cChannel* cchannel = d->GetCurrentlyTunedTransponder();
562     if (cchannel)
563     {
564       oneDevice["Frequency"] = cchannel->Frequency();
565       oneDevice["SignalStrength"] = d->SignalStrength();
566       oneDevice["SignalQuality"] = d->SignalQuality();
567
568     }
569     else
570     {
571       oneDevice["Frequency"] = 0;
572       oneDevice["SignalStrength"] = 0;
573       oneDevice["SignalQuality"] = 0;
574     }
575
576     jsdevices.append(oneDevice);
577   }
578
579   js["Devices"] = jsdevices;
580
581
582   Json::Value jstimers(Json::arrayValue);
583
584   LOCK_TIMERS_READ;
585   LOCK_CHANNELS_READ; // Because this calls timer->Channel() .. necessary?
586
587   int numTimers = Timers->Count();
588   const cTimer* timer;
589   for (int i = 0; i < numTimers; i++)
590   {
591     timer = Timers->Get(i);
592
593     if (timer->Recording())
594     {
595       Json::Value oneTimer;
596       oneTimer["Recording"] = timer->Recording();
597       oneTimer["StartTime"] = (int)timer->StartTime();
598       oneTimer["StopTime"] = (int)timer->StopTime();
599       oneTimer["File"] = timer->File();
600
601       cRecordControl* crc = cRecordControls::GetRecordControl(timer);
602       if (crc)
603       {
604         cDevice* crcd = crc->Device();
605         oneTimer["DeviceNumber"] = crcd->DeviceNumber();
606       }
607       else
608       {
609         oneTimer["DeviceNumber"] = Json::Value::null;
610       }
611
612       const cChannel* channel = timer->Channel();
613       if (channel)
614       {
615         oneTimer["ChannelName"] = channel->Name();
616       }
617       else
618       {
619         oneTimer["ChannelName"] = Json::Value::null;
620       }
621
622       jstimers.append(oneTimer);
623     }
624
625   }
626   js["CurrentRecordings"] = jstimers;
627
628
629   js["Result"] = true;
630   return true;
631 }
632
633 bool VDRClient::timerset(PFMap& postFields, Json::Value& js) // RETHROWS
634 {
635   logger->debug("timerset");
636
637   std::string sTimerString = getVarString(postFields, "timerstring");
638
639   logger->debug("timerset: '{}'", sTimerString);
640   cTimer *timer = new cTimer;
641   if (!timer->Parse(sTimerString.c_str()))
642   {
643     delete timer;
644     js["Result"] = false;
645     js["Error"] = "Failed to parse timer request details";
646     return true;
647   }
648
649   LOCK_TIMERS_WRITE;
650   Timers->SetExplicitModify();
651
652   cTimer *t = Timers->GetTimer(timer);
653   if (t)
654   {
655     delete timer;
656     js["Result"] = false;
657     js["Error"] = "Timer already exists";
658     return true;
659   }
660
661   Timers->Add(timer);
662   Timers->SetModified();
663
664   js["Result"] = true;
665   return true;
666 }
667
668 bool VDRClient::recinfo(PFMap& postFields, Json::Value& js) // RETHROWS
669 {
670   logger->debug("recinfo");
671
672   std::string reqfilename = getVarString(postFields, "filename");
673   logger->debug("recinfo: {}", reqfilename);
674
675   LOCK_RECORDINGS_READ;
676
677   const cRecording *recording = Recordings->GetByName(reqfilename.c_str());
678
679   if (!recording)
680   {
681     logger->error("recinfo: recinfo found no recording");
682     js["Result"] = false;
683     return true;
684   }
685
686   js["IsNew"] = recording->IsNew();
687   js["LengthInSeconds"] = recording->LengthInSeconds();
688   js["FileSizeMB"] = recording->FileSizeMB();
689   js["Name"] = recording->Name() ? recording->Name() : Json::Value::null;
690   js["Priority"] = recording->Priority();
691   js["LifeTime"] = recording->Lifetime();
692   js["Start"] = (Json::UInt)recording->Start();
693
694   js["CurrentlyRecordingStart"] = 0;
695   js["CurrentlyRecordingStop"] = 0;
696   cRecordControl *rc = cRecordControls::GetRecordControl(recording->FileName());
697   if (rc)
698   {
699     js["CurrentlyRecordingStart"] = (Json::UInt)rc->Timer()->StartTime();
700     js["CurrentlyRecordingStop"] = (Json::UInt)rc->Timer()->StopTime();
701   }
702
703   js["ResumePoint"] = 0;
704
705   const cRecordingInfo *info = recording->Info();
706   if (info)
707   {
708     js["ChannelName"] = info->ChannelName() ? info->ChannelName() : Json::Value::null;
709     js["Title"] = info->Title() ? info->Title() : Json::Value::null;
710     js["ShortText"] = info->ShortText() ? info->ShortText() : Json::Value::null;
711     js["Description"] = info->Description() ? info->Description() : Json::Value::null;
712
713     const cComponents* components = info->Components();
714     if (!components)
715     {
716       js["Components"] = Json::Value::null;
717     }
718     else
719     {
720       Json::Value jscomponents;
721
722       tComponent* component;
723       for (int i = 0; i < components->NumComponents(); i++)
724       {
725         component = components->Component(i);
726
727         Json::Value oneComponent;
728         oneComponent["Stream"] = component->stream;
729         oneComponent["Type"] = component->type;
730         oneComponent["Language"] = component->language ? component->language : Json::Value::null;
731         oneComponent["Description"] = component->description ? component->description : Json::Value::null;
732         jscomponents.append(oneComponent);
733       }
734
735       js["Components"] = jscomponents;
736     }
737
738     cResumeFile ResumeFile(recording->FileName(), recording->IsPesRecording());
739     if (ResumeFile.Read() >= 0) js["ResumePoint"] = floor(ResumeFile.Read() / info->FramesPerSecond());
740   }
741
742   js["Result"] = true;
743   return true;
744 }
745
746 bool VDRClient::recstop(PFMap& postFields, Json::Value& js) // RETHROWS
747 {
748   logger->debug("recstop");
749
750   std::string reqfilename = getVarString(postFields, "filename");
751   logger->debug("recstop: {}", reqfilename);
752
753   LOCK_TIMERS_WRITE;
754   LOCK_RECORDINGS_WRITE; // May not need write here, but to be safe..
755
756   cRecording *recording = Recordings->GetByName(reqfilename.c_str());
757
758   if (!recording)
759   {
760     logger->error("recstop: recstop found no recording");
761     js["Result"] = false;
762     return true;
763   }
764
765   cRecordControl *rc = cRecordControls::GetRecordControl(recording->FileName());
766   if (!rc)
767   {
768     logger->error("recstop: not currently recording");
769     js["Result"] = false;
770     return true;
771   }
772
773   cTimer* timer = rc->Timer();
774   if (!timer)
775   {
776     logger->error("recstop: timer not found");
777     js["Result"] = false;
778     return true;
779   }
780
781   timer->ClrFlags(tfActive);
782
783   js["Result"] = true;
784   return true;
785 }
786
787
788 bool VDRClient::recdel(PFMap& postFields, Json::Value& js) // RETHROWS
789 {
790   logger->debug("recdel");
791
792   std::string reqfilename = getVarString(postFields, "filename");
793   logger->debug("recdel: {}", reqfilename);
794
795   LOCK_RECORDINGS_WRITE;
796
797   cRecording *recording = Recordings->GetByName(reqfilename.c_str());
798
799   if (!recording)
800   {
801     js["Result"] = false;
802     js["Error"] = "Could not find recording to delete";
803     return true;
804   }
805
806   logger->debug("recdel: Deleting recording: {}", recording->Name());
807   cRecordControl *rc = cRecordControls::GetRecordControl(recording->FileName());
808   if (rc)
809   {
810     js["Result"] = false;
811     js["Error"] = "This recording is still recording.. ho ho";
812     return true;
813   }
814
815   if (recording->Delete())
816   {
817     Recordings->DelByName(recording->FileName());
818     js["Result"] = true;
819   }
820   else
821   {
822     js["Result"] = false;
823     js["Error"] = "Failed to delete recording";
824   }
825
826   return true;
827 }
828
829 bool VDRClient::recrename(PFMap& postFields, Json::Value& js) // RETHROWS
830 {
831   logger->debug("recrename");
832
833   std::string fileNameToAffect = getVarString(postFields, "filename");
834   std::string requestedNewName = getVarString(postFields, "newname");
835
836   try
837   {
838     LOCK_RECORDINGS_WRITE;
839     cRecording* recordingObj = Recordings->GetByName(fileNameToAffect.c_str());
840     if (!recordingObj) throw 2;
841
842     std::string newName(recordingObj->Folder());
843     logger->debug("newname after folder copy: #{}#");
844     if (newName.length()) newName += FOLDERDELIMCHAR;
845     newName += requestedNewName;
846
847     logger->debug("RM2 NEWLOC:  #{}#", newName);
848
849     bool moveSuccess = recordingObj->ChangeName(newName.c_str());
850
851     js["Result"] = moveSuccess;
852     js["NewRecordingFileName"] = recordingObj->FileName();
853   }
854   catch (BadParamException& e)
855   {
856     js["Result"] = false;
857     logger->error("recmove: Bad parameters");
858     js["Error"] = "Bad request parameters";
859   }
860   catch (int e)
861   {
862     js["Result"] = false;
863     if (e == 2)
864     {
865       logger->error("recmove: Could not find recording to move");
866       js["Error"] = "Bad filename";
867     }
868   }
869
870   return true;
871 }
872
873 bool VDRClient::recmove(PFMap& postFields, Json::Value& js) // RETHROWS
874 {
875   logger->debug("recmove");
876
877   std::string fileNameToAffect = getVarString(postFields, "filename");
878   std::string requestedNewDirName = getVarString(postFields, "newpath", true /* empty new path is ok */);
879
880   try
881   {
882     LOCK_RECORDINGS_WRITE;
883     cRecording* recordingObj = Recordings->GetByName(fileNameToAffect.c_str());
884     if (!recordingObj) throw 2;
885
886     std::string newName;
887     if (requestedNewDirName.length()) newName = requestedNewDirName + FOLDERDELIMCHAR;
888     newName += recordingObj->BaseName();
889
890     logger->debug("RM2 NEWLOC:  #{}#", newName);
891
892     bool moveSuccess = recordingObj->ChangeName(newName.c_str());
893
894     js["Result"] = moveSuccess;
895     js["NewRecordingFileName"] = recordingObj->FileName();
896   }
897   catch (BadParamException& e)
898   {
899     js["Result"] = false;
900     logger->error("recmove: Bad parameters");
901     js["Error"] = "Bad request parameters";
902   }
903   catch (int e)
904   {
905     js["Result"] = false;
906     if (e == 2)
907     {
908       logger->error("recmove: Could not find recording to move");
909       js["Error"] = "Bad filename";
910     }
911   }
912
913   return true;
914 }
915
916 bool VDRClient::timersetactive(PFMap& postFields, Json::Value& js) // RETHROWS
917 {
918   logger->debug("timersetactive");
919
920   std::string rChannelID = getVarString(postFields, "ChannelID");
921   std::string rName = getVarString(postFields, "Name");
922   std::string rStartTime = getVarString(postFields, "StartTime");
923   std::string rStopTime = getVarString(postFields, "StopTime");
924   std::string rWeekDays = getVarString(postFields, "WeekDays");
925   std::string tNewActive = getVarString(postFields, "SetActive");
926
927   logger->debug("timersetactive: {} {}:{}:{}:{}:{}", tNewActive, rChannelID, rName, rStartTime, rStopTime, rWeekDays);
928
929   if ((tNewActive != "true") && (tNewActive != "false"))
930   {
931     js["Result"] = false;
932     js["Error"] = "Bad request parameters";
933     return true;
934   }
935
936
937   LOCK_TIMERS_WRITE;
938   Timers->SetExplicitModify();
939
940   cTimer* timer = findTimer(Timers, rChannelID.c_str(), rName.c_str(), rStartTime.c_str(), rStopTime.c_str(), rWeekDays.c_str());
941   if (timer)
942   {
943     if (tNewActive == "true") timer->SetFlags(tfActive);
944     else timer->ClrFlags(tfActive);
945
946     js["Result"] = true;
947     Timers->SetModified();
948     return true;
949   }
950
951   js["Result"] = false;
952   js["Error"] = "Timer not found";
953   return true;
954 }
955
956 bool VDRClient::timerdel(PFMap& postFields, Json::Value& js) // RETHROWS
957 {
958   logger->debug("timerdel");
959
960   std::string rChannelID = getVarString(postFields, "ChannelID");
961   std::string rName = getVarString(postFields, "Name");
962   std::string rStartTime = getVarString(postFields, "StartTime");
963   std::string rStopTime = getVarString(postFields, "StopTime");
964   std::string rWeekDays = getVarString(postFields, "WeekDays");
965
966   logger->debug("timerdel: {}:{}:{}:{}:{}", rChannelID, rName, rStartTime, rStopTime, rWeekDays);
967
968   LOCK_TIMERS_WRITE;
969   Timers->SetExplicitModify();
970
971   cTimer* timer = findTimer(Timers, rChannelID.c_str(), rName.c_str(), rStartTime.c_str(), rStopTime.c_str(), rWeekDays.c_str());
972   if (timer)
973   {
974     if (timer->Recording())
975     {
976       logger->debug("timerdel: Unable to delete timer - timer is running");
977       js["Result"] = false;
978       js["Error"] = "Timer is running";
979       return true;
980     }
981
982     Timers->Del(timer);
983     Timers->SetModified();
984     js["Result"] = true;
985     return true;
986   }
987
988   js["Result"] = false;
989   js["Error"] = "Timer not found";
990   return true;
991 }
992
993 bool VDRClient::timerisrecording(PFMap& postFields, Json::Value& js) // RETHROWS
994 {
995   logger->debug("timerisrecording");
996
997   std::string rChannelID = getVarString(postFields, "ChannelID");
998   std::string rName = getVarString(postFields, "Name");
999   std::string rStartTime = getVarString(postFields, "StartTime");
1000   std::string rStopTime = getVarString(postFields, "StopTime");
1001   std::string rWeekDays = getVarString(postFields, "WeekDays");
1002
1003   logger->debug("timerisrecording: {}:{}:{}:{}:{}", rChannelID, rName, rStartTime, rStopTime, rWeekDays);
1004
1005   LOCK_TIMERS_READ;
1006
1007   const cTimer* timer = findTimer(Timers, rChannelID.c_str(), rName.c_str(), rStartTime.c_str(), rStopTime.c_str(), rWeekDays.c_str());
1008   if (timer)
1009   {
1010     js["Recording"] = timer->Recording();
1011     js["Pending"] = timer->Pending();
1012     js["Result"] = true;
1013     return true;
1014   }
1015
1016   js["Result"] = false;
1017   js["Error"] = "Timer not found";
1018   return true;
1019 }
1020
1021 bool VDRClient::recresetresume(PFMap& postFields, Json::Value& js) // RETHROWS
1022 {
1023   logger->debug("recresetresume");
1024
1025   std::string reqfilename = getVarString(postFields, "filename");
1026   logger->debug("recresetresume: {}", reqfilename);
1027
1028
1029   cStateKey StateKey;
1030   const cRecordings* Recordings = cRecordings::GetRecordingsRead(StateKey);
1031
1032   const cRecording* recording = Recordings->GetByName(reqfilename.c_str());
1033
1034   if (!recording)
1035   {
1036     StateKey.Remove();
1037
1038     js["Result"] = false;
1039     js["Error"] = "Could not find recording to reset resume";
1040     return true;
1041   }
1042
1043   logger->debug("recresetresume: Reset resume for: {}", recording->Name());
1044
1045   cResumeFile ResumeFile(recording->FileName(), recording->IsPesRecording());
1046   StateKey.Remove();
1047
1048
1049   if (ResumeFile.Read() >= 0)
1050   {
1051     ResumeFile.Delete();
1052     js["Result"] = true;
1053     return true;
1054   }
1055   else
1056   {
1057     js["Result"] = false;
1058     js["Error"] = "Recording has no resume point";
1059     return true;
1060   }
1061 }
1062
1063 bool VDRClient::timeredit(PFMap& postFields, Json::Value& js) // RETHROWS
1064 {
1065   logger->debug("timeredit");
1066
1067   std::string oldName      = getVarString(postFields, "OldName");
1068   std::string oldActive    = getVarString(postFields, "OldActive");
1069   std::string oldChannelID = getVarString(postFields, "OldChannelID");
1070   std::string oldDay       = getVarString(postFields, "OldDay");
1071   std::string oldWeekDays  = getVarString(postFields, "OldWeekDays");
1072   std::string oldStartTime = getVarString(postFields, "OldStartTime");
1073   std::string oldStopTime  = getVarString(postFields, "OldStopTime");
1074   std::string oldPriority  = getVarString(postFields, "OldPriority");
1075   std::string oldLifetime  = getVarString(postFields, "OldLifetime");
1076
1077   logger->debug("timeredit: {} {} {} {} {} {} {} {} {}", oldName, oldActive, oldChannelID, oldDay, oldWeekDays, oldStartTime, oldStopTime, oldPriority, oldLifetime);
1078
1079   std::string newName      = getVarString(postFields, "NewName");
1080   std::string newActive    = getVarString(postFields, "NewActive");
1081   std::string newChannelID = getVarString(postFields, "NewChannelID");
1082   std::string newDay       = getVarString(postFields, "NewDay");
1083   std::string newWeekDays  = getVarString(postFields, "NewWeekDays");
1084   std::string newStartTime = getVarString(postFields, "NewStartTime");
1085   std::string newStopTime  = getVarString(postFields, "NewStopTime");
1086   std::string newPriority  = getVarString(postFields, "NewPriority");
1087   std::string newLifetime  = getVarString(postFields, "NewLifetime");
1088
1089   logger->debug("timeredit: {} {} {} {} {} {} {} {} {}", newName, newActive, newChannelID, newDay, newWeekDays, newStartTime, newStopTime, newPriority, newLifetime);
1090
1091   LOCK_TIMERS_WRITE;
1092   Timers->SetExplicitModify();
1093
1094   cTimer* timer = findTimer2(Timers, oldName.c_str(), oldActive.c_str(), oldChannelID.c_str(), oldDay.c_str(), oldWeekDays.c_str(), oldStartTime.c_str(), oldStopTime.c_str(), oldPriority.c_str(), oldLifetime.c_str());
1095   if (!timer)
1096   {
1097     js["Result"] = false;
1098     js["Error"] = "Timer not found";
1099     return true;
1100   }
1101
1102   Timers->SetModified();
1103
1104   // Old version commented below (now removed) used to set each thing individually based on whether it had changed. However, since
1105   // the only way to change the timer channel appears to be with the cTimer::Parse function, might as well use that
1106   // for everything it supports
1107   // Except flags. Get current flags, set using Parse, then add/remove active as needed the other way.
1108
1109   time_t nstt = std::stoi(newStartTime);
1110   struct tm nstm;
1111   localtime_r(&nstt, &nstm);
1112   int nssf = (nstm.tm_hour * 100) + nstm.tm_min;
1113
1114   time_t nztt = std::stoi(newStopTime);
1115   struct tm nztm;
1116   localtime_r(&nztt, &nztm);
1117   int nzsf = (nztm.tm_hour * 100) + nztm.tm_min;
1118
1119   std::replace(newName.begin(), newName.end(), ':', '|');
1120
1121   // ? Convert to std::string?
1122   cString parseBuffer = cString::sprintf("%u:%s:%s:%04d:%04d:%d:%d:%s:%s",
1123                           timer->Flags(), newChannelID.c_str(), *(cTimer::PrintDay(std::stoi(newDay), std::stoi(newWeekDays), true)),
1124                           nssf, nzsf, std::stoi(newPriority), std::stoi(newLifetime), newName.c_str(), timer->Aux() ? timer->Aux() : "");
1125
1126   logger->debug("timeredit: new parse: {}", *parseBuffer);
1127
1128   bool parseResult = timer->Parse(*parseBuffer);
1129   if (!parseResult)
1130   {
1131     js["Result"] = false;
1132     js["Error"] = "Timer parsing failed";
1133     return true;
1134   }
1135
1136   if (timer->HasFlags(tfActive) != !(strcasecmp(newActive.c_str(), "true")))
1137   {
1138     logger->debug("timeredit: {} {} set new active: {}", timer->HasFlags(tfActive), !(strcasecmp(newActive.c_str(), "true")), newActive);
1139
1140     if (strcasecmp(newActive.c_str(), "true") == 0)
1141     {
1142       timer->SetFlags(tfActive);
1143     }
1144     else if (strcasecmp(newActive.c_str(), "false") == 0)
1145     {
1146       timer->ClrFlags(tfActive);
1147     }
1148     else
1149     {
1150       js["Result"] = false;
1151       js["Error"] = "Bad request parameters";
1152       return true;
1153     }
1154   }
1155
1156   js["Result"] = true;
1157   return true;
1158 }
1159
1160 bool VDRClient::epgfilteradd(PFMap& postFields, Json::Value& js) // RETHROWS
1161 {
1162   std::string channel = getVarString(postFields, "channel");
1163   std::string programme = getVarString(postFields, "programme");
1164
1165   logger->debug("epgFilterAdd: {} {}", channel, programme);
1166
1167   libconfig::Config epgFilter;
1168   if (!loadEpgFilter(epgFilter))
1169   {
1170     js["Result"] = false;
1171     js["Error"] = "Error initialising EPG filter";
1172     return true;
1173   }
1174
1175   libconfig::Setting& setting = epgFilter.lookup("filters");
1176   libconfig::Setting& newPair = setting.add(libconfig::Setting::Type::TypeGroup);
1177   libconfig::Setting& newChannel = newPair.add("c", libconfig::Setting::Type::TypeString);
1178   newChannel = channel;
1179   libconfig::Setting& newProgramme = newPair.add("p", libconfig::Setting::Type::TypeString);
1180   newProgramme = programme;
1181
1182   if (!saveEpgFilter(epgFilter))
1183   {
1184     js["Result"] = false;
1185     js["Error"] = "Failed to save EPG filter";
1186     return true;
1187   }
1188
1189   js["Result"] = true;
1190   return true;
1191 }
1192
1193 bool VDRClient::epgfilterdel(PFMap& postFields, Json::Value& js) // RETHROWS
1194 {
1195   std::string channel = getVarString(postFields, "channel");
1196   std::string programme = getVarString(postFields, "programme");
1197
1198   logger->debug("epgFilterDel: {} {}", channel, programme);
1199
1200   libconfig::Config epgFilter;
1201   if (!loadEpgFilter(epgFilter))
1202   {
1203     js["Result"] = false;
1204     js["Error"] = "Error initialising EPG filter";
1205     return true;
1206   }
1207
1208   try
1209   {
1210     libconfig::Setting& setting = epgFilter.lookup("filters");
1211     int numFilters = setting.getLength();
1212     int x;
1213     for (x = 0; x < numFilters; x++)
1214     {
1215       libconfig::Setting& pair = setting[x];
1216       std::string c;
1217       std::string p;
1218       if (!pair.lookupValue("c", c) || !pair.lookupValue("p", p))
1219       {
1220         js["Result"] = false;
1221         js["Error"] = "Filter file format error";
1222         return true;
1223       }
1224       if ((c == channel) && (p == programme))
1225       {
1226         setting.remove(x);
1227
1228         if (!saveEpgFilter(epgFilter))
1229         {
1230           js["Result"] = false;
1231           js["Error"] = "Failed to save EPG filter";
1232           return true;
1233         }
1234
1235         logger->debug("Found and deleted: {} {}", c, p);
1236         js["Result"] = true;
1237         return true;
1238       }
1239     }
1240
1241     js["Result"] = false;
1242     js["Error"] = "Channel/Programme not found";
1243     return true;
1244   }
1245   catch (const std::exception& e)
1246   {
1247     js["Result"] = false;
1248     js["Error"] = "Unknown error";
1249     return true;
1250   }
1251 }
1252
1253 bool VDRClient::epgfilterget(PFMap& postFields, Json::Value& js) // RETHROWS
1254 {
1255   logger->debug("epgFilterget");
1256
1257   libconfig::Config epgFilter;
1258   if (!loadEpgFilter(epgFilter))
1259   {
1260     js["Result"] = false;
1261     js["Error"] = "Error initialising EPG filter";
1262     return true;
1263   }
1264
1265   try
1266   {
1267     libconfig::Setting& setting = epgFilter.lookup("filters");
1268     int numFilters = setting.getLength();
1269     int x;
1270     Json::Value jsfilters(Json::arrayValue);
1271     for (x = 0; x < numFilters; x++)
1272     {
1273       libconfig::Setting& pair = setting[x];
1274       std::string c;
1275       std::string p;
1276       if (!pair.lookupValue("c", c) || !pair.lookupValue("p", p))
1277       {
1278         js["Result"] = false;
1279         js["Error"] = "Filter file format error";
1280         return true;
1281       }
1282       Json::Value oneFilter;
1283       oneFilter["c"] = c;
1284       oneFilter["p"] = p;
1285       jsfilters.append(oneFilter);
1286     }
1287     js["EPGFilters"] = jsfilters;
1288   }
1289   catch (const std::exception& e)
1290   {
1291     js["Result"] = false;
1292     js["Error"] = "Unknown error";
1293     return true;
1294   }
1295
1296   js["Result"] = true;
1297   return true;
1298 }
1299
1300 //////////////////////////////////////////////////////////////////////////////////////////////////
1301
1302 const cEvent* VDRClient::getEvent(const cChannels* Channels, const cSchedules* Schedules,
1303                                   Json::Value& js, int channelNumber, int eventID, int aroundTime)
1304 {
1305   const cChannel* channel = NULL;
1306
1307   for (channel = Channels->First(); channel; channel = Channels->Next(channel))
1308   {
1309     if (channel->GroupSep()) continue;
1310     if (channel->Number() == channelNumber) break;
1311   }
1312
1313   if (!channel)
1314   {
1315     logger->error("getevent: Could not find requested channel: {}", channelNumber);
1316     js["Error"] = "Could not find channel";
1317     return NULL;
1318   }
1319
1320   const cSchedule *Schedule = Schedules->GetSchedule(channel->GetChannelID());
1321   if (!Schedule)
1322   {
1323     logger->error("getevent: Could not find requested channel: {}", channelNumber);
1324     js["Error"] = "Internal schedules error (2)";
1325     return NULL;
1326   }
1327
1328   const cEvent* event = NULL;
1329   if (eventID)
1330     event = Schedule->GetEvent(eventID);
1331   else
1332     event = Schedule->GetEventAround(aroundTime);
1333
1334   if (!event)
1335   {
1336     logger->error("getevent: Could not find requested event: {}", eventID);
1337     js["Error"] = "Internal schedules error (3)";
1338     return NULL;
1339   }
1340
1341   return event;
1342 }
1343
1344 cTimer* VDRClient::findTimer(cTimers* Timers,
1345                              const char* rChannelID, const char* rName, const char* rStartTime, const char* rStopTime, const char* rWeekDays)
1346 {
1347   int numTimers = Timers->Count();
1348   cTimer* timer;
1349   for (int i = 0; i < numTimers; i++)
1350   {
1351     timer = Timers->Get(i);
1352
1353     logger->debug("findtimer: current: {}", (const char*)timer->ToText(true));
1354     logger->debug("findtimer: {}", (const char*)timer->Channel()->GetChannelID().ToString());
1355     logger->debug("findtimer: {}", rChannelID);
1356     logger->debug("findtimer: {}", timer->File());
1357     logger->debug("findtimer: {}", rName);
1358     logger->debug("findtimer: {}", timer->StartTime());
1359     logger->debug("findtimer: {}", rStartTime);
1360     logger->debug("findtimer: {}", timer->StopTime());
1361     logger->debug("findtimer: {}", rStopTime);
1362     logger->debug("findtimer: {}", timer->WeekDays());
1363     logger->debug("findtimer: {}", rWeekDays);
1364
1365     if (
1366             (strcmp(timer->Channel()->GetChannelID().ToString(), rChannelID) == 0)
1367          && (strcmp(timer->File(), rName) == 0)
1368          && (timer->StartTime() == atoi(rStartTime))
1369          && (timer->StopTime() == atoi(rStopTime))
1370          && (timer->WeekDays() == atoi(rWeekDays))
1371        )
1372     {
1373       logger->debug("findtimer: found");
1374       return timer;
1375     }
1376   }
1377   logger->debug("findtimer: no timer found");
1378   return NULL;
1379 }
1380
1381 // Differs only from above by taking const Timers and returning const cTimer
1382 const cTimer* VDRClient::findTimer(const cTimers* Timers,
1383                              const char* rChannelID, const char* rName, const char* rStartTime, const char* rStopTime, const char* rWeekDays)
1384 {
1385   int numTimers = Timers->Count();
1386   const cTimer* timer;
1387   for (int i = 0; i < numTimers; i++)
1388   {
1389     timer = Timers->Get(i);
1390
1391     logger->debug("findtimer: current: {}", (const char*)timer->ToText(true));
1392     logger->debug("findtimer: {}", (const char*)timer->Channel()->GetChannelID().ToString());
1393     logger->debug("findtimer: {}", rChannelID);
1394     logger->debug("findtimer: {}", timer->File());
1395     logger->debug("findtimer: {}", rName);
1396     logger->debug("findtimer: {}", timer->StartTime());
1397     logger->debug("findtimer: {}", rStartTime);
1398     logger->debug("findtimer: {}", timer->StopTime());
1399     logger->debug("findtimer: {}", rStopTime);
1400     logger->debug("findtimer: {}", timer->WeekDays());
1401     logger->debug("findtimer: {}", rWeekDays);
1402
1403     if (
1404             (strcmp(timer->Channel()->GetChannelID().ToString(), rChannelID) == 0)
1405          && (strcmp(timer->File(), rName) == 0)
1406          && (timer->StartTime() == atoi(rStartTime))
1407          && (timer->StopTime() == atoi(rStopTime))
1408          && (timer->WeekDays() == atoi(rWeekDays))
1409        )
1410     {
1411       logger->debug("findtimer: found");
1412       return timer;
1413     }
1414   }
1415   logger->debug("findtimer: no timer found");
1416   return NULL;
1417 }
1418
1419 cTimer* VDRClient::findTimer2(cTimers* Timers, const char* rName, const char* rActive, const char* rChannelID, const char* rDay, const char* rWeekDays, const char* rStartTime, const char* rStopTime, const char* rPriority, const char* rLifetime)
1420 {
1421   int numTimers = Timers->Count();
1422   cTimer* timer;
1423   logger->debug("findtimer2: {} {} {} {} {} {} {} {} {}", rName, rActive, rChannelID, rDay, rWeekDays, rStartTime, rStopTime, rPriority, rLifetime);
1424   for (int i = 0; i < numTimers; i++)
1425   {
1426     timer = Timers->Get(i);
1427
1428     logger->debug("findtimer2: search: {} {} {} {} {} {} {} {} {}", timer->File(), timer->HasFlags(tfActive), (const char*)timer->Channel()->GetChannelID().ToString(),
1429                                                                                         (int)timer->Day(), timer->WeekDays(), (int)timer->StartTime(), (int)timer->StopTime(),
1430                                                                                         timer->Priority(), timer->Lifetime());
1431
1432     if (    (strcmp(timer->File(), rName) == 0)
1433          && (timer->HasFlags(tfActive) == !(strcasecmp(rActive, "true")))
1434          && (strcmp(timer->Channel()->GetChannelID().ToString(), rChannelID) == 0)
1435          && (timer->Day() == atoi(rDay))
1436          && (timer->WeekDays() == atoi(rWeekDays))
1437          && (timer->StartTime() == atoi(rStartTime))
1438          && (timer->StopTime() == atoi(rStopTime))
1439          && (timer->Priority() == atoi(rPriority))
1440          && (timer->Lifetime() == atoi(rLifetime))
1441        )
1442     {
1443       logger->debug("findtimer2: found");
1444       return timer;
1445     }
1446   }
1447   logger->debug("findtimer2: no timer found");
1448   return NULL;
1449 }
1450
1451 int VDRClient::getVarInt(PFMap& postFields, const char* paramName) // THROWS
1452 {
1453   auto i = postFields.find(paramName);
1454   if (i == postFields.end()) throw BadParamException(paramName);
1455   int r;
1456   try { r = std::stoi(i->second); }
1457   catch (const std::exception& e) { throw BadParamException(paramName); }
1458   return r;
1459 }
1460
1461 std::string VDRClient::getVarString(PFMap& postFields, const char* paramName, bool emptyOk) // THROWS
1462 {
1463   auto i = postFields.find(paramName);
1464   if (i == postFields.end()) throw BadParamException(paramName);
1465   if (!emptyOk && i->second.empty()) throw BadParamException(paramName);
1466   return i->second;
1467 }
1468
1469 bool VDRClient::loadEpgFilter(libconfig::Config& epgFilter)
1470 {
1471   std::string epgFilterFile(configDir + std::string("/epgfilter.conf"));
1472   FILE* fp = fopen(epgFilterFile.c_str(), "a");
1473   if (!fp)
1474   {
1475     logger->error("loadEpgFilter: Error: Failed to fopen epgfilter.conf");
1476     return false;
1477   }
1478   fclose(fp);
1479
1480   try
1481   {
1482     epgFilter.readFile(epgFilterFile.c_str());
1483   }
1484   catch (const libconfig::FileIOException &fioex)
1485   {
1486     logger->error("loadEpgFilter: Error: Failed to read filter file");
1487     return false;
1488   }
1489   catch(const libconfig::ParseException &pex)
1490   {
1491     logger->error("loadEpgFilter: Parse error at {}: {} - {}", pex.getFile(), pex.getLine(), pex.getError());
1492     return false;
1493   }
1494
1495   try
1496   {
1497     libconfig::Setting& setting = epgFilter.lookup("filters");
1498
1499     if (!setting.isList())
1500     {
1501       logger->error("loadEpgFilter: Error: Failed to read filter file (2)");
1502       return false;
1503     }
1504   }
1505   catch (const libconfig::SettingNotFoundException& e)
1506   {
1507     libconfig::Setting& setting = epgFilter.getRoot();
1508     setting.add("filters", libconfig::Setting::Type::TypeList);
1509   }
1510
1511   return true;
1512 }
1513
1514 bool VDRClient::saveEpgFilter(libconfig::Config& epgFilter)
1515 {
1516   std::string epgFilterFile(configDir + std::string("/epgfilter.conf"));
1517   try
1518   {
1519     epgFilter.writeFile(epgFilterFile.c_str());
1520     logger->debug("saveEpgFilter: EPG filter saved");
1521     return true;
1522   }
1523   catch (const libconfig::FileIOException& e)
1524   {
1525     logger->error("saveEpgFilter: Error: File write error");
1526     return false;
1527   }
1528 }