summaryrefslogtreecommitdiff
path: root/vdr-vdrmanager/helpers.cpp
blob: 57dab9bded1058bac72826e5e83b87e3dec79aa3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
/*
 * event und message handler
 */

#include <time.h>
#include <unistd.h>
#include <values.h>
#include <vdr/plugin.h>
#include <vdr/timers.h>
#include <vdr/recording.h>
#include <vdr/channels.h>
#include <vdr/epg.h>
#include <vdr/videodir.h>
#include <vdr/menu.h>
#include "helpers.h"
#include "vdrmanagerthread.h"
#include <memory>
#include <vdr/cutter.h>
#include <vdr/sources.h>
#include <fstream>

#define TIMER_SEP		"#|#|#"
// Taken from vdr-ive
#define INDEXFILESUFFIX   "/index.vdr"
#define LENGTHFILESUFFIX  "/length.vdr"

string cHelpers::GetRecordings(string args) {
	return SafeCall(GetRecordingsIntern);
}

string cHelpers::GetTimers(string args) {
	return SafeCall(GetTimersIntern);
}

string cHelpers::GetChannels(string args) {
	return SafeCall(GetChannelsIntern, args);
}

string cHelpers::GetChannelEvents(string args) {
	return SafeCall(GetEventsIntern, Trim(args), "");
}

string cHelpers::SetChannel(string args) {
	return SafeCall(SetChannelIntern, args);
}

string cHelpers::GetTimeEvents(string args) {

	args = Trim(args);

	size_t space = args.find(' ');
	if (space == string::npos) {
		return SafeCall(GetEventsIntern, "", args);
	}

	string when = args.substr(0, space);
	string wantedChannels = args.substr(space + 1);

	return SafeCall(GetEventsIntern, Trim(wantedChannels), Trim(when));
}

string cHelpers::SetTimer(string args) {
	return SafeCall(SetTimerIntern, args);
}

string cHelpers::DelRecording(string args) {
	return SafeCall(DelRecordingIntern, args);
}

string cHelpers::SearchEvents(string args) {

	args = Trim(args);

	string wantedChannels;
	string pattern;

	size_t space = args.find(':');
	if (space == string::npos) { //so only search term
		pattern = args;
		wantedChannels = "";
	} else {
		wantedChannels = args.substr(0, space);
		pattern = args.substr(space + 1);
	}
	pattern = UnMapSpecialChars(pattern);
	return SafeCall(SearchEventsIntern, Trim(wantedChannels), Trim(pattern));
}

string cHelpers::GetTimersIntern() {

	string result = "START\r\n";

	// iterate through all timers
	for (cTimer * timer = Timers.First(); timer; timer = Timers.Next(timer)) {
		result += ToText(timer);
	}

	return result + "END\r\n";
}

string cHelpers::GetRecordingsIntern() {

	int FreeMB, UsedMB;
#if APIVERSNUM < 20102
	int Percent = VideoDiskSpace(&FreeMB, &UsedMB);
#else
	int Percent = cVideoDirectory::VideoDiskSpace(&FreeMB, &UsedMB);
#endif

	std::stringstream sstm;

	sstm << "START|" << (FreeMB + UsedMB) << ":" << FreeMB << ":" << Percent
			<< "\r\n";

	string result = sstm.str();

	//iterate through all recordings
	cRecording* recording = NULL;
	for (int i = 0; i < Recordings.Count(); i++) {
		recording = Recordings.Get(i);
		result += ToText(recording);
	}
	return result + "END\r\n";
}

string cHelpers::GetChannelsIntern(string wantedChannels) {

	string result = "START\r\n";
	string currentGroup = "";

	char number[10];
	for (cChannel * channel = Channels.First(); channel; channel =
			Channels.Next(channel)) {

		// channel group
		if (channel->GroupSep()) {
			currentGroup = channel->Name();
			continue;
		}

		// channel filtering
		if (IsWantedChannel(channel, wantedChannels)) {
			// current group
			if (currentGroup.length() > 0) {
				result += "C0:";
				result += currentGroup;
				result += "\r\n";
				currentGroup = "";
			}

			// channel
			snprintf(number, sizeof(number) - 1, "C%d", channel->Number());
			result += number;
			result += ":";
			result += channel->Name();
			result += ":";
			result += channel->Provider();
			result += ":";
			result += channel->GetChannelID().ToString();
			result += ":";
			result += GetAudioTracks(channel);
			result += ":";
			result += MapSpecialChars(cSource::ToString(channel->Source()));
			result += "\r\n";
		}
	}

	return result + "END\r\n";
}

string cHelpers::SetChannelIntern(const string args) {

	if (args.size() == 0) {
		return "!ERROR:SetChannel;empty args\r\n";
	}

	cChannel *channel;
	bool isnum = true;
	for (int i = 0; i < (int) args.length(); i++) {
		if (!std::isdigit(args[i])) {
			isnum = false;
			break;
		}

	}

	if (isnum) {
		int nr = atoi(args.c_str());
		channel = Channels.GetByNumber(nr);
	} else {
		tChannelID chid = tChannelID::FromString(args.c_str());
		channel = Channels.GetByChannelID(chid);
	}

	if (!channel) {
		return "!ERROR:SetChannel;Unable to find channel " + args + "\r\n";
	}

	ostringstream outStream;

	if (!cDevice::PrimaryDevice()->SwitchChannel(channel, true)) {
		outStream << channel->Number();
		return "!ERROR:SetChannel;Error switching to channel " + outStream.str()
				+ "\r\n";
	}

	return "START\r\n" + MapSpecialChars(channel->GetChannelID().ToString())
			+ "\r\nEND\r\n";
}

string cHelpers::GetAudioTracks(const cChannel* channel) {

	string result = "";
	int count = 0;
	for (int i = 0; channel->Apid(i) != 0; ++i, ++count)
		;
	for (int i = 0; channel->Dpid(i) != 0; ++i, ++count)
		;

	if (count > 1) {
		int index = 1;
		string sep = "";
		for (int i = 0; channel->Apid(i) != 0; ++i, ++index) {
			result += sep + "a," + (const char*) itoa(index) + ","
					+ channel->Alang(i);
			sep = "|";
		}
		for (int i = 0; channel->Dpid(i) != 0; ++i, ++index) {
			result += sep + "d," + (const char*) itoa(index) + ","
					+ channel->Dlang(i);
			sep = "|";
		}

	}
	return result;
}

string cHelpers::GetEventsIntern(string wantedChannels, string when) {

	when = ToUpper(when);
	time_t wantedTime;
	if (when == "NOW" || when == "NEXT") {
		wantedTime = time(0);
	} else {
		wantedTime = atol(when.c_str());
	}

	string result = "START\r\n";

	cSchedulesLock schedulesLock;
	const cSchedules * schedules = cSchedules::Schedules(schedulesLock);
	for (cSchedule * schedule = schedules->First(); schedule; schedule =
			schedules->Next(schedule)) {

		cChannel * channel = Channels.GetByChannelID(schedule->ChannelID());
		if (!IsWantedChannel(channel, wantedChannels)) {
			continue;
		}

		const cList<cEvent> * events = schedule->Events();
		for (cEvent * event = events->First(); event;
				event = events->Next(event)) {
			if (IsWantedTime(wantedTime, event)) {
				cEvent * match = event;
				if (when == "NEXT") {
					match = events->Next(match);
					if (!match) {
						break;
					}
				}

				result += ToText(match);

				if (when.length() > 0) {
					break;
				}
			}
		}
	}

	return result + "END\r\n";
}

string cHelpers::DelRecording(cRecording * recording) {

	cString FileName = recording->FileName();

#if VDRVERSNUM < 20102
	if (cCutter::Active(recording->FileName())) {
		cCutter::Stop();
		recording = Recordings.GetByName(FileName); // cCutter::Stop() might have deleted it if it was the edited version
		// we continue with the code below even if recording is NULL,
		// in order to have the menu updated etc.
	}
#else
	if (RecordingsHandler.GetUsage(FileName)) {
		RecordingsHandler.Del(FileName);
		recording = Recordings.GetByName(FileName); // RecordingsHandler.Del() might have deleted it if it was the edited version
		// we continue with the code below even if recording is NULL,
		// in order to have the menu updated etc.
	}
#endif

	if (cReplayControl::NowReplaying()
			&& strcmp(cReplayControl::NowReplaying(), FileName) == 0) {
		cControl::Shutdown();
	}

	if (!recording || recording->Delete()) {
		cReplayControl::ClearLastReplayed(FileName);
		Recordings.DelByName(FileName);
#if VDRVERSNUM > 10727
		cVideoDiskUsage::ForceCheck();
#endif
	}

	return "START\r\nEND\r\n";
}

string cHelpers::DelRecordingIntern(string args) {

	if (args.size() == 0) {
		return Error("empty args");
	}

	int index = atoi(args.c_str());

	cRecording *recording = Recordings.Get(index);
	if (!recording) {
		return Error("Recording not found");
	}

	cRecordControl *rc = cRecordControls::GetRecordControl(
			recording->FileName());

	if (!rc) {
		return cHelpers::DelRecording(recording);
	}

	/**
	 * this should come as a parameter later
	 */

	bool forceDelete = true;

	if (forceDelete == false) {
		return Error("Recording is in use by a timer");
	}

	cTimer *timer = rc->Timer();
	if (timer) {
		timer->Skip();
		cRecordControls::Process(time(NULL));
		if (timer->IsSingleEvent()) {
			isyslog("deleting timer %s", *timer->ToDescr());
			Timers.Del(timer);
		}
		Timers.SetModified();
	}
	return cHelpers::DelRecording(recording);
}
//
//	return "START\r\nEND\r\n";
//	if (r->Delete()) {
//		cRecordControl* rc = cRecordControls::GetRecordControl(r->FileName());
//		//cTimer *timer = rc->Timer();
//		//if (timer) {
//		//isyslog("deleting timer %s", *timer->ToDescr());
//		//Timers.sel(timer);
//		Timers.SetModified();
//		//}
//		Recordings.DelByName(r->FileName());
//		return "START\r\nEND\r\n";
//	} else {
//		return "!ERROR:Failed\r\n";
//	}

string cHelpers::SetTimerIntern(char op, string param) {

	switch (op) {
	case 'C': // new timer
	case 'c': {
		auto_ptr<cTimer> newTimer(new cTimer);
		if (!newTimer->Parse(param.c_str())) {
			return Error("Error in timer settings");
		}

		cTimer* checkTimer = Timers.GetTimer(newTimer.get());
		if (checkTimer) {
			return Error("Timer already defined");
		}

		Timers.Add(newTimer.get());
		Timers.SetModified();
		dsyslog("[vdrmanager] timer %s added", *newTimer->ToDescr());
		newTimer.release();
		break;
	}
	case 'D':
	case 'd': {
		if (Timers.BeingEdited()) {
			return Error("Timers are being edited - try again later");
		}

		dsyslog("[vdrmanager] try parse %s ", param.c_str());

		auto_ptr<cTimer> timer(new cTimer);
		if (!timer->Parse(param.c_str())) {
			return Error("Error in timer settings");
		}

		dsyslog("[vdrmanager] timer %s parsed", *timer->ToDescr());

		cTimer * t = Timers.GetTimer(timer.get());

		if (!t) {
			return Error("Timer not defined");
		}

		/**
		 * this should come lates as a command line parameter
		 */
		bool forceDelete = true;

		if (t->Recording()) {
			if (forceDelete == true) {
				t->Skip();
				cRecordControls::Process(time(NULL));
			} else {
				return Error("Timer  is recording");
			}
		}

		dsyslog("[vdrmanager] deleting timer %s", *t->ToDescr());
		Timers.Del(t);
		Timers.SetModified();
		break;
	}
	case 'M':
	case 'm': {

		if (Timers.BeingEdited()) {
			return Error("Timers are being edited - try again later");
		}

		string sep = string(TIMER_SEP);

		size_t idx = param.find(sep);
		if (idx == string::npos) {
			return Error("no separator found");
		}

		string newt = param.substr(0, idx);
		string oldt = param.substr(idx + sep.size());

		auto_ptr<cTimer> otimer(new cTimer);
		if (!otimer->Parse(oldt.c_str())) {
			return Error("Error in timer settings");
		}

		cTimer* oldTimer = Timers.GetTimer(otimer.get());
		if (oldTimer == 0) {
			return Error("Timer not defined");
		}

		cTimer copy = *oldTimer;
		if (!copy.Parse(newt.c_str())) {
			return Error("Error in timer settings");
		}

		*oldTimer = copy;
		Timers.SetModified();
		dsyslog("[vdrmanager] timer %s modified (%s)", *oldTimer->ToDescr(),
				oldTimer->HasFlags(tfActive) ? "active" : "inactive");

		break;
	}
	case 'T':
	case 't': {
		if (Timers.BeingEdited()) {
			return Error("Timers are being edited - try again later");
		}

		auto_ptr<cTimer> timer(new cTimer);
		if (!timer->Parse(param.c_str())) {
			return Error("Error in timer settings");
		}

		cTimer* toggleTimer = Timers.GetTimer(timer.get());
		if (toggleTimer == 0) {
			return Error("Timer not defined");
		}

		toggleTimer->OnOff();
		Timers.SetModified();
		dsyslog("[vdrmanager] timer %s toggled %s", *toggleTimer->ToDescr(),
				toggleTimer->HasFlags(tfActive) ? "on" : "off");
		break;
	}
	default:
		return Error("unknown timer command");
	}
	return "START\r\nEND\r\n";
}

string cHelpers::SetTimerIntern(string args) {
//C dasdasda#|#|#
//C 1 as:asd:SadA:sd  ada:a :ada
// separete timer number
//size_t sep = args.find('');
//if (sep == string::npos) {
//return "!ERROR:no separator found\r\n";
//}

	if (Timers.BeingEdited()) {
		return Error("Timers are being edited - try again later");
	}

	char operation = args[0];

	args = Trim(args.substr(1));

// Use StringReplace here because if ':' are characters in the
// title or aux string it breaks parsing of timer definition
// in VDRs cTimer::Parse method.  The '|' will be replaced
// back to ':' by the cTimer::Parse() method.

	// Fix was submitted by rofafor: see
// http://www.vdr-portal.de/board/thread.php?threadid=100398
	string params = replaceAll(args, "|##", "|");

//replace also newlines
	params = replaceAll(params, "||#", "\n");

	string result = SetTimerIntern(operation, params);

	return result;
}

string cHelpers::Error(const string& msg) {
	return "START\r\n!ERROR:" + msg + "\r\nEND\r\n";
}

string cHelpers::SearchEventsIntern(string wantedChannels, string pattern) {

	string result = "START\r\n";

	cSchedulesLock schedulesLock;
	const cSchedules * schedules = cSchedules::Schedules(schedulesLock);
	for (cSchedule * schedule = schedules->First(); schedule; schedule =
			schedules->Next(schedule)) {

		cChannel * channel = Channels.GetByChannelID(schedule->ChannelID());
		if (!IsWantedChannel(channel, wantedChannels)) {
			continue;
		}

		const cList<cEvent> * events = schedule->Events();
		for (cEvent * event = events->First(); event;
				event = events->Next(event)) {

			if (IsWantedTime(0, event) && IsWantedEvent(event, pattern)) { //time must be ok, so stop > now
				result += ToText(event);
			}
		}
	}

	return result + "END\r\n";
}

//copied from vdr-live

long cHelpers::Duration(cRecording* recording) {
	long RecLength = 0;
	if (!recording->FileName())
		return 0;
#if VDRVERSNUM < 10704
	cString filename = cString::sprintf("%s%s", recording->FileName(), INDEXFILESUFFIX);
	if (*filename) {
		if (access(filename, R_OK) == 0) {
			struct stat buf;
			if (stat(filename, &buf) == 0) {
				struct tIndex {int offset; uchar type; uchar number; short reserved;};
				int delta = buf.st_size % sizeof(tIndex);
				if (delta) {
					delta = sizeof(tIndex) - delta;
					esyslog("ERROR: invalid file size (%ld) in '%s'", buf.st_size, *filename);
				}
				RecLength = (buf.st_size + delta) / sizeof(tIndex) / SecondsToFrames(60);
			}
		}
	}
#elif VDRVERSNUM < 10721
	// open index file for reading only
	cIndexFile *index = new cIndexFile(recording->FileName(), false, recording->IsPesRecording());
	if (index && index->Ok()) {
		RecLength = (int) (index->Last() / SecondsToFrames(60, recording->FramesPerSecond()));
	}
	delete index;
#else
	return recording->LengthInSeconds() / 60;
#endif
	if (RecLength == 0) {
		cString lengthFile = cString::sprintf("%s%s", recording->FileName(),
				LENGTHFILESUFFIX);
		ifstream length(*lengthFile);
		if (length)
			length >> RecLength;
	}

	return RecLength;
}

string cHelpers::ToText(cRecording * recording) {
	const cRecordingInfo * info = recording->Info();
#if APIVERSNUM >= 10705
	const cEvent * event = info->GetEvent();
#endif
	/**
	 tChannelID ChannelID(void) const;
	 const cSchedule *Schedule(void) const { return schedule; }
	 tEventID EventID(void) const { return eventID; }
	 uchar TableID(void) const { return tableID; }
	 uchar Version(void) const { return version; }
	 int RunningStatus(void) const { return runningStatus; }
	 const char *Title(void) const { return title; }
	 const char *ShortText(void) const { return shortText; }
	 const char *Description(void) const { return description; }
	 const cComponents *Components(void) const { return components; }
	 uchar Contents(int i = 0) const { return (0 <= i && i < MaxEventContents) ? contents[i] : 0; }
	 int ParentalRating(void) const { return parentalRating; }
	 time_t StartTime(void) const { return startTime; }
	 time_t EndTime(void) const { return startTime + duration; }
	 int Duration(void) const { return duration; }
	 time_t Vps(void) const { return vps; }
	 time_t Seen(void) const { return seen; }
	 bool SeenWithin(int Seconds) const { return time(NULL) - seen < Seconds; }
	 bool HasTimer(void) const;
	 bool IsRunning(bool OrAboutToStart = false) const;
	 static const char *ContentToString(uchar Content);
	 cString GetParentalRatingString(void) const;
	 cString GetDateString(void) const;
	 cString GetTimeString(void) const;
	 cString GetEndTimeString(void) const;
	 cString GetVpsString(void) const;
	 */

	char buf[100];
	string result = "";

#if VDRVERSNUM < 10726
	time_t startTime = recording->start;
#else
	time_t startTime = recording->Start();
#endif

	time_t endTime = startTime + RecordingLengthInSeconds(recording);

	snprintf(buf, sizeof(buf) - 1, "%d", recording->Index());
	result = buf;
	result += ":";

	snprintf(buf, sizeof(buf) - 1, "%lu", startTime);
	result += buf;
	result += ":";

	snprintf(buf, sizeof(buf) - 1, "%lu", endTime);
	result += buf;
	result += ":";

	if (info->ChannelName()) {
		result += MapSpecialChars(info->ChannelName());
	} else {
		result += "<unknown>";
	}
	result += ":";

	if (info->Title()) {
		result += MapSpecialChars(info->Title());
#if APIVERSNUM >= 10705
	} else if (event->Title()) {
		result += MapSpecialChars(event->Title());
#endif
	} else {
		result += recording->Name();
	}
	result += ":";

	result += MapSpecialChars(info->ShortText() ? info->ShortText() : "");
	result += ":";

	result += MapSpecialChars(info->Description() ? info->Description() : "");
	result += ":";

	result += MapSpecialChars(recording->FileName());
	result += ":";

	snprintf(buf, sizeof(buf) - 1, "%d", DirSizeMB(recording->FileName()));
	result += buf;

	result += ":";
	result += MapSpecialChars(info->ChannelID().ToString());

	result += ":";

	int length = RecordingLengthInSeconds(recording);

	snprintf(buf, sizeof(buf) - 1, "%d", length);
	result += buf;

	result += ":";

	struct stat st;
	if (stat(recording->FileName(), &st) == 0) {
		result += MapSpecialChars(
				cString::sprintf("%lu:%llu.rec", (unsigned long) st.st_dev,
						(unsigned long long) st.st_ino));
	} else {
		result += "";
	}

	result += ":";

	cRecordControl *rc = cRecordControls::GetRecordControl(
			recording->FileName());
	if (rc) {
		cTimer *timer = rc->Timer();
		if (timer) {
			char buf[100];
			snprintf(buf, sizeof(buf) - 1, "%lu", timer->StopTime());
			result += buf;
		}
	}

	result += ":";
	//Feature #1319
	result += MapSpecialChars(recording->Name());

	result += "\r\n";
	return result;
}

string cHelpers::ToText(cTimer * timer) {

	const cChannel * channel = timer->Channel();
	const char * channelName = channel->Name();

//cSchedulesLock schedulesLock;
//  const cSchedules * schedules = cSchedules::Schedules(schedulesLock);

//  const cSchedule * schedule = schedules->GetSchedule(channel->GetChannelID());

//const cList<cEvent> * events = schedule->Events();
//  cEvent * match = NULL;
//  for(cEvent * event = events->First(); event; event = events->Next(event)) {
//
//time_t startTime = event->StartTime();
//    time_t stopTime = startTime + event->Duration();
//if(startTime <= timer->StartTime() && timer->StopTime() >= stopTime){
//  match = event;
//  break;
//}
//  }

	string result;
	char buf[100];
	snprintf(buf, sizeof(buf) - 1, "T%d", timer->Index());
	result = buf;
	result += ":";
	snprintf(buf, sizeof(buf) - 1, "%u", timer->Flags());
	result += buf;
	result += ":";
	snprintf(buf, sizeof(buf) - 1, "%d", timer->Channel()->Number());
	result += buf;
	result += ":";
	result += MapSpecialChars(channelName);
	result += ":";
	snprintf(buf, sizeof(buf) - 1, "%lu", timer->StartTime());
	result += buf;
	result += ":";
	snprintf(buf, sizeof(buf) - 1, "%lu", timer->StopTime());
	result += buf;
	result += ":";
	snprintf(buf, sizeof(buf) - 1, "%d", timer->Priority());
	result += buf;
	result += ":";
	snprintf(buf, sizeof(buf) - 1, "%d", timer->Lifetime());
	result += buf;
	result += ":";
	result += MapSpecialChars(timer->File());
	result += ":";
	result += MapSpecialChars(timer->Aux() ? timer->Aux() : "");
	const cEvent * event = timer->Event();
	dsyslog("[vdrmanager] timer's event is NULL. Try find it");
	if (!event) {
		cChannel * channel = Channels.GetByChannelID(
				timer->Channel()->GetChannelID());
		if (channel) {
			cSchedulesLock schedulesLock;
			const cSchedules * schedules = cSchedules::Schedules(schedulesLock);
			const cSchedule * schedule = schedules->GetSchedule(
					channel->GetChannelID());
			if (schedule) {
				const cList<cEvent> * events = schedule->Events();
				for (cEvent * ev = events->First(); event;
						ev = events->Next(ev)) {
					if (timer->StartTime() <= ev->StartTime()
							&& timer->StopTime()
									>= ev->StartTime() + ev->Duration()) {
						event = ev;
						dsyslog(
								"[vdrmanager] timer's event was NULL, but found via time!");
						break;
					}
				}
			}
		}
	}

	if (event) {
		result += ":";
		result += event->ShortText() ? MapSpecialChars(event->ShortText()) : "";
		result += ":";
		result +=
				event->Description() ?
						MapSpecialChars(event->Description()) : "";
	} else {
		result += "::";
	}

	result += ":";
	result += MapSpecialChars(timer->Channel()->GetChannelID().ToString());

	result += ":";

	result += ConvertWeekdays(timer->WeekDays());

	result += "\r\n";

	return result;
}

string cHelpers::ToText(const cEvent * event) {

	cChannel * channel = Channels.GetByChannelID(
			event->Schedule()->ChannelID());

// search assigned timer

	//eTimerMatch TimerMatch = tmNone;
	cTimer * eventTimer = Timers.GetMatch(event);

//	if(eventTimer){
//
//	for (cTimer * timer = Timers.First(); timer; timer = Timers.Next(timer)) {
//		if (timer->Channel() == channel
//				&& timer->StartTime() <= event->StartTime()
//				&& timer->StopTime()
//						>= event->StartTime() + event->Duration()) {
//			eventTimer = timer;
//			break;
//		}
//	}

	char buf[100];
	string result;
	snprintf(buf, sizeof(buf) - 1, "E%d", channel->Number());
	result = buf;
	result += ":";
	result += MapSpecialChars(channel->Name());
	result += ":";
	snprintf(buf, sizeof(buf) - 1, "%lu", event->StartTime());
	result += buf;
	result += ":";
	snprintf(buf, sizeof(buf) - 1, "%lu",
			event->StartTime() + event->Duration());
	result += buf;
	result += ":";
	result += MapSpecialChars(event->Title());
	result += ":";
	result += MapSpecialChars(event->Description() ? event->Description() : "");
	result += ":";
	result += MapSpecialChars(event->ShortText() ? event->ShortText() : "");
	result += ":";
	result += MapSpecialChars(channel->GetChannelID().ToString());
	result += ":";
	result += GetAudioTracks(channel);
	result += ":";

	if (event->Contents(0)) {
		string sep = "";
		for (int i = 0; event->Contents(i); i++) {
			uchar c = event->Contents(i);
			result += sep;
			snprintf(buf, sizeof(buf) - 1, "%u", c);
			result += buf;
			sep = " ";
		}
	}
	result += "\r\n";

	if (eventTimer) {
		result += ToText(eventTimer);
	}

	return result;
}

bool cHelpers::IsWantedEvent(cEvent * event, string pattern) {

	string text = event->Title();
	if (event->Description()) {
		text += event->Description();
	}

	return ToLower(text).find(ToLower(pattern)) != string::npos;
}

bool cHelpers::IsWantedChannel(cChannel * channel, string wantedChannels) {

	if (!channel) {
		return false;
	}

	if (wantedChannels.length() == 0) {
		return true;
	}

	int number = channel->Number();
	const char * delims = ",;";
	char * state;
	char * buffer = (char *) malloc(wantedChannels.size() + 1);
	strcpy(buffer, wantedChannels.c_str());

	bool found = false;
	for (char * token = strtok_r(buffer, delims, &state); token; token =
			strtok_r(NULL, delims, &state)) {
		const char * rangeSep = strchr(token, '-');
		if (rangeSep == NULL) {
			// single channel
			if (atoi(token) == number) {
				found = true;
			}
		} else {
			// channel range
			int start = atoi(token);
			while (*rangeSep && *rangeSep == '-')
				rangeSep++;
			int end = *rangeSep ? atoi(rangeSep) : INT_MAX;

			if (start <= number && number <= end) {
				found = true;
			}
		}
	}
//Bug #1236
	free(buffer);

	return found;
}

bool cHelpers::IsWantedTime(time_t when, cEvent * event) {

	time_t startTime = event->StartTime();
	time_t stopTime = startTime + event->Duration();

	if (when == 0) {
		return stopTime >= time(0);
	}

	return startTime <= when && when < stopTime;
}

string cHelpers::ToUpper(string text) {
	for (unsigned i = 0; i < text.length(); i++) {
		if (islower(text[i]))
			text[i] = toupper(text[i]);
	}

	return text;
}

string cHelpers::ToLower(string text) {
	for (unsigned i = 0; i < text.length(); i++) {
		if (isupper(text[i]))
			text[i] = tolower(text[i]);
	}

	return text;
}

string cHelpers::Trim(string str) {
	int a = str.find_first_not_of(" \t");
	int b = str.find_last_not_of(" \t");
	if (a == -1)
		a = 0;
	if (b == -1)
		b = str.length() - 1;
	return str.substr(a, (b - a) + 1);
}

string cHelpers::SafeCall(string (*f)()) {
// loop, if vdr modified list and we crash
	for (int i = 0; i < 3; i++) {
		try {
			return f();

		} catch (exception &ex) {
			esyslog("[vdrmanager] catch an exception: %s", ex.what());
		} catch (...) {
			esyslog("[vdrmanager] catch an exception");
			usleep(100);
		}
	}

	return "";
}

string cHelpers::SafeCall(string (*f)(string arg), string arg) {
// loop, if vdr modified list and we crash
	for (int i = 0; i < 3; i++) {
		try {
			return f(arg);
		} catch (const exception& ex) {
			esyslog("[vdrmanager] catch an exception 1: %s", ex.what());
		} catch (...) {
			esyslog("[vdrmanager] catch an exception 1");
			usleep(100);
		}
	}

	return "";
}

string cHelpers::SafeCall(string (*f)(string arg1, string arg2), string arg1,
		string arg2) {
// loop, if vdr modified list and we crash
	for (int i = 0; i < 3; i++) {
		try {
			return f(arg1, arg2);
		} catch (exception &ex) {
			esyslog("[vdrmanager] catch an exception 2: %s", ex.what());
		} catch (...) {
			esyslog("[vdrmanager] catch an exception 2");
			usleep(100);
		}
	}

	return "";
}
string cHelpers::MapSpecialChars(cString text) {

	return MapSpecialChars((const char *) text);
}

string cHelpers::MapSpecialChars(const string text) {
	return MapSpecialChars(text.c_str());
}

string cHelpers::MapSpecialChars(const char * p) {

//const char * p = text.c_str();
	string result = "";
	while (*p) {
		switch (*p) {
		case ':':
			result += "|##";
			break;
		case '\r':
			break;
		case '\n':
			result += "||#";
			break;
		default:
			result += *p;
			break;
		}
		p++;
	}
	return result;
}

//from live plugin StringReplace
string cHelpers::replaceAll(string const& text, string const& substring,
		string const& replacement) {
	string result = text;
	string::size_type pos = 0;
	while ((pos = result.find(substring, pos)) != string::npos) {
		result.replace(pos, substring.length(), replacement);
		pos += replacement.length();
	}
	return result;
}

string cHelpers::UnMapSpecialChars(string text) {

	string ntext = replaceAll(text, "|##", ":");
	ntext = replaceAll(ntext, "||#", "\n");

	return ntext;
}

/**
 * based on vdr-restfulapi's RecordingLengthInSeconds
 */
int cHelpers::RecordingLengthInSeconds(cRecording* recording) {
	return Duration(recording) * 60;
}

//These three methodes were stolen from vdr-restfulapi project. Thanks!
std::queue<int> cHelpers::ConvertToBinary(int v) {
	int b;
	std::queue<int> res;

	while (v != 0) {
		b = v % 2;
		res.push(b);
		v = (v - b) / 2;
	}
	return res;
}

std::string cHelpers::ConvertWeekdays(int v) {
	std::queue<int> b = cHelpers::ConvertToBinary(v);
	int counter = 0;
	std::ostringstream res;
	while (!b.empty() && counter < 7) {
		int val = b.front();
		switch (counter) {
		case 0:
			res << (val == 1 ? 'M' : '-');
			break;
		case 1:
			res << (val == 1 ? 'T' : '-');
			break;
		case 2:
			res << (val == 1 ? 'W' : '-');
			break;
		case 3:
			res << (val == 1 ? 'T' : '-');
			break;
		case 4:
			res << (val == 1 ? 'F' : '-');
			break;
		case 5:
			res << (val == 1 ? 'S' : '-');
			break;
		case 6:
			res << (val == 1 ? 'S' : '-');
			break;
		}
		b.pop();
		counter++;
	}
	while (counter < 7) {
		res << '-';
		counter++;
	}
	return res.str();
}

int cHelpers::ConvertWeekdays(std::string v) {
	const char* str = v.c_str();
	int res = 0;
	if (str[0] == 'M')
		res += 64;
	if (str[1] == 'T')
		res += 32;
	if (str[2] == 'W')
		res += 16;
	if (str[3] == 'T')
		res += 8;
	if (str[4] == 'F')
		res += 4;
	if (str[5] == 'S')
		res += 2;
	if (str[6] == 'S')
		res += 1;
	return res;
}