]> git.vomp.tv Git - jsonserver.git/blob - vdrclient.c
Switch recmove to use cRecording::ChangeName()
[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 void VDRClient::pathsForRecordingName(const cRecordings* Recordings, const std::string& recordingName,
830                            std::string& dirNameSingleDate,
831                            std::string& dirNameSingleTitle,
832                            std::string& dirNameSingleFolder,
833                            std::string& dirNameFullPathTitle,
834                            std::string& dirNameFullPathDate)  // throws int
835 {
836   const char* t;
837   {
838     const cRecording* recordingObj = Recordings->GetByName(recordingName.c_str());
839     if (!recordingObj) throw 2;
840     t = recordingObj->FileName();
841
842     cRecordControl *rc = cRecordControls::GetRecordControl(recordingObj->FileName());
843     if (rc) throw 3;
844
845     logger->debug("paths: recording: {}", recordingObj->Name());
846   } // unlock recordings
847
848   logger->debug("paths: recording: {}", t);
849
850   dirNameFullPathDate = t;
851   int k, j, m;
852
853   // Find the datedirname
854   for(k = strlen(t) - 1; k >= 0; k--)
855   {
856     if (t[k] == '/')
857     {
858       logger->debug("recmoverename: l1: {}", strlen(&t[k+1]) + 1);
859       dirNameSingleDate.assign(&t[k+1], strlen(t) - k - 1);
860       logger->debug("paths: dirNameSingleDate: '{}'", dirNameSingleDate);
861       break;
862     }
863   }
864
865   // Find the titledirname
866
867   for(j = k-1; j >= 0; j--)
868   {
869     if (t[j] == '/')
870     {
871       logger->debug("recmoverename: l2: {}", k - j);
872       dirNameSingleTitle.assign(&t[j+1], k - j - 1);
873       logger->debug("paths: dirNameSingleTitle: '{}'", dirNameSingleTitle);
874       break;
875     }
876   }
877
878   // Find the foldername
879
880   const char* vidDirStr = cVideoDirectory::Name();
881   int vidDirStrLen = strlen(vidDirStr);
882
883   logger->debug("recmoverename: j = {}, strlenvd = {}", j, vidDirStrLen);
884   if (j > vidDirStrLen) // Rec is in a subfolder now
885   {
886     for(m = j-1; m >= 0; m--)
887     {
888       if (t[m] == '/')
889       {
890         logger->debug("recmoverename: l3: {}", j - m);
891         dirNameSingleFolder.assign(&t[m+1], j - m - 1);
892         logger->debug("paths: dirNameSingleFolder: '{}'", dirNameSingleFolder);
893         break;
894       }
895     }
896   }
897
898   dirNameFullPathTitle.assign(t, k);
899   logger->debug("paths: dirNameFullPathTitle: '{}'", dirNameFullPathTitle);
900 }
901
902 bool VDRClient::recrename(PFMap& postFields, Json::Value& js) // RETHROWS
903 {
904   logger->debug("recrename");
905
906   std::string fileNameToAffect = getVarString(postFields, "filename");
907   std::string requestedNewStr = getVarString(postFields, "newname");
908
909   std::string dirNameSingleDate;
910   std::string dirNameSingleTitle;
911   std::string dirNameSingleFolder;
912   std::string dirNameFullPathTitle;
913   std::string dirNameFullPathDate;
914
915 #warning Switch this to Recording->ChangeName ?
916
917   try
918   {
919     LOCK_RECORDINGS_WRITE;
920
921     pathsForRecordingName(Recordings,
922                           fileNameToAffect, dirNameSingleDate,
923                           dirNameSingleTitle, dirNameSingleFolder,
924                           dirNameFullPathTitle, dirNameFullPathDate);
925
926     char* requestedNewSingleTitle = (char*)malloc(requestedNewStr.size() + 1);
927     strcpy(requestedNewSingleTitle, requestedNewStr.c_str());
928     logger->debug("recmoverename: to: {}", requestedNewSingleTitle);
929
930     requestedNewSingleTitle = ExchangeChars(requestedNewSingleTitle, true);
931     if (!strlen(requestedNewSingleTitle)) throw 9;
932     logger->debug("recmoverename: EC: {}", requestedNewSingleTitle);
933
934     const char* vidDirStr = cVideoDirectory::Name();
935     logger->debug("recmoverename: viddir: {}", vidDirStr);
936
937     // Could be a new path - construct that first and test
938
939     std::string newDirNameFullPathTitle = vidDirStr;
940     newDirNameFullPathTitle.append("/");
941
942     if (!dirNameSingleFolder.empty())
943     {
944       newDirNameFullPathTitle.append(dirNameSingleFolder);
945       newDirNameFullPathTitle.append("/");
946     }
947
948     newDirNameFullPathTitle.append(requestedNewSingleTitle);
949     free(requestedNewSingleTitle);
950
951     logger->debug("recrename: NPT2: {}", newDirNameFullPathTitle);
952
953     struct stat dstat;
954     int statret = stat(newDirNameFullPathTitle.c_str(), &dstat);
955     if ((statret == -1) && (errno == ENOENT)) // Dir does not exist
956     {
957       logger->debug("recrename: new path does not exist (1)");
958       int mkdirret = mkdir(newDirNameFullPathTitle.c_str(), 0755);
959       if (mkdirret != 0) throw 4;
960     }
961     else if ((statret == 0) && (! (dstat.st_mode && S_IFDIR)))
962     {
963       // Something exists but it's not a dir
964       throw 5;
965     }
966
967     // New path now created or was there already
968
969     std::string newDirNameFullPathDate = newDirNameFullPathTitle + "/";
970     newDirNameFullPathDate.append(dirNameSingleDate);
971
972     logger->debug("recrename: doing rename '{}' '{}'", dirNameFullPathDate, newDirNameFullPathDate);
973     if (rename(dirNameFullPathDate.c_str(), newDirNameFullPathDate.c_str()) != 0) throw 8;
974
975     // Success. Test for remove old dir containter
976     rmdir(dirNameFullPathTitle.c_str()); // can't do anything about a fail result at this point.
977
978     Recordings->Update();
979     js["Result"] = true;
980     js["NewRecordingFileName"] = newDirNameFullPathDate;
981   }
982   catch (int e)
983   {
984     js["Result"] = false;
985     if (e == 1)
986     {
987       logger->error("recrename: Bad parameters");
988       js["Error"] = "Bad request parameters";
989     }
990     else if (e == 2)
991     {
992       logger->error("recrename: Could not find recording to move");
993       js["Error"] = "Bad filename";
994     }
995     else if (e == 3)
996     {
997       logger->error("recrename: Could not move recording, it is still recording");
998       js["Error"] = "Cannot move recording in progress";
999     }
1000     else if (e == 4)
1001     {
1002       logger->error("recrename: Failed to make new dir (1)");
1003       js["Error"] = "Failed to create new directory (1)";
1004     }
1005     else if (e == 5)
1006     {
1007       logger->error("recrename: Something already exists? (1)");
1008       js["Error"] = "Something already exists at the new path (1)";
1009     }
1010     else if (e == 8)
1011     {
1012       logger->error("recrename: Rename failed");
1013       js["Error"] = "Rename failed";
1014     }
1015     else if (e == 9)
1016     {
1017       logger->error("recrename: ExchangeChars lost our string");
1018       js["Error"] = "Rename failed";
1019     }
1020   }
1021
1022   return true;
1023 }
1024
1025 bool VDRClient::recmove(PFMap& postFields, Json::Value& js) // RETHROWS
1026 {
1027   logger->debug("recmove");
1028
1029   std::string fileNameToAffect = getVarString(postFields, "filename");
1030   std::string requestedNewDirName = getVarString(postFields, "newpath", true /* empty new path is ok */);
1031
1032   try
1033   {
1034     LOCK_RECORDINGS_WRITE;
1035     cRecording* recordingObj = Recordings->GetByName(fileNameToAffect.c_str());
1036     if (!recordingObj) throw 2;
1037
1038     std::string newName;
1039     if (requestedNewDirName.length()) newName = requestedNewDirName + FOLDERDELIMCHAR;
1040     newName += recordingObj->BaseName();
1041
1042     logger->debug("RM2 NEWLOC:  #{}#", newName);
1043
1044     bool moveSuccess = recordingObj->ChangeName(newName.c_str());
1045
1046     js["Result"] = moveSuccess;
1047     js["NewRecordingFileName"] = recordingObj->FileName();
1048   }
1049   catch (BadParamException& e)
1050   {
1051     js["Result"] = false;
1052     logger->error("recmove: Bad parameters");
1053     js["Error"] = "Bad request parameters";
1054   }
1055   catch (int e)
1056   {
1057     js["Result"] = false;
1058     if (e == 2)
1059     {
1060       logger->error("recmove: Could not find recording to move");
1061       js["Error"] = "Bad filename";
1062     }
1063   }
1064
1065   return true;
1066 }
1067
1068 bool VDRClient::timersetactive(PFMap& postFields, Json::Value& js) // RETHROWS
1069 {
1070   logger->debug("timersetactive");
1071
1072   std::string rChannelID = getVarString(postFields, "ChannelID");
1073   std::string rName = getVarString(postFields, "Name");
1074   std::string rStartTime = getVarString(postFields, "StartTime");
1075   std::string rStopTime = getVarString(postFields, "StopTime");
1076   std::string rWeekDays = getVarString(postFields, "WeekDays");
1077   std::string tNewActive = getVarString(postFields, "SetActive");
1078
1079   logger->debug("timersetactive: {} {}:{}:{}:{}:{}", tNewActive, rChannelID, rName, rStartTime, rStopTime, rWeekDays);
1080
1081   if ((tNewActive != "true") && (tNewActive != "false"))
1082   {
1083     js["Result"] = false;
1084     js["Error"] = "Bad request parameters";
1085     return true;
1086   }
1087
1088
1089   LOCK_TIMERS_WRITE;
1090   Timers->SetExplicitModify();
1091
1092   cTimer* timer = findTimer(Timers, rChannelID.c_str(), rName.c_str(), rStartTime.c_str(), rStopTime.c_str(), rWeekDays.c_str());
1093   if (timer)
1094   {
1095     if (tNewActive == "true") timer->SetFlags(tfActive);
1096     else timer->ClrFlags(tfActive);
1097
1098     js["Result"] = true;
1099     Timers->SetModified();
1100     return true;
1101   }
1102
1103   js["Result"] = false;
1104   js["Error"] = "Timer not found";
1105   return true;
1106 }
1107
1108 bool VDRClient::timerdel(PFMap& postFields, Json::Value& js) // RETHROWS
1109 {
1110   logger->debug("timerdel");
1111
1112   std::string rChannelID = getVarString(postFields, "ChannelID");
1113   std::string rName = getVarString(postFields, "Name");
1114   std::string rStartTime = getVarString(postFields, "StartTime");
1115   std::string rStopTime = getVarString(postFields, "StopTime");
1116   std::string rWeekDays = getVarString(postFields, "WeekDays");
1117
1118   logger->debug("timerdel: {}:{}:{}:{}:{}", rChannelID, rName, rStartTime, rStopTime, rWeekDays);
1119
1120   LOCK_TIMERS_WRITE;
1121   Timers->SetExplicitModify();
1122
1123   cTimer* timer = findTimer(Timers, rChannelID.c_str(), rName.c_str(), rStartTime.c_str(), rStopTime.c_str(), rWeekDays.c_str());
1124   if (timer)
1125   {
1126     if (timer->Recording())
1127     {
1128       logger->debug("timerdel: Unable to delete timer - timer is running");
1129       js["Result"] = false;
1130       js["Error"] = "Timer is running";
1131       return true;
1132     }
1133
1134     Timers->Del(timer);
1135     Timers->SetModified();
1136     js["Result"] = true;
1137     return true;
1138   }
1139
1140   js["Result"] = false;
1141   js["Error"] = "Timer not found";
1142   return true;
1143 }
1144
1145 bool VDRClient::timerisrecording(PFMap& postFields, Json::Value& js) // RETHROWS
1146 {
1147   logger->debug("timerisrecording");
1148
1149   std::string rChannelID = getVarString(postFields, "ChannelID");
1150   std::string rName = getVarString(postFields, "Name");
1151   std::string rStartTime = getVarString(postFields, "StartTime");
1152   std::string rStopTime = getVarString(postFields, "StopTime");
1153   std::string rWeekDays = getVarString(postFields, "WeekDays");
1154
1155   logger->debug("timerisrecording: {}:{}:{}:{}:{}", rChannelID, rName, rStartTime, rStopTime, rWeekDays);
1156
1157   LOCK_TIMERS_READ;
1158
1159   const cTimer* timer = findTimer(Timers, rChannelID.c_str(), rName.c_str(), rStartTime.c_str(), rStopTime.c_str(), rWeekDays.c_str());
1160   if (timer)
1161   {
1162     js["Recording"] = timer->Recording();
1163     js["Pending"] = timer->Pending();
1164     js["Result"] = true;
1165     return true;
1166   }
1167
1168   js["Result"] = false;
1169   js["Error"] = "Timer not found";
1170   return true;
1171 }
1172
1173 bool VDRClient::recresetresume(PFMap& postFields, Json::Value& js) // RETHROWS
1174 {
1175   logger->debug("recresetresume");
1176
1177   std::string reqfilename = getVarString(postFields, "filename");
1178   logger->debug("recresetresume: {}", reqfilename);
1179
1180
1181   cStateKey StateKey;
1182   const cRecordings* Recordings = cRecordings::GetRecordingsRead(StateKey);
1183
1184   const cRecording* recording = Recordings->GetByName(reqfilename.c_str());
1185
1186   if (!recording)
1187   {
1188     StateKey.Remove();
1189
1190     js["Result"] = false;
1191     js["Error"] = "Could not find recording to reset resume";
1192     return true;
1193   }
1194
1195   logger->debug("recresetresume: Reset resume for: {}", recording->Name());
1196
1197   cResumeFile ResumeFile(recording->FileName(), recording->IsPesRecording());
1198   StateKey.Remove();
1199
1200
1201   if (ResumeFile.Read() >= 0)
1202   {
1203     ResumeFile.Delete();
1204     js["Result"] = true;
1205     return true;
1206   }
1207   else
1208   {
1209     js["Result"] = false;
1210     js["Error"] = "Recording has no resume point";
1211     return true;
1212   }
1213 }
1214
1215 bool VDRClient::timeredit(PFMap& postFields, Json::Value& js) // RETHROWS
1216 {
1217   logger->debug("timeredit");
1218
1219   std::string oldName      = getVarString(postFields, "OldName");
1220   std::string oldActive    = getVarString(postFields, "OldActive");
1221   std::string oldChannelID = getVarString(postFields, "OldChannelID");
1222   std::string oldDay       = getVarString(postFields, "OldDay");
1223   std::string oldWeekDays  = getVarString(postFields, "OldWeekDays");
1224   std::string oldStartTime = getVarString(postFields, "OldStartTime");
1225   std::string oldStopTime  = getVarString(postFields, "OldStopTime");
1226   std::string oldPriority  = getVarString(postFields, "OldPriority");
1227   std::string oldLifetime  = getVarString(postFields, "OldLifetime");
1228
1229   logger->debug("timeredit: {} {} {} {} {} {} {} {} {}", oldName, oldActive, oldChannelID, oldDay, oldWeekDays, oldStartTime, oldStopTime, oldPriority, oldLifetime);
1230
1231   std::string newName      = getVarString(postFields, "NewName");
1232   std::string newActive    = getVarString(postFields, "NewActive");
1233   std::string newChannelID = getVarString(postFields, "NewChannelID");
1234   std::string newDay       = getVarString(postFields, "NewDay");
1235   std::string newWeekDays  = getVarString(postFields, "NewWeekDays");
1236   std::string newStartTime = getVarString(postFields, "NewStartTime");
1237   std::string newStopTime  = getVarString(postFields, "NewStopTime");
1238   std::string newPriority  = getVarString(postFields, "NewPriority");
1239   std::string newLifetime  = getVarString(postFields, "NewLifetime");
1240
1241   logger->debug("timeredit: {} {} {} {} {} {} {} {} {}", newName, newActive, newChannelID, newDay, newWeekDays, newStartTime, newStopTime, newPriority, newLifetime);
1242
1243   LOCK_TIMERS_WRITE;
1244   Timers->SetExplicitModify();
1245
1246   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());
1247   if (!timer)
1248   {
1249     js["Result"] = false;
1250     js["Error"] = "Timer not found";
1251     return true;
1252   }
1253
1254   Timers->SetModified();
1255
1256   // Old version commented below (now removed) used to set each thing individually based on whether it had changed. However, since
1257   // the only way to change the timer channel appears to be with the cTimer::Parse function, might as well use that
1258   // for everything it supports
1259   // Except flags. Get current flags, set using Parse, then add/remove active as needed the other way.
1260
1261   time_t nstt = std::stoi(newStartTime);
1262   struct tm nstm;
1263   localtime_r(&nstt, &nstm);
1264   int nssf = (nstm.tm_hour * 100) + nstm.tm_min;
1265
1266   time_t nztt = std::stoi(newStopTime);
1267   struct tm nztm;
1268   localtime_r(&nztt, &nztm);
1269   int nzsf = (nztm.tm_hour * 100) + nztm.tm_min;
1270
1271   std::replace(newName.begin(), newName.end(), ':', '|');
1272
1273   // ? Convert to std::string?
1274   cString parseBuffer = cString::sprintf("%u:%s:%s:%04d:%04d:%d:%d:%s:%s",
1275                           timer->Flags(), newChannelID.c_str(), *(cTimer::PrintDay(std::stoi(newDay), std::stoi(newWeekDays), true)),
1276                           nssf, nzsf, std::stoi(newPriority), std::stoi(newLifetime), newName.c_str(), timer->Aux() ? timer->Aux() : "");
1277
1278   logger->debug("timeredit: new parse: {}", *parseBuffer);
1279
1280   bool parseResult = timer->Parse(*parseBuffer);
1281   if (!parseResult)
1282   {
1283     js["Result"] = false;
1284     js["Error"] = "Timer parsing failed";
1285     return true;
1286   }
1287
1288   if (timer->HasFlags(tfActive) != !(strcasecmp(newActive.c_str(), "true")))
1289   {
1290     logger->debug("timeredit: {} {} set new active: {}", timer->HasFlags(tfActive), !(strcasecmp(newActive.c_str(), "true")), newActive);
1291
1292     if (strcasecmp(newActive.c_str(), "true") == 0)
1293     {
1294       timer->SetFlags(tfActive);
1295     }
1296     else if (strcasecmp(newActive.c_str(), "false") == 0)
1297     {
1298       timer->ClrFlags(tfActive);
1299     }
1300     else
1301     {
1302       js["Result"] = false;
1303       js["Error"] = "Bad request parameters";
1304       return true;
1305     }
1306   }
1307
1308   js["Result"] = true;
1309   return true;
1310 }
1311
1312 bool VDRClient::epgfilteradd(PFMap& postFields, Json::Value& js) // RETHROWS
1313 {
1314   std::string channel = getVarString(postFields, "channel");
1315   std::string programme = getVarString(postFields, "programme");
1316
1317   logger->debug("epgFilterAdd: {} {}", channel, programme);
1318
1319   libconfig::Config epgFilter;
1320   if (!loadEpgFilter(epgFilter))
1321   {
1322     js["Result"] = false;
1323     js["Error"] = "Error initialising EPG filter";
1324     return true;
1325   }
1326
1327   libconfig::Setting& setting = epgFilter.lookup("filters");
1328   libconfig::Setting& newPair = setting.add(libconfig::Setting::Type::TypeGroup);
1329   libconfig::Setting& newChannel = newPair.add("c", libconfig::Setting::Type::TypeString);
1330   newChannel = channel;
1331   libconfig::Setting& newProgramme = newPair.add("p", libconfig::Setting::Type::TypeString);
1332   newProgramme = programme;
1333
1334   if (!saveEpgFilter(epgFilter))
1335   {
1336     js["Result"] = false;
1337     js["Error"] = "Failed to save EPG filter";
1338     return true;
1339   }
1340
1341   js["Result"] = true;
1342   return true;
1343 }
1344
1345 bool VDRClient::epgfilterdel(PFMap& postFields, Json::Value& js) // RETHROWS
1346 {
1347   std::string channel = getVarString(postFields, "channel");
1348   std::string programme = getVarString(postFields, "programme");
1349
1350   logger->debug("epgFilterDel: {} {}", channel, programme);
1351
1352   libconfig::Config epgFilter;
1353   if (!loadEpgFilter(epgFilter))
1354   {
1355     js["Result"] = false;
1356     js["Error"] = "Error initialising EPG filter";
1357     return true;
1358   }
1359
1360   try
1361   {
1362     libconfig::Setting& setting = epgFilter.lookup("filters");
1363     int numFilters = setting.getLength();
1364     int x;
1365     for (x = 0; x < numFilters; x++)
1366     {
1367       libconfig::Setting& pair = setting[x];
1368       std::string c;
1369       std::string p;
1370       if (!pair.lookupValue("c", c) || !pair.lookupValue("p", p))
1371       {
1372         js["Result"] = false;
1373         js["Error"] = "Filter file format error";
1374         return true;
1375       }
1376       if ((c == channel) && (p == programme))
1377       {
1378         setting.remove(x);
1379
1380         if (!saveEpgFilter(epgFilter))
1381         {
1382           js["Result"] = false;
1383           js["Error"] = "Failed to save EPG filter";
1384           return true;
1385         }
1386
1387         logger->debug("Found and deleted: {} {}", c, p);
1388         js["Result"] = true;
1389         return true;
1390       }
1391     }
1392
1393     js["Result"] = false;
1394     js["Error"] = "Channel/Programme not found";
1395     return true;
1396   }
1397   catch (const std::exception& e)
1398   {
1399     js["Result"] = false;
1400     js["Error"] = "Unknown error";
1401     return true;
1402   }
1403 }
1404
1405 bool VDRClient::epgfilterget(PFMap& postFields, Json::Value& js) // RETHROWS
1406 {
1407   logger->debug("epgFilterget");
1408
1409   libconfig::Config epgFilter;
1410   if (!loadEpgFilter(epgFilter))
1411   {
1412     js["Result"] = false;
1413     js["Error"] = "Error initialising EPG filter";
1414     return true;
1415   }
1416
1417   try
1418   {
1419     libconfig::Setting& setting = epgFilter.lookup("filters");
1420     int numFilters = setting.getLength();
1421     int x;
1422     Json::Value jsfilters(Json::arrayValue);
1423     for (x = 0; x < numFilters; x++)
1424     {
1425       libconfig::Setting& pair = setting[x];
1426       std::string c;
1427       std::string p;
1428       if (!pair.lookupValue("c", c) || !pair.lookupValue("p", p))
1429       {
1430         js["Result"] = false;
1431         js["Error"] = "Filter file format error";
1432         return true;
1433       }
1434       Json::Value oneFilter;
1435       oneFilter["c"] = c;
1436       oneFilter["p"] = p;
1437       jsfilters.append(oneFilter);
1438     }
1439     js["EPGFilters"] = jsfilters;
1440   }
1441   catch (const std::exception& e)
1442   {
1443     js["Result"] = false;
1444     js["Error"] = "Unknown error";
1445     return true;
1446   }
1447
1448   js["Result"] = true;
1449   return true;
1450 }
1451
1452 //////////////////////////////////////////////////////////////////////////////////////////////////
1453
1454 const cEvent* VDRClient::getEvent(const cChannels* Channels, const cSchedules* Schedules,
1455                                   Json::Value& js, int channelNumber, int eventID, int aroundTime)
1456 {
1457   const cChannel* channel = NULL;
1458
1459   for (channel = Channels->First(); channel; channel = Channels->Next(channel))
1460   {
1461     if (channel->GroupSep()) continue;
1462     if (channel->Number() == channelNumber) break;
1463   }
1464
1465   if (!channel)
1466   {
1467     logger->error("getevent: Could not find requested channel: {}", channelNumber);
1468     js["Error"] = "Could not find channel";
1469     return NULL;
1470   }
1471
1472   const cSchedule *Schedule = Schedules->GetSchedule(channel->GetChannelID());
1473   if (!Schedule)
1474   {
1475     logger->error("getevent: Could not find requested channel: {}", channelNumber);
1476     js["Error"] = "Internal schedules error (2)";
1477     return NULL;
1478   }
1479
1480   const cEvent* event = NULL;
1481   if (eventID)
1482     event = Schedule->GetEvent(eventID);
1483   else
1484     event = Schedule->GetEventAround(aroundTime);
1485
1486   if (!event)
1487   {
1488     logger->error("getevent: Could not find requested event: {}", eventID);
1489     js["Error"] = "Internal schedules error (3)";
1490     return NULL;
1491   }
1492
1493   return event;
1494 }
1495
1496 cTimer* VDRClient::findTimer(cTimers* Timers,
1497                              const char* rChannelID, const char* rName, const char* rStartTime, const char* rStopTime, const char* rWeekDays)
1498 {
1499   int numTimers = Timers->Count();
1500   cTimer* timer;
1501   for (int i = 0; i < numTimers; i++)
1502   {
1503     timer = Timers->Get(i);
1504
1505     logger->debug("findtimer: current: {}", (const char*)timer->ToText(true));
1506     logger->debug("findtimer: {}", (const char*)timer->Channel()->GetChannelID().ToString());
1507     logger->debug("findtimer: {}", rChannelID);
1508     logger->debug("findtimer: {}", timer->File());
1509     logger->debug("findtimer: {}", rName);
1510     logger->debug("findtimer: {}", timer->StartTime());
1511     logger->debug("findtimer: {}", rStartTime);
1512     logger->debug("findtimer: {}", timer->StopTime());
1513     logger->debug("findtimer: {}", rStopTime);
1514     logger->debug("findtimer: {}", timer->WeekDays());
1515     logger->debug("findtimer: {}", rWeekDays);
1516
1517     if (
1518             (strcmp(timer->Channel()->GetChannelID().ToString(), rChannelID) == 0)
1519          && (strcmp(timer->File(), rName) == 0)
1520          && (timer->StartTime() == atoi(rStartTime))
1521          && (timer->StopTime() == atoi(rStopTime))
1522          && (timer->WeekDays() == atoi(rWeekDays))
1523        )
1524     {
1525       logger->debug("findtimer: found");
1526       return timer;
1527     }
1528   }
1529   logger->debug("findtimer: no timer found");
1530   return NULL;
1531 }
1532
1533 // Differs only from above by taking const Timers and returning const cTimer
1534 const cTimer* VDRClient::findTimer(const cTimers* Timers,
1535                              const char* rChannelID, const char* rName, const char* rStartTime, const char* rStopTime, const char* rWeekDays)
1536 {
1537   int numTimers = Timers->Count();
1538   const cTimer* timer;
1539   for (int i = 0; i < numTimers; i++)
1540   {
1541     timer = Timers->Get(i);
1542
1543     logger->debug("findtimer: current: {}", (const char*)timer->ToText(true));
1544     logger->debug("findtimer: {}", (const char*)timer->Channel()->GetChannelID().ToString());
1545     logger->debug("findtimer: {}", rChannelID);
1546     logger->debug("findtimer: {}", timer->File());
1547     logger->debug("findtimer: {}", rName);
1548     logger->debug("findtimer: {}", timer->StartTime());
1549     logger->debug("findtimer: {}", rStartTime);
1550     logger->debug("findtimer: {}", timer->StopTime());
1551     logger->debug("findtimer: {}", rStopTime);
1552     logger->debug("findtimer: {}", timer->WeekDays());
1553     logger->debug("findtimer: {}", rWeekDays);
1554
1555     if (
1556             (strcmp(timer->Channel()->GetChannelID().ToString(), rChannelID) == 0)
1557          && (strcmp(timer->File(), rName) == 0)
1558          && (timer->StartTime() == atoi(rStartTime))
1559          && (timer->StopTime() == atoi(rStopTime))
1560          && (timer->WeekDays() == atoi(rWeekDays))
1561        )
1562     {
1563       logger->debug("findtimer: found");
1564       return timer;
1565     }
1566   }
1567   logger->debug("findtimer: no timer found");
1568   return NULL;
1569 }
1570
1571 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)
1572 {
1573   int numTimers = Timers->Count();
1574   cTimer* timer;
1575   logger->debug("findtimer2: {} {} {} {} {} {} {} {} {}", rName, rActive, rChannelID, rDay, rWeekDays, rStartTime, rStopTime, rPriority, rLifetime);
1576   for (int i = 0; i < numTimers; i++)
1577   {
1578     timer = Timers->Get(i);
1579
1580     logger->debug("findtimer2: search: {} {} {} {} {} {} {} {} {}", timer->File(), timer->HasFlags(tfActive), (const char*)timer->Channel()->GetChannelID().ToString(),
1581                                                                                         (int)timer->Day(), timer->WeekDays(), (int)timer->StartTime(), (int)timer->StopTime(),
1582                                                                                         timer->Priority(), timer->Lifetime());
1583
1584     if (    (strcmp(timer->File(), rName) == 0)
1585          && (timer->HasFlags(tfActive) == !(strcasecmp(rActive, "true")))
1586          && (strcmp(timer->Channel()->GetChannelID().ToString(), rChannelID) == 0)
1587          && (timer->Day() == atoi(rDay))
1588          && (timer->WeekDays() == atoi(rWeekDays))
1589          && (timer->StartTime() == atoi(rStartTime))
1590          && (timer->StopTime() == atoi(rStopTime))
1591          && (timer->Priority() == atoi(rPriority))
1592          && (timer->Lifetime() == atoi(rLifetime))
1593        )
1594     {
1595       logger->debug("findtimer2: found");
1596       return timer;
1597     }
1598   }
1599   logger->debug("findtimer2: no timer found");
1600   return NULL;
1601 }
1602
1603 int VDRClient::getVarInt(PFMap& postFields, const char* paramName) // THROWS
1604 {
1605   auto i = postFields.find(paramName);
1606   if (i == postFields.end()) throw BadParamException(paramName);
1607   int r;
1608   try { r = std::stoi(i->second); }
1609   catch (const std::exception& e) { throw BadParamException(paramName); }
1610   return r;
1611 }
1612
1613 std::string VDRClient::getVarString(PFMap& postFields, const char* paramName, bool emptyOk) // THROWS
1614 {
1615   auto i = postFields.find(paramName);
1616   if (i == postFields.end()) throw BadParamException(paramName);
1617   if (!emptyOk && i->second.empty()) throw BadParamException(paramName);
1618   return i->second;
1619 }
1620
1621 bool VDRClient::loadEpgFilter(libconfig::Config& epgFilter)
1622 {
1623   std::string epgFilterFile(configDir + std::string("/epgfilter.conf"));
1624   FILE* fp = fopen(epgFilterFile.c_str(), "a");
1625   if (!fp)
1626   {
1627     logger->error("loadEpgFilter: Error: Failed to fopen epgfilter.conf");
1628     return false;
1629   }
1630   fclose(fp);
1631
1632   try
1633   {
1634     epgFilter.readFile(epgFilterFile.c_str());
1635   }
1636   catch (const libconfig::FileIOException &fioex)
1637   {
1638     logger->error("loadEpgFilter: Error: Failed to read filter file");
1639     return false;
1640   }
1641   catch(const libconfig::ParseException &pex)
1642   {
1643     logger->error("loadEpgFilter: Parse error at {}: {} - {}", pex.getFile(), pex.getLine(), pex.getError());
1644     return false;
1645   }
1646
1647   try
1648   {
1649     libconfig::Setting& setting = epgFilter.lookup("filters");
1650
1651     if (!setting.isList())
1652     {
1653       logger->error("loadEpgFilter: Error: Failed to read filter file (2)");
1654       return false;
1655     }
1656   }
1657   catch (const libconfig::SettingNotFoundException& e)
1658   {
1659     libconfig::Setting& setting = epgFilter.getRoot();
1660     setting.add("filters", libconfig::Setting::Type::TypeList);
1661   }
1662
1663   return true;
1664 }
1665
1666 bool VDRClient::saveEpgFilter(libconfig::Config& epgFilter)
1667 {
1668   std::string epgFilterFile(configDir + std::string("/epgfilter.conf"));
1669   try
1670   {
1671     epgFilter.writeFile(epgFilterFile.c_str());
1672     logger->debug("saveEpgFilter: EPG filter saved");
1673     return true;
1674   }
1675   catch (const libconfig::FileIOException& e)
1676   {
1677     logger->error("saveEpgFilter: Error: File write error");
1678     return false;
1679   }
1680 }