Finished implementing opt-in-telemetry function

This commit is contained in:
ivanThePleasant 2022-03-31 12:56:47 +03:00
parent 03a135678e
commit 937fc9874a

View File

@ -0,0 +1,102 @@
'use strict';
const { resolve } = require('path');
const fse = require('fs-extra');
const chalk = require('chalk');
const fetch = require('node-fetch');
const { v4: uuidv4 } = require('uuid');
const machineID = require('../utils/machine-id');
const readPackageJSON = async path => {
try {
const packageObj = await fse.readJson(path);
return packageObj;
} catch (err) {
console.error(`${chalk.red('Error')}: ${err.message}`);
}
};
const writePackageJSON = async (path, file, spacing) => {
try {
await fse.writeJson(path, file, { spaces: spacing });
return true;
} catch (err) {
console.error(`${chalk.red('Error')}: ${err.message}`);
return false;
}
};
const generateNewPackageJSON = packageObj => {
if (!packageObj.strapi) {
return {
...packageObj,
strapi: {
uuid: uuidv4(),
telemetryDisabled: false,
},
};
} else {
return {
...packageObj,
strapi: {
...packageObj.strapi,
uuid: packageObj.strapi.uuid ? packageObj.strapi.uuid : uuidv4(),
telemetryDisabled: false,
},
};
}
};
const sendEvent = async uuid => {
try {
await fetch('https://analytics.strapi.io/track', {
method: 'POST',
body: JSON.stringify({
event: 'didOptInTelemetry',
uuid,
deviceId: machineID(),
}),
headers: { 'Content-Type': 'application/json' },
});
} catch (e) {
//...
}
};
module.exports = async function optInTelemetry() {
const packageJSONPath = resolve(process.cwd(), 'package.json');
const exists = await fse.pathExists(packageJSONPath);
if (!exists) {
console.log(`${chalk.yellow('Warning')}: could not find package.json`);
process.exit(0);
}
const packageObj = await readPackageJSON(packageJSONPath);
if (
packageObj.strapi &&
packageObj.strapi.uuid &&
packageObj.strapi.telemetryDisabled === false
) {
console.log(`${chalk.yellow('Warning:')} telemetry is already enabled`);
process.exit(0);
}
const updatedPackageJSON = generateNewPackageJSON(packageObj);
const write = await writePackageJSON(packageJSONPath, updatedPackageJSON, 2);
if (!write) {
console.log(
`${chalk.yellow(
'Warning'
)}: There has been an error, please set "telemetryDisabled": false in the "strapi" object of your package.json manually.`
);
process.exit(0);
}
await sendEvent(updatedPackageJSON.strapi.uuid);
console.log(`${chalk.green('Successfully opted in to Strapi telemetry')}`);
process.exit(0);
};