|
| 1 | +export const parser = { |
| 2 | + parse(url) { |
| 3 | + let ret = {}; |
| 4 | + |
| 5 | + let regex = /^([^:]+):\/\/([^\/]+)(.*)$/; //protocol, login, urlpath |
| 6 | + let result = regex.exec(url); |
| 7 | + |
| 8 | + if (!result) { |
| 9 | + throw new Error('bad url'); |
| 10 | + } |
| 11 | + |
| 12 | + ret.full = url; |
| 13 | + ret.protocol = result[1]; |
| 14 | + ret.urlpath = result[3]; |
| 15 | + |
| 16 | + let parts = ret.urlpath.split('/'); |
| 17 | + ret.basename = parts.pop().split(/\?|#/)[0]; |
| 18 | + ret.basepath = parts.join('/'); |
| 19 | + |
| 20 | + let loginSplit = result[2].split('@'); |
| 21 | + let hostport = loginSplit[0].split(':'); |
| 22 | + let userpass = [null, null]; |
| 23 | + if (loginSplit.length === 2) { |
| 24 | + userpass = loginSplit[0].split(':'); |
| 25 | + hostport = loginSplit[1].split(':'); |
| 26 | + } |
| 27 | + |
| 28 | + ret.user = userpass[0]; |
| 29 | + ret.pass = userpass[1]; |
| 30 | + ret.host = hostport[0]; |
| 31 | + ret.auth = ret.user && ret.pass ? `${ret.user}:${ret.pass}` : ''; |
| 32 | + |
| 33 | + ret.port = |
| 34 | + null == hostport[1] ? Url.protocolDefaultPort(ret.protocol) : hostport[1]; |
| 35 | + ret.portDefined = null != hostport[1]; |
| 36 | + ret.location = `${ret.host}:${ret.port}`; |
| 37 | + |
| 38 | + if (ret.protocol == 'unix') { |
| 39 | + ret.socket = ret.port; |
| 40 | + ret.port = undefined; |
| 41 | + } |
| 42 | + |
| 43 | + return ret; |
| 44 | + }, |
| 45 | + |
| 46 | + full(parsed) { |
| 47 | + return `${parsed.protocol}://${parsed.location}/${parsed.urlpath}`; |
| 48 | + }, |
| 49 | + |
| 50 | + isAbsolute(url) { |
| 51 | + return /^[^:]+:\/\//.test(url); |
| 52 | + }, |
| 53 | + |
| 54 | + protocolDefaultPort(protocol) { |
| 55 | + switch (protocol) { |
| 56 | + case 'rtsp': |
| 57 | + return 554; |
| 58 | + case 'http': |
| 59 | + return 80; |
| 60 | + case 'https': |
| 61 | + return 443; |
| 62 | + } |
| 63 | + return 0; |
| 64 | + } |
| 65 | +}; |
0 commit comments