Debian Codegraph @

src/files/castleinternalurlutils.pas

raw
1 {
2 Copyright 2023-2023 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Internal URL utilities. }
17 unit CastleInternalUrlUtils;
18
19 {$I castleconf.inc}
20
21 interface
22
23 { Turn URL into a nice component name.
24 May return '' if not possible. }
25 function GetBaseNameFromUrl(const Url: String): String;
26
27 { Get parent directory name from URL, sans Sketchfab model id.
28 E.g. from
29 'castle-data:/sketchfab/cat-123abc/scene.gltf'
30 get
31 'cat'
32 Returns '' if no useful parent directory.
33 }
34 function GetUrlParentName(const Url: String): String;
35
36 implementation
37
38 uses UriParser, SysUtils,
39 CastleStringUtils, CastleUriUtils;
40
41 function IsModelId(const Id: String): Boolean;
42 begin
43 Result := CharsPos(AllChars - ['0'..'9', 'a'..'f', 'A'..'F'], Id) = 0;
44 end;
45
46 function GetUrlParentName(const Url: String): String;
47 var
48 U: TUri;
49 PosIdDelimiter: Integer;
50 begin
51 U := ParseUri(Url);
52 Result := ExtractUriName(UriExcludeSlash(U.Path));
53
54 // strip Sketchfab model id
55 PosIdDelimiter := BackPos('-', Result);
56 if (PosIdDelimiter <> 0) and
57 (IsModelId(SEnding(Result, PosIdDelimiter + 1))) then
58 Result := Copy(Result, 1, PosIdDelimiter - 1);
59
60 if Result = '/' then
61 Result := '';
62 end;
63
64 function GetBaseNameFromUrl(const Url: String): String;
65 var
66 UrlBase: String;
67 SB: TStringBuilder;
68 I: Integer;
69 C: Char;
70 NextUpCase: Boolean;
71 UrlParentName: String;
72 begin
73 UrlBase := ExtractUriName(Url);
74 UrlBase := DeleteUriExt(UrlBase);
75
76 { This case happens esp. for Sketchfab-imported models.
77 Use parent directory name then. }
78 if SameText(UrlBase, 'scene') then
79 begin
80 UrlParentName := GetUrlParentName(Url);
81 if UrlParentName <> '' then
82 UrlBase := UrlParentName;
83 end;
84
85 SB := TStringBuilder.Create;
86 try
87 NextUpCase := true;
88 for I := 1 to Length(UrlBase) do
89 begin
90 C := UrlBase[I];
91 if C in ['a'..'z', 'A'..'Z', '0'..'9'] then
92 begin
93 if NextUpCase then
94 begin
95 SB.Append(UpCase(C));
96 NextUpCase := C in ['0'..'9'];
97 end else
98 SB.Append(C);
99 end else
100 NextUpCase := true;
101 end;
102 Result := SB.ToString;
103 finally FreeAndNil(SB) end;
104 end;
105
106 end.