94 lines
2.4 KiB
JavaScript
94 lines
2.4 KiB
JavaScript
|
const { prompt } = require('enquirer');
|
||
|
const program = require('commander');
|
||
|
const pkg = require("./package.json");
|
||
|
const fs = require("fs");
|
||
|
const validUrl = require("valid-url");
|
||
|
const request = require("request");
|
||
|
const ora = require("ora");
|
||
|
const Funnies = require("funnies").Funnies;
|
||
|
|
||
|
let funnies = new Funnies();
|
||
|
|
||
|
program.version(pkg.version)
|
||
|
.command("shorten [url]")
|
||
|
.action(shorten);
|
||
|
|
||
|
program
|
||
|
.command("upload [path]")
|
||
|
.action(upload);
|
||
|
|
||
|
program.on("command:*", () => {
|
||
|
console.error("Invalid command: %s\nSee --help for a list of available commands.", program.args.join(" "));
|
||
|
process.exit(1);
|
||
|
});
|
||
|
|
||
|
program.parse(process.argv);
|
||
|
|
||
|
async function upload(path) {
|
||
|
if (!path || !fs.existsSync(path)) {
|
||
|
const response = await prompt([
|
||
|
{
|
||
|
type: 'input',
|
||
|
name: 'path',
|
||
|
message: 'Which file would you like to upload?',
|
||
|
hint: "Type a file path (e.g file.txt, ../file.txt)",
|
||
|
validate: (input) => fs.existsSync(input) ? true : "Invalid file path"
|
||
|
}
|
||
|
]);
|
||
|
path = response.path;
|
||
|
}
|
||
|
|
||
|
doRequest("file", path);
|
||
|
}
|
||
|
|
||
|
async function shorten(url) {
|
||
|
if (!url || !validUrl.isWebUri(url)) {
|
||
|
const response = await prompt([
|
||
|
{
|
||
|
type: 'input',
|
||
|
name: 'url',
|
||
|
message: 'Which URL would you like to shorten?',
|
||
|
hint: "Type a URL (e.g http://tilde.team)",
|
||
|
validate: (input) => validUrl.isWebUri(input) ? true : "Invalid URL"
|
||
|
}
|
||
|
]);
|
||
|
url = response.url;
|
||
|
}
|
||
|
|
||
|
doRequest("shorten", url);
|
||
|
}
|
||
|
|
||
|
function doRequest(action, data) {
|
||
|
const spinner = ora(funnies.message()).start();
|
||
|
|
||
|
let formData = {}
|
||
|
|
||
|
switch (action) {
|
||
|
case "file":
|
||
|
// in the form data, set file to be a file stream
|
||
|
// data is our file path if the action is 'file'
|
||
|
formData["file"] = fs.createReadStream(data);
|
||
|
break;
|
||
|
case "shorten":
|
||
|
// in the form data, set shorten to be the url to shorten
|
||
|
// data is our url if the action is 'shorten'
|
||
|
formData["shorten"] = data;
|
||
|
break;
|
||
|
default:
|
||
|
spinner.fail("Invalid action!");
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
// make a post request to ttm.sh with our form data that we made above
|
||
|
request.post({
|
||
|
url: "https://ttm.sh",
|
||
|
formData: formData
|
||
|
}, (err, res, body) => {
|
||
|
if (res.statusCode !== 200 || err) {
|
||
|
spinner.fail(`Whoops! There was a problem while completing your request [HTTP ${res.statusCode}] - ${err.message}`);
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
spinner.succeed(body.trim());
|
||
|
});
|
||
|
}
|