-
Notifications
You must be signed in to change notification settings - Fork 0
/
unit1.pas
3856 lines (3529 loc) · 120 KB
/
unit1.pas
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
{
TODO:
}
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls, Menus, Buttons, SynMemo;
const
APP_NAME = 'BEER Media Server';
SHORT_APP_NAME = 'BMS';
APP_VERSION = '2.0.130525';
SHORT_APP_VERSION = '2.0';
type
{ TForm1 }
TForm1 = class(TForm)
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
CheckBoxLog: TCheckBox;
MemoLog: TSynMemo;
procedure BitBtn2Click(Sender: TObject);
procedure CheckBoxLogChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ private declarations }
procedure AsyncFromCreate({%H-}Data: PtrInt);
public
{ public declarations }
end;
var
Form1: TForm1;
TrayIcon: TTrayIcon;
procedure InitAfterApplicationInitialize;
implementation
uses
LCLIntf, blcksock, synsock, synautil,
DOM, XMLWrite, XMLRead, MediaInfoDll,
//Lua, lualib, lauxlib,
lua52,
{$IFDEF Windows}
interfacebase, win32int, windows, // for Hook SUSPEND EVENT
{$ENDIF}
lazutf8classes, inifiles, comobj, contnrs, process, SynRegExpr,
dateutils, simpleipc,
unit2;
{$R *.lfm}
const
HTTP_HEAD_SERVER = 'OS/1.0, UPnP/1.0, ' + SHORT_APP_NAME + '/' + SHORT_APP_VERSION;
INI_SEC_SYSTEM = 'SYSTEM';
INI_SEC_MIKeys = 'MInfoKeys';
INI_SEC_SCRIPTS = 'SCRIPTS';
MEDIA_INFO_DB_FILENAME = 'mi.db';
MEDIA_INFO_DB_HEADER = 'midb01';
MAX_ONMEM_LOG = 500;
type
{ TMyApp }
TMyApp = class
public
Log: TStringListUTF8;
LogFile: TFileStreamUTF8;
PopupMenu: TPopupMenu;
constructor Create;
destructor Destroy; override;
procedure OnTrayIconClick(Sender: TObject);
procedure OnMenuShowClick(Sender: TObject);
procedure OnMenuQuitClick(Sender: TObject);
procedure AddLog(const line: string);
procedure WMPowerBoadcast(var msg: TMessage);
end;
{ THttpDaemon }
THttpDaemon = class(TThread)
private
Sock: TTCPBlockSocket;
line: string;
th_list: TObjectList;
procedure AddLog;
public
SendAliveFlag: boolean;
constructor Create;
destructor Destroy; override;
procedure Execute; override;
end;
{ THttpThrd }
TClientInfo = class;
THttpThrd = class(TThread)
private
Sock: TTCPBlockSocket;
line: string;
L_S: Plua_State;
ClientInfo: TClientInfo;
procedure AddLog;
function DoPlay(sno: integer; const fname, request: string): boolean;
function DoPlayTranscode(sno: integer; const fname, request: string): boolean;
function DoBrowse(docr, docw: TXMLDocument): boolean;
function SendRaw(buf: Pointer; len: integer): boolean; overload;
function SendRaw(const buf: string): boolean; overload;
public
Done: boolean;
Headers: TStringListUTF8;
InputData, OutputData: TMemoryStream;
UniOutput: boolean;
InHeader: string;
constructor Create(hSock: TSocket);
destructor Destroy; override;
procedure Execute; override;
function ProcessHttpRequest(const Request, URI: string): integer;
end;
{ TSSDPDaemon }
TSSDPDaemon = class(TThread)
private
Sock: TUDPBlockSocket;
line: string;
procedure AddLog;
public
constructor Create;
destructor Destroy; override;
procedure Execute; override;
end;
{ TGetMediaInfo }
TGetMediaInfo = class(TValStringList)
private
public
FileName, AccTime: string;
FileSize: Int64;
IsTemp: boolean;
PlayInfo: TStringList;
constructor Create(const fname: string; mi: Cardinal; ExKeys: TStringList);
destructor Destroy; override;
procedure GetPlayInfo(L: PLua_State; get_new: boolean = False);
procedure SaveToStream(Stream: TStream); override;
procedure LoadFromStream(Stream: TStream); override;
end;
{ TMediaInfoCollector }
TMediaInfoCollector = class(TThread)
private
miHandle: Cardinal;
mi_list, mi_ac_list, exkey_list: TStringListUTF8;
MaxMediaInfo: integer;
public
cs_list, cs_ac_list, cs_pr_list, cs_get_mi: TCriticalSection;
PriorityList: TStringListUTF8;
constructor Create;
destructor Destroy; override;
procedure Execute; override;
function GetMediaInfo(const fname: string): TGetMediaInfo;
procedure AddExKey(const key: string);
procedure ClearMediaInfo;
procedure LoadMediaInfo;
procedure SaveMediaInfo;
end;
{ TClientInfo }
TClientInfo = class
private
public
L_S: Plua_State;
CurId, CurDir: string;
chunks: TStringList;
FullInfoCount: integer;
CurFileList: TStringList;
LastAccTime: TDateTime;
ScriptFileName: string;
SortType: integer;
InfoTable: TValStringList;
constructor Create;
destructor Destroy; override;
end;
{ TChunkObj }
TChunkObj = class
bin: string;
time: integer;
end;
{ TMySimpleIPCServer }
TMySimpleIPCServer = class(TSimpleIPCServer)
private
cs_vsl: TCriticalSection;
vsl: TValStringList;
procedure DoMessage(Sender: TObject);
public
constructor {%H-}Create;
destructor Destroy; override;
function GetValue(const vname: string): string;
procedure SetValue(const vname, val: string);
end;
var
iniFile: TIniFile;
ExecPath, TempPath, UUID, DAEMON_PORT: string;
MAX_REQUEST_COUNT, SEND_DATA_TIMEOUT: integer;
MyApp: TMyApp;
thHttpDaemon: THttpDaemon;
thSSDPDAemon: TSSDPDaemon;
thMIC: TMediaInfoCollector;
SIPCServer: TMySimpleIPCServer;
MediaDirs: TStringList;
ClientInfoList: TStringList;
MyIPAddr: string;
function Alloc({%H-}ud, ptr: Pointer; {%H-}osize, nsize: size_t) : Pointer; cdecl;
begin
try
Result:= ptr;
ReallocMem(Result, nSize);
except
Result:= nil;
end;
end;
function print_func(L : Plua_State) : Integer; cdecl;
var
i, c: integer;
s: string;
begin
Result := 0;
if not Assigned(MyApp) then Exit;
c:= lua_gettop(L);
s:= '';
for i:= 1 to c do s:= s + lua_tostring(L, i);
MyApp.AddLog(s);
end;
function tonumberDef_func(L : Plua_State) : Integer; cdecl;
var
s: string;
n: lua_Number;
begin
s:= lua_tostring(L, 1);
n:= lua_tonumber(L, 2);
lua_pushnumber(L, StrToFloatDef(s, n));
Result := 1;
end;
function regexpr_matches_func(L : Plua_State) : Integer; cdecl;
var
s1, s2: string;
begin
s1:= lua_tostring(L, 1);
s2:= lua_tostring(L, 2);
try
lua_pushboolean(L, ExecRegExpr(s2, s1));
except
on E: Exception do begin
luaL_error(L, PChar(E.Message), []);
end;
end;
Result := 1;
end;
function ScriptFileExists_func(L : Plua_State) : Integer; cdecl;
var
s, s1, s2: string;
b: boolean;
begin
s:= lua_tostring(L, 1);
b:= FileExistsUTF8(ExecPath + 'script/' + s + '.lua');
if not b then begin
s1:= SIPCServer.GetValue('UserScripts');
while not b do begin
s2:= Fetch(s1, '|');
if s2 = '' then Break;
b:= FileExistsUTF8(ExecPath + 'script/' + s2 + '/' + s + '.lua');
end;
end;
lua_pushboolean(L, b);
Result := 1;
end;
function ExtractFileName_func(L : Plua_State) : Integer; cdecl;
begin
lua_pushstring(L, ExtractFileName(lua_tostring(L, 1)));
Result := 1;
end;
function ExtractFilePath_func(L : Plua_State) : Integer; cdecl;
begin
lua_pushstring(L, ExtractFilePath(lua_tostring(L, 1)));
Result := 1;
end;
function GetCmdStdOut_func(L : Plua_State) : Integer; cdecl;
var
s: string;
proc: TPipeProcExec;
begin
proc:= TPipeProcExec.Create;
try
s:= lua_tostring(L, 1);
{$IFDEF Windows}
if ExtractFilePath(s) = '' then s:= ExecPath + s;
{$ENDIF}
proc.Cmds.Add('"' + s + '" ' + lua_tostring(L, 2));
proc.Start;
while not proc.Done do ;
lua_pushstring(L, proc.OutputMsgs[0]);
Result := 1;
finally
//proc.Terminate;
//proc.WaitFor;
proc.Free;
end;
end;
function FileExists_func(L : Plua_State) : Integer; cdecl;
begin
lua_pushboolean(L, FileExistsUTF8(lua_tostring(L, 1)));
Result := 1;
end;
(*
function GetTempFileName_func(L : Plua_State) : Integer; cdecl;
begin
lua_pushstring(L, FileUtil.GetTempFileName(lua_tostring(L, 1), lua_tostring(L, 2)));
Result := 1;
end;
function DeleteFileMatches_func(L : Plua_State) : Integer; cdecl;
var
info: TSearchRec;
dir, reg: string;
begin
Result := 0;
dir:= lua_tostring(L, 1);
reg:= lua_tostring(L, 2);
if dir = '' then Exit;
if FindFirstUTF8(dir+'*', faAnyFile, info) = 0 then
try
repeat
if (info.Name <> '.') and (info.Name <> '..') and
ExecRegExpr(reg, info.Name) then begin
if info.Attr and faDirectory <> 0 then begin
//RemoveDirPerfect(dir+info.Name+'/');
end else begin
DeleteFileUTF8(dir + info.Name);
end;
end;
until FindNextUTF8(info) <> 0;
finally
FindCloseUTF8(Info);
end;
end;
*)
procedure InitLua(L: Plua_State);
procedure regTable(const tablename, funcname: string; func: lua_CFunction);
begin
lua_getglobal(L, PChar(tablename));
if lua_isnil(L, -1) then begin
lua_pop(L, 1);
lua_newtable(L);
lua_setglobal(L, PChar(tablename));
lua_getglobal(L, PChar(tablename));
end;
lua_pushstring(L, funcname);
lua_pushcfunction(L, func);
lua_settable(L, -3);
lua_setglobal(L, PChar(tablename));
end;
begin
luaL_openlibs(L);
lua_register(L, 'print', @print_func);
lua_register(L, 'tonumberDef', @tonumberDef_func);
regTable('fileu', 'ExtractFileName', @ExtractFileName_func);
regTable('fileu', 'ExtractFilePath', @ExtractFilePath_func);
regTable('fileu', 'GetCmdStdOut', @GetCmdStdOut_func);
regTable('fileu', 'FileExists', @FileExists_func);
//regTable('fileu', 'GetTempFileName', @GetTempFileName_func);
//regTable('fileu', 'DeleteFileMatches', @DeleteFileMatches_func);
regTable('regexpr', 'matches', @regexpr_matches_func);
lua_register(L, 'BMS_ScriptFileExists', @ScriptFileExists_func);
lua_pushstring(L, ExecPath); lua_setglobal(L, 'BMS_ExecPath');
lua_pushstring(L, TempPath); lua_setglobal(L, 'BMS_TempPath');
lua_getglobal(L, 'package');
lua_pushstring(L, 'path');
lua_pushstring(L, ExecPath + 'script' + DirectorySeparator + '?.lua');
lua_settable(L, -3);
lua_pushstring(L, 'cpath');
lua_pushstring(L, ExecPath + 'script' + DirectorySeparator + '?.dll');
lua_settable(L, -3);
lua_pop(L, 1);
end;
procedure CallLua(L: Plua_State; nargs, nresults: Integer);
begin
if lua_pcall(L, nargs, nresults, 0) <> 0 then
Raise Exception.Create('Lua Runtime Error('+lua_tostring(L, -1)+')');
end;
function DumpWriter({%H-}L: Plua_State; const p: Pointer; sz: size_t;
ud: Pointer): Integer; cdecl;
var
DumpSize: LongWord;
begin
DumpSize:= PLongWord(ud^)^;
PLongWord(ud^)^:= DumpSize + sz;
ReallocMem(PChar(ud^), SizeOf(LongWord)+DumpSize+sz);
move(Byte(p^), (PChar(ud^)+SizeOf(LongWord)+DumpSize)^, sz);
Result:= 0;
end;
function LoadLuaRawRaw(L: Plua_State; const code, module: string; GetBin: boolean): string;
var
DumpCode: PChar;
begin
Result:= '';
if luaL_loadbuffer(L, PChar(code), Length(code), PChar(module)) <> 0 then
Raise Exception.Create(module + ' Compile Error(' + lua_tostring(L, -1)+')');
if GetBin then begin
// コンパイル済みコードを保持
GetMem(DumpCode, SizeOf(LongWord));
try
PLongWord(DumpCode)^:= 0;
lua_dump(L, @DumpWriter, @DumpCode);
SetLength(Result, PLongWord(DumpCode)^);
move((DumpCode+SizeOf(LongWord))^, Result[1], PLongWord(DumpCode)^);
finally
FreeMem(DumpCode);
end;
end;
CallLua(L, 0, 0);
end;
function LoadLuaRaw(L: Plua_State; const fname: string;
const code: string = ''; code_t: integer = 0): string;
var
sl: TStringListUTF8;
begin
if fname = '' then Exit;
if (code <> '') and (GetFileTime(fname) = code_t) then begin
LoadLuaRawRaw(L, code, fname + '.lua', False);
Result:= '';
end else begin
sl:= TStringListUTF8.Create;
try
try
sl.LoadFromFile(fname);
except
Exit;
end;
if (sl.Count > 0) and (Length(sl[0]) >= 3) and
(sl[0][1] = #$EF) and (sl[0][2] = #$BB) and (sl[0][3] = #$BF) then begin
// BOM を削除
sl[0]:= Copy(sl[0], 4, MaxInt);
end;
Result:= LoadLuaRawRaw(L, sl.Text, fname, True);
finally
sl.Free;
end;
end;
end;
procedure LoadLua(L: Plua_State; const fname: string; chunks: TStringList);
var
s, s1, s2, chunk: string;
i: Integer;
obj: TChunkObj;
begin
if fname = '' then Exit;
if ExtractFilePath(fname) = '' then begin
s:= ExecPath + 'script/' + fname + '.lua';
if FileExistsUTF8(s) then begin
i:= chunks.IndexOf(fname);
if i < 0 then begin
obj:= TChunkObj.Create;
chunks.AddObject(fname, obj);
end else
obj:= TChunkObj(chunks.Objects[i]);
chunk:= LoadLuaRaw(L, s, obj.bin, obj.time);
if chunk <> '' then begin
obj.bin:= chunk;
obj.time:= GetFileTime(s);
end;
end;
s1:= SIPCServer.GetValue('UserScripts');
while True do begin
s2:= Fetch(s1, '|');
if s2 = '' then Break;
s:= ExecPath + 'script/' + s2 + '/' + fname + '.lua';
if not FileExistsUTF8(s) then Continue;
i:= chunks.IndexOf(s2 + '/' + fname);
if i < 0 then begin
obj:= TChunkObj.Create;
chunks.AddObject(s2 + '/' + fname, obj);
end else
obj:= TChunkObj(chunks.Objects[i]);
chunk:= LoadLuaRaw(L, s, obj.bin, obj.time);
if chunk <> '' then begin
obj.bin:= chunk;
obj.time:= GetFileTime(s);
end;
end;
end else
LoadLuaRaw(L, fname);
end;
procedure MIValue2LuaTable(L: PLua_State; const key, val: string);
var
s, ss: string;
isnill: boolean;
begin
s:= key;
ss:= Fetch(s, ';');
if s = '' then begin
lua_pushstring(L, ss);
lua_pushstring(L, val);
lua_rawset(L, -3);
end else begin
lua_pushstring(L, ss);
lua_rawget(L, -2);
isnill:= lua_isnil(L, -1);
if isnill then begin
lua_pop(L, 1);
lua_pushstring(L, ss);
lua_newtable(L);
end;
MIValue2LuaTable(L, s, val);
if isnill then begin
lua_rawset(L, -3);
end else begin
lua_pop(L, 1);
end;
end;
end;
procedure LuaTable2ValStringList(L: PLua_State; sl: TValStringList);
begin
lua_pushnil(L); // first key
while lua_next(L, -2) <> 0 do begin
// uses 'key' (at index -2) and 'value' (at index -1)
sl.AddVal(lua_tostring(L, -2), lua_tostring(L, -1));
// removes 'value'; keeps 'key' for next iteration
lua_pop(L, 1);
end;
end;
procedure ValStringList2LuaTable(L: PLua_State; sl: TValStringList);
var
i: integer;
begin
for i:= 0 to sl.Count-1 do begin
lua_pushstring(L, sl[i]);
lua_pushstring(L, sl.Vali[i]);
lua_rawset(L, -3);
end;
end;
procedure SendAlive;
var
sock: TUDPBlockSocket;
s: string;
begin
// Sends an advertisement "alive" message on multicast
sock:= TUDPBlockSocket.Create;
try
sock.Family:= SF_IP4;
sock.CreateSocket();
sock.Bind(MyIPAddr{'0.0.0.0'}, '0');
sock.MulticastTTL:= 1;
sock.Connect('239.255.255.250', '1900'{SSDP});
if sock.LastError = 0 then begin
//{
s:=
'NOTIFY * HTTP/1.1' + CRLF +
'HOST: 239.255.255.250:1900'+ CRLF +
'CACHE-CONTROL: max-age=1800'+ CRLF +
'LOCATION: http://' + MyIPAddr + ':' + DAEMON_PORT +
'/desc.xml' + CRLF +
'NT: upnp:rootdevice'+ CRLF +
'NTS: ssdp:alive'+ CRLF +
'SERVER: ' + HTTP_HEAD_SERVER + CRLF +
'USN: uuid:' + UUID + '::upnp:rootdevice' +
CRLF + CRLF;
sock.SendString(s);
s:=
'NOTIFY * HTTP/1.1' + CRLF +
'HOST: 239.255.255.250:1900'+ CRLF +
'CACHE-CONTROL: max-age=1800'+ CRLF +
'LOCATION: http://' + MyIPAddr + ':' + DAEMON_PORT +
'/desc.xml' + CRLF +
'NT: uuid:' + UUID + CRLF +
'NTS: ssdp:alive'+ CRLF +
'SERVER: ' + HTTP_HEAD_SERVER + CRLF +
'USN: uuid:' + UUID +
CRLF + CRLF;
sock.SendString(s);
//}
s:=
'NOTIFY * HTTP/1.1' + CRLF +
'HOST: 239.255.255.250:1900'+ CRLF +
'CACHE-CONTROL: max-age=1800'+ CRLF +
'LOCATION: http://' + MyIPAddr + ':' + DAEMON_PORT +
'/desc.xml' + CRLF +
'NT: urn:schemas-upnp-org:device:MediaServer:1' + CRLF +
'NTS: ssdp:alive'+ CRLF +
'SERVER: ' + HTTP_HEAD_SERVER + CRLF +
'USN: uuid:' + UUID + '::urn:schemas-upnp-org:device:MediaServer:1' +
CRLF + CRLF;
sock.SendString(s);
//{
s:=
'NOTIFY * HTTP/1.1' + CRLF +
'HOST: 239.255.255.250:1900'+ CRLF +
'CACHE-CONTROL: max-age=1800'+ CRLF +
'LOCATION: http://' + MyIPAddr + ':' + DAEMON_PORT +
'/desc.xml' + CRLF +
'NT: urn:schemas-upnp-org:service:ContentDirectory:1' + CRLF +
'NTS: ssdp:alive'+ CRLF +
'SERVER: ' + HTTP_HEAD_SERVER + CRLF +
'USN: uuid:' + UUID + '::urn:schemas-upnp-org:service:ContentDirectory:1' +
CRLF + CRLF;
sock.SendString(s);
s:=
'NOTIFY * HTTP/1.1' + CRLF +
'HOST: 239.255.255.250:1900'+ CRLF +
'CACHE-CONTROL: max-age=1800'+ CRLF +
'LOCATION: http://' + MyIPAddr + ':' + DAEMON_PORT +
'/desc.xml' + CRLF +
'NT: urn:schemas-upnp-org:service:ConnectionManager:1' + CRLF +
'NTS: ssdp:alive'+ CRLF +
'SERVER: ' + HTTP_HEAD_SERVER + CRLF +
'USN: uuid:' + UUID + '::urn:schemas-upnp-org:service:ConnectionManager:1' +
CRLF + CRLF;
sock.SendString(s);
//}
end;
finally
sock.Free;
end;
end;
procedure SendByebye;
var
sock: TUDPBlockSocket;
s: string;
begin
// Sends an advertisement "byebye" message on multicast
sock:= TUDPBlockSocket.Create;
try
Sock.Family:= SF_IP4;
sock.CreateSocket();
sock.Bind(MyIPAddr{'0.0.0.0'}, '0');
sock.MulticastTTL:= 1;
sock.Connect('239.255.255.250', '1900'{SSDP});
if sock.LastError = 0 then begin
//{
s:=
'NOTIFY * HTTP/1.1' + CRLF +
'HOST: 239.255.255.250:1900'+ CRLF +
'NT: upnp:rootdevice'+ CRLF +
'NTS: ssdp:byebye'+ CRLF +
'USN: uuid:' + UUID + '::upnp:rootdevice' +
CRLF + CRLF;
sock.SendString(s);
//}
s:=
'NOTIFY * HTTP/1.1' + CRLF +
'HOST: 239.255.255.250:1900'+ CRLF +
'NT: urn:schemas-upnp-org:device:MediaServer:1' + CRLF +
'NTS: ssdp:byebye'+ CRLF +
'USN: uuid:' + UUID + '::urn:schemas-upnp-org:device:MediaServer:1' +
CRLF + CRLF;
sock.SendString(s);
//{
s:=
'NOTIFY * HTTP/1.1' + CRLF +
'HOST: 239.255.255.250:1900'+ CRLF +
'NT: urn:schemas-upnp-org:service:ContentDirectory:1' + CRLF +
'NTS: ssdp:byebye'+ CRLF +
'USN: uuid:' + UUID + '::urn:schemas-upnp-org:service:ContentDirectory:1' +
CRLF + CRLF;
sock.SendString(s);
s:=
'NOTIFY * HTTP/1.1' + CRLF +
'HOST: 239.255.255.250:1900'+ CRLF +
'NT: urn:schemas-upnp-org:service:ConnectionManager:1' + CRLF +
'NTS: ssdp:byebye'+ CRLF +
'USN: uuid:' + UUID + '::urn:schemas-upnp-org:service:ConnectionManager:1' +
CRLF + CRLF;
sock.SendString(s);
//}
end;
finally
sock.Free;
end;
end;
function GetLineHeader: string;
begin
Result:= '*** ' + FormatDateTime('mm/dd hh:nn:ss ', Now);
end;
var
PrevWndProc: WNDPROC;
{$IFDEF Windows}
function WndCallback(Ahwnd: HWND; uMsg: UINT; wParam: WParam; lParam: LParam):LRESULT; stdcall;
var
msg: TMessage;
begin
case uMsg of
WM_POWERBROADCAST: begin
msg.Result:= Windows.DefWindowProc(Ahwnd, uMsg, WParam, LParam); //not sure about this one
msg.msg:= uMsg;
msg.wParam:= wParam;
msg.lParam:= lParam;
MyApp.WMPowerBoadcast(msg);
Result:= msg.Result;
Exit;
end;
WM_ENDSESSION: begin
SendByebye;
end;
end;
result:=CallWindowProc(PrevWndProc,Ahwnd, uMsg, WParam, LParam);
end;
{$ENDIF}
procedure InitAfterApplicationInitialize;
begin
{$IFDEF Windows}
PrevWndProc:= {%H-}Windows.WNDPROC(SetWindowLong(Widgetset.AppHandle, GWL_WNDPROC,{%H-}PtrInt(@WndCallback)));
{$ENDIF}
end;
{ TMyApp }
constructor TMyApp.Create;
var
mi: TMenuItem;
i: integer;
sl: TStringList;
sock: TBlockSocket;
s, tray_msg: String;
begin
tray_msg:= '';
UUID:= '';
if FileExistsUTF8(ExecPath + 'UUID') then begin
sl:= TStringListUTF8.Create;
try
sl.LoadFromFile(ExecPath + 'UUID');
if sl.Count > 0 then UUID:= sl[0];
finally
sl.Free;
end;
end;
if UUID = '' then begin
UUID:= Copy(CreateClassID, 2, 36); // 新しいUUIDを作成
sl:= TStringListUTF8.Create;
try
sl.Add(UUID);
sl.SaveToFile(ExecPath + 'UUID');
finally
sl.Free;
end;
end;
DAEMON_PORT:= iniFile.ReadString(INI_SEC_SYSTEM, 'HTTP_PORT', '5008');
Log:= TStringListUTF8.Create;
MAX_REQUEST_COUNT:= iniFile.ReadInteger(INI_SEC_SYSTEM, 'MAX_REQUEST_COUNT', 0);
SEND_DATA_TIMEOUT:= iniFile.ReadInteger(INI_SEC_SYSTEM, 'SEND_DATA_TIMEOUT', 60*60);
if SEND_DATA_TIMEOUT > 0 then SEND_DATA_TIMEOUT:= SEND_DATA_TIMEOUT * 1000
else SEND_DATA_TIMEOUT:= MaxInt;
MediaDirs:= TStringListUTF8.Create;
iniFile.ReadSectionValues('MediaDirs', MediaDirs);
i:= 0;
while i < MediaDirs.Count do begin
if (MediaDirs.Names[i] = '') or (MediaDirs.ValueFromIndex[i] = '') or
(Trim(MediaDirs[i])[1] = ';') then begin
MediaDirs.Delete(i);
end else
Inc(i);
end;
if MediaDirs.Count = 0 then
tray_msg:= tray_msg + CR + 'ERROR: bms.iniにおいて[MediaDirs]が未設定です。';
if not DirectoryExistsUTF8(TempPath) then
ForceDirectoriesUTF8(TempPath);
ClientInfoList:= TStringListUTF8_mod.Create;
ClientInfoList.Sorted:= True;
thMIC:= TMediaInfoCollector.Create;
try
thMIC.LoadMediaInfo;
except
tray_msg:= tray_msg + CR + 'ERROR: ' + MEDIA_INFO_DB_FILENAME + 'が破損しています。';
end;
sl:= TStringListUTF8.Create;
try
iniFile.ReadSections(sl);
if sl.IndexOf(INI_SEC_MIKeys) < 0 then
tray_msg:= tray_msg + CR + 'WARNING: bms.iniにおいて[' + INI_SEC_MIKeys + ']が未設定です。';
finally
sl.Free;
end;
thMIC.Start;
SIPCServer:= TMySimpleIPCServer.Create;
SIPCServer.ServerID:= 'SIPC:' + SHORT_APP_NAME + SHORT_APP_VERSION + ':' + DAEMON_PORT;
SIPCServer.vsl.Vals['UserScripts']:= iniFile.ReadString(INI_SEC_SCRIPTS, 'user', '');
SIPCServer.OnMessage:= @SIPCServer.DoMessage;
SIPCServer.Global:= True;
SIPCServer.StartServer;
sl:= TStringListUTF8.Create;
try
sock:= TBlockSocket.Create;
try
sock.Family:= SF_IP4;
sock.ResolveNameToIP(sock.LocalName, sl);
if sl.Count > 0 then begin
s:= iniFile.ReadString(INI_SEC_SYSTEM, 'IP_INTERFACE', '');
if s <> '' then begin
i:= StrToIntDef(s, 0);
if i > 0 then begin
if i <= sl.Count then
MyIPAddr:= sl[i-1];
end else if sl.IndexOf(s) >= 0 then
MyIPAddr:= s;
end;
if MyIPAddr = '' then
MyIPAddr:= sl[0];
end;
finally
sock.Free;
end;
finally
sl.Free;
end;
if MyIPAddr <> '' then begin
// Run HTTP Daemon
thHttpDaemon:= THttpDaemon.Create;
// Run SSDP Daemon
thSSDPDaemon:= TSSDPDaemon.Create;
//SendAlive;
end else begin
tray_msg:= tray_msg + CR + 'ERROR: 自己 IP アドレスが取得できませんでした。';
end;
PopupMenu:= TPopupMenu.Create(nil);
mi:= TMenuItem.Create(nil);
mi.Caption:= '&Show';
mi.OnClick:= @OnMenuShowClick;
PopupMenu.Items.Add(mi);
mi:= TMenuItem.Create(nil);
mi.Caption:= '-';
PopupMenu.Items.Add(mi);
mi:= TMenuItem.Create(nil);
mi.Caption:= '&Quit';
mi.OnClick:= @OnMenuQuitClick;
PopupMenu.Items.Add(mi);
TrayIcon.PopUpMenu := PopupMenu;
TrayIcon.OnClick:= @MyApp.OnTrayIconClick;
if tray_msg <> '' then begin
TrayIcon.BalloonHint:= tray_msg;
TrayIcon.ShowBalloonHint;
end;
end;
destructor TMyApp.Destroy;
var
i: Integer;
begin
SendByebye;
if Assigned(thSSDPDaemon) then begin
thSSDPDaemon.Terminate;
//thSSDPDaemon.Sock.CloseSocket;
thSSDPDaemon.WaitFor;
thSSDPDaemon.Free;
end;
if Assigned(thHttpDaemon) then begin
thHttpDaemon.Terminate;
//thHTTPDaemon.Sock.CloseSocket;
thHttpDaemon.WaitFor;
thHttpDaemon.Free;
end;
SIPCServer.Free;
if Assigned(thMIC) then begin
tHMIC.Suspended:= False;
thMIC.Terminate;
thMIC.WaitFor;
if iniFile.ReadInteger(INI_SEC_SYSTEM, 'SAVE_MEDIAINFO', 0) <> 0 then begin
try
thMIC.SaveMediaInfo;
except
end;
end else begin
DeleteFileUTF8(ExecPath + 'db/' + MEDIA_INFO_DB_FILENAME);
end;
thMIC.Free;
end;
for i:= 0 to ClientInfoList.Count-1 do ClientInfoList.Objects[i].Free;
ClientInfoList.Free;
Log.Free;
LogFile.Free;
MediaDirs.Free;
while PopupMenu.Items.Count > 0 do begin
PopupMenu.Items[0].Free;
//PopupMenu.Items.Delete(0);
end;
PopupMenu.Free;
inherited Destroy;
end;
procedure TMyApp.OnTrayIconClick(Sender: TObject);
begin
if Assigned(Form1) then begin
Form1.Show;
Form1.WindowState:= wsNormal;
end else begin
Application.CreateForm(TForm1, Form1);
try
//TrayIcon.PopupMenu.Items[1].Visible:= False;
if Form1.ShowModal = mrClose then begin
Application.Terminate;
Exit;
end;
//TrayIcon.PopupMenu.Items[1].Visible:= True;
finally
FreeAndNil(Form1);
end;
end;
end;
procedure TMyApp.OnMenuShowClick(Sender: TObject);
begin
OnTrayIconClick(nil);
end;
procedure TMyApp.OnMenuQuitClick(Sender: TObject);
begin
Application.Terminate;
end;
procedure TMyApp.AddLog(const line: string);
var
s: string;
begin
Log.Add(line);
while Log.Count > MAX_ONMEM_LOG do Log.Delete(0);