summaryrefslogtreecommitdiff
path: root/smarttvfactory.c
blob: 10af7c430a05540c7a7ed5579bb6452efcdaba99 (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
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
 /*
 * smarttvfactory.c: VDR on Smart TV plugin
 *
 * Copyright (C) 2012 - 2016 T. Lohmar
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 * Or, point your browser to http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 *
 */

#ifndef STANDALONE
#include <vdr/recording.h>
#include <vdr/videodir.h>
#endif

#include <iostream>

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netdb.h>
#include <fcntl.h>
#include <errno.h>
#include <dirent.h>

#include <iostream>
#include <fstream>
#include <sstream>

#include "smarttvfactory.h"
#include "httpresource.h"
#include "httpclient.h"
#include "url.h"

#include "responselive.h"

#ifndef STANDALONE
#define PORT 8000
#else
#define PORT 9000
#endif

#define OKAY 0
#define ERROR (-1)

#define DEBUG


using namespace std;

void SmartTvServerStartThread(void* arg) {
  SmartTvServer* m = (SmartTvServer*)arg;
  m->threadLoop();
  delete m;
  pthread_exit(NULL);
}

cCmd::cCmd(string t) :mTitle(), mCommand(), mConfirm(false) {
  // find column
 
  mTitle = t.substr(0, t.find(':'));
  trim(mTitle);
  if (mTitle[mTitle.size()-1] == '?') {
    mConfirm =true;
    mTitle.erase(mTitle.end()-1);
    trim(mTitle);
  }
  mTitle = cUrlEncode::doXmlSaveEncode(mTitle);

  mCommand = t.substr(t.find(':')+1);
  trim(mCommand);
};

void cCmd::trim(string &t) {
  int m=0;
  for (uint i=0; i<t.size(); i++) 
    if (!((t[i] == 32) || (t[i] == 9)) ) {
      m =i;
      break;
    }
  t.erase(0, m);
  
  m = t.size() -1;
  for (int i= t.size()-1; i >=0; i--)
    if (!((t[i] == 32) || (t[i] == 9)) ) {
      m= i;
      break;
    }
  t.erase(m+1);
}


void cRecEntryBase::print(string pref) {
  *(mLog->log()) << pref 
		 << ": l= " << mLevel 
    		 << " B= " << mName 
		 << endl;
};

void cRecEntry::print(string pref) {
  *(mLog->log()) << pref 
		 << ": l= " << mLevel 
		 << " sfs= " << mSubfolders.size()
		 << " E= " << mTitle
		 << endl;
};

void cRecFolder::print(string pref) {
  *(mLog->log()) << pref 
		 << ": l= " << mLevel 
		 << " es= " << mEntries.size()
		 << " F= " << mName 
		 << endl;
  for (list<cRecEntryBase*>::iterator iter = mEntries.begin(); iter != mEntries.end(); ++iter)
    (*iter)->print(pref + "+" + mName);
    
};

#if APIVERSNUM > 20300
cRecEntry::cRecEntry(string n, int l, Log* lg, const cRecording* r) : cRecEntryBase(n, l, false, lg), mRec(r), mSubfolders(), 
  mError(false), mTitle(n)  {
#else
cRecEntry::cRecEntry(string n, int l, Log* lg, cRecording* r) : cRecEntryBase(n, l, false, lg), mRec(r), mSubfolders(), 
  mError(false), mTitle(n)  {
#endif

  size_t pos = 0;
  size_t l_pos = 0;
  for (int i = 0; i <= l; i++) {
    if (l_pos == string::npos) {
      *(mLog->log()) << mLog->getTimeString()
		     << " ERROR: " 
		     << " Name= " << n
		     << endl;
      mError = true;
      break;
    }
    pos = n.find('~', l_pos);
    string dir = n.substr(l_pos, (pos -l_pos));

    /*
    *(mLog->log()) << " (p= " << pos
		   << " l= " << l_pos
		   << " d= " << dir
		   << ")"; 
*/
    mSubfolders.push_back(dir);
    
    l_pos = pos +1;
  } 
  //  *(mLog->log()) << endl; 

  *(mLog->log()) << mLog->getTimeString()
		 << " L= " << mLevel << " " << l
		 << " SFs= " << mSubfolders.size()
		 << " FName= " << mName
		 << endl;

  int idx = mSubfolders.size() -1;
  if (idx != l) {
    *(mLog->log()) << mLog->getTimeString()
		   << " ERROR: mName= " << mName
		   << " Level (" << l
		   << ") missmatches subfolders (" << mSubfolders.size()
		   << ")"
		   << endl;
  }
  else
    mName = mSubfolders[idx];
}

int cRecEntry::writeXmlItem(string * msg, string own_ip, int own_port) {
  string hdr = "";
  char f[400];

  hdr += "<item>\n";
  hdr += "<title>" + mTitle +"</title>\n";
  hdr += "<isfolder>false</isfolder>\n";

  snprintf(f, sizeof(f), "http://%s:%d%s", own_ip.c_str(), own_port,
	   cUrlEncode::doUrlSaveEncode(mRec->FileName()).c_str());

  string mime = "video/mpeg";
  string programme = "NA";
  string desc = "NA";
  int no = -1;

  hdr += "<enclosure url=\"";
  hdr += f;
  hdr += "\" type=\""+mime+"\" />\n";

  hdr += "<guid>" + cUrlEncode::doUrlSaveEncode(mRec->FileName()) + "</guid>\n";
  
  snprintf(f, sizeof(f), "%d", no);
  hdr += "<number>";
  hdr += f;
  hdr += "</number>\n";
  hdr += "<programme>" + programme +"</programme>\n";
  hdr += "<description>" + desc + "</description>\n";

  snprintf(f, sizeof(f), "%ld", mRec->Start());
  hdr += "<start>";
  hdr += f;
  hdr += "</start>\n";

  snprintf(f, sizeof(f), "%d", mRec->LengthInSeconds());
  hdr += "<duration>";

  hdr += f;
  hdr += "</duration>\n";

  snprintf(f, sizeof(f), "<fps>%.2f</fps>\n", mRec->FramesPerSecond());
  hdr += f;
  
  if (mRec->IsPesRecording())
    hdr += "<ispes>true</ispes>\n";
  else
    hdr += "<ispes>false</ispes>\n";

  if (mRec->IsNew()) 
    hdr += "<isnew>true</isnew>\n";
  else
    hdr += "<isnew>false</isnew>\n";

  hdr += "</item>\n";

  *msg += hdr;
  return 0;
}

int cRecFolder::writeXmlItem(string * msg, string own_ip, int own_port) {
  string hdr = "";

  hdr += "<item>\n";
  hdr += "<title>" + mName +"</title>\n";
  hdr += "<guid>" + cUrlEncode::doUrlSaveEncode(mPath) + "</guid>\n";

  hdr += "<isfolder>true</isfolder>\n";
  hdr += "</item>\n";

  *msg += hdr;
  return 0;
}

int cRecFolder::writeXmlFolder(string* msg, string own_ip, int own_port) {
  string hdr = "";
  hdr += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  hdr += "<rss version=\"2.0\">\n";
  hdr+= "<channel>\n";
  hdr+= "<title>VDR Recordings List</title>\n";

  *msg += hdr;

  //iter over all items
  for (list<cRecEntryBase*>::iterator iter = mEntries.begin(); iter != mEntries.end(); ++iter) {
    (*iter)->writeXmlItem(msg, own_ip, own_port);
  }

  hdr = "</channel>\n";
  hdr += "</rss>\n";
  
  *msg += hdr;

  //  *(mLog->log())<< DEBUGPREFIX << " Recording Count= " <<item_count<< endl;

  return OKAY;

}

void cRecFolder::appendEntry(cRecFolder* entry) {
  *(mLog->log()) << mLog->getTimeString() << " appendEntry "
		 << " mName= " << mName
		 << " ol= " << mLevel
		 << " Folder" 
		 << " l= " << entry->mLevel
		<< " Name= " << entry->mName  
		<< endl;
  mEntries.push_back(entry);
}


void cRecFolder::appendEntry(cRecEntry* entry) {

  // root: append to mEntries
  if (entry->mLevel == mLevel) {
    *(mLog->log()) << mLog->getTimeString() << " appendEntry "
		   << " mName= " << mName
		   << " ol= " << mLevel
		   << " Entry" 
		   << " l= " << entry->mLevel
		   << " Name= " << entry->mName  
		   << endl;

    mEntries.push_back(entry);
    return;
  }

  *(mLog->log()) << mLog->getTimeString() << " - appendEntry "
		 << " mName= " << mName
		 << " ol= " << mLevel
		 << " Entry" 
		 << " l= " << entry->mLevel
		 << " sf= " << (entry->mSubfolders).size()
		 << " f= " << entry->mSubfolders[mLevel]
		 << " Name= " << entry->mName  
		 << endl;
  
  // find needed subfolder
  bool found = false;
  for (list<cRecEntryBase*>::iterator iter= mEntries.begin(); iter != mEntries.end(); ++iter) {
    if (((*iter)->mName == entry->mSubfolders[mLevel]) && ((*iter)->mIsFolder)) {
      ((cRecFolder*)(*iter))->appendEntry(entry);
      found = true;
      break;
    }
  }
  if (!found) {
    string p = ((mPath == "") ? entry->mSubfolders[mLevel] : mPath + "~" + entry->mSubfolders[mLevel]);
    cRecFolder* folder = new cRecFolder(entry->mSubfolders[mLevel], p, mLevel +1, mLog);
    appendEntry(folder);
    folder->appendEntry(entry);
  }
  // check, if a subfolder is needed
}

cRecFolder* cRecFolder::GetFolder(list<string> *folder_list) {
  string name = folder_list->front();
  cRecFolder* dir = NULL;
  *(mLog->log()) << mLog->getTimeString() 
		 << " GetFolder name= " << name << endl;
  for (list<cRecEntryBase*>::iterator iter= mEntries.begin(); iter != mEntries.end(); ++iter) {
    if (((*iter)->mName == name) && ((*iter)->mIsFolder)) {
      dir = (cRecFolder*)(*iter);
      break;
    }
  }  
  if (dir != NULL) {
    folder_list->pop_front();
    if (folder_list->size() != 0)
      return dir->GetFolder(folder_list);
    else 
      return dir;
  }
  return NULL;
}

sUsageStatistics::sUsageStatistics(string fn, Log* l) : collectionDay(), clientEntry(), enabled(true), collectionWindow(3600), 
  usageStatLogFilename(fn), mLog(l) { 

  time_t rawtime; 
  time (&rawtime);
  struct tm * now = localtime (&rawtime);

  now->tm_min = 0;
  now->tm_sec = 0;
  collectionDay = mktime(now);
  
  if (fn.length() == 0)
    enabled = false;

  if (enabled) 
    *(mLog->log()) << mLog->getTimeString()
		   << ": UsageStats is enabled, StatsFile= "
		   << usageStatLogFilename
		   << " collectionWindow=" << collectionWindow
		   << endl;
  else
    *(mLog->log()) << mLog->getTimeString()
                   << ": UsageStats is disabled "
                   << endl;
};

sUsageStatistics::~sUsageStatistics() {
  writeEntries();
}

void sUsageStatistics::checkDay() {
  time_t rawtime;
  time (&rawtime);

  if ((collectionDay + collectionWindow ) > rawtime) {
    *(mLog->log()) << mLog->getTimeString()
		   << ": UsageStats - check: Still not time to write time left= " 
		   << (collectionDay + collectionWindow ) - rawtime
		   << endl;
    return;
  }

  writeEntries();

  while (collectionDay < rawtime) {
      collectionDay += collectionWindow;
  }

  // Flush and reset
  clientEntry.clear();
}

void sUsageStatistics::writeEntries() {
  ofstream ofs;
  ofs.open(usageStatLogFilename.c_str(), ios::out | ios::app);

  char timebuf [80];
  strftime(timebuf, sizeof(timebuf), "%Y-%m-%d %H:%M:%S", localtime(&collectionDay));

  *(mLog->log()) << mLog->getTimeString()
		 << ": UsageStats: "<< timebuf << " appending " << clientEntry.size() << " entries to log" << endl;

  for (uint i = 0; i < clientEntry.size(); i++) {
    ofs << timebuf << " client " << clientEntry[i].ipAddr 
	<< " Dur= " << clientEntry[i].usage 
	<< " sec Count= " << clientEntry[i].count 
	<< endl;
  }
  
  ofs.close();
}

void sUsageStatistics::addUsageInfo (string ip, double dur) {
  if (!enabled)
    return;

  checkDay();

  bool found = false;
  for (uint i = 0; i < clientEntry.size(); i++) {
    if (clientEntry[i].ipAddr == ip) {
      found = true;
      clientEntry[i].usage += dur;
      clientEntry[i].count += 1;
      *(mLog->log()) << mLog->getTimeString() 
		     << ": UsageStats: adding info for " << ip << " dur= " << dur << " sec to existing record" << endl;
      break;
    }
  }
  if (!found) {
    sUsageStatsEntry elm (ip, dur);
    *(mLog->log()) << mLog->getTimeString() 
		   << ": UsageStats: adding info for " << ip << " dur= " << dur << " sec to a new record" << endl;
    clientEntry.push_back(sUsageStatsEntry(ip, dur));
  }
}

SmartTvServer::SmartTvServer(): cStatus(), mRequestCount(0), isInited(false), serverPort(PORT), mServerFd(-1),
  mSegmentDuration(10), mHasMinBufferTime(40),  mLiveChannels(20), 
  clientList(), mConTvClients(), mRecCmds(), mCmdCmds(), mRecMsg(), mCmdMsg(), mActiveSessions(0), mHttpClientId(0), 
  mConfig(NULL), mMaxFd(0),
  mManagedUrls(NULL), mActRecordings(), mRecordings(NULL), mRecState(0), mClientBlackList(), 
  mUsageStatistics(NULL){

}


SmartTvServer::~SmartTvServer() {

  delete mRecordings;

  if (mConfig != NULL)
    delete mConfig;

  for (uint i =0; i < mRecCmds.size(); i++)
    delete mRecCmds[i];

  for (uint i =0; i < mCmdCmds.size(); i++)
    delete mCmdCmds[i];

  if (mUsageStatistics != NULL)
    delete mUsageStatistics;
}

// Status methods
void SmartTvServer::Recording(const cDevice *Device, const char *Name, const char *FileName, bool On) {
#ifndef DEBUG
  *(mLog.log()) << getTimeString() << ": SmartTvServer::Recording: Recording"  
		<< ((On) ? " started" : " stopped")
		<< endl;
#endif
  stringstream msg;  
  string name ;
  
  if (Name == NULL) {
    if (FileName == NULL) {
      *(mLog.log()) << mLog.getTimeString() << ": WARNING in SmartTvServer::Recording: Name and FileName are NULL. Return.  " << endl;
      return;
    }

#if APIVERSNUM > 20300
    LOCK_RECORDINGS_READ;
    const cRecording* rec = Recordings->GetByName(FileName);
#else
    cThreadLock RecordingsLock(&Recordings);
    cRecording* rec = Recordings.GetByName(FileName);
#endif
    if (rec == NULL) {
      *(mLog.log()) << mLog.getTimeString() << ": WARNING in SmartTvServer::Recording: No Recording Entry found. Return.  " << endl;
      return;
    }
    name = rec->Name();
  }
  else 
    name = Name;

  string method = (On) ? "RECSTART" : "RECSTOP";

  // keep track of active recordings
  if (FileName != NULL) {
    if (On)
      AddActRecording(name, FileName);
    else
      DelActRecording(name, FileName);
  }

  string guid = (FileName == NULL) ? "" : cUrlEncode::doUrlSaveEncode(FileName);

  msg << "{\"type\":\""+method+"\",\"name\":\"" << name << "\",\"guid\":\""+guid+"\"}";

  *(mLog.log()) << mLog.getTimeString()
		<< ": SmartTvServer::Recording: Recording"
		<< ((On) ? " started" : " stopped")
		<< " Msg=  " << msg.str() 
		<< endl;

  
  for (uint i = 0; i < mConTvClients.size(); i ++) {
    if ((mConTvClients[i]->ip).compare("") != 0) {

      int cfd=  connectToClient(mConTvClients[i]->ip, mConTvClients[i]->lastKeepAlive);
      if (cfd < 0) 
	continue;
      addHttpResource(cfd, new cHttpInfoClient(cfd, mHttpClientId, serverPort, this, mConTvClients[i]->ip, msg.str()));
    }
  }
};

  //TODO: Store active recordings in a Database
  // The database should contain only active recordings
  // database for active recordings: entry is FileName (i.e. guid)
  // store only, when FileName is not NULL 

void SmartTvServer::AddActRecording(string n, string fn) {
  mActRecordings.push_back(new cActiveRecording(n, fn));
  *(mLog.log()) << mLog.getTimeString()
		<< " AddActRecording fn= " << fn
		<< " CurListSize= " << mActRecordings.size()
		<< endl;    
}

void SmartTvServer::DelActRecording(string n, string fn) {  
  int del_count =0;
  for (list<cActiveRecording*>::iterator itr = mActRecordings.begin(); itr != mActRecordings.end(); /*nothing*/) {
    if ((*itr)->mFilename == fn) {
        itr = mActRecordings.erase(itr);
	del_count ++;
    }
    else
      ++itr;
  }

  *(mLog.log()) << mLog.getTimeString()
		<< " DelActRecording Deleted " << n
		<< " Occurances= " << del_count
		<< " CurListSize= " << mActRecordings.size()
		<< endl;
}

bool SmartTvServer::IsActRecording(string fn) {
  for (list<cActiveRecording*>::iterator itr = mActRecordings.begin(); itr != mActRecordings.end(); ++itr) {
    if ((*itr)->mFilename == fn) {
      return true;
    }
  }
  return false;
}

//thlo: Try to clean up
void SmartTvServer::pushToClients(cHttpResourceBase* resource) {
  for (uint i = 0; i < mConTvClients.size(); i ++) {
    if ((mConTvClients[i]->ip).compare("") != 0) {
      
      int cfd=  connectToClient(mConTvClients[i]->ip, mConTvClients[i]->lastKeepAlive);
      if (cfd < 0) 
	continue;
      addHttpResource(cfd, resource);
    }
  }
}


void SmartTvServer::TimerChange(const cTimer *Timer, eTimerChange Change) {
 #ifndef DEBUG
  *(mLog.log()) << mLog.getTimeString() << ": SmartTvServer::TimerChange" 
		<< endl;
#endif

  stringstream msg;
  string method = "";
  switch (Change) {
  case tcMod:
    method = "TCMOD";
    break;
  case tcAdd:
    method = "TCADD";
    break;
  case tcDel:
    method = "TCDEL";
    break;
  }


  if (Timer == NULL) {
    *(mLog.log()) << mLog.getTimeString() << ": WARNING in SmartTvServer::TimerChange - Timer is NULL. Method= " << method << ", returning" << endl;
    return;
  }

  string name = Timer->File();  
  if (Timer->Event() != NULL) {
    if (Timer->Event()->Title() != NULL)
      name = Timer->Event()->Title();
  }


  msg << "{\"type\":\"" << method << "\",\"name\":\"" << name << "\", \"start\":" << Timer->Start() <<"}";

#ifndef DEBUG
  *(mLog.log()) << mLog.getTimeString() << ": SmartTvServer::TimerChange: Msg=  " << msg.str() << endl;
#endif

  for (uint i = 0; i < mConTvClients.size(); i ++) {
    if ((mConTvClients[i]->ip).compare("") != 0) {
      int cfd=  connectToClient(mConTvClients[i]->ip, mConTvClients[i]->lastKeepAlive);
      if (cfd < 0) 
	continue;
      addHttpResource(cfd, new cHttpInfoClient(cfd, mHttpClientId, serverPort, this, mConTvClients[i]->ip, msg.str()));
    }
  } 
}

void SmartTvServer::OsdStatusMessage(const char *Message) {
  *(mLog.log()) << mLog.getTimeString() << ": SmartTvServer::OsdStatusMessage: Msg=  " << ((Message != NULL) ? Message : "") << endl;

  if (Message == NULL)
    return;

  string msg = Message;

  for (uint i = 0; i < mConTvClients.size(); i ++) {
    if ((mConTvClients[i]->ip).compare("") != 0) {
      int cfd=  connectToClient(mConTvClients[i]->ip, mConTvClients[i]->lastKeepAlive);
      if (cfd < 0) 
	continue;
      addHttpResource(cfd, new cHttpMesgPushClient(cfd, mHttpClientId, serverPort, this, mConTvClients[i]->ip, msg));
    }
  } 
}

void SmartTvServer::cleanUp() {
  // close listening ports
  
  for (list<cHttpResourceBase*>::iterator iter = clientList.begin(); iter != clientList.end();) {
    close((*iter)->mFd);
    delete *iter;
    iter = clientList.erase(iter);
  }

  // close server port
  close(mServerFd);

  // Leave thread
  pthread_cancel(mThreadId);
  pthread_join(mThreadId, NULL);

  mLog.shutdown();
}


void SmartTvServer::updateTvClient(string ip, string mac, time_t upd) {

  bool found = false;
  for (uint i = 0; i < mConTvClients.size(); i++) {
    if (mConTvClients[i]->mac ==  mac) {
      *(mLog.log()) << mLog.getTimeString() << ": SmartTvServer::updateTvClient: Found Entry for Mac= " << mac
		    << endl;
      found = true;
      mConTvClients[i]->ip = ip;
      mConTvClients[i]->lastKeepAlive = upd;
      break;
    }
  }
  if (found == false) {
    *(mLog.log()) << mLog.getTimeString() << ": SmartTvServer::updateTvClient: Append Entry for Mac= " << mac
		  << endl;
    sClientEntry * entry = new sClientEntry(mac, ip, upd);
    mConTvClients.push_back(entry);
  }
};

void SmartTvServer::removeTvClient(string ip, string mac, time_t upd) {
  // remove client with mac from list
  bool found = false;
  vector<sClientEntry*>::iterator iter;
  for (iter = mConTvClients.begin() ; iter != mConTvClients.end(); ++iter)
    if ((*iter)->mac == mac) {
      found = true;
      *(mLog.log()) << mLog.getTimeString() << ": SmartTvServer::removeTvClient: Found Entry for Mac= " << mac
		    << endl;
      iter = mConTvClients.erase(iter);
      break;
    }
      
  if (!found ) {
    *(mLog.log()) << mLog.getTimeString() << ": SmartTvServer::removeTvClient: No entry for Mac= " << mac
		  << " found"
		  << endl;
  }
}

cManageUrls* SmartTvServer::getUrlsObj() { 
  if (mManagedUrls == NULL)
    mManagedUrls = new cManageUrls(mConfigDir);

  return mManagedUrls;
};

void SmartTvServer::storeYtVideoId(string guid) {
  if (mManagedUrls == NULL)
    mManagedUrls = new cManageUrls(mConfigDir);

  mManagedUrls->appendEntry("YT", guid);
}

bool SmartTvServer::deleteYtVideoId(string guid) {
  if (mManagedUrls == NULL)
    mManagedUrls = new cManageUrls(mConfigDir);

  return mManagedUrls->deleteEntry("YT", guid);
}



void SmartTvServer::pushYtVideoId(string vid_id, bool store) {
  //  time_t now =  time(NULL);
  for (uint i = 0; i < mConTvClients.size(); i ++) {
    if ((mConTvClients[i]->ip).compare("") != 0) {
      //      pushYtVideoIdToClient(vid_id, mConTvClients[i]->ip, store);
      int cfd=  connectToClient(mConTvClients[i]->ip, mConTvClients[i]->lastKeepAlive);
      if (cfd < 0)
	return;
      addHttpResource(cfd, new cHttpYtPushClient(cfd, mHttpClientId, serverPort, this, mConTvClients[i]->ip, vid_id, store));
    }
  }
}



int SmartTvServer::connectToClient(string peer, time_t last_update) {
  if ((time(NULL) - last_update) > 60) {
    *(mLog.log()) << mLog.getTimeString() << ": SmartTvServer::connectToClient: expired client= " << peer << endl;
    return -1;
  }
  *(mLog.log()) << mLog.getTimeString() << ": SmartTvServer::connectToClient: client= " << peer << endl;

  int cfd; 
  struct sockaddr_in server; 
  cfd = socket(AF_INET, SOCK_STREAM, 0); 

  if (cfd <0) { 
    *(mLog.log()) << mLog.getTimeString() << ": Error: Cannot create client socket" << endl;
    return -1; 
  }
  
  memset((char *) &server, 0, sizeof(server));
  server.sin_family = AF_INET; 
  server.sin_port = htons(80);
  server.sin_addr.s_addr =inet_addr(peer.c_str());

  setNonBlocking(cfd);

  if (connect(cfd, (const struct sockaddr *) &server, sizeof(struct sockaddr_in)) <0) { 
    if (errno != EINPROGRESS) {
      *(mLog.log()) << mLog.getTimeString() << ": Error while connecting" << endl; 
      return -1; 
    }
    else
      *(mLog.log()) << mLog.getTimeString() << ": Connecting" << endl; 
  }
  return cfd;
}


void SmartTvServer::addHttpResource(int rfd, cHttpResourceBase* resource) {

  FD_SET(rfd, &mReadState);       
  FD_SET(rfd, &mWriteState);      
  clientList.push_back(resource);
  
  mHttpClientId++;
  if (rfd > mMaxFd) {
    mMaxFd = rfd;
  }    
  mActiveSessions ++;
}

void SmartTvServer::pushCfgServerAddressToTv( string tv_addr) {
  *(mLog.log()) << mLog.getTimeString() << ": SmartTvServer::pushCfgServerAddressToTv TV= " << tv_addr 
		<< endl;
  
  int cfd=  connectToClient(tv_addr, time(NULL));
  if (cfd < 0)
    return;
  addHttpResource(cfd, new cHttpCfgPushClient(cfd, mHttpClientId, serverPort, this, tv_addr));
}

int SmartTvServer::runAsThread() {
  int res = pthread_create(&mThreadId, NULL, (void*(*)(void*))SmartTvServerStartThread, (void *)this);
  if (res != 0) {
    *(mLog.log()) << mLog.getTimeString() << ": Error creating thread. res= " << res 
		  << endl;
    return 0;
  } 
  return 1;
}

void SmartTvServer::threadLoop() {
  *(mLog.log()) << mLog.getTimeString() << ": SmartTvServer Thread Started " << endl;

  loop();

  *(mLog.log()) << mLog.getTimeString() << ": SmartTvServer Thread Stopped "  << endl;
}

//---------------------------------------------------
void SmartTvServer::setNonBlocking(int fd) {
  int oldflags = fcntl(fd, F_GETFL, 0);
  oldflags |= O_NONBLOCK;
  fcntl(fd, F_SETFL, oldflags);
}

void SmartTvServer::clrWriteFlag(int fd) {
  FD_CLR(fd, &mWriteState);
}

void SmartTvServer::setWriteFlag(int fd) {
  FD_SET(fd, &mWriteState);      
}

int SmartTvServer::openPipe() {
  int pipefd[2];

  //  if (pipe2(pipefd, O_NONBLOCK) == -1) {
  if (pipe(pipefd) == -1) {
    return 0;
  }
  setNonBlocking(pipefd[0]);
  setNonBlocking(pipefd[1]);

  *(mLog.log()) << mLog.getTimeString() << ": SmartTvServer::openPipe pipefd[0]= " << pipefd[0] 
		<< " pipefd[1]= " << pipefd[1] << endl;

  addHttpResource(pipefd[0], new cHttpResourcePipe(pipefd[0], this));
  return pipefd[1];
}

list<cHttpResourceBase*>::iterator SmartTvServer::closeHttpResource(list<cHttpResourceBase*>::iterator to_close) {
  int req_id = (*to_close)->mReqId;
  int rfd = (*to_close)->mFd;
  

  close((*to_close)->mFd);
  delete *to_close;
  list<cHttpResourceBase*>::iterator iter = clientList.erase(to_close);
  mActiveSessions--;
  *(mLog.log()) << mLog.getTimeString() << ": - Closing Session mReqId= " << req_id << endl;
  logActiveSessionIds();

  FD_CLR(rfd, &mReadState);     
  FD_CLR(rfd, &mWriteState);
  return iter;
}


void SmartTvServer::logActiveSessionIds() {
  *(mLog.log()) << mLog.getTimeString() << ": mActiveSessions= " << mActiveSessions 
		<< " size= " << clientList.size() << " ReqIds= [ ";

  for (list<cHttpResourceBase*>::iterator iter = clientList.begin(); iter != clientList.end(); ++iter) {
    *(mLog.log()) << (*iter)->mReqId << " ";
  }
  *(mLog.log()) << "]" << endl;
}

void SmartTvServer::acceptHttpResource(int &req_id) {
  int rfd = 0;
  sockaddr_in sadr;
  char ipstr[INET6_ADDRSTRLEN + 1];
  socklen_t addr_size = sizeof(sadr);

  string ip_ver = "ipv6";

  if((rfd = accept(mServerFd, (sockaddr*)&sadr, &addr_size))!= -1){
    req_id ++;

    switch (sadr.sin_family) {
    case AF_INET:
      ip_ver = "ip_v4";
      inet_ntop(AF_INET, &(sadr.sin_addr), ipstr, sizeof ipstr);      
      break;
    case AF_INET6:
      inet_ntop(AF_INET6, &(sadr.sin_addr), ipstr, sizeof ipstr);      
      break;
    default:
      ip_ver = "Unknown";
      break;
    }

    
#ifndef DEBUG
    *(mLog.log()) << mLog.getTimeString() << ": fd= " << rfd
		  << " --------------------- Received connection ---------------------" << endl;
#endif

    FD_SET(rfd, &mReadState);       
    //FD_SET(rfd, &mWriteState);      
    
    if (rfd > mMaxFd) {
      mMaxFd = rfd;
    }
    
    clientList.push_back(new cHttpResource(rfd, req_id, serverPort, ipstr, this));
    mActiveSessions ++;
    *(mLog.log()) << mLog.getTimeString() << ": + New Session mReqId= " << req_id 
		  << " ver= " << ip_ver << " " << sadr.sin_family
		  << " IP= " << ipstr
		  << endl;
    logActiveSessionIds();
  }
  else{
    *(mLog.log()) << mLog.getTimeString() << ": Error accepting " <<  errno << endl;
  }    
  
}


cRecFolder* SmartTvServer::GetRecDb() {
#if APIVERSNUM > 20300
  static cStateKey RecordingsStateKey;
  bool changed = cRecordings::GetRecordingsRead(RecordingsStateKey);
#else  
  bool changed = Recordings.StateChanged(mRecState);
#endif
  *(mLog.log()) << mLog.getTimeString()
		<< " GetRecDb Changed= " << ((changed) ? "Yes" : "No")
		<< endl;
  if (changed) {
    
    delete mRecordings;
    mRecordings = new cRecFolder(".", "", 0, &mLog);
    CreateRecDb();
  }  
  return mRecordings;
}

void SmartTvServer::CreateRecDb() {
#if APIVERSNUM > 20300
  LOCK_RECORDINGS_READ
  const cRecording *recording = Recordings->First();
#else
  cRecording *recording = Recordings.First();
#endif
  *(mLog.log()) << mLog.getTimeString() << ": CreateRecDb "
		<< " NewState= " << mRecState
		<< endl;
  
  while (recording != NULL) {
    string name = recording->Name();

    //    (mRecordings->mEntries).push_back(new cRecEntry(recording->Name(), recording->HierarchyLevels()));
    cRecEntry* entry = new cRecEntry(recording->Name(), recording->HierarchyLevels(), &mLog, recording);
    mRecordings->appendEntry(entry);
    //    (mRecordings->mEntries).appendEntry(entry, 0);

    /*
    *(mLog.log()) << mLog.getTimeString() 
		  << " L= " << recording->HierarchyLevels()
      		  << " FName= " << recording->Name() 
		  << endl;
*/    
#if APIVERSNUM > 20300
    recording = Recordings->Next(recording);
#else
    recording = Recordings.Next(recording);
#endif
  }


  *(mLog.log()) << " Summary " << endl;
  mRecordings->print("");
  
  
  *(mLog.log()) << " Summary -done " << endl;

}

void SmartTvServer::loop() {
  int req_id = 0;
  int ret = 0;
  struct timeval timeout;

  fd_set read_set;
  fd_set write_set;

  FD_ZERO(&read_set);
  FD_ZERO(&write_set);

  FD_ZERO(&mReadState);
  FD_ZERO(&mWriteState);

  FD_SET(mServerFd, &mReadState);
  mMaxFd = mServerFd;

  *(mLog.log()) << mLog.getTimeString() << ": mServerFd= " << mServerFd << endl;

  int handeled_fds = 0;

  for (;;) {                    
    FD_ZERO(&read_set);
    FD_ZERO(&write_set);
    read_set = mReadState;
    write_set = mWriteState;

    if (ret != handeled_fds) {
      // Only ok, when the server has closed a handing HTTP connection
      *(mLog.log()) << mLog.getTimeString() << ": WARNING: Select-ret= " << ret 
		    << " != handeled_fds= " << handeled_fds << endl;
    }

    handeled_fds = 0;
    timeout.tv_sec = 5;
    timeout.tv_usec = 0;

    ret = select(mMaxFd + 1, &read_set, &write_set, NULL, &timeout);
    
    if (ret == 0) {
      // timeout: Check for dead TCP connections
      for (list<cHttpResourceBase*>::iterator iter = clientList.begin(); iter != clientList.end();) {
	if ((*iter)->checkStatus() == ERROR) {
	    *(mLog.log()) << mLog.getTimeString() << ": WARNING: Timeout - Dead Client fd=" <<  (*iter)->mFd  
			  << " mReqId= " << (*iter)->mReqId << endl;
	    iter = closeHttpResource(iter);
	}
	else
	  ++iter;
      }
      continue;
    } // timeout

    if (ret < 0){
      *(mLog.log()) << mLog.getTimeString() << ": ERROR: select error errno= " <<  errno << endl;
      continue;
    } // Error

    // new accept
    if (FD_ISSET(mServerFd, &read_set)) {
      handeled_fds ++;
      acceptHttpResource(req_id);
    }

    // Check for data on already accepted connections
    for (list<cHttpResourceBase*>::iterator iter = clientList.begin(); iter != clientList.end(); ) {
      if (FD_ISSET((*iter)->mFd, &read_set)) {
	handeled_fds ++;
	int n = 0;
	ioctl((*iter)->mFd, FIONREAD, &n);
	if ( n == 0) {
	  // Nothing to read, so client has killed the connection
	  *(mLog.log()) << mLog.getTimeString() << ": fd= " << (*iter)->mFd << " mReqId= " << (*iter)->mReqId
			<< " ------ Check Read: Closing (n=0)-------" 
			<< endl;
	  
	  iter = closeHttpResource(iter);
	  continue;
	}
	if ( (*iter)->handleRead() < 0){
	  //#ifndef DEBUG
	  *(mLog.log()) << mLog.getTimeString() << ": fd= " << (*iter)->mFd 
			<< " mReqId= " << (*iter)->mReqId 
			<< " --------------------- Check Read: Closing ---------------------" 
			<< endl;
	  //#endif
	  iter = closeHttpResource(iter);
	  continue;
	}

      } // if (FD_ISSET)
      ++iter;
    }

    // Check for write
    for (list<cHttpResourceBase*>::iterator iter = clientList.begin(); iter != clientList.end();) {
      if (FD_ISSET((*iter)->mFd, &write_set)) {
	handeled_fds++;
	// HandleWrite
	if ( (*iter)->handleWrite() < 0){
	  //#ifndef DEBUG
	  *(mLog.log()) << mLog.getTimeString() << ": fd= " << (*iter)->mFd 
			<< " mReqId= " << (*iter)->mReqId 
			<< " --------------------- Check Write: Closing ---------------------" << endl;
	  //#endif
	  iter = closeHttpResource(iter);
	  continue;
	}	
      } // if (FD_ISSET)
      ++iter;
    }

  } // for (;;) 
} // org bracket

int SmartTvServer::isServing() {
  *(mLog.log()) << mLog.getTimeString() << ": SmartTvServer::isServing: mActiveSessions= " << mActiveSessions << endl;
  time_t now = time(NULL);
  bool connected_tv = false;
  for (uint i = 0; i < mConTvClients.size(); i++) {
    if ( (now - mConTvClients[i]->lastKeepAlive) < 60) {
      *(mLog.log()) << mLog.getTimeString() << ": SmartTvServer::isServing: Found a connected TV: mac= " << mConTvClients[i]->mac 
		    << " ip=" << mConTvClients[i]->ip  << endl;
      connected_tv = true;
      break;
    } 
  }
  return (mActiveSessions != 0 ? true : false) or connected_tv;
}

int SmartTvServer::getActiveHttpSessions() {
  return mActiveSessions;
}

string SmartTvServer::processNestedItemList(string pref, cList<cNestedItem> *cmd, vector<cCmd*> *cmd_list) {
  char f[400];
  string msg ="";

  for (cNestedItem *c = cmd->First(); c; c = cmd->Next(c)) {
    if (c->SubItems()) {
      cCmd *itm = new cCmd(c->Text());
      msg += processNestedItemList( pref+itm->mTitle+"~", c->SubItems(), cmd_list);
      delete itm;
    }
    else {
      cCmd *itm = new cCmd(c->Text());

      cmd_list->push_back(itm);
      snprintf(f, sizeof(f), "<item cmd=\"%zu\" confirm=\"%s\">%s</item>\n", cmd_list->size()-1, ((itm->mConfirm)?"true":"false"), 
	       (pref + itm->mTitle).c_str());
      msg += f;
    }
  }

  return msg;
}

void SmartTvServer::initRecCmds() {
  mRecMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  mRecMsg += "<reccmds>\n";
  mRecMsg += processNestedItemList("", &RecordingCommands, &mRecCmds);
  mRecMsg += "</reccmds>\n";

  *(mLog.log()) << mLog.getTimeString() << ": reccmds.conf parsed" << endl;
}

void SmartTvServer::initCmdCmds() {
  mCmdMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  mCmdMsg += "<cmdcmds>\n";
  mCmdMsg += processNestedItemList("", &Commands, &mCmdCmds);
  mCmdMsg += "</cmdcmds>\n";

  *(mLog.log()) << mLog.getTimeString() << ": commands.conf parsed" << endl;
}


void SmartTvServer::initServer(string dir, cSmartTvConfig* cfg) {
  /* This function initialtes the listening socket for the server
   * and sets isInited to true
   */
  esyslog("SmartTvWeb: initServer dir= %s", dir.c_str());
  mConfigDir = dir;
  int ret;
  struct sockaddr_in sock;
  int yes = 1;

#ifndef STANDALONE
  //  mConfig = new cSmartTvConfig(dir); 
  mConfig = cfg;
  mConfig->Initialize(dir);
  serverPort = mConfig->getServerPort();
  mLog.init(mConfig->getLogFile());

  *(mLog.log()) << mLog.getTimeString() << ": LogFile= " << mConfig->getLogFile() << endl;

  initRecCmds();
  initCmdCmds();
 
#else
  mConfig = new cSmartTvConfig("."); 
  mLog.init(mConfig->getLogFile());
  esyslog ("SmartTvWeb: Logfile created");
  esyslog ("SmartTvWeb: Listening on port= %d", PORT);

#endif

  mRecordings = new cRecFolder(".", "", 0, &mLog);

  mConfig->printConfig();

  mSegmentDuration= mConfig->getSegmentDuration();
  mHasMinBufferTime= mConfig->getHasMinBufferTime();
  mLiveChannels = mConfig->getLiveChannels();

  //mUsageStatistics = new sUsageStatistics("/multimedia/video/usage.txt", &mLog);
  mUsageStatistics = new sUsageStatistics(mConfig->getUsageStatsLogFile(), &mLog);

  *(mLog.log()) << mLog.getTimeString() <<": HTTP server listening on port " <<  serverPort << endl;

  mServerFd = socket(PF_INET, SOCK_STREAM, 0);
  if (mServerFd <0) {
    *(mLog.log()) << mLog.getTimeString() << ": Error: Cannot create serving socket, exit" << endl;
    exit(1); 
  }

  ret = setsockopt(mServerFd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
  if (ret <0) {
    *(mLog.log()) << mLog.getTimeString() << ": Error: Cannot set sockopts on serving socket, exit" << endl;
    exit(1); 
  }

  memset((char *) &sock, 0, sizeof(sock));
  sock.sin_family = AF_INET;

  if (mConfig->getServerAddress() == "")
    sock.sin_addr.s_addr = htonl(INADDR_ANY);
  else {
    *(mLog.log()) << mLog.getTimeString() << ": Binding Server to " << mConfig->getServerAddress() << endl;
    sock.sin_addr.s_addr = inet_addr(mConfig->getServerAddress().c_str());
  }
  sock.sin_port = htons(serverPort);

  ret = bind(mServerFd, (struct sockaddr *) &sock, sizeof(sock));
  if (ret !=0) {
    *(mLog.log()) << mLog.getTimeString() << ": Error: Cannot bind serving socket, exit" << endl;
    exit(1); 
  }
  
  /*
  struct ifreq ifr;

  ifr.ifr_addr.sa_family = AF_INET;
  strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);
  ioctl(mServerFd, SIOCGIFADDR, &ifr);
  string own_ip = inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr);
  *(mLog.log()) << " own if ip= " << own_ip << endl; 
*/

  ret = listen(mServerFd, 5);
  if (ret <0) {
    *(mLog.log()) << mLog.getTimeString() << ": Error: Cannot set listening on serving socket, exit" << endl;
    exit(1); 
  }

  isInited = true;
}


void SmartTvServer::addToBlackList(string c) {
  if (isBlackListed(c))
    return;
  mClientBlackList.push_back(c);
  *(mLog.log()) << mLog.getTimeString() << " addToBlackList IpAddr= " << c << endl;
}

void SmartTvServer::removeFromBlackList(string c) {
  for (list<string>::iterator it=mClientBlackList.begin(); it != mClientBlackList.end(); ++it) {
    if (*it == c) {
      mClientBlackList.erase(it);
      *(mLog.log()) << mLog.getTimeString() << " removeFromBlackList IpAddr= " << c << endl;
      break;
    }
  }  
  *(mLog.log()) << mLog.getTimeString() << " removeFromBlackList IpAddr= " << c  << " Failed" << endl;
}

bool SmartTvServer::isBlackListed(string c) {
  for (list<string>::iterator it=mClientBlackList.begin(); it != mClientBlackList.end(); ++it) {
    if (*it == c) {
      return true;
    }
  }
  return false;
}

list<string> *SmartTvServer::getBlackList() {
  return &mClientBlackList;
}