2018-03-20 12:59:29 -04:00
|
|
|
var unzip = require('./unzip');
|
2016-03-18 19:51:40 -04:00
|
|
|
|
|
|
|
/**
|
2018-02-26 15:42:12 -05:00
|
|
|
* If input a buffer, transforms buffer into a UTF-8 string.
|
2018-04-05 13:32:06 -04:00
|
|
|
* If input is encoded in zip or gzip format, the input will be extracted and decoded.
|
2018-02-26 15:42:12 -05:00
|
|
|
* If input is a string, passes that string along to the given callback.
|
2018-03-24 11:09:43 -04:00
|
|
|
* @param {Buffer | string} input Project data
|
|
|
|
* @param {Function} callback Error or stringified project data
|
|
|
|
* @return {void}
|
2016-03-18 19:51:40 -04:00
|
|
|
*/
|
|
|
|
module.exports = function (input, callback) {
|
2018-02-26 15:42:12 -05:00
|
|
|
if (typeof input === 'string') {
|
|
|
|
// Pass string to callback
|
2018-03-15 18:25:36 -04:00
|
|
|
return callback(null, [input, null]);
|
2018-02-26 15:42:12 -05:00
|
|
|
}
|
|
|
|
|
2016-03-18 19:51:40 -04:00
|
|
|
// Validate input type
|
2018-02-26 15:42:12 -05:00
|
|
|
var typeError = 'Input must be a Buffer or a string.';
|
|
|
|
if (!Buffer.isBuffer(input)) {
|
2018-03-15 18:25:36 -04:00
|
|
|
try {
|
|
|
|
input = new Buffer(input);
|
|
|
|
} catch (e) {
|
|
|
|
return callback(typeError);
|
|
|
|
}
|
2018-02-26 15:42:12 -05:00
|
|
|
}
|
2016-03-18 19:51:40 -04:00
|
|
|
|
|
|
|
// Determine format
|
|
|
|
// We don't use the file suffix as this is unreliable and mine-type
|
|
|
|
// information is unavailable from Scratch's project CDN. Instead, we look
|
|
|
|
// at the first few bytes from the provided buffer (byte signature).
|
|
|
|
// https://en.wikipedia.org/wiki/List_of_file_signatures
|
|
|
|
var signature = input.slice(0, 3).join(' ');
|
|
|
|
var isLegacy = false;
|
|
|
|
var isZip = false;
|
2018-04-05 13:32:06 -04:00
|
|
|
var isGZip = false;
|
2016-03-18 19:51:40 -04:00
|
|
|
|
|
|
|
if (signature.indexOf('83 99 114') === 0) isLegacy = true;
|
|
|
|
if (signature.indexOf('80 75') === 0) isZip = true;
|
2018-04-05 13:32:06 -04:00
|
|
|
if (signature.indexOf('31 139') === 0) isGZip = true;
|
2016-03-18 19:51:40 -04:00
|
|
|
|
2018-04-05 13:32:06 -04:00
|
|
|
// If not legacy, zip, or gzip, convert buffer to UTF-8 string and return
|
|
|
|
if (!isZip && !isLegacy && !isGZip) {
|
2018-03-15 18:25:36 -04:00
|
|
|
return callback(null, [input.toString('utf-8'), null]);
|
|
|
|
}
|
2016-03-18 19:51:40 -04:00
|
|
|
|
|
|
|
// Return error if legacy encoding detected
|
2018-04-05 13:32:06 -04:00
|
|
|
if (isLegacy) return callback('Parser only supports Scratch 2.X and above');
|
2016-03-18 19:51:40 -04:00
|
|
|
|
2018-04-05 13:32:06 -04:00
|
|
|
unzip(input, isGZip, callback);
|
2016-03-18 19:51:40 -04:00
|
|
|
};
|