ceffilescheme.pas 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. (*
  2. * Delphi Chromium Embedded
  3. *
  4. * Usage allowed under the restrictions of the Lesser GNU General Public License
  5. * or alternatively the restrictions of the Mozilla Public License 1.1
  6. *
  7. * Software distributed under the License is distributed on an "AS IS" basis,
  8. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
  9. * the specific language governing rights and limitations under the License.
  10. *
  11. * Unit owner : Henri Gourvest <hgourvest@gmail.com>
  12. * Web site : http://www.progdigy.com
  13. * Repository : http://code.google.com/p/delphichromiumembedded/
  14. * Group : http://groups.google.com/group/delphichromiumembedded
  15. *)
  16. {$IFDEF FPC}
  17. {$MODE DELPHI}{$H+}
  18. {$ENDIF}
  19. unit ceffilescheme;
  20. {$R 'ceffilescheme.res'}
  21. {$WARN SYMBOL_PLATFORM OFF}
  22. interface
  23. uses ceflib, Classes;
  24. type
  25. TFileScheme = class(TCefResourceHandlerOwn)
  26. private
  27. FPath: string;
  28. FDataStream: TStream;
  29. FStatus: Integer;
  30. FStatusText: string;
  31. FMimeType: string;
  32. protected
  33. function ProcessRequest(const request: ICefRequest;
  34. const callback: ICefCallback): Boolean; override;
  35. procedure GetResponseHeaders(const response: ICefResponse;
  36. out responseLength: Int64; out redirectUrl: ustring); override;
  37. function ReadResponse(const dataOut: Pointer; bytesToRead: Integer;
  38. var bytesRead: Integer; const callback: ICefCallback): Boolean; override;
  39. public
  40. constructor Create(const browser: ICefBrowser; const frame: ICefFrame;
  41. const schemeName: ustring; const request: ICefRequest); override;
  42. destructor Destroy; override;
  43. end;
  44. implementation
  45. uses Windows, SysUtils, Registry, Contnrs;
  46. function Escape(const str: ustring): string;
  47. var
  48. p: PWideChar;
  49. begin
  50. Result := '';
  51. p := PWideChar(str);
  52. while p^ <> #0 do
  53. begin
  54. if Ord(p^) > 255 then
  55. Result := Result + '\u' + IntToHex(Ord(p^), 4) else
  56. if (AnsiChar(p^) in ['\', '"']) then
  57. Result := Result + '\' + p^ else
  58. Result := Result + p^;
  59. inc(p);
  60. end;
  61. end;
  62. type
  63. TFileInfo = class
  64. name: ustring;
  65. size: Int64;
  66. date: TFileTime;
  67. attr: Integer;
  68. constructor Create(const aname: ustring; asize: Int64; adate: TFileTime; aattr: Integer);
  69. function DisplaySize: string;
  70. function DisplayDate: string;
  71. function Display: string;
  72. end;
  73. constructor TFileInfo.Create(const aname: ustring; asize: Int64; adate: TFileTime; aattr: Integer);
  74. begin
  75. name := aname;
  76. size := asize;
  77. date := adate;
  78. attr := aattr;
  79. end;
  80. function TFileInfo.DisplaySize: string;
  81. const
  82. s: array[0..5] of Int64 = (
  83. 1024,
  84. 1048576,
  85. 1073741824,
  86. 1099511627776,
  87. 1125899906842624,
  88. 1152921504606846976);
  89. begin
  90. if size < S[0] then Result := Format('%d B', [size]) else
  91. if size < S[1] then Result := Format('%0.1f kB', [size/S[0]]) else
  92. if size < S[2] then Result := Format('%0.1f MB', [size/S[1]]) else
  93. if size < S[3] then Result := Format('%0.1f GB', [size/S[2]]) else
  94. if size < S[4] then Result := Format('%0.1f TB', [size/S[3]]) else
  95. if size < S[5] then Result := Format('%0.1f PB', [size/S[4]]) else
  96. Result := 'big';
  97. end;
  98. function TFileInfo.DisplayDate: string;
  99. var
  100. local: TFileTime;
  101. sys: TSystemTime;
  102. dt: TDateTime;
  103. begin
  104. FileTimeToLocalFileTime(date, local);
  105. FileTimeToSystemTime(local, sys);
  106. with sys do
  107. dt := EncodeDate(wYear, wMonth, wDay) + EncodeTime(wHour, wMinute, wSecond, wMilliSeconds);
  108. Result := DateTimeToStr(dt);
  109. end;
  110. function TFileInfo.Display: string;
  111. var
  112. d: Integer;
  113. begin
  114. if attr and faDirectory = faDirectory then
  115. d := 1 else d := 0;
  116. Result := Format('<script>addRow("%s","%0:s",%d,"%s","%s");</script>'#13#10, [Escape(name), d, DisplaySize, DisplayDate])
  117. end;
  118. function FileSortCompare(Item1, Item2: TFileInfo): Integer;
  119. begin
  120. if (Item1.attr and faDirectory = faDirectory) then
  121. begin
  122. if (Item2.attr and faDirectory = faDirectory) then
  123. Result := CompareText(Item1.name, Item2.name) else
  124. Result := -1;
  125. end else
  126. if (Item2.attr and faDirectory <> faDirectory) then
  127. Result := CompareText(Item1.name, Item2.name) else
  128. Result := 1;
  129. end;
  130. function HTTPDecode(const AStr: ustring): rbstring;
  131. var
  132. Sp, Rp, Cp: PAnsiChar;
  133. src: rbstring;
  134. begin
  135. src := rbstring(AStr);
  136. SetLength(Result, Length(src));
  137. Sp := PAnsiChar(src);
  138. Rp := PAnsiChar(Result);
  139. while Sp^ <> #0 do
  140. begin
  141. case Sp^ of
  142. '+': Rp^ := ' ';
  143. '%': begin
  144. Inc(Sp);
  145. if Sp^ = '%' then
  146. Rp^ := '%'
  147. else
  148. begin
  149. Cp := Sp;
  150. Inc(Sp);
  151. if (Cp^ <> #0) and (Sp^ <> #0) then
  152. Rp^ := AnsiChar(StrToInt('$' + Char(Cp^) + Char(Sp^)))
  153. else
  154. begin
  155. Result := '';
  156. Exit;
  157. end;
  158. end;
  159. end;
  160. else
  161. Rp^ := Sp^;
  162. end;
  163. Inc(Rp);
  164. Inc(Sp);
  165. end;
  166. SetLength(Result, Rp - PAnsiChar(Result));
  167. end;
  168. function ParseFileUrl(const url: ustring): ustring;
  169. label
  170. error;
  171. var
  172. p, s: PWideChar;
  173. state: Integer;
  174. begin
  175. p := PWideChar(url);
  176. s := nil;
  177. state := 0;
  178. while True do
  179. begin
  180. case state of
  181. 0: case p^ of
  182. ':': state := 1;
  183. #0: goto error;
  184. end;
  185. 1: if p^ = '/' then
  186. state := 2 else
  187. goto error;
  188. 2: if p^ = '/' then
  189. begin
  190. state := 3;
  191. s := p;
  192. end else
  193. goto error;
  194. 3: case p^ of
  195. '/':
  196. begin
  197. p[-1] := ':';
  198. p^ := '\';
  199. state := 4;
  200. end;
  201. #0:
  202. goto error;
  203. else
  204. p[-1] := p^;
  205. end;
  206. 4:
  207. begin
  208. case p^ of
  209. '/': p^ := '\';
  210. #0:
  211. {$IFDEF UNICODE}
  212. Exit(ustring(HTTPDecode(string(UTF8String(s)))));
  213. {$ELSE}
  214. begin
  215. Result := UTF8Decode(HTTPDecode(s));
  216. Exit;
  217. end;
  218. {$ENDIF}
  219. end;
  220. end;
  221. end;
  222. Inc(p);
  223. end;
  224. error:
  225. Result := '';
  226. end;
  227. { TFileScheme }
  228. constructor TFileScheme.Create(const browser: ICefBrowser; const frame: ICefFrame;
  229. const schemeName: ustring; const request: ICefRequest);
  230. begin
  231. inherited;
  232. FDataStream := nil;
  233. end;
  234. destructor TFileScheme.Destroy;
  235. begin
  236. if FDataStream <> nil then
  237. FDataStream.Free;
  238. inherited;
  239. end;
  240. procedure TFileScheme.GetResponseHeaders(const response: ICefResponse;
  241. out responseLength: Int64; out redirectUrl: ustring);
  242. begin
  243. response.Status := FStatus;
  244. response.StatusText := FStatusText;
  245. response.MimeType := FMimeType;
  246. responseLength := FDataStream.Size;
  247. end;
  248. function TFileScheme.ProcessRequest(const request: ICefRequest;
  249. const callback: ICefCallback): Boolean;
  250. var
  251. rec: TSearchRec;
  252. reg: TRegistry;
  253. Items: TObjectList;
  254. i: Integer;
  255. rc: TResourceStream;
  256. procedure OutPut(const str: string);
  257. {$IFDEF UNICODE}
  258. var
  259. rb: rbstring;
  260. {$ENDIF}
  261. begin
  262. {$IFDEF UNICODE}
  263. rb := rbstring(str);
  264. FDataStream.Write(rb[1], Length(rb))
  265. {$ELSE}
  266. FDataStream.Write(str[1], Length(str))
  267. {$ENDIF}
  268. end;
  269. procedure OutputUTF8(const str: string);
  270. var
  271. rb: rbstring;
  272. begin
  273. {$IFDEF UNICODE}
  274. rb := utf8string(str);
  275. {$ELSE}
  276. rb := UTF8Encode(str);
  277. {$ENDIF}
  278. FDataStream.Write(rb[1], Length(rb))
  279. end;
  280. var
  281. n: Integer;
  282. begin
  283. Result := True;
  284. FPath := ParseFileUrl(Request.Url);
  285. n := Pos('?', FPath);
  286. if n > 0 then
  287. SetLength(FPath, n-1);
  288. if FindFirst(FPath, 0, rec) = 0 then
  289. begin
  290. FStatus := 200;
  291. FStatusText := 'OK';
  292. FindClose(rec);
  293. reg := TRegistry.Create;
  294. try
  295. reg.RootKey := HKEY_CLASSES_ROOT;
  296. if reg.OpenKey(ExtractFileExt(FPath), False) then
  297. FMimeType := reg.ReadString('Content Type') else
  298. if LowerCase(ExtractFileExt(FPath)) = '.pdf' then
  299. FMimeType := 'application/pdf';
  300. finally
  301. reg.Free;
  302. end;
  303. if FMimeType = '' then
  304. FMimeType := 'application/octet-stream';
  305. FDataStream := TFileStream.Create(FPath, fmOpenRead or fmShareDenyNone);
  306. end else
  307. if DirectoryExists(FPath) then
  308. begin
  309. FStatus := 200;
  310. FStatusText := 'OK';
  311. Items := TObjectList.Create(True);
  312. try
  313. FPath := IncludeTrailingPathDelimiter(FPath);
  314. FDataStream := TMemoryStream.Create;
  315. rc := TResourceStream.Create(HInstance, 'CEFFILESCHEMEDIR', RT_RCDATA);
  316. try
  317. rc.SaveToStream(FDataStream);
  318. finally
  319. rc.Free;
  320. end;
  321. OutPut(Format('<script>start("%s");</script>'#13#10, [escape(FPath)]));
  322. if FindFirst(FPath + '*.*', faAnyFile, rec) = 0 then
  323. begin
  324. repeat
  325. if rec.Name <> '.' then
  326. Items.Add(TFileInfo.Create(rec.Name, rec.Size, rec.FindData.ftLastWriteTime, rec.Attr));
  327. until FindNext(rec) <> 0;
  328. FindClose(rec);
  329. end;
  330. Items.Sort(@FileSortCompare);
  331. for i := 0 to Items.Count - 1 do
  332. OutPut(TFileInfo(Items[i]).Display);
  333. FDataStream.Seek(0, soFromBeginning);
  334. FMimeType := 'text/html';
  335. finally
  336. Items.Free;
  337. end;
  338. end else
  339. begin
  340. FStatus := 404;
  341. FStatusText := 'Not found';
  342. // error
  343. FDataStream := TMemoryStream.Create;
  344. OutputUTF8('<html><head><meta http-equiv="content-type" content="text/html; '+
  345. 'charset=UTF-8"/></head><body><h1>'+ FPath+'</h1><h2>not found</h2></body></html>');
  346. FMimeType := 'text/html';
  347. FDataStream.Seek(0, soFromBeginning);
  348. end;
  349. callback.Cont;
  350. end;
  351. function TFileScheme.ReadResponse(const dataOut: Pointer; bytesToRead: Integer;
  352. var bytesRead: Integer; const callback: ICefCallback): Boolean;
  353. begin
  354. BytesRead := FDataStream.Read(DataOut^, BytesToRead);
  355. Result := True;
  356. callback.Cont;
  357. end;
  358. end.