Archived
64 lines
1.7 KiB
JavaScript
64 lines
1.7 KiB
JavaScript
const { ArgumentType, SimpleCommandExceptionType, LiteralMessage } = require('brigadier-commands')
|
|
const path = require('path/posix')
|
|
|
|
const EXAMPLES = ['songs/amogus.mid', 'images/cat.jpg', 'videos/badapple.mp4']
|
|
const INVALID_URL_EXCEPTION = new SimpleCommandExceptionType(new LiteralMessage('Invalid URL'))
|
|
|
|
class LocationArgumentType extends ArgumentType {
|
|
constructor (allowPaths, allowUrls, root = '') {
|
|
super()
|
|
this.allowPaths = allowPaths
|
|
this.allowUrls = allowUrls
|
|
this.root = root
|
|
}
|
|
|
|
static location (root = '') { return new LocationArgumentType(true, true, root) }
|
|
static path (root = '') { return new LocationArgumentType(true, false, root) }
|
|
static url () { return new LocationArgumentType(false, true) }
|
|
|
|
parse (reader) {
|
|
const string = reader.readString()
|
|
|
|
if (this.allowUrls) {
|
|
if (string.startsWith('http://') || string.startsWith('https://')) {
|
|
return string
|
|
}
|
|
// TODO: Maybe support data URLs?
|
|
}
|
|
|
|
if (!this.allowPaths) {
|
|
throw INVALID_URL_EXCEPTION.create()
|
|
}
|
|
|
|
const root = path.resolve(this.root)
|
|
|
|
const splitPath = string.split(path.sep)
|
|
const sanitizedSplitPath = []
|
|
let depth = 0
|
|
for (const part of splitPath) {
|
|
if (part === '' || part === '.') continue
|
|
|
|
if (part === '..') {
|
|
if ((depth - 1) < 0) continue // Do not allow escaping the root directory
|
|
depth--
|
|
} else {
|
|
depth++
|
|
}
|
|
|
|
sanitizedSplitPath.push(part)
|
|
}
|
|
|
|
return [root, ...sanitizedSplitPath].join(path.sep)
|
|
}
|
|
|
|
static isUrl (string) {
|
|
return string.startsWith('http://') || string.startsWith('https://')
|
|
}
|
|
|
|
getExamples () {
|
|
return EXAMPLES
|
|
}
|
|
}
|
|
|
|
module.exports = LocationArgumentType
|