-
Notifications
You must be signed in to change notification settings - Fork 0
/
WimTiVoServer.cpp
2782 lines (2717 loc) · 127 KB
/
WimTiVoServer.cpp
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
/////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2020 William C Bonner
/////////////////////////////////////////////////////////////////////////////
// WimTiVoServer.cpp : Defines the entry point for the console application.
//
// Other Things to look at:
// StreamBaby http://code.google.com/p/streambaby/
// TiVoStream http://code.google.com/p/tivostream/wiki/native_video_formats
// http://www.tivocommunity.com/tivo-vb/showthread.php?t=403066
// TiVoSDKs .Net Libraries http://code.google.com/p/tivo-sdks/source/browse/trunk/Tivo.Hme/Tivo.Hmo/Calypso16.cs?spec=svn112&r=112
// TiVoServer http://tivoserver.cvs.sourceforge.net/viewvc/tivoserver/tivoserver/BeaconManager.cc?revision=1.16&view=markup
// TiVo Disk Space Viewer http://peterkellner.net/2008/01/18/tivospaceviewerwithlinq/
// According to this page, the TiVo times are HEX encoded seconds since January 1, 1970 0:00:00 UTC. http://www.tivocommunity.com/tivo-vb/archive/index.php/t-314742.html
// http://porkrind.org/missives/tivo-desktop-on-linux/ is somethign useful I found after resetting my TiVo too many times.
// ffmpeg getting started: http://ffmpeg.org/trac/ffmpeg/wiki/Using%20libav*
// some possible settings info: http://pytivo.sourceforge.net/forum/hd-tivo-ideal-settings-t40.html
// Logon to Tivo with username: "tivo" password: MAK
// STL Reference I like to use: http://cplusplus.com/reference/fstream/ofstream/ofstream/
// I'm going to try to use XMLLite for XML Processing. http://msdn.microsoft.com/en-us/library/windows/desktop/ms752864(v=vs.85).aspx
// XMLLite processes IStream objects.
// Is an MSDN article that I want to read more fully. I think it'll have good shortcuts for proper ways of dealing with IStreams. http://msdn.microsoft.com/en-us/magazine/cc163436.aspx#S5
// SHCreateMemStream function http://msdn.microsoft.com/en-us/library/windows/desktop/bb773831(v=vs.85).aspx
// SHCreateStreamOnFile function http://msdn.microsoft.com/en-us/library/windows/desktop/bb759864(v=vs.85).aspx
// Smart Pointer Reference: http://msdn.microsoft.com/en-us/library/hh279674.aspx
// WinINet vs. WinHTTP: http://msdn.microsoft.com/en-us/library/windows/desktop/hh227298(v=vs.85).aspx
// robocopy c:\Users\Wim\Downloads\ffmpeg-20130318-git-519ebb5-win64-shared\bin $(TargetDir) *.dll
// robocopy c:\Users\Wim\Downloads\ffmpeg-20130318-git-519ebb5-win64-shared\bin c:\Users\Wim\Documents\ss\WimTiVoServer\x64\Release *.dll
// robocopy c:\Users\Wim\Downloads\ffmpeg-20130318-git-519ebb5-win64-shared\bin c:\Users\Wim\Documents\ss\WimTiVoServer\x64\Debug *.dll
// Here are some FFMPEG command lines used by pyTiVo to transfer files to the tivo: (The first was the only 1080i wtv file)
// ffmpeg.exe -i D:\RECORD~1\Grimm_KINGDT_2013_03_15_21_00_00.wtv -vcodec copy -b 8922k -maxrate 30000k -bufsize 4096k -ab 448k -ar 48000 -acodec copy -map 0:1 -map 0:0 -report -f vob -
// "D:\\pytivo\\bin\\ffmpeg.exe" -i "D:\\Videos\\TAKEN_2\\Taken_2_t00.mkv" -vcodec copy -b 6726k -maxrate 30000k -bufsize 4096k -ab 448k -ar 48000 -acodec copy -map 0:0 -map 0:1 -report -f vob -
// "D:\\pytivo\\bin\\ffmpeg.exe" -i "D:\\Videos\\archer\\Archer.2009.S03E12.HDTV.x264.mp4" -vcodec mpeg2video -b 16384k -maxrate 30000k -bufsize 4096k -ab 448k -ar 48000 -acodec ac3 -copyts -map 0:0 -map 0:1 -report -f vob -
// "D:\\pytivo\\bin\\ffmpeg.exe" -i "D:\\Videos\\THE_INTOUCHABLES\\THE_INTOUCHABLES_t08.mkv" -vcodec copy -b 7017k -maxrate 30000k -bufsize 4096k -ab 448k -ar 48000 -acodec copy -map 0:0 -map 0:1 -report -f vob -
// This one managed to encode the subtitles from the DVD correctly, but the image quality was poor
// "c:\\Users\\Wim\\Downloads\\ffmpeg-20130306-git-28adecf-win64-static\\bin\\ffmpeg.exe" -report -i THE_INTOUCHABLES_t08.mkv -filter_complex "[0:0][0:2]overlay" -acodec copy THE_INTOUCHABLES.vob
// This one I copied some of the commands from the pyTiVo examples and it came out looking pretty good.
// "c:\\Users\\Wim\\Downloads\\ffmpeg-20130306-git-28adecf-win64-static\\bin\\ffmpeg.exe" -report -i THE_INTOUCHABLES_t08.mkv -vcodec mpeg2video -b 16384k -maxrate 30000k -bufsize 4096k -ab 448k -ar 48000 -filter_complex "[0:0][0:2]overlay" -acodec copy THE_INTOUCHABLES.vob
// "c:\\Users\\Wim\\Downloads\\ffmpeg-20130306-git-28adecf-win64-static\\bin\\ffmpeg.exe" -report -i THE_INTOUCHABLES_t08.mkv -vcodec mpeg2video -b 16384k -maxrate 30000k -bufsize 4096k -ab 448k -ar 48000 -filter_complex "[0:0][0:2]overlay" -acodec copy -sn THE_INTOUCHABLES.mkv
// ffmpeg.exe -report -i \\Acid\Videos\LIFE_OF_PI\Life_of_Pi_t00.mkv -vcodec mpeg2video -b 16384k -maxrate 30000k -bufsize 4096k -ab 448k -ar 48000 -filter_complex "[0:0][0:7]overlay" -acodec copy -sn \\Acid\TiVo\Life_of_Pi.mkv
// Here's an experiment in making a decent quality file for the ipad with subtitles, it seemed to compare favorbly with the original.
// "c:\\Users\\Wim\\Downloads\\ffmpeg-20130318-git-519ebb5-win64-static\\bin\\ffmpeg.exe" -report -i THE_INTOUCHABLES_t08.mkv -filter_complex "[0:0][0:2]overlay" -ac 2 THE_INTOUCHABLES.mp4
#include "stdafx.h"
#include "WimTiVoServer.h"
#include "CTiVo.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// The one and only application object
CWinApp theApp;
using namespace std;
//////////////////////////////////////////////////////////////////////////////
HANDLE terminateEvent_http = NULL;
HANDLE terminateEvent_beacon = NULL;
HANDLE terminateEvent_populate = NULL;
SERVICE_STATUS_HANDLE serviceStatusHandle = NULL;
bool pauseService = false;
CWinThread * threadHandle = NULL;
SOCKET ControlSocket = INVALID_SOCKET;
bool bConsoleExists = false;
HANDLE ApplicationLogHandle = NULL;
cTiVoServer myServer;
CCriticalSection ccTiVoFileListCritSec;
std::vector<cTiVoFile> TiVoFileList;
enum TiVoFileListSortOrder {
CaptureDateReverse, // !CaptureDate
Title, // Title
CaptureDate,
TitleReverse
};
TiVoFileListSortOrder CurrentTiVoFileListSortOrder = CaptureDateReverse;
std::map<std::string, CString> TiVoSerialMap;
/////////////////////////////////////////////////////////////////////////////
#pragma comment(lib, "version")
CString GetFileVersion(const CString & filename, const int digits = 4)
{
CString rval;
// get The Version number of the file
DWORD dwVerHnd = 0;
DWORD nVersionInfoSize = ::GetFileVersionInfoSize((LPTSTR)filename.GetString(), &dwVerHnd);
if (nVersionInfoSize > 0)
{
UINT *puVersionLen = new UINT;
LPVOID pVersionInfo = new char[nVersionInfoSize];
BOOL bTest = ::GetFileVersionInfo((LPTSTR)filename.GetString(), dwVerHnd, nVersionInfoSize, pVersionInfo);
// Pull out the version number
if (bTest)
{
LPVOID pVersionNum = NULL;
bTest = ::VerQueryValue(pVersionInfo, _T("\\"), &pVersionNum, puVersionLen);
if (bTest)
{
DWORD dwFileVersionMS = ((VS_FIXEDFILEINFO *)pVersionNum)->dwFileVersionMS;
DWORD dwFileVersionLS = ((VS_FIXEDFILEINFO *)pVersionNum)->dwFileVersionLS;
switch (digits)
{
default:
case 4:
rval.Format(_T("%d.%d.%d.%d"), HIWORD(dwFileVersionMS), LOWORD(dwFileVersionMS), HIWORD(dwFileVersionLS), LOWORD(dwFileVersionLS));
break;
case 3:
rval.Format(_T("%d.%d.%d"), HIWORD(dwFileVersionMS), LOWORD(dwFileVersionMS), HIWORD(dwFileVersionLS));
break;
case 2:
rval.Format(_T("%d.%d"), HIWORD(dwFileVersionMS), LOWORD(dwFileVersionMS));
break;
case 1:
rval.Format(_T("%d"), HIWORD(dwFileVersionMS));
}
}
}
delete puVersionLen;
delete [] pVersionInfo;
}
return(rval);
}
/////////////////////////////////////////////////////////////////////////////
CString FindEXEFromPath(const CString & csEXE)
{
CString csFullPath;
//PathFindOnPath();
CFileFind finder;
if (finder.FindFile(csEXE))
{
finder.FindNextFile();
csFullPath = finder.GetFilePath();
finder.Close();
}
else
{
TCHAR filename[MAX_PATH];
unsigned long buffersize = sizeof(filename) / sizeof(TCHAR);
// Get the file name that we are running from.
GetModuleFileName(AfxGetResourceHandle(), filename, buffersize );
PathRemoveFileSpec(filename);
PathAppend(filename, csEXE);
if (finder.FindFile(filename))
{
finder.FindNextFile();
csFullPath = finder.GetFilePath();
finder.Close();
}
else
{
CString csPATH;
csPATH.GetEnvironmentVariable(_T("PATH"));
int iStart = 0;
CString csToken(csPATH.Tokenize(_T(";"), iStart));
while (csToken != _T(""))
{
if (csToken.Right(1) != _T("\\"))
csToken.AppendChar(_T('\\'));
csToken.Append(csEXE);
if (finder.FindFile(csToken))
{
finder.FindNextFile();
csFullPath = finder.GetFilePath();
finder.Close();
break;
}
csToken = csPATH.Tokenize(_T(";"), iStart);
}
}
}
return(csFullPath);
}
CString ReplaceExtension(const CString & OriginalPath, const CString & NewExtension)
{
CString rVal(OriginalPath);
rVal.Truncate(rVal.ReverseFind(_T('.')));
rVal.Append(NewExtension);
while (rVal.Replace(_T(".."),_T(".")) > 0);
return(rVal);
}
/////////////////////////////////////////////////////////////////////////////
const CString QuoteFileName(const CString & Original)
{
CString csQuotedString(Original);
if (csQuotedString.Find(_T(" ")) >= 0)
{
csQuotedString.Insert(0,_T('"'));
csQuotedString.AppendChar(_T('"'));
}
return(csQuotedString);
}
/////////////////////////////////////////////////////////////////////////////
const CString GetLogFileName()
{
static CString csLogFileName;
if (csLogFileName.IsEmpty())
{
TCHAR szLogFilePath[MAX_PATH] = _T("");
SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, szLogFilePath);
std::wostringstream woss;
woss << AfxGetAppName();
time_t timer;
time(&timer);
struct tm UTC;
if (!gmtime_s(&UTC, &timer))
{
woss << "-";
woss.fill('0');
woss << UTC.tm_year + 1900 << "-";
woss.width(2);
woss << UTC.tm_mon + 1;
}
PathAppend(szLogFilePath, woss.str().c_str());
PathAddExtension(szLogFilePath, _T(".txt"));
csLogFileName = CString(szLogFilePath);
}
return(csLogFileName);
}
/////////////////////////////////////////////////////////////////////////////
void PopulateTiVoFileList(std::vector<cTiVoFile> & TiVoFileList, CCriticalSection & ccTiVoFileListCritSec, std::string FileSpec, bool Recurse = false)
{
#ifdef _DEBUG
TRACE("%s %s %s\n", CStringA(CTime::GetCurrentTime().Format(_T("[%Y-%m-%dT%H:%M:%S]"))).GetString(), __FUNCTION__, FileSpec.c_str());
std::cout << "[" << getTimeISO8601() << "] " << __FUNCTION__ << " " << FileSpec.c_str() << std::endl;
#endif
// 2020-03-18 Change to read registry each time as opposed to only on load, only write if nothing read
CString csLocalSkipExtensions;
CString csRegKey(_T("Software\\WimsWorld\\"));
csRegKey.Append(theApp.m_pszAppName);
TCHAR vData[1024];
DWORD cbData = sizeof(vData);
if (ERROR_SUCCESS == RegGetValue(HKEY_LOCAL_MACHINE, csRegKey, _T("IgnoreExt"), RRF_RT_REG_SZ, NULL, vData, &cbData))
csLocalSkipExtensions = CString(vData);
if (csLocalSkipExtensions.IsEmpty())
{
csLocalSkipExtensions = _T("txt;srt;nfo;sfv");
RegSetKeyValue(HKEY_LOCAL_MACHINE, csRegKey, _T("IgnoreExt"), REG_SZ, csLocalSkipExtensions.GetString(), csLocalSkipExtensions.GetLength() * sizeof(TCHAR) + 1);
}
CFileFind finder;
BOOL bWorking = finder.FindFile(CString(CStringA(FileSpec.c_str())));
while (bWorking)
{
bWorking = finder.FindNextFile();
if (finder.IsDots())
continue;
if (finder.IsHidden())
continue;
if (finder.IsSystem())
continue;
if (finder.IsTemporary())
continue;
if (finder.IsDirectory())
{
if (Recurse)
{
std::stringstream ss;
ss << CStringA(finder.GetFilePath()).GetString() << "\\*";
PopulateTiVoFileList(TiVoFileList, ccTiVoFileListCritSec, ss.str(), Recurse);
}
continue;
}
bool SkipExtension = false;
int iPos = 0;
CString csToken(csLocalSkipExtensions.Tokenize(_T(";"), iPos));
while (!csToken.IsEmpty())
{
if (finder.GetFileName().Right(csToken.GetLength()).CompareNoCase(csToken) == 0) // Added 2020-02-28 to ignore text files
SkipExtension = true;
csToken = csLocalSkipExtensions.Tokenize(_T(";"), iPos);
}
if (SkipExtension) // Added 2020-02-28 to ignore text files
continue;
if (finder.GetLength() > 0)
{
bool bNotInList = true;
ccTiVoFileListCritSec.Lock();
for (auto & TiVoFile : TiVoFileList)
if (!TiVoFile.GetPathName().CompareNoCase(finder.GetFilePath()))
{
CTime FinderTime;
if (finder.GetLastWriteTime(FinderTime))
if (FinderTime > TiVoFile.GetLastWriteTime())
TiVoFile.SetPathName(finder);
bNotInList = false;
break;
}
ccTiVoFileListCritSec.Unlock();
if (bNotInList)
{
cTiVoFile TiVoFile;
TiVoFile.SetPathName(finder);
if (!TiVoFile.GetSourceFormat().Left(6).CompareNoCase(_T("video/")))
{
ccTiVoFileListCritSec.Lock();
TiVoFileList.push_back(TiVoFile);
ccTiVoFileListCritSec.Unlock();
}
}
}
}
finder.Close();
}
void CleanTiVoFileList(std::vector<cTiVoFile> & TiVoFileList, CCriticalSection & ccTiVoFileListCritSec)
{
#ifdef _DEBUG
TRACE("%s %s\n", CStringA(CTime::GetCurrentTime().Format(_T("[%Y-%m-%dT%H:%M:%S]"))).GetString(), __FUNCTION__);
std::cout << "[" << getTimeISO8601() << "] " << __FUNCTION__ << std::endl;
#endif
ccTiVoFileListCritSec.Lock();
for (auto TiVoFile = TiVoFileList.begin(); TiVoFile != TiVoFileList.end(); TiVoFile++)
{
CFileStatus status;
if (!CFile::GetStatus(TiVoFile->GetPathName(), status))
{
TiVoFileList.erase(TiVoFile);
TiVoFile = TiVoFileList.begin();
}
}
ccTiVoFileListCritSec.Unlock();
}
/////////////////////////////////////////////////////////////////////////////
void printerr(TCHAR * errormsg)
{
if (bConsoleExists)
_ftprintf(stderr, _T("%s\n"), errormsg);
else if (ApplicationLogHandle != NULL)
{
LPCTSTR lpStrings[] = { errormsg, NULL };
ReportEvent(ApplicationLogHandle, EVENTLOG_INFORMATION_TYPE, 0, WIMSWORLD_EVENT_GENERIC, NULL, 1, 0, lpStrings, NULL);
}
}
int GetTiVoQueryFormats(SOCKET DataSocket, const char* InBuffer)
{
// 4.4.6 QueryFormats
// This command returns meta-data describing all the formats in which the Server is able to provide a particular type of data, and uses the following URL syntax.
// http://{machine}/TiVoConnect?Command=QueryFormats&SourceFormat={mime-type}
TRACE("%s %s\n", CStringA(CTime::GetCurrentTime().Format(_T("[%Y-%m-%dT%H:%M:%S]"))).GetString(), __FUNCTION__);
#ifdef DEBUG
if (bConsoleExists)
{
CStringA csInBuffer(InBuffer);
int pos = csInBuffer.FindOneOf("\r\n");
if (pos > 0)
csInBuffer.Delete(pos, csInBuffer.GetLength());
struct sockaddr_in adr_inet;/* AF_INET */
int sa_len = sizeof(adr_inet);
getpeername(DataSocket, (struct sockaddr*)&adr_inet, &sa_len);
std::cout << "[" << getTimeISO8601(true) << "] " << __FUNCTION__ << "\t" << inet_ntoa(adr_inet.sin_addr) << " " << csInBuffer.GetString() << endl;
}
#endif // DEBUG
int rval = 0;
char MyHostName[255] = { 0 }; // winsock hostname used for data recordkeeping
gethostname(MyHostName, sizeof(MyHostName));
char XMLDataBuff[1024 * 11];
CComPtr<IStream> spMemoryStream(::SHCreateMemStream(NULL, 0));
CComPtr<IXmlWriter> pWriter;
if (SUCCEEDED(CreateXmlWriter(__uuidof(IXmlWriter), (void**)&pWriter, NULL)))
{
pWriter->SetOutput(spMemoryStream);
pWriter->SetProperty(XmlWriterProperty_Indent, TRUE);
pWriter->WriteStartDocument(XmlStandalone_Omit);
pWriter->WriteStartElement(NULL, _T("TiVoFormats"), NULL);
pWriter->WriteStartElement(NULL, _T("Format"), NULL);
pWriter->WriteElementString(NULL, _T("ContentType"), NULL, _T("video/x-tivo-mpeg"));
pWriter->WriteElementString(NULL, _T("Description"), NULL, _T("TiVo Recording"));
pWriter->WriteEndElement();
//pWriter->WriteStartElement(NULL,_T("Format"),NULL);
// pWriter->WriteElementString(NULL, _T("ContentType"), NULL, _T("video/mpeg"));
// pWriter->WriteElementString(NULL, _T("Description"), NULL, _T("MPEG-2 Video"));
//pWriter->WriteEndElement();
pWriter->WriteStartElement(NULL, _T("Format"), NULL);
pWriter->WriteElementString(NULL, _T("ContentType"), NULL, _T("video/x-tivo-mpeg-ts"));
pWriter->WriteElementString(NULL, _T("Description"), NULL, _T("TiVo TS Recording"));
pWriter->WriteEndElement();
//pWriter->WriteStartElement(NULL,_T("Format"),NULL);
// pWriter->WriteElementString(NULL, _T("ContentType"), NULL, _T("video/x-tivo-raw-tts"));
// pWriter->WriteElementString(NULL, _T("Description"), NULL, NULL);
//pWriter->WriteEndElement();
pWriter->WriteFullEndElement();
pWriter->WriteComment(L" Copyright © 2024 William C Bonner ");
pWriter->WriteEndDocument();
pWriter->Flush();
// Allocates enough memeory for the xml content.
STATSTG ssStreamData = { 0 };
spMemoryStream->Stat(&ssStreamData, STATFLAG_NONAME);
SIZE_T cbSize = ssStreamData.cbSize.LowPart;
if (cbSize >= sizeof(XMLDataBuff))
cbSize = sizeof(XMLDataBuff) - 1;
// Copies the content from the stream to the buffer.
LARGE_INTEGER position;
position.QuadPart = 0;
spMemoryStream->Seek(position, STREAM_SEEK_SET, NULL);
ULONG cbRead;
spMemoryStream->Read(XMLDataBuff, cbSize, &cbRead);
XMLDataBuff[cbSize] = '\0';
}
/* Create HTTP Header */
std::stringstream HttpResponse;
HttpResponse << "HTTP/1.1 200 OK\r\n";
HttpResponse << "Server: WimTiVoServer/1.0\r\n";
HttpResponse << "Date: " << getTimeRFC1123() << "\r\n";
HttpResponse << "Content-Type: text/xml\r\n";
HttpResponse << "Content-Length: " << strlen(XMLDataBuff) << "\r\n";
HttpResponse << "Connection: close\r\n";
HttpResponse << "\r\n";
send(DataSocket, HttpResponse.str().c_str(), HttpResponse.str().length(), 0);
send(DataSocket, XMLDataBuff, strlen(XMLDataBuff), 0);
#ifdef DEBUG
if (bConsoleExists)
{
std::cout << "[ ] " << HttpResponse.str() << std::endl;
std::cout << "[ ] " << XMLDataBuff << std::endl;
}
#endif // DEBUG
return(0);
}
UINT PopulateTiVoFileList(LPVOID lvp)
{
HANDLE LocalTerminationEventHandle = lvp;
CString csLocalContainers;
if (csLocalContainers.IsEmpty())
{
CString csRegKey(_T("Software\\WimsWorld\\"));
csRegKey.Append(theApp.m_pszAppName);
TCHAR vData[1024];
DWORD cbData = sizeof(vData);
if (ERROR_SUCCESS == RegGetValue(HKEY_LOCAL_MACHINE, csRegKey, _T("Container"), RRF_RT_REG_SZ, NULL, vData, &cbData))
csLocalContainers = CString(vData);
}
#ifdef CACHE_FILE
CString csXMLCacheName;
if (csXMLCacheName.IsEmpty())
{
CString csRegKey(_T("Software\\WimsWorld\\"));
csRegKey.Append(theApp.m_pszAppName);
TCHAR vData[MAX_PATH];
DWORD cbData = sizeof(vData);
if (ERROR_SUCCESS != RegGetValue(HKEY_LOCAL_MACHINE, csRegKey, _T("XMLCacheDirectory"), RRF_RT_REG_SZ, NULL, vData, &cbData))
{
unsigned long buffersize = sizeof(vData) / sizeof(TCHAR);
GetModuleFileName(AfxGetResourceHandle(), vData, buffersize);
PathRemoveFileSpec(vData);
}
PathAppend(vData, _T("WimTivoServerCache.xml"));
csXMLCacheName = CString(vData);
}
#endif // CACHE_FILE
if (ApplicationLogHandle != NULL)
{
CString csSubstitutionText(__FUNCTION__);
csSubstitutionText.Append(_T(" Has Started"));
csSubstitutionText.Append(_T("\nffprobe.exe: ")); csSubstitutionText.Append(FindEXEFromPath(_T("ffprobe.exe")));
csSubstitutionText.Append(_T("\nffmpeg.exe: ")); csSubstitutionText.Append(FindEXEFromPath(_T("ffmpeg.exe")));
csSubstitutionText.Append(_T("\ncsLocalContainers: ")); csSubstitutionText.Append(csLocalContainers);
LPCTSTR lpStrings[] = { csSubstitutionText.GetString(), NULL };
ReportEvent(ApplicationLogHandle,EVENTLOG_INFORMATION_TYPE,0,WIMSWORLD_EVENT_GENERIC,NULL,1,0,lpStrings,NULL);
}
do {
ccTiVoFileListCritSec.Lock();
auto TiVoFileListSizeBefore = TiVoFileList.size();
ccTiVoFileListCritSec.Unlock();
CleanTiVoFileList(TiVoFileList, ccTiVoFileListCritSec);
int iPos = 0;
CString csToken(csLocalContainers.Tokenize(_T(";"), iPos));
while (!csToken.IsEmpty())
{
PopulateTiVoFileList(TiVoFileList, ccTiVoFileListCritSec, CStringA(csToken).GetString(), true);
ccTiVoFileListCritSec.Lock();
std::sort(TiVoFileList.begin(), TiVoFileList.end(), cTiVoFileCompareDateReverse);
CurrentTiVoFileListSortOrder = CaptureDateReverse;
ccTiVoFileListCritSec.Unlock();
csToken = csLocalContainers.Tokenize(_T(";"), iPos);
}
std::stringstream ss;
ss.imbue(std::locale(""));
ccTiVoFileListCritSec.Lock();
auto TiVoFileListSizeAfter = TiVoFileList.size();
ss << "[" << getTimeISO8601(true) << "] " __FUNCTION__ " TiVoFileListSizeBefore: " << TiVoFileListSizeBefore << " TiVoFileListSizeAfter: " << TiVoFileListSizeAfter << std::endl;
ccTiVoFileListCritSec.Unlock();
if (bConsoleExists)
{
std::cout << ss.str().c_str();
if (TiVoFileListSizeBefore != TiVoFileListSizeAfter)
{
std::wofstream m_LogFile(GetLogFileName().GetString(), std::ios_base::out | std::ios_base::app | std::ios_base::ate);
if (m_LogFile.is_open())
{
m_LogFile << ss.str().c_str();
m_LogFile.close();
}
}
}
TRACE(ss.str().c_str());
if ((ApplicationLogHandle != NULL) && (TiVoFileListSizeBefore != TiVoFileListSizeAfter))
{
CString csSubstitutionText(__FUNCTION__);
csSubstitutionText.Append(_T("\ncsLocalContainers: ")); csSubstitutionText.Append(csLocalContainers);
csSubstitutionText.Append(_T("\n"));
csSubstitutionText.Append(CString(ss.str().c_str()));
LPCTSTR lpStrings[] = { csSubstitutionText.GetString(), NULL };
ReportEvent(ApplicationLogHandle,EVENTLOG_INFORMATION_TYPE,0,WIMSWORLD_EVENT_GENERIC,NULL,1,0,lpStrings,NULL);
}
#ifdef CACHE_FILE
if ((TiVoFileListSizeBefore != TiVoFileListSizeAfter) && !csXMLCacheName.IsEmpty())
{
HRESULT hr;
CComPtr<IStream> pOutFileStream;
CComPtr<IXmlWriter> pWriter;
if (SUCCEEDED(hr = ::SHCreateStreamOnFile(csXMLCacheName.GetString(), STGM_READWRITE | STGM_CREATE, &pOutFileStream)))
if (SUCCEEDED(hr = CreateXmlWriter(__uuidof(IXmlWriter), (void**)&pWriter, NULL)))
if (SUCCEEDED(hr = pWriter->SetOutput(pOutFileStream)))
{
pWriter->SetProperty(XmlWriterProperty_Indent, TRUE);
pWriter->WriteStartDocument(XmlStandalone_Omit);
pWriter->WriteStartElement(NULL, L"TiVoFileList", NULL);
ccTiVoFileListCritSec.Lock();
for (auto iter = TiVoFileList.begin(); iter != TiVoFileList.end(); iter++)
iter->WriteToXML(pWriter);
ccTiVoFileListCritSec.Unlock();
pWriter->WriteEndElement(); // TiVoFileList
//pWriter->WriteFullEndElement();
pWriter->WriteComment(L" Copyright © 2024 William C Bonner ");
pWriter->WriteEndDocument();
pWriter->Flush();
}
}
#endif // CACHE_FILE
} while (WAIT_TIMEOUT == WaitForSingleObject(LocalTerminationEventHandle, 15*60*1000));
if (ApplicationLogHandle != NULL)
{
CString csSubstitutionText(__FUNCTION__);
csSubstitutionText.Append(_T(" Has Stopped"));
LPCTSTR lpStrings[] = { csSubstitutionText.GetString(), NULL };
ReportEvent(ApplicationLogHandle,EVENTLOG_INFORMATION_TYPE,0,WIMSWORLD_EVENT_GENERIC,NULL,1,0,lpStrings,NULL);
}
return(0);
}
int GetTivoQueryContainer(SOCKET DataSocket, const char * InBuffer)
{
// 4.4.4 QueryContainer
// This command returns meta-data describing the contents of one of the containers available from the Server, and uses the following URL syntax.
// http://{machine}/TiVoConnect?Command=QueryContainer
TRACE("%s %s\n", CStringA(CTime::GetCurrentTime().Format(_T("[%Y-%m-%dT%H:%M:%S]"))).GetString(), __FUNCTION__);
CStringA csInBuffer(InBuffer);
int pos = csInBuffer.FindOneOf("\r\n");
if (pos > 0)
csInBuffer.Delete(pos,csInBuffer.GetLength());
struct sockaddr_in adr_inet;/* AF_INET */
int sa_len = sizeof(adr_inet);
getpeername(DataSocket, (struct sockaddr*)&adr_inet, &sa_len);
char TiVoAddress[NI_MAXHOST];
getnameinfo((struct sockaddr*)&adr_inet, sizeof(struct sockaddr), TiVoAddress, NI_MAXHOST, nullptr, NULL, NI_NUMERICHOST);
if (bConsoleExists)
std::cout << "[" << getTimeISO8601(true) << "] " << __FUNCTION__ << "\t" << TiVoAddress << " " << csInBuffer.GetString() << endl;
int rval = 0;
const int XMLDataBuffSize = 1024;
char* XMLDataBuff = new char[XMLDataBuffSize];
XMLDataBuff[0] = 0;
CComPtr<IXmlWriter> pWriter;
CreateXmlWriter(__uuidof(IXmlWriter), reinterpret_cast<void**>(&pWriter), NULL);
// from: http://stackoverflow.com/questions/3037946/how-can-i-store-xml-in-buffer-using-xmlite
CComPtr<IStream> spMemoryStream(::SHCreateMemStream(NULL, 0));
if ((pWriter != NULL) && (spMemoryStream != NULL))
{
TCHAR buffer[256] = TEXT("");
DWORD dwSize = sizeof(buffer);
GetComputerNameEx(ComputerNameDnsHostname, buffer, &dwSize);
CString csMyHostName(buffer);
CString csContainer;
int iAnchorOffset = 0;
CString csAnchorItem;
TiVoFileListSortOrder RequestedTiVoFileListSortOrder = CaptureDateReverse;
ccTiVoFileListCritSec.Lock();
int iItemCount = TiVoFileList.size();
ccTiVoFileListCritSec.Unlock();
int curPos = 0;
CString csToken(csInBuffer.Tokenize("& ?",curPos));
while (csToken != "")
{
TCHAR lpszBuffer[_MAX_PATH];
DWORD dwBufferLength = sizeof(lpszBuffer) / sizeof(TCHAR);
InternetCanonicalizeUrl(csToken.GetString(), lpszBuffer, &dwBufferLength, ICU_DECODE);
csToken = CString(lpszBuffer, dwBufferLength);
CStringA csKey(csToken.Left(csToken.Find(_T("="))));
CStringA csValue(csToken.Right(csToken.GetLength() - (csToken.Find(_T("="))+1)));
if (!csKey.CompareNoCase("Container"))
{
// 4.4.4.1 Container
// This optional parameter may be set to the relative path of a container available from the Server, as shown here (assume "Foo" is a valid container).
// http://{machine}/TiVoConnect?Command=QueryContainer&Container=/Foo
// In this example, meta-data describing the contents of the container named "Foo" would be returned.
// When the Container parameter is missing, the default value is "/", which corresponds to the Server's "root container".
std::wcout << L"[ ] " << csToken.GetString() << std::endl;
csContainer = csValue;
}
else if (!csKey.CompareNoCase("Recurse"))
{
// 4.4.4.2 Recurse
// This optional parameter indicates whether or not the meta-data should contain only the items immediately within the container, or also every item contained within all "descendent" containers.
// http://{machine}/TiVoConnect?Command=QueryContainer&Recurse={flag}
// The value of {flag} is either "Yes" or "No". When the Recurse parameter is missing, the default value is "No".
std::wcout << L"[ ] " << csToken.GetString() << std::endl;
}
else if (!csKey.CompareNoCase("DoGenres"))
std::wcout << L"[ ] " << csToken.GetString() << std::endl;
else if (!csKey.CompareNoCase("SerialNum"))
{
std::wcout << L"[ ] " << csToken.GetString();
TiVoSerialMap[TiVoAddress] = CString(csValue);
if ((std::atoi(csValue.Left(1)) >= 6) && (0 != csValue.Left(3).Compare("649")))
std::wcout << L" (High Definition TiVo)";
if ((std::atoi(csValue.Left(1)) >= 7) || (0 == csValue.Left(3).Compare("663")))
std::wcout << L" (Tivos supports transport streams)";
if ((0 == csValue.Left(3).Compare("849")) || (0 == csValue.Left(3).Compare("8F9")))
std::wcout << L" (4K TiVo)";
std::wcout << std::endl;
}
else if (!csKey.CompareNoCase("SortOrder"))
{
// 4.4.4.3 SortOrder
// This optional parameter indicates the order in which items should appear in the meta-data.
// http://{machine}/TiVoConnect?Command=QueryContainer&SortOrder={order}
// {order} is a comma-delimited list of sort criteria, indicating the level(s) of sorting desired. Items are sorted according to the first entry in this list, then by the second, then by the third, and so on.
// Possible values for the construction of {order} are:
// • Type – Items appear in an order based on their general type. All containers sort before non-container items. Containers representing folders sort before those representing playlists.
// • Title – Items appear alphabetically based on the text contained in their associated Item.Details.Title element (described in section 5.7.1.1).
// • CreationDate – Items appear sorted from oldest the newest based on an appropriate "creation" date (for example, the capture date of an image). If no such date is available, the creation date of the file containing the item's data is used instead.
// • LastChangeDate – Items appear sorted from most- to least-recently modified.
// • Random – Items appear in "randomized" order based on a "seed" supplied by the Client (described in section 4.4.4.4). This value may not be used with any other.
// Any entry in the list can be prefixed with an exclamation point (!) to request sorting in the opposite direction at the corresponding level. For example, "!Date,Title" sorts from newest to oldest and then alphabetically.
// With "SortOrder=Random", note that randomization occurs across the entire sequence of items returned in the meta-data.
// When the SortOrder parameter is missing, items appear in the container's "native" order. For a music playlist, for example, the items would appear in the order authored. For a file system folder, items would appear potentially "at random" according to how the file system is feeling.
// When "streaming" sorted meta-data using multiple QueryContainer commands, Clients should specify the same {order} in each command.
std::wcout << L"[ ] " << csToken.GetString() << std::endl;
if (!csValue.CompareNoCase("!CaptureDate"))
RequestedTiVoFileListSortOrder = CaptureDateReverse;
else if (!csValue.CompareNoCase("Title"))
RequestedTiVoFileListSortOrder = Title;
else if (!csValue.CompareNoCase("CaptureDate"))
RequestedTiVoFileListSortOrder = CaptureDate;
else if (!csValue.CompareNoCase("!Title"))
RequestedTiVoFileListSortOrder = TitleReverse;
}
else if (!csKey.CompareNoCase("RandomSeed"))
{
// 4.4.4.4 RandomSeed
// This parameter is required when the SortOrder parameter is “Random”.
// http://{machine}/TiVoConnect?Command=QueryContainer&SortOrder=Random&RandomSeed={seed}
// {seed} can be any positive, non-zero, 32-bit unsigned integer value chosen by the Client (0-4294967295). Different values result in different item orderings. However, the same {seed} always produces the same ordering (assuming an unchanging set of items).
// When "streaming" randomized meta-data using multiple QueryContainer commands, Clients should specify the same {seed} in each command.
// This parameter is ignored unless the SortOrder parameter is "Random”.
std::wcout << L"[ ] " << csToken.GetString() << std::endl;
}
else if (!csKey.CompareNoCase("RandomStart"))
{
// 4.4.4.5 RandomStart
// This optional parameter indicates which item should appear first in otherwise randomized metadata.
// http://{machine}/TiVoConnect?Command=QueryContainer&SortOrder={order}&RandomSeed={seed}&RandomStart={url}
// When "streaming" randomized meta-data using multiple QueryContainer commands, Clients should specify the same {url} in each command.
// This parameter is ignored unless the SortOrder parameter is "Random”.
std::wcout << L"[ ] " << csToken.GetString() << std::endl;
}
else if (!csKey.CompareNoCase("AnchorOffset"))
{
// 4.4.4.8 AnchorOffset
// This optional parameter supplies an "offset" to be applied to the location of the anchor, changing its effective location.
// http://{machine}/TiVoConnect?Command=QueryContainer&AnchorItem={url}&AnchorOffset={offset}
// {offset} is a positive or negative integer. When {offset} is positive, the effective location of the anchor is shifted downwards. When {offset} is negative, the location is shifted upwards.
// When the AnchorOffset parameter is missing, no offset is applied to the anchor.
std::wcout << L"[ ] " << csToken.GetString() << std::endl;
iAnchorOffset = atoi(csValue.GetString());
iAnchorOffset++; // Simplify for the -1 offset that the TiVo actually uses.
}
else if (!csKey.CompareNoCase("Filter"))
{
// 4.4.4.10 Filter
// This optional parameter limits the types of items that appear in the meta-data.
// http://{machine}/TiVoConnect?Command=QueryContainer&Filter={filter}
// {filter} is a comma-delimited list of MIME types, indicating the desired value(s) for the Details.ContentType element of each item.
// Any entry can contain a wildcard (*) in place of the "major" or "minor" portion of the MIME type. For example, "image/*" would match any item with a general MIME type of "image".
// Any entry in the list also can be prefixed with an exclamation point (!) to limit the items returned to those NOT of the specified type.
// When the Filter parameter is missing, the default value is "*/*". This will result in no restriction of the types of items appearing in the meta - data.
std::wcout << L"[ ] " << csToken.GetString() << std::endl;
}
else if (!csKey.CompareNoCase("ItemCount"))
{
// 4.4.4.6 ItemCount
// This optional parameter indicates the maximum number of items that should be described in the meta-data, relative to the "anchor" (described in section 4.4.4.7).
// http://{machine}/TiVoConnect?Command=QueryContainer&ItemCount={count}
// {count} is a positive or negative integer. When {count} is positive, the items immediately following the anchor are described. When {count} is negative, the items immediately preceding the anchor are described. However, for the remaining discussion, assume {count} refers only to the absolute (non-negative magnitude) integer value.
// If the container holds more than {count} items, "partial" meta-data is returned. Note that the meta-data will have fewer than {count} items if the container itself has fewer.
// When the ItemCount parameter is missing, all items (preceding or following the anchor) are described.
std::wcout << L"[ ] " << csToken.GetString() << std::endl;
iItemCount = min(iItemCount, atoi(CStringA(csValue).GetString()));
}
else if (!csKey.CompareNoCase("AnchorItem"))
{
// 4.4.4.7 AnchorItem
// This optional parameter supplies the URL of the item that should precede (or follow) the first (or last) item described in the meta-data, if possible. This item is known as the "anchor" and its exact meaning depends on the value of the ItemCount parameter (described in section 4.4.4.4).
// http://{machine}/TiVoConnect?Command=QueryContainer&AnchorItem={url}
// When the AnchorItem parameter is missing or ignored, the anchor is the imaginary item that precedes (or follows) the first (or last) item in the container.
// If the item identified by {url} no longer exists, then the item immediately following (or preceding) the position in the container the missing item would have occupied is used as the anchor instead. If this position cannot be determined, the AnchorItem parameter is ignored.
// Note that {url} must be escaped as described in section 4.4.1.
std::wcout << L"[ ] " << csToken.GetString() << std::endl;
csAnchorItem = csValue;
}
csToken = csInBuffer.Tokenize("& ?",curPos);
}
pWriter->SetOutput(spMemoryStream);
pWriter->SetProperty(XmlWriterProperty_Indent, TRUE);
pWriter->WriteStartDocument(XmlStandalone_Omit);
pWriter->WriteStartElement(NULL,L"TiVoContainer",L"http://www.tivo.com/developer/calypso-protocol-1.6/");
if (csContainer.Compare(_T("%2F")) == 0)
{
pWriter->WriteStartElement(NULL,_T("Details"),NULL);
pWriter->WriteElementString(NULL,_T("Title"),NULL, csMyHostName.GetString());
pWriter->WriteElementString(NULL,_T("ContentType"),NULL, _T("x-tivo-container/tivo-server"));
pWriter->WriteElementString(NULL,_T("SourceFormat"),NULL, _T("x-tivo-container/folder"));
pWriter->WriteElementString(NULL,_T("TotalItems"),NULL, _T("1"));
pWriter->WriteEndElement(); // Details
pWriter->WriteStartElement(NULL,_T("Item"),NULL);
pWriter->WriteStartElement(NULL,_T("Details"),NULL);
pWriter->WriteElementString(NULL,_T("Title"),NULL, csMyHostName.GetString());
pWriter->WriteElementString(NULL,_T("ContentType"),NULL, _T("x-tivo-container/tivo-videos"));
pWriter->WriteElementString(NULL,_T("SourceFormat"),NULL, _T("x-tivo-container/folder"));
pWriter->WriteEndElement(); // Details
pWriter->WriteStartElement(NULL,_T("Links"),NULL);
pWriter->WriteStartElement(NULL,_T("Content"),NULL);
std::wstring MyURL(L"/TiVoConnect?Command=QueryContainer\&Container="); MyURL.append(csMyHostName.GetString());
pWriter->WriteElementString(NULL, _T("Url"), NULL, MyURL.c_str());
pWriter->WriteElementString(NULL,_T("ContentType"),NULL, _T("x-tivo-container/tivo-videos"));
pWriter->WriteFullEndElement(); // Content
pWriter->WriteFullEndElement(); // Links
pWriter->WriteFullEndElement(); // Item
pWriter->WriteElementString(NULL,_T("ItemStart"),NULL, _T("0"));
pWriter->WriteElementString(NULL,_T("ItemCount"),NULL, _T("1"));
}
else if (csContainer.Compare(csMyHostName) == 0)
{
CString csTemporary;
ccTiVoFileListCritSec.Lock();
if (CurrentTiVoFileListSortOrder != RequestedTiVoFileListSortOrder)
{
switch (RequestedTiVoFileListSortOrder)
{
case Title:
std::sort(TiVoFileList.begin(), TiVoFileList.end(), cTiVoFileCompareTitle);
CurrentTiVoFileListSortOrder = Title;
break;
case TitleReverse:
std::sort(TiVoFileList.begin(), TiVoFileList.end(), cTiVoFileCompareTitle);
CurrentTiVoFileListSortOrder = TitleReverse;
break;
case CaptureDate:
std::sort(TiVoFileList.begin(), TiVoFileList.end(), cTiVoFileCompareDate);
CurrentTiVoFileListSortOrder = CaptureDate;
break;
default:
case CaptureDateReverse:
std::sort(TiVoFileList.begin(), TiVoFileList.end(), cTiVoFileCompareDateReverse);
CurrentTiVoFileListSortOrder = CaptureDateReverse;
break;
}
}
if (csAnchorItem.IsEmpty())
if (!TiVoFileList.empty())
csAnchorItem = TiVoFileList.begin()->GetURL();
auto pItem = TiVoFileList.begin();
int ItemStart = 0;
if (iItemCount > 0)
{
for (pItem = TiVoFileList.begin(); pItem != TiVoFileList.end(); pItem++)
{
if (!pItem->GetURL().CompareNoCase(csAnchorItem))
{
std::wcout << L"[ ] Anchoritem Found: " << csAnchorItem.GetString() << std::endl;
break;
}
ItemStart++;
}
if (pItem == TiVoFileList.end())
{
std::wcout << L"[ ] Anchoritem NOT Found: " << csAnchorItem.GetString() << std::endl;
pItem = TiVoFileList.begin();
ItemStart = 0;
}
while ((pItem != TiVoFileList.begin()) && (pItem != TiVoFileList.end()) && (iAnchorOffset != 0))
if (iAnchorOffset < 0)
{
pItem--;
ItemStart--;
if (pItem->GetDuration() > 1000)
iAnchorOffset++;
}
else
{
pItem++;
ItemStart++;
if (pItem->GetDuration() > 1000)
iAnchorOffset--;
}
}
csTemporary.Format(_T("%d"), ItemStart);
pWriter->WriteElementString(NULL, _T("ItemStart"), NULL, csTemporary.GetString());
csTemporary.Format(_T("%d"), min(iItemCount, TiVoFileList.size()));
pWriter->WriteElementString(NULL, _T("ItemCount"), NULL, csTemporary.GetString());
pWriter->WriteStartElement(NULL, _T("Details"), NULL);
pWriter->WriteElementString(NULL, _T("Title"), NULL, csMyHostName.GetString());
pWriter->WriteElementString(NULL, _T("ContentType"), NULL, _T("x-tivo-container/folder"));
pWriter->WriteElementString(NULL, _T("SourceFormat"), NULL, _T("x-tivo-container/folder"));
csTemporary.Format(_T("%d"), TiVoFileList.size());
pWriter->WriteElementString(NULL, L"TotalItems", NULL, csTemporary.GetString());
std::wstring MyVersion(std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(myServer.m_swversion));
pWriter->WriteElementString(NULL, _T("UniqueId"), NULL, MyVersion.c_str());
pWriter->WriteEndElement(); // Details
while ((pItem != TiVoFileList.end()) && (iItemCount > 0))
{
#ifdef DEBUG
std::wcout << L"[ ] Item: " << pItem->GetURL().GetString() << L" " << pItem->GetPathName().GetString() << L" Duration: " << pItem->GetDuration() << std::endl;
#else
std::wcout << L"[ ] Item: " << pItem->GetPathName().GetString() << L" Duration: " << pItem->GetDuration() << std::endl;
#endif // DEBUG
if (pItem->GetDuration() > 1000) // This might not work for .TiVo files, needs further checking
{
pItem->GetTiVoItem(pWriter, TiVoSerialMap[TiVoAddress]);
iItemCount--;
}
pItem++;
}
ccTiVoFileListCritSec.Unlock();
}
else //if ((csContainer.Compare(_T("%2FTiVoNowPlaying")) == 0) || (csContainer.Compare(_T("%2FNowPlaying")) == 0))
{
ccTiVoFileListCritSec.Lock();
if (CurrentTiVoFileListSortOrder != RequestedTiVoFileListSortOrder)
{
switch(RequestedTiVoFileListSortOrder)
{
case Title:
std::sort(TiVoFileList.begin(), TiVoFileList.end(), cTiVoFileCompareTitle);
CurrentTiVoFileListSortOrder = Title;
break;
case TitleReverse:
std::sort(TiVoFileList.begin(), TiVoFileList.end(), cTiVoFileCompareTitle);
CurrentTiVoFileListSortOrder = TitleReverse;
break;
case CaptureDate:
std::sort(TiVoFileList.begin(), TiVoFileList.end(), cTiVoFileCompareDate);
CurrentTiVoFileListSortOrder = CaptureDate;
break;
default:
case CaptureDateReverse:
std::sort(TiVoFileList.begin(), TiVoFileList.end(), cTiVoFileCompareDateReverse);
CurrentTiVoFileListSortOrder = CaptureDateReverse;
break;
}
}
// If Anchoritem not empty
// set pointer to anchor item in list
// move pointer to anchoroffset
// while itemcount > 0 and not at list end
// output xml
// move pointer forward
// decrement itemcount
auto pItem = TiVoFileList.begin();
for (pItem = TiVoFileList.begin(); pItem != TiVoFileList.end(); pItem++)
if (!pItem->GetURL().CompareNoCase(csAnchorItem))
{
std::wcout << L"[ ] Anchoritem Found: " << csAnchorItem.GetString() << std::endl;
break;
}
if (pItem == TiVoFileList.end())
{
std::wcout << L"[ ] Anchoritem NOT Found: " << csAnchorItem.GetString() << std::endl;
pItem = TiVoFileList.begin();
}
while ((pItem != TiVoFileList.begin()) && (pItem != TiVoFileList.end()) && (iAnchorOffset != 0))
if (iAnchorOffset < 0)
{
pItem--;
if (pItem->GetDuration() > 1000)
iAnchorOffset++;
}
else
{
pItem++;
if (pItem->GetDuration() > 1000)
iAnchorOffset--;
}
CString csTemporary;
csTemporary.Format(_T("%d"), pItem - TiVoFileList.begin());
pWriter->WriteElementString(NULL,L"ItemStart",NULL, csTemporary.GetString());
csTemporary.Format(_T("%d"), iItemCount);
pWriter->WriteElementString(NULL,L"ItemCount",NULL, csTemporary.GetString());
pWriter->WriteStartElement(NULL,L"Details",NULL);
pWriter->WriteElementString(NULL,L"Title",NULL, csMyHostName.GetString());
pWriter->WriteElementString(NULL,L"ContentType",NULL, L"x-tivo-container/folder");
pWriter->WriteElementString(NULL,L"SourceFormat",NULL, L"x-tivo-container/folder");
csTemporary.Format(_T("%d"), TiVoFileList.size());
pWriter->WriteElementString(NULL,L"TotalItems",NULL, csTemporary.GetString());
pWriter->WriteEndElement();
while ((pItem != TiVoFileList.end()) && (iItemCount > 0))
{
#ifdef DEBUG
std::wcout << L"[ ] Item: " << pItem->GetURL().GetString() << L" " << pItem->GetPathName().GetString() << L" Duration: " << pItem->GetDuration() << std::endl;
#else
std::wcout << L"[ ] Item: " << pItem->GetPathName().GetString() << L" Duration: " << pItem->GetDuration() << std::endl;
#endif // DEBUG
if (pItem->GetDuration() > 1000) // This might not work for .TiVo files, needs further checking
{
pItem->GetTiVoItem(pWriter, TiVoSerialMap[TiVoAddress]);
iItemCount--;
}
pItem++;
}
ccTiVoFileListCritSec.Unlock();
}
pWriter->WriteEndElement(); // TiVoContainer
pWriter->WriteComment(L" Copyright © 2024 William C Bonner ");
pWriter->WriteEndDocument();
pWriter->Flush();
// Allocates enough memeory for the xml content.
STATSTG ssStreamData = {0};
spMemoryStream->Stat(&ssStreamData, STATFLAG_NONAME);
SIZE_T cbSize = ssStreamData.cbSize.LowPart;
if (cbSize >= XMLDataBuffSize)
{
delete[] XMLDataBuff;
XMLDataBuff = new char[cbSize+1];
}
// Copies the content from the stream to the buffer.
LARGE_INTEGER position;
position.QuadPart = 0;
spMemoryStream->Seek(position, STREAM_SEEK_SET, NULL);
ULONG cbRead;
spMemoryStream->Read(XMLDataBuff, cbSize, &cbRead);
XMLDataBuff[cbSize] = '\0';
}
/* Create HTTP Header */
std::stringstream HttpResponse;
HttpResponse << "HTTP/1.1 200 OK\r\n";
HttpResponse << "Server: WimTiVoServer/1.0\r\n";
HttpResponse << "Date: " << getTimeRFC1123() << "\r\n";
HttpResponse << "Content-Type: text/xml\r\n";
HttpResponse << "Content-Length: " << strlen(XMLDataBuff) << "\r\n";
// HttpResponse << "Connection: close\r\n";
HttpResponse << "Expires: 0\r\n";
HttpResponse << "Access-Control-Allow-Origin: *\r\n";
HttpResponse << "\r\n";
send(DataSocket, HttpResponse.str().c_str(), HttpResponse.str().length(),0);
send(DataSocket, XMLDataBuff, strlen(XMLDataBuff), 0);
#ifdef _DEBUG
std::cout << "[ ] " << HttpResponse.str() << std::endl;
std::cout << "[ ] " << XMLDataBuff << std::endl;
#endif
delete[] XMLDataBuff;
#ifdef _DEBUG
std::cout << "[" << getTimeISO8601() << "] " << __FUNCTION__ << "\texiting" << endl;
#endif
return(0);
}
int GetTiVoTVBusQuery(SOCKET DataSocket, const char * InBuffer)
{
TRACE("%s %s\n", CStringA(CTime::GetCurrentTime().Format(_T("[%Y-%m-%dT%H:%M:%S]"))).GetString(), __FUNCTION__);
CStringA csInBuffer(InBuffer);
int pos = csInBuffer.FindOneOf("\r\n");
if (pos > 0)
csInBuffer.Delete(pos,csInBuffer.GetLength());
if (bConsoleExists)
{
struct sockaddr_in adr_inet;/* AF_INET */
int sa_len = sizeof(adr_inet);
getpeername(DataSocket, (struct sockaddr*)&adr_inet, &sa_len);
std::cout << "[" << getTimeISO8601(true) << "] " << __FUNCTION__ << "\t" << inet_ntoa(adr_inet.sin_addr) << " " << csInBuffer.GetString() << endl;
}
cTiVoFile TiVoFileToSend;
int curPos = 0;
CString csToken(csInBuffer.Tokenize("& ?", curPos));
while (csToken != "")
{
TCHAR lpszBuffer[_MAX_PATH];
DWORD dwBufferLength = sizeof(lpszBuffer) / sizeof(TCHAR);