forked from Acode-Foundation/Acode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUrl.js
More file actions
337 lines (295 loc) · 8.83 KB
/
Url.js
File metadata and controls
337 lines (295 loc) · 8.83 KB
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
import URLParse from "url-parse";
import path from "./Path";
import Uri from "./Uri";
export default {
/**
* Returns basename from a url eg. 'index.html' from 'ftp://localhost/foo/bar/index.html'
* @param {string} url
* @returns {string}
*/
basename(url) {
url = this.parse(url).url;
const protocol = this.getProtocol(url);
if (protocol === "content:") {
try {
let { rootUri, docId, isFileUri } = Uri.parse(url);
if (isFileUri) return this.basename(rootUri);
if (docId.endsWith("/")) docId = docId.slice(0, -1);
docId = docId.split(":").pop();
return this.pathname(docId).split("/").pop();
} catch (error) {
return null;
}
} else {
if (url.endsWith("/")) url = url.slice(0, -1);
return this.pathname(url).split("/").pop();
}
},
/**
* Checks if given urls are same or not
* @param {...String} urls
* @returns {Boolean}
*/
areSame(...urls) {
let firstUrl = urls[0];
if (firstUrl.endsWith("/")) firstUrl = firstUrl.slice(0, -1);
return urls.every((url) => {
if (url.endsWith("/")) url = url.slice(0, -1);
return firstUrl === url;
});
},
/**
*
* @param {String} url
* returns the extension of the path, from the last occurrence of the . (period)
* character to end of string in the last portion of the path.
* If there is no . in the last portion of the path, or if there are no .
* characters other than the first character of the basename of path (see path.basename()),
* an empty string is returned.
* @returns {String}
*/
extname(url) {
const name = this.basename(url);
if (name) return path.extname(name);
else return null;
},
/**
* Join all arguments together and normalize the resulting path.
* @param {...string} pathnames
* @returns {String}
*/
join(...pathnames) {
if (pathnames.length < 2)
throw new Error("Join(), requires at least two parameters");
let { url, query } = this.parse(pathnames[0]);
const protocol = (this.PROTOCOL_PATTERN.exec(url) || [])[0] || "";
if (protocol === "content://") {
try {
if (pathnames[1].startsWith("/")) pathnames[1] = pathnames[1].slice(1);
const contentUri = Uri.parse(url);
let [root, pathname] = contentUri.docId.split(":");
let newDocId = path.join(pathname, ...pathnames.slice(1));
if (/^content:\/\/com.termux/.test(url)) {
const rootCondition = root.endsWith("/");
const newDocIdCondition = newDocId.startsWith("/");
if (rootCondition === newDocIdCondition) {
root = root.slice(0, -1);
} else if (!rootCondition === !newDocIdCondition) {
root += "/";
}
return `${contentUri.rootUri}::${root}${newDocId}${query}`;
}
// if pathname is undefined, meaning a docId/volume (e.g :primary:)
// has not been detected, so no newDocId's ":" will be added.
if (!pathname) {
// Ensure proper path separator between root and newDocId
let separator = "";
if (root.endsWith("/") && newDocId.startsWith("/")) {
// Both have separator, strip one from newDocId
newDocId = newDocId.slice(1);
} else if (!root.endsWith("/") && !newDocId.startsWith("/")) {
// Neither has separator, add one
separator = "/";
}
return `${contentUri.rootUri}::${root}${separator}${newDocId}${query}`;
}
return `${contentUri.rootUri}::${root}:${newDocId}${query}`;
} catch (error) {
return null;
}
} else if (protocol) {
url = url.replace(new RegExp("^" + protocol), "");
pathnames[0] = url;
return protocol + path.join(...pathnames) + query;
} else {
return path.join(url, ...pathnames.slice(1)) + query;
}
},
/**
* Make url safe by encoding url components
* @param {string} url
* @returns {string}
*/
safe(url) {
let { url: uri, query } = this.parse(url);
url = uri;
const protocol = (this.PROTOCOL_PATTERN.exec(url) || [])[0] || "";
if (protocol) url = url.replace(new RegExp("^" + protocol), "");
const parts = url.split("/").map((part, i) => {
if (i === 0) return part;
return fixedEncodeURIComponent(part);
});
return protocol + parts.join("/") + query;
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
return "%" + c.charCodeAt(0).toString(16);
});
}
},
/**
* Gets pathname from url eg. gets '/foo/bar' from 'ftp://myhost.com/foo/bar'
* @param {string} url
* @returns {string}
*/
pathname(url) {
if (typeof url !== "string" || !this.PROTOCOL_PATTERN.test(url)) return url;
url = url.split("?")[0];
const protocol = (this.PROTOCOL_PATTERN.exec(url) || [])[0] || "";
if (protocol === "content://") {
try {
const { rootUri, docId, isFileUri } = Uri.parse(url);
if (isFileUri) return this.pathname(rootUri);
else return "/" + (docId.split(":")[1] || docId);
} catch (error) {
return null;
}
} else {
if (protocol) url = url.replace(new RegExp("^" + protocol), "");
if (protocol !== "file:///")
return "/" + url.split("/").slice(1).join("/");
return "/" + url;
}
},
/**
* Returns dirname from url eg. 'ftp://localhost/foo/' from 'ftp://localhost/foo/bar'
* @param {string} url
* @returns {string}
*/
dirname(url) {
if (typeof url !== "string") throw new Error("URL must be string");
const urlObj = this.parse(url);
url = urlObj.url;
const protocol = this.getProtocol(url);
if (protocol === "content:") {
try {
let { rootUri, docId, isFileUri } = Uri.parse(url);
if (isFileUri) return this.dirname(rootUri);
else {
if (docId.endsWith("/")) docId = docId.slice(0, -1);
docId = [...docId.split("/").slice(0, -1), ""].join("/");
return Uri.format(rootUri, docId);
}
} catch (error) {
return null;
}
} else {
if (url.endsWith("/")) url = url.slice(0, -1);
return [...url.split("/").slice(0, -1), ""].join("/") + urlObj.query;
}
},
/**
* Parse given url into url and query
* @param {string} url
* @returns {{url:string, query:string}}}
*/
parse(url) {
const [uri, query = ""] = url.split(/(?=\?)/);
return {
url: uri,
query,
};
},
/**
* Formate Url object to string
* @param {object} urlObj
* @param {"ftp:"|"sftp:"|"http:"|"https:"} urlObj.protocol
* @param {string|number} urlObj.hostname
* @param {string} [urlObj.path]
* @param {string} [urlObj.username]
* @param {string} [urlObj.password]
* @param {string|number} [urlObj.port]
* @param {object} [urlObj.query]
* @returns {string}
*/
formate(urlObj) {
let { protocol, hostname, username, password, path, port, query } = urlObj;
const enc = (str) => encodeURIComponent(str);
if (!protocol || !hostname)
throw new Error("Cannot formate url. Missing 'protocol' and 'hostname'.");
let string = `${protocol}//`;
if (username && password) string += `${enc(username)}:${enc(password)}@`;
else if (username) string += `${username}@`;
string += hostname;
if (port) string += `:${port}`;
if (path) {
if (!path.startsWith("/")) path = "/" + path;
string += path;
}
if (query && typeof query === "object") {
string += "?";
for (let key in query) string += `${enc(key)}=${enc(query[key])}&`;
string = string.slice(0, -1);
}
return string;
},
/**
* Returns protocol of a url e.g. 'ftp:' from 'ftp://localhost/foo/bar'
* @param {string} url
* @returns {"ftp:"|"sftp:"|"http:"|"https:"}
*/
getProtocol(url) {
return (/^([a-z]+:)\/\/\/?/i.exec(url) || [])[1] || "";
},
/**
*
* @param {string} url
* @returns {string}
*/
hidePassword(url) {
const { protocol, username, hostname, pathname } = URLParse(url);
if (protocol === "file:") {
return url;
} else {
return `${protocol}//${username}@${hostname}${pathname}`;
}
},
/**
* Decodes url and returns username, password, hostname, pathname, port and query
* @param {string} url
* @returns {URLObject}
*/
decodeUrl(url) {
const uuid = "uuid" + Math.floor(Math.random() + Date.now() * 1000000);
if (/#/.test(url)) {
url = url.replace(/#/g, uuid);
}
let { username, password, hostname, pathname, port, query } = URLParse(
url,
true,
);
if (pathname) {
pathname = decodeURIComponent(pathname);
pathname = pathname.replace(new RegExp(uuid, "g"), "#");
}
if (username) {
username = decodeURIComponent(username);
}
if (password) {
password = decodeURIComponent(password);
}
if (port) {
port = Number.parseInt(port);
}
let { keyFile, passPhrase } = query;
if (keyFile) {
query.keyFile = decodeURIComponent(keyFile);
}
if (passPhrase) {
query.passPhrase = decodeURIComponent(passPhrase);
}
return { username, password, hostname, pathname, port, query };
},
/**
* Removes trailing slash from url
* @param {string} url
* @returns
*/
trimSlash(url) {
const parsed = this.parse(url);
if (parsed.url.endsWith("/")) {
parsed.url = parsed.url.slice(0, -1);
}
return this.join(parsed.url, parsed.query);
},
PROTOCOL_PATTERN: /^[a-z]+:\/\/\/?/i,
};