Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove dynamic imports #16

Merged
merged 3 commits into from
Oct 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/Utils/generics.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export declare function promiseTimeout<T>(ms: number | undefined, promise: (reso
export declare const generateMessageID: () => string;
export declare function bindWaitForEvent<T extends keyof BaileysEventMap>(ev: BaileysEventEmitter, event: T): (check: (u: BaileysEventMap[T]) => boolean | undefined, timeoutMs?: number) => Promise<void>;
export declare const bindWaitForConnectionUpdate: (ev: BaileysEventEmitter) => (check: (u: Partial<import("../Types").ConnectionState>) => boolean | undefined, timeoutMs?: number) => Promise<void>;
export declare const printQRIfNecessaryListener: (ev: BaileysEventEmitter, logger: Logger) => void;
export declare const printQRIfNecessaryListener: (ev: BaileysEventEmitter, _: Logger) => void;
/**
* utility that fetches latest baileys version from the master branch.
* Use to ensure your WA connection is always on the latest version
Expand Down
10 changes: 3 additions & 7 deletions lib/Utils/generics.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const boom_1 = require("@hapi/boom");
const axios_1 = __importDefault(require("axios"));
const crypto_1 = require("crypto");
const os_1 = require("os");
const qrcode_terminal_1 = __importDefault(require("qrcode-terminal"));
const WAProto_1 = require("../../WAProto");
const baileys_version_json_1 = require("../Defaults/baileys-version.json");
const Types_1 = require("../Types");
Expand Down Expand Up @@ -177,15 +178,10 @@ function bindWaitForEvent(ev, event) {
exports.bindWaitForEvent = bindWaitForEvent;
const bindWaitForConnectionUpdate = (ev) => bindWaitForEvent(ev, 'connection.update');
exports.bindWaitForConnectionUpdate = bindWaitForConnectionUpdate;
const printQRIfNecessaryListener = (ev, logger) => {
const printQRIfNecessaryListener = (ev, _) => {
ev.on('connection.update', async ({ qr }) => {
if (qr) {
const QR = await import('qrcode-terminal')
.then(m => m.default || m)
.catch(() => {
logger.error('QR code terminal not added as dependency');
});
QR === null || QR === void 0 ? void 0 : QR.generate(qr, { small: true });
qrcode_terminal_1.default.generate(qr, { small: true });
}
});
};
Expand Down
4 changes: 2 additions & 2 deletions lib/Utils/link-preview.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUrlInfo = void 0;
const link_preview_js_1 = require("link-preview-js");
const messages_1 = require("./messages");
const messages_media_1 = require("./messages-media");
const THUMBNAIL_WIDTH_PX = 192;
Expand All @@ -25,12 +26,11 @@ const getUrlInfo = async (text, opts = {
// retries
const retries = 0;
const maxRetry = 5;
const { getLinkPreview } = await import('link-preview-js');
let previewLink = text;
if (!text.startsWith('https://') && !text.startsWith('http://')) {
previewLink = 'https://' + previewLink;
}
const info = await getLinkPreview(previewLink, {
const info = await (0, link_preview_js_1.getLinkPreview)(previewLink, {
...opts.fetchOpts,
followRedirects: 'manual',
handleRedirects: (baseURL, forwardedURL) => {
Expand Down
20 changes: 11 additions & 9 deletions lib/Utils/messages-media.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,18 @@ var __importStar = (this && this.__importStar) || function (mod) {
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getStatusCodeForMediaRetry = exports.decryptMediaRetryData = exports.decodeMediaRetryNode = exports.encryptMediaRetryRequest = exports.getWAUploadToServer = exports.extensionForMediaMessage = exports.downloadEncryptedContent = exports.downloadContentFromMessage = exports.getUrlFromDirectPath = exports.encryptedStream = exports.getHttpStream = exports.generateThumbnail = exports.getStream = exports.toBuffer = exports.toReadable = exports.getAudioWaveform = exports.getAudioDuration = exports.mediaMessageSHA256B64 = exports.generateProfilePicture = exports.encodeBase64EncodedStringForUpload = exports.extractImageThumb = exports.getMediaKeys = exports.hkdfInfoKey = void 0;
const boom_1 = require("@hapi/boom");
const axios_1 = __importDefault(require("axios"));
const child_process_1 = require("child_process");
const Crypto = __importStar(require("crypto"));
const events_1 = require("events");
const fs_1 = require("fs");
const music_metadata_1 = __importDefault(require("music-metadata"));
const os_1 = require("os");
const path_1 = require("path");
const stream_1 = require("stream");
Expand Down Expand Up @@ -188,22 +193,21 @@ const mediaMessageSHA256B64 = (message) => {
};
exports.mediaMessageSHA256B64 = mediaMessageSHA256B64;
async function getAudioDuration(buffer) {
const musicMetadata = await import('music-metadata');
let metadata;
if (Buffer.isBuffer(buffer)) {
metadata = await musicMetadata.parseBuffer(buffer, undefined, { duration: true });
metadata = await music_metadata_1.default.parseBuffer(buffer, undefined, { duration: true });
}
else if (typeof buffer === 'string') {
const rStream = (0, fs_1.createReadStream)(buffer);
try {
metadata = await musicMetadata.parseStream(rStream, undefined, { duration: true });
metadata = await music_metadata_1.default.parseStream(rStream, undefined, { duration: true });
}
finally {
rStream.destroy();
}
}
else {
metadata = await musicMetadata.parseStream(buffer, undefined, { duration: true });
metadata = await music_metadata_1.default.parseStream(buffer, undefined, { duration: true });
}
return metadata.format.duration;
}
Expand Down Expand Up @@ -313,8 +317,7 @@ async function generateThumbnail(file, mediaType, options) {
}
exports.generateThumbnail = generateThumbnail;
const getHttpStream = async (url, options = {}) => {
const { default: axios } = await import('axios');
const fetched = await axios.get(url.toString(), { ...options, responseType: 'stream' });
const fetched = await axios_1.default.get(url.toString(), { ...options, responseType: 'stream' });
return fetched.data;
};
exports.getHttpStream = getHttpStream;
Expand Down Expand Up @@ -525,7 +528,6 @@ exports.extensionForMediaMessage = extensionForMediaMessage;
const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options }, refreshMediaConn) => {
return async (stream, { mediaType, fileEncSha256B64, timeoutMs }) => {
var _a, _b;
const { default: axios } = await import('axios');
// send a query JSON to obtain the url & auth token to upload our media
let uploadInfo = await refreshMediaConn(false);
let urls;
Expand All @@ -545,7 +547,7 @@ const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options },
if (maxContentLengthBytes && reqBody.length > maxContentLengthBytes) {
throw new boom_1.Boom(`Body too large for "${hostname}"`, { statusCode: 413 });
}
const body = await axios.post(url, reqBody, {
const body = await axios_1.default.post(url, reqBody, {
...options,
headers: {
...options.headers || {},
Expand All @@ -572,7 +574,7 @@ const getWAUploadToServer = ({ customUploadHosts, fetchAgent, logger, options },
}
}
catch (error) {
if (axios.isAxiosError(error)) {
if (axios_1.default.isAxiosError(error)) {
result = (_a = error.response) === null || _a === void 0 ? void 0 : _a.data;
}
const isLast = hostname === ((_b = hosts[uploadInfo.hosts.length - 1]) === null || _b === void 0 ? void 0 : _b.hostname);
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,12 @@
"futoin-hkdf": "^1.5.1",
"libphonenumber-js": "^1.10.20",
"libsignal": "github:adiwajshing/libsignal-node",
"link-preview-js": "^3.0.0",
"music-metadata": "^7.12.3",
"node-cache": "^5.1.2",
"pino": "^7.0.0",
"protobufjs": "^6.11.3",
"qrcode-terminal": "^0.12.0",
"uuid": "^9.0.0",
"ws": "^8.13.0"
},
Expand All @@ -68,9 +70,7 @@
"eslint": "^8.0.0",
"jest": "^27.0.6",
"jimp": "^0.16.1",
"link-preview-js": "^3.0.0",
"open": "^8.4.2",
"qrcode-terminal": "^0.12.0",
"release-it": "^15.10.3",
"sharp": "^0.30.5",
"ts-jest": "^27.0.3",
Expand Down
10 changes: 3 additions & 7 deletions src/Utils/generics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { randomBytes } from 'crypto'
import { platform, release } from 'os'
import { Logger } from 'pino'
import QR from 'qrcode-terminal'
import { proto } from '../../WAProto'
import { version as baileysVersion } from '../Defaults/baileys-version.json'
import { BaileysEventEmitter, BaileysEventMap, DisconnectReason, WACallUpdateType, WAVersion } from '../Types'
Expand Down Expand Up @@ -209,15 +210,10 @@

export const bindWaitForConnectionUpdate = (ev: BaileysEventEmitter) => bindWaitForEvent(ev, 'connection.update')

export const printQRIfNecessaryListener = (ev: BaileysEventEmitter, logger: Logger) => {
export const printQRIfNecessaryListener = (ev: BaileysEventEmitter, _: Logger) => {

Check failure on line 213 in src/Utils/generics.ts

View workflow job for this annotation

GitHub Actions / check-lint

'_' is defined but never used
ev.on('connection.update', async({ qr }) => {
if(qr) {
const QR = await import('qrcode-terminal')
.then(m => m.default || m)
.catch(() => {
logger.error('QR code terminal not added as dependency')
})
QR?.generate(qr, { small: true })
QR.generate(qr, { small: true })
}
})
}
Expand Down
2 changes: 1 addition & 1 deletion src/Utils/link-preview.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { AxiosRequestConfig } from 'axios'
import { getLinkPreview } from 'link-preview-js'
import { Logger } from 'pino'
import { WAMediaUploadFunction, WAUrlInfo } from '../Types'
import { prepareWAMessageMedia } from './messages'
Expand Down Expand Up @@ -46,7 +47,6 @@ export const getUrlInfo = async(
const retries = 0
const maxRetry = 5

const { getLinkPreview } = await import('link-preview-js')
let previewLink = text
if(!text.startsWith('https://') && !text.startsWith('http://')) {
previewLink = 'https://' + previewLink
Expand Down
7 changes: 2 additions & 5 deletions src/Utils/messages-media.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Boom } from '@hapi/boom'
import { AxiosRequestConfig } from 'axios'
import axios, { AxiosRequestConfig } from 'axios'
import { exec } from 'child_process'
import * as Crypto from 'crypto'
import { once } from 'events'
import { createReadStream, createWriteStream, promises as fs, WriteStream } from 'fs'
import type { IAudioMetadata } from 'music-metadata'
import musicMetadata, { IAudioMetadata } from 'music-metadata'
import { tmpdir } from 'os'
import { join } from 'path'
import type { Logger } from 'pino'
Expand Down Expand Up @@ -186,7 +186,6 @@ export const mediaMessageSHA256B64 = (message: WAMessageContent) => {
}

export async function getAudioDuration(buffer: Buffer | string | Readable) {
const musicMetadata = await import('music-metadata')
let metadata: IAudioMetadata
if(Buffer.isBuffer(buffer)) {
metadata = await musicMetadata.parseBuffer(buffer, undefined, { duration: true })
Expand Down Expand Up @@ -324,7 +323,6 @@ export async function generateThumbnail(
}

export const getHttpStream = async(url: string | URL, options: AxiosRequestConfig & { isStream?: true } = {}) => {
const { default: axios } = await import('axios')
const fetched = await axios.get(url.toString(), { ...options, responseType: 'stream' })
return fetched.data as Readable
}
Expand Down Expand Up @@ -602,7 +600,6 @@ export const getWAUploadToServer = (
refreshMediaConn: (force: boolean) => Promise<MediaConnInfo>,
): WAMediaUploadFunction => {
return async(stream, { mediaType, fileEncSha256B64, timeoutMs }) => {
const { default: axios } = await import('axios')
// send a query JSON to obtain the url & auth token to upload our media
let uploadInfo = await refreshMediaConn(false)

Expand Down
Loading