added my custom logger library

pull/29/head
tycrek 3 years ago
parent 9b344a69bf
commit 1021daab8d
No known key found for this signature in database
GPG Key ID: 25D74F3943625263

@ -22,12 +22,12 @@ const { name: ASS_NAME, version: ASS_VERSION } = require('./package.json');
//#endregion
// Welcome :D
log(`\n * ${ASS_NAME} v${ASS_VERSION} * \n`);
log.blank().info(`* ${ASS_NAME} v${ASS_VERSION} *`).blank();
// Set up premium frontend
const FRONTEND_NAME = 'ass-x'; // <-- Change this to use a custom frontend
const ASS_PREMIUM = fs.existsSync(`./${FRONTEND_NAME}/package.json`) ? (require('submodule'), require(`./${FRONTEND_NAME}`)) : { enabled: false };
log(`Frontend: ${ASS_PREMIUM.enabled ? ASS_PREMIUM.brand : '<none>'}${ASS_PREMIUM.enabled && ASS_PREMIUM.index ? ' (with index)' : ''}`);
log.info('Frontend: ', ASS_PREMIUM.enabled ? ASS_PREMIUM.brand : '<none>', ASS_PREMIUM.enabled && ASS_PREMIUM.index ? 'with index' : null);
//#region Variables, module setup
const app = express();
@ -39,7 +39,7 @@ const ROUTERS = {
// Read users and data
const users = require('./auth');
const data = require('./data');
log(`StorageEngine: ${data.name} (${data.type})`);
log.info('StorageEngine: ', data.name, data.type);
//#endregion
// Create thumbnails directory
@ -85,9 +85,14 @@ app.use('/:resourceId', (req, _, next) => (req.resourceId = req.params.resourceI
// Error handler
app.use(([err, , res,]) => {
console.error(err);
log.error(err);
res.sendStatus(CODE_INTERNAL_SERVER_ERROR);
});
// Host the server
app.listen(port, host, () => log(`Users: ${Object.keys(users).length}\nFiles: ${data.size}\n\nListening on: ${host}:${port}${ASS_PREMIUM.enabled ? ` (frontend: ${getTrueHttp()}${getTrueDomain()}${ASS_PREMIUM.endpoint})` : ''}\n`));
app.listen(port, host, () => {
log.info('Users', `${Object.keys(users).length}`)
.info('Files', `${data.size}`)
.blank()
.info('Listening on', `${host}:${port}`, `${ASS_PREMIUM.enabled ? `frontend: ${getTrueHttp()}${getTrueDomain()}${ASS_PREMIUM.endpoint}` : ''}`);
});

@ -10,7 +10,8 @@ if (!fs.existsSync(path('auth.json'))) {
let users = {};
users[generateToken()] = { username: 'ass', count: 0 };
fs.writeJsonSync(path('auth.json'), { users }, { spaces: 4 });
log(`File created: auth.json\n\n!! Important: save this token in a secure spot: ${Object.keys(users)[0]}`);
log.debug('File created', 'auth.json')
.success('!! Important', `Save this token in a secure spot: ${Object.keys(users)[0]}`)
}
const users = require('./auth.json').users || {};
@ -21,9 +22,9 @@ fs.watch(path('auth.json'), { persistent: false },
.then((json) => {
if (!(arrayEquals(Object.keys(users), Object.keys(json.users)))) {
Object.keys(json.users).forEach((token) => (!Object.prototype.hasOwnProperty.call(users, token)) && (users[token] = json.users[token]));
log(`New token added: ${Object.keys(users)[Object.keys(users).length - 1]}`);
log.info('New token added', Object.keys(users)[Object.keys(users).length - 1] || 'No new token');
}
})
.catch(console.error));
.catch(log.c.error));
module.exports = users;

@ -1,6 +1,9 @@
const check = require("check-node-version");
const ENGINES = require('./package.json').engines;
const TLog = require('@tycrek/log');
const logger = new TLog();
function doCheck() {
return new Promise((resolve, reject) =>
check(ENGINES, (err, { isSatisfied: allSatisfied }) =>
@ -15,5 +18,5 @@ function doCheck() {
if (require.main !== module) module.exports = doCheck;
else doCheck()
.then(console.log)
.catch((err) => console.error(err) && process.exit(1));
.then((result) => logger.success(result))
.catch((err) => logger.error(err) && process.exit(1));

@ -2,6 +2,8 @@ const uuid = require('uuid').v4;
const fs = require('fs-extra');
const path = require('path');
const randomGen = require('./random');
const TLog = require('@tycrek/log');
const log = new TLog();
const MAX_USERNAME = 20;
@ -11,6 +13,7 @@ module.exports = () => uuid().replace(/-/g, '');
if (require.main === module) {
const token = module.exports();
const authPath = path.join(__dirname, '..', 'auth.json');
let name = '';
fs.readJson(authPath)
.then((auth) => {
@ -18,13 +21,17 @@ if (require.main === module) {
const username = process.argv[2] ? process.argv[2].replace(/[^\da-z_]/gi, '').substring(0, MAX_USERNAME) : randomGen({ length: 20 }); // skipcq: JS-0074
if (!auth.users) auth.users = {};
if (Object.values(auth.users).findIndex((user) => user.username === username) !== -1) {
console.log('Username already exists!');
log.error('Username already exists', username);
process.exit(1);
}
auth.users[token] = { username, count: 0 };
name = auth.users[token].username;
fs.writeJsonSync(authPath, auth, { spaces: 4 });
})
.then(() => console.log(`A new token has been generated and automatically applied. You do not need to restart 'ass'.\n\nYour token: ${token}`))
.catch(console.error);
.then(() => log
.comment('A new token has been generated and automatically applied.')
.comment('You do not need to restart \'ass\'.')
.success('Your token', token, `username: ${name}`))
.catch(log.c.error);
}

@ -1,7 +1,7 @@
const fs = require('fs-extra');
const path = require('path');
const { s3enabled } = require('./config.json');
const { formatBytes } = require('./utils');
const { formatBytes, log } = require('./utils');
const { bucketSize } = require('./storage');
module.exports = () => {
@ -28,20 +28,19 @@ module.exports = () => {
// Get AWS size
bucketSize()
.then((s3size) => {
console.log('---- Usage metrics ----\n');
console.log(`Users: ${Object.keys(users).length}`);
console.log(`Files: ${Object.keys(data).length}`);
console.log(`S3 size: ${s3enabled ? s3size : '--'}`);
console.log('');
console.log(`Total size: ${formatBytes(totalSize)}`);
console.log(`Untracked size: ${formatBytes(oldSize)}`);
console.log('');
log.info('---- Usage metrics ----')
.blank()
.info('Users', Object.keys(users).length)
.info('Files', Object.keys(data).length)
.info('S3 size', s3enabled ? s3size : '--')
.blank()
.info('Total size', formatBytes(totalSize))
.info('Old files', formatBytes(oldSize))
.blank();
Object.values(users).forEach(({ username, count, size }) => {
console.log(`- ${username}: ${formatBytes(size)} (${count} files)`);
});
Object.values(users).forEach(({ username, count, size }) => log.info(`- ${username}`, formatBytes(size), `${count} files`));
})
.catch(console.error);
.catch(log.c.error);
}
if (require.main === module) module.exports();

39
package-lock.json generated

@ -10,6 +10,7 @@
"license": "ISC",
"dependencies": {
"@tycrek/ass-storage-engine": "0.2.6",
"@tycrek/log": "^0.2.2",
"any-shell-escape": "^0.1.1",
"aws-sdk": "^2.930.0",
"check-node-version": "^4.1.0",
@ -590,6 +591,23 @@
"node": ">=12"
}
},
"node_modules/@tycrek/log": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/@tycrek/log/-/log-0.2.2.tgz",
"integrity": "sha512-mTKOlLBt4Fffk6MfB0pPsgFun1+7BTYMX8echef6aVPe7kAGetMSwNqAg8wadz9u9NOk6bveeoCCyK1cWectTg==",
"dependencies": {
"chalk": "^4.1.1",
"luxon": "^1.27.0"
},
"engines": {
"node": ">=14.x.x",
"npm": ">=7.x.x"
},
"funding": {
"type": "patreon",
"url": "https://patreon.com/tycrek"
}
},
"node_modules/@types/node": {
"version": "10.17.60",
"resolved": "https://registry.npmjs.org/@types/node/-/node-10.17.60.tgz",
@ -1956,9 +1974,9 @@
}
},
"node_modules/luxon": {
"version": "1.27.0",
"resolved": "https://registry.npmjs.org/luxon/-/luxon-1.27.0.tgz",
"integrity": "sha512-VKsFsPggTA0DvnxtJdiExAucKdAnwbCCNlMM5ENvHlxubqWd0xhZcdb4XgZ7QFNhaRhilXCFxHuoObP5BNA4PA==",
"version": "1.28.0",
"resolved": "https://registry.npmjs.org/luxon/-/luxon-1.28.0.tgz",
"integrity": "sha512-TfTiyvZhwBYM/7QdAVDh+7dBTBA29v4ik0Ce9zda3Mnf8on1S5KJI8P2jKFZ8+5C0jhmr0KwJEO/Wdpm0VeWJQ==",
"engines": {
"node": "*"
}
@ -3819,6 +3837,15 @@
}
}
},
"@tycrek/log": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/@tycrek/log/-/log-0.2.2.tgz",
"integrity": "sha512-mTKOlLBt4Fffk6MfB0pPsgFun1+7BTYMX8echef6aVPe7kAGetMSwNqAg8wadz9u9NOk6bveeoCCyK1cWectTg==",
"requires": {
"chalk": "^4.1.1",
"luxon": "^1.27.0"
}
},
"@types/node": {
"version": "10.17.60",
"resolved": "https://registry.npmjs.org/@types/node/-/node-10.17.60.tgz",
@ -4922,9 +4949,9 @@
}
},
"luxon": {
"version": "1.27.0",
"resolved": "https://registry.npmjs.org/luxon/-/luxon-1.27.0.tgz",
"integrity": "sha512-VKsFsPggTA0DvnxtJdiExAucKdAnwbCCNlMM5ENvHlxubqWd0xhZcdb4XgZ7QFNhaRhilXCFxHuoObP5BNA4PA=="
"version": "1.28.0",
"resolved": "https://registry.npmjs.org/luxon/-/luxon-1.28.0.tgz",
"integrity": "sha512-TfTiyvZhwBYM/7QdAVDh+7dBTBA29v4ik0Ce9zda3Mnf8on1S5KJI8P2jKFZ8+5C0jhmr0KwJEO/Wdpm0VeWJQ=="
},
"map-age-cleaner": {
"version": "0.1.3",

@ -35,6 +35,7 @@
},
"dependencies": {
"@tycrek/ass-storage-engine": "0.2.6",
"@tycrek/log": "^0.2.2",
"any-shell-escape": "^0.1.1",
"aws-sdk": "^2.930.0",
"check-node-version": "^4.1.0",

@ -115,7 +115,7 @@ router.get('/delete/:deleteId', (req, res, next) => {
return Promise.all([s3enabled ? deleteS3(fileData) : fs.rmSync(path(fileData.path)), (!fileData.is || (fileData.is.image || fileData.is.video)) ? fs.rmSync(path(diskFilePath, 'thumbnails/', fileData.thumbnail)) : () => Promise.resolve()]);
})
.then(() => data.del(req.ass.resourceId))
.then(() => (log(`Deleted: ${oldName} (${oldType})`), res.type('text').send('File has been deleted!'))) // skipcq: JS-0090
.then(() => (log.success('Deleted', oldName, oldType), res.type('text').send('File has been deleted!'))) // skipcq: JS-0090
.catch(next);
});

@ -61,7 +61,7 @@ router.post('/', (req, res, next) => {
data.put(resourceId.split('.')[0], req.file).then(() => {
// Log the upload
const logInfo = `${req.file.originalname} (${req.file.mimetype}, ${formatBytes(req.file.size)})`;
log(`Uploaded: ${logInfo} (user: ${users[req.token] ? users[req.token].username : '<token-only>'})`);
log.success('File uploaded', logInfo, `uploaded by ${users[req.token] ? users[req.token].username : '<token-only>'}`);
// Build the URLs
const resourceUrl = `${getTrueHttp()}${trueDomain}/${resourceId}`;

@ -1,5 +1,6 @@
const fs = require('fs-extra');
const Path = require('path');
const TLog = require('@tycrek/log');
const fetch = require('node-fetch');
const sanitize = require('sanitize-filename');
const { DateTime } = require('luxon');
@ -16,8 +17,6 @@ try {
if (ex.code !== 'MODULE_NOT_FOUND') console.error(ex);
}
const path = (...paths) => Path.join(__dirname, ...paths);
function getTrueHttp() {
return ('http').concat(useSsl ? 's' : '').concat('://');
}
@ -74,6 +73,9 @@ function getDatedDirname() {
return `${diskFilePath}${diskFilePath.endsWith('/') ? '' : '/'}${year}-${`0${month}`.slice(-2)}`; // skipcq: JS-0074
}
const path = (...paths) => Path.join(__dirname, ...paths);
const logger = new TLog();
const idModes = {
zws: 'zws', // Zero-width spaces (see: https://zws.im/)
og: 'original', // Use original uploaded filename
@ -99,7 +101,7 @@ module.exports = {
getDatedDirname,
randomHexColour,
sanitize,
log: console.log,
log: logger,
verify: (req, users) => req.headers.authorization && Object.prototype.hasOwnProperty.call(users, req.headers.authorization),
renameFile: (req, newName) => new Promise((resolve, reject) => {
try {

Loading…
Cancel
Save