Antonio Laguna

Antonio Laguna

Sends an image directly to compress-or-die

// Menu: Compress Or Die
// Description: Sends an image directly to compress-or-die
// Twitter: @ant_laguna
const http = await npm('http');
const [input] = await drop('Drop an image');
const { name, path, type } = input;
function getProcess(image) {
if (image.includes('png')) {
return '/png-process';
} else if (image.includes('svg')) {
return '/svg-process';
} else {
return '/jpg-process';
}
}
if (!type.startsWith('image')) {
await arg(`File type not supported`);
} else {
const file = await readFile(path);
const fileSize = Buffer.byteLength(file);
const options = {
method: 'POST',
hostname: 'compress-or-die.com',
port: 80,
path: '/api',
headers: {
'Content-Type': type,
'Content-Length': fileSize,
'X-Document-Name': name
}
};
const data = [];
const session = await new Promise((accept, reject) => {
const request = http.request(options, response => {
response.on('data', chunk => data.push(chunk));
response.on('end', () => {
const response = Buffer.concat(data).toString('utf-8');
const regex = /(_.+):(.+)/g;
let result;
const fields = {};
while (result = regex.exec(response)) {
fields[result[1]] = result[2];
}
if (fields._VERSION !== '1') {
accept('');
console.log('Version missmatch');
} else {
accept(fields._SESSION);
}
});
response.on('error', reject);
});
request.write(file);
request.end();
});
if (!session) {
await arg('An error occurred');
} else {
const url = `https://compress-or-die.com${getProcess(type)}?session=${session}`
await exec(`open ${url}`);
}
}