From 9b45bc21fe414dc037542568e6a9464a6329d1a8 Mon Sep 17 00:00:00 2001 From: tycrek Date: Sun, 12 Sep 2021 19:27:27 -0600 Subject: [PATCH] migrated `utils.js` to `utils.ts`, goddam! --- package-lock.json | 13 +++++++ package.json | 1 + src/definitions.d.ts | 3 ++ src/generators/gfycat.ts | 2 +- src/generators/random.ts | 2 +- src/generators/token.ts | 2 +- src/generators/zws.ts | 2 +- src/logger.ts | 22 +++++++++++ src/storage.js | 6 +-- src/{utils.js => utils.ts} | 79 ++++++++++++++++++-------------------- 10 files changed, 84 insertions(+), 48 deletions(-) create mode 100644 src/logger.ts rename src/{utils.js => utils.ts} (56%) diff --git a/package-lock.json b/package-lock.json index efa5ea2..c9c2c6d 100755 --- a/package-lock.json +++ b/package-lock.json @@ -44,6 +44,7 @@ "@types/express": "^4.17.13", "@types/ffmpeg-static": "^3.0.0", "@types/fs-extra": "^9.0.12", + "@types/luxon": "^2.0.3", "@types/node": "^16.9.0", "@types/node-fetch": "^2.5.12", "@types/stream-to-array": "^2.3.0", @@ -794,6 +795,12 @@ "@types/node": "*" } }, + "node_modules/@types/luxon": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@types/luxon/-/luxon-2.0.3.tgz", + "integrity": "sha512-qhyivlWLuSnQa6EMx7W2oPiMUD4/F9BLuQynZe3jBgmfCS6Xr+Ock1+ZotN6xEkdJvdckyX+z1r5fyvi31GV5Q==", + "dev": true + }, "node_modules/@types/mime": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.2.tgz", @@ -5293,6 +5300,12 @@ "@types/node": "*" } }, + "@types/luxon": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@types/luxon/-/luxon-2.0.3.tgz", + "integrity": "sha512-qhyivlWLuSnQa6EMx7W2oPiMUD4/F9BLuQynZe3jBgmfCS6Xr+Ock1+ZotN6xEkdJvdckyX+z1r5fyvi31GV5Q==", + "dev": true + }, "@types/mime": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.2.tgz", diff --git a/package.json b/package.json index 582877c..22cd0cb 100755 --- a/package.json +++ b/package.json @@ -71,6 +71,7 @@ "@types/express": "^4.17.13", "@types/ffmpeg-static": "^3.0.0", "@types/fs-extra": "^9.0.12", + "@types/luxon": "^2.0.3", "@types/node": "^16.9.0", "@types/node-fetch": "^2.5.12", "@types/stream-to-array": "^2.3.0", diff --git a/src/definitions.d.ts b/src/definitions.d.ts index e6946a7..8c70b8c 100644 --- a/src/definitions.d.ts +++ b/src/definitions.d.ts @@ -24,6 +24,9 @@ export interface FileData { timestamp: number token: string opengraph: OpenGraphData + + // I found this in utils and idk where it comes from + destination: string } export interface IsPossible { diff --git a/src/generators/gfycat.ts b/src/generators/gfycat.ts index a9caf2a..4e70570 100644 --- a/src/generators/gfycat.ts +++ b/src/generators/gfycat.ts @@ -20,4 +20,4 @@ function genString(count = MIN_LENGTH) { return gfycat.concat(getWord(animals)); }; -module.exports = ({ gfyLength }: { gfyLength: number }) => genString(gfyLength); +export default ({ gfyLength }: { gfyLength: number }) => genString(gfyLength); diff --git a/src/generators/random.ts b/src/generators/random.ts index 9d32ffd..6c62522 100644 --- a/src/generators/random.ts +++ b/src/generators/random.ts @@ -1,2 +1,2 @@ import cryptoRandomString from 'crypto-random-string'; -module.exports = ({ length }: { length: number }) => cryptoRandomString({ length, type: 'alphanumeric' }); +export default ({ length }: { length: number }) => cryptoRandomString({ length, type: 'alphanumeric' }); diff --git a/src/generators/token.ts b/src/generators/token.ts index 8b8bd2b..546f0f8 100644 --- a/src/generators/token.ts +++ b/src/generators/token.ts @@ -7,7 +7,7 @@ const log = new TLog(); const MAX_USERNAME = 20; -module.exports = () => uuid().replace(/-/g, ''); +export default () => uuid().replace(/-/g, ''); // If directly called on the command line, generate a new token if (require.main === module) { diff --git a/src/generators/zws.ts b/src/generators/zws.ts index a64cf28..7618080 100644 --- a/src/generators/zws.ts +++ b/src/generators/zws.ts @@ -1,3 +1,3 @@ const lengthGen = require('./lengthGen'); const zeroWidthChars = ['\u200B', '\u200C', '\u200D', '\u2060']; -module.exports = ({ length }: { length: number }) => lengthGen(length, zeroWidthChars); +export default ({ length }: { length: number }) => lengthGen(length, zeroWidthChars); diff --git a/src/logger.ts b/src/logger.ts new file mode 100644 index 0000000..502b9a8 --- /dev/null +++ b/src/logger.ts @@ -0,0 +1,22 @@ +const TLog = require('@tycrek/log'); + +// Set up logging +const logger = new TLog({ + level: process.env.LOG_LEVEL || (process.env.NODE_ENV === 'production' ? 'info' : 'debug'), + timestamp: { + enabled: true, + colour: 'grey', + preset: 'DATETIME_MED' + }, +}); + +// Enable the Express logger +logger.enable.express({ handle500: false }).debug('Plugin enabled', 'Express'); + +/** + * @type {TLog} + */ +// yeet + + +export default logger; \ No newline at end of file diff --git a/src/storage.js b/src/storage.js index c396335..b228d25 100644 --- a/src/storage.js +++ b/src/storage.js @@ -4,9 +4,9 @@ const fs = require('fs-extra'); const aws = require('aws-sdk'); const multer = require('multer'); -const Thumbnail = require('./thumbnails'); -const Vibrant = require('./vibrant'); -const Hash = require('./hash'); +const Thumbnail = require('./thumbnails').default; +const Vibrant = require('./vibrant').default; +const Hash = require('./hash').default; const { getDatedDirname, sanitize, generateId, formatBytes, log } = require('./utils'); const { s3enabled, s3endpoint, s3bucket, s3usePathStyle, s3accessKey, s3secretKey, saveAsOriginal, maxUploadSize, mediaStrict } = require('../config.json'); const { CODE_UNSUPPORTED_MEDIA_TYPE } = require('../MagicNumbers.json'); diff --git a/src/utils.js b/src/utils.ts similarity index 56% rename from src/utils.js rename to src/utils.ts index 50771b0..6693ec4 100644 --- a/src/utils.js +++ b/src/utils.ts @@ -1,39 +1,41 @@ -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'); -const token = require('./generators/token'); -const zwsGen = require('./generators/zws'); -const randomGen = require('./generators/random'); -const gfyGen = require('./generators/gfycat'); +import { AssRequest, FileData } from './definitions'; +import fs from 'fs-extra'; +import Path from 'path'; +import fetch from 'node-fetch'; +import sanitize from 'sanitize-filename'; +import { DateTime } from 'luxon'; +import token from './generators/token'; +import zwsGen from './generators/zws'; +import randomGen from './generators/random'; +import gfyGen from './generators/gfycat'; +import logger from './logger'; const { HTTP, HTTPS, KILOBYTES } = require('../MagicNumbers.json'); // Catch config.json not existing when running setup script try { var { useSsl, port, domain, isProxied, diskFilePath, saveWithDate, s3bucket, s3endpoint, s3usePathStyle } = require('../config.json'); // skipcq: JS-0239, JS-0102 } catch (ex) { + // @ts-ignore if (ex.code !== 'MODULE_NOT_FOUND') console.error(ex); } -function getTrueHttp() { +export function getTrueHttp() { return ('http').concat(useSsl ? 's' : '').concat('://'); } -function getTrueDomain(d = domain) { +export function getTrueDomain(d = domain) { return d.concat((port === HTTP || port === HTTPS || isProxied) ? '' : `:${port}`); } -function getS3url(s3key, ext) { +export function getS3url(s3key: string, ext: string) { return `https://${s3usePathStyle ? `${s3endpoint}/${s3bucket}` : `${s3bucket}.${s3endpoint}`}/${s3key}${ext}`; } -function getDirectUrl(resourceId) { +export function getDirectUrl(resourceId: string) { return `${getTrueHttp()}${getTrueDomain()}/${resourceId}/direct`; } -function randomHexColour() { // From: https://www.geeksforgeeks.org/javascript-generate-random-hex-codes-color/ +export function randomHexColour() { // From: https://www.geeksforgeeks.org/javascript-generate-random-hex-codes-color/ const letters = '0123456789ABCDEF'; let colour = '#'; for (let i = 0; i < 6; i++) // skipcq: JS-0074 @@ -41,29 +43,29 @@ function randomHexColour() { // From: https://www.geeksforgeeks.org/javascript-g return colour; } -function getResourceColor(colorValue, vibrantValue) { +export function getResourceColor(colorValue: string, vibrantValue: string) { return colorValue === '&random' ? randomHexColour() : colorValue === '&vibrant' ? vibrantValue : colorValue; } -function formatTimestamp(timestamp) { +export function formatTimestamp(timestamp: number) { return DateTime.fromMillis(timestamp).toLocaleString(DateTime.DATETIME_MED); } -function formatBytes(bytes, decimals = 2) { // skipcq: JS-0074 +export function formatBytes(bytes: number, decimals = 2) { // skipcq: JS-0074 if (bytes === 0) return '0 Bytes'; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; const i = Math.floor(Math.log(bytes) / Math.log(KILOBYTES)); return parseFloat((bytes / Math.pow(KILOBYTES, i)).toFixed(decimals < 0 ? 0 : decimals)).toString().concat(` ${sizes[i]}`); } -function replaceholder(data, size, timestamp, originalname) { +export function replaceholder(data: string, size: number, timestamp: number, originalname: string) { return data .replace(/&size/g, formatBytes(size)) .replace(/&filename/g, originalname) .replace(/×tamp/g, formatTimestamp(timestamp)); } -function getDatedDirname() { +export function getDatedDirname() { if (!saveWithDate) return diskFilePath; // Get current month and year @@ -73,19 +75,13 @@ function getDatedDirname() { return `${diskFilePath}${diskFilePath.endsWith('/') ? '' : '/'}${year}-${`0${month}`.slice(-2)}`; // skipcq: JS-0074 } -// Set up pathing & the logger -const path = (...paths) => Path.join(process.cwd(), ...paths); // '..' was added to make it easier to run files after moving the project to src/ -const logger = new TLog({ - level: process.env.LOG_LEVEL || (process.env.NODE_ENV === 'production' ? 'info' : 'debug'), - timestamp: { - enabled: true, - colour: 'grey', - preset: 'DATETIME_MED' - }, -}); +export function arrayEquals(arr1: any[], arr2: any[]) { + return arr1.length === arr2.length && arr1.slice().sort().every((value: string, index: number) => value === arr2.slice().sort()[index]) +}; + -// Enable the Express logger -logger.enable.express({ handle500: false }).debug('Plugin enabled', 'Express'); +// Set up pathing +export const path = (...paths: string[]) => Path.join(process.cwd(), ...paths); // '..' was added to make it easier to run files after moving the project to src/ const idModes = { zws: 'zws', // Zero-width spaces (see: https://zws.im/) @@ -99,8 +95,8 @@ GENERATORS.set(idModes.zws, zwsGen); GENERATORS.set(idModes.r, randomGen); GENERATORS.set(idModes.gfy, gfyGen); +export const isProd = require('@tycrek/isprod')(); module.exports = { - isProd: require('@tycrek/isprod')(), path, getTrueHttp, getTrueDomain, @@ -113,26 +109,27 @@ module.exports = { getDatedDirname, randomHexColour, sanitize, - verify: (req, users) => req.headers.authorization && Object.prototype.hasOwnProperty.call(users, req.headers.authorization), - renameFile: (req, newName) => new Promise((resolve, reject) => { + verify: (req: AssRequest, users: JSON) => req.headers.authorization && Object.prototype.hasOwnProperty.call(users, req.headers.authorization), + renameFile: (req: AssRequest, newName: string) => new Promise((resolve: Function, reject) => { try { - const paths = [req.file.destination, newName]; - fs.rename(path(req.file.path), path(...paths)); - req.file.path = Path.join(...paths); + const paths = [req.file!.destination, newName]; + fs.rename(path(req.file!.path), path(...paths)); + req.file!.path = Path.join(...paths); resolve(); } catch (err) { reject(err); } }), generateToken: () => token(), - generateId: (mode, length, gfyLength, originalName) => (GENERATORS.has(mode) ? GENERATORS.get(mode)({ length, gfyLength }) : originalName), - arrayEquals: (arr1, arr2) => arr1.length === arr2.length && arr1.slice().sort().every((value, index) => value === arr2.slice().sort()[index]), - downloadTempS3: (file) => new Promise((resolve, reject) => + generateId: (mode: string, length: number, gfyLength: number, originalName: string) => (GENERATORS.has(mode) ? GENERATORS.get(mode)({ length, gfyLength }) : originalName), + arrayEquals, + downloadTempS3: (file: FileData) => new Promise((resolve: Function, reject) => fetch(getS3url(file.randomId, file.ext)) .then((f2) => f2.body.pipe(fs.createWriteStream(Path.join(__dirname, diskFilePath, sanitize(file.originalname))).on('close', () => resolve()))) .catch(reject)), } +export const log = logger; /** * @type {TLog} */