@hiroosy/baileys-lite 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hiroosy/baileys-lite",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "A Lightweight Baileys built with NodeJs 18+",
5
5
  "repository": {
6
6
  "type": "git",
@@ -485,11 +485,11 @@ export class AIRichBuilder {
485
485
  }
486
486
  }
487
487
 
488
- async send(jid, { forwarded, quoted, quotedParticipant, botJid, ...sendOptions } = {}) {
488
+ async send(jid, { forwarded, quoted, quotedParticipant, botJid, bypassDownload = true, ...sendOptions } = {}) {
489
489
  if (!this._client) throw new Error('AIRichBuilder.send() needs a client — use sock.aiRich() or new AIRichBuilder(sock)')
490
490
  const sent = await this._client.sendMessage(jid, { aiRich: this, forwarded, quoted, quotedParticipant, botJid }, sendOptions)
491
491
  const richResponse = sent?.message?.botForwardedMessage?.message?.richResponseMessage
492
- if (!sent?.key?.id || !richResponse?.unifiedResponse) return sent
492
+ if (!bypassDownload || !sent?.key?.id || !richResponse?.unifiedResponse) return sent
493
493
  try {
494
494
  const userId = this._client.user?.id ?? this._client.authState?.creds?.me?.id
495
495
  const edit = this.buildEdit(jid, sent.key, sent.message)
@@ -508,6 +508,28 @@ export class AIRichBuilder {
508
508
  }
509
509
  }
510
510
 
511
+ const isPlainObject = v => !!v && typeof v === 'object' && !Array.isArray(v) && !Buffer.isBuffer(v)
512
+
513
+ // spec.html accepts: 'html' | ['html', 'Tab title'] | [['html', 'Tab 1'], ['html', 'Tab 2']]
514
+ // optionally with spec.htmlOptions = { url, trustedSources }, or a trailing/second options object.
515
+ // Before, the options had no way in through the spec form and trusted_sources was always [].
516
+ const addHtmlFromSpec = (builder, html, htmlOptions) => {
517
+ let options = isPlainObject(htmlOptions) ? { ...htmlOptions } : {}
518
+ let items
519
+ if (!Array.isArray(html)) {
520
+ items = [html]
521
+ } else if (Array.isArray(html[0])) {
522
+ items = [...html]
523
+ } else if (html.length === 2 && typeof html[0] === 'string' && isPlainObject(html[1])) {
524
+ items = [html[0]]
525
+ options = { ...html[1], ...options }
526
+ } else {
527
+ items = [html]
528
+ }
529
+ if (isPlainObject(items[items.length - 1])) options = { ...items.pop(), ...options }
530
+ builder.addHtml(...items, options)
531
+ }
532
+
511
533
  export const aiRichBuilderFromSpec = spec => {
512
534
  const b = new AIRichBuilder()
513
535
  if (spec.title) b.setTitle(spec.title)
@@ -525,6 +547,6 @@ export const aiRichBuilderFromSpec = spec => {
525
547
  if (spec.tip) b.addTip(spec.tip)
526
548
  if (spec.suggest) b.addSuggest(spec.suggest, spec.suggestOptions)
527
549
  if (spec.process) b.addProcess(spec.process)
528
- if (spec.html) b.addHtml(...(Array.isArray(spec.html[0]) ? spec.html : [spec.html]))
550
+ if (spec.html) addHtmlFromSpec(b, spec.html, spec.htmlOptions)
529
551
  return b
530
552
  }
@@ -0,0 +1,166 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { once } from 'node:events'
3
+ import { promises as fs } from 'node:fs'
4
+ import { Boom } from './boom.js'
5
+
6
+ // Dependency-free image thumbnails. Used when none of sharp / @napi-rs/image / jimp is installed,
7
+ // so a missing optional library never results in a media message without jpegThumbnail
8
+ // (the recipient sees that as a grey box).
9
+ // 1. built-in decoder (vendored jpeg-js + pngjs) for JPEG / PNG
10
+ // 2. ffmpeg for everything else (webp, gif, bmp, ...) and for big files, so the event loop is not
11
+ // blocked by a pure-JS decode of a multi-megapixel photo
12
+
13
+ const JPEG_QUALITY = 50
14
+ const BUILTIN_PREFERRED_MAX_BYTES = 2 * 1024 * 1024
15
+ const FFMPEG_TIMEOUT_MS = 15_000
16
+
17
+ const isJpeg = b => b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff
18
+ const isPng = b => b.length > 8 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47
19
+
20
+ async function readHeader(path) {
21
+ const handle = await fs.open(path, 'r')
22
+ try {
23
+ const header = Buffer.alloc(16)
24
+ const { bytesRead } = await handle.read(header, 0, 16, 0)
25
+ return header.subarray(0, bytesRead)
26
+ } finally {
27
+ await handle.close()
28
+ }
29
+ }
30
+
31
+ async function decodeRaster(buffer) {
32
+ if (isJpeg(buffer)) {
33
+ const { default: decode } = await import('../vendor/jpeg-js/decoder.js')
34
+ return decode(buffer, { useTArray: true, formatAsRGBA: true, tolerantDecoding: true })
35
+ }
36
+ if (isPng(buffer)) {
37
+ const { read } = await import('../vendor/pngjs/png-sync.js')
38
+ return read(buffer)
39
+ }
40
+ throw new Boom('unsupported image format for built-in decoder')
41
+ }
42
+
43
+ // area-average downscale; transparent pixels are composited over white (JPEG has no alpha)
44
+ function resizeToRgba({ data, width: sw, height: sh }, dw, dh) {
45
+ const out = Buffer.allocUnsafe(dw * dh * 4)
46
+ const xr = sw / dw
47
+ const yr = sh / dh
48
+ for (let dy = 0; dy < dh; dy++) {
49
+ const y0 = Math.floor(dy * yr)
50
+ const y1 = Math.min(sh, Math.max(y0 + 1, Math.ceil((dy + 1) * yr)))
51
+ for (let dx = 0; dx < dw; dx++) {
52
+ const x0 = Math.floor(dx * xr)
53
+ const x1 = Math.min(sw, Math.max(x0 + 1, Math.ceil((dx + 1) * xr)))
54
+ let r = 0
55
+ let g = 0
56
+ let b = 0
57
+ for (let y = y0; y < y1; y++) {
58
+ let i = (y * sw + x0) * 4
59
+ for (let x = x0; x < x1; x++, i += 4) {
60
+ const a = data[i + 3] / 255
61
+ r += data[i] * a + 255 * (1 - a)
62
+ g += data[i + 1] * a + 255 * (1 - a)
63
+ b += data[i + 2] * a + 255 * (1 - a)
64
+ }
65
+ }
66
+ const n = (y1 - y0) * (x1 - x0)
67
+ const o = (dy * dw + dx) * 4
68
+ out[o] = Math.round(r / n)
69
+ out[o + 1] = Math.round(g / n)
70
+ out[o + 2] = Math.round(b / n)
71
+ out[o + 3] = 255
72
+ }
73
+ }
74
+ return out
75
+ }
76
+
77
+ async function builtinThumb(buffer, width) {
78
+ const image = await decodeRaster(buffer)
79
+ if (!image?.width || !image?.height || !image.data?.length) throw new Boom('could not decode image')
80
+ const dw = Math.max(1, Math.min(width, image.width)) // never upscale
81
+ const dh = Math.max(1, Math.round((image.height * dw) / image.width))
82
+ const { default: encode } = await import('../vendor/jpeg-js/encoder.js')
83
+ const rgba = resizeToRgba(image, dw, dh)
84
+ const { data } = encode({ data: rgba, width: dw, height: dh }, JPEG_QUALITY)
85
+ return { buffer: Buffer.from(data), original: { width: image.width, height: image.height } }
86
+ }
87
+
88
+ async function runFfmpeg(command, args, input) {
89
+ const child = spawn(command, args, { stdio: [Buffer.isBuffer(input) ? 'pipe' : 'ignore', 'pipe', 'pipe'] })
90
+ const out = []
91
+ const err = []
92
+ child.stdout.on('data', c => out.push(c))
93
+ child.stderr.on('data', c => err.push(c))
94
+ if (Buffer.isBuffer(input)) {
95
+ child.stdin.on('error', () => {})
96
+ child.stdin.end(input)
97
+ }
98
+ const timer = setTimeout(() => child.kill('SIGKILL'), FFMPEG_TIMEOUT_MS)
99
+ try {
100
+ const [code] = await once(child, 'close')
101
+ if (code !== 0) throw new Boom(`${command} failed (code ${code}): ${Buffer.concat(err).toString('utf8').trim()}`)
102
+ return Buffer.concat(out)
103
+ } finally {
104
+ clearTimeout(timer)
105
+ }
106
+ }
107
+
108
+ async function probeDimensions(input) {
109
+ try {
110
+ const src = Buffer.isBuffer(input) ? 'pipe:0' : input
111
+ const args = ['-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=width,height', '-of', 'csv=p=0', src]
112
+ const [width, height] = (await runFfmpeg('ffprobe', args, input)).toString('utf8').trim().split(',').map(Number)
113
+ return width > 0 && height > 0 ? { width, height } : {}
114
+ } catch {
115
+ return {}
116
+ }
117
+ }
118
+
119
+ async function ffmpegThumb(input, width) {
120
+ const src = Buffer.isBuffer(input) ? 'pipe:0' : input
121
+ const args = [
122
+ '-loglevel', 'error', '-i', src, '-an', '-sn', '-dn', '-map_metadata', '-1',
123
+ '-vf', `scale=w='min(${width},iw)':h=-2`,
124
+ '-frames:v', '1', '-q:v', '12', '-c:v', 'mjpeg', '-f', 'image2pipe', 'pipe:1'
125
+ ]
126
+ const buffer = await runFfmpeg('ffmpeg', args, input)
127
+ if (!buffer.length) throw new Boom('ffmpeg produced no output')
128
+ return { buffer, original: await probeDimensions(input) }
129
+ }
130
+
131
+ /**
132
+ * @param {Buffer | string} input image bytes or a file path
133
+ * @param {number} width thumbnail width in px
134
+ * @returns {Promise<{ buffer: Buffer, original: { width?: number, height?: number } }>}
135
+ */
136
+ export async function extractImageThumbFallback(input, width = 32) {
137
+ let header
138
+ let size
139
+ if (Buffer.isBuffer(input)) {
140
+ header = input
141
+ size = input.length
142
+ } else {
143
+ header = await readHeader(input)
144
+ size = (await fs.stat(input)).size
145
+ }
146
+ const decodable = isJpeg(header) || isPng(header)
147
+ const big = size > BUILTIN_PREFERRED_MAX_BYTES
148
+ const attempts = []
149
+ if (decodable) {
150
+ const builtin = async () => builtinThumb(Buffer.isBuffer(input) ? input : await fs.readFile(input), width)
151
+ attempts.push(builtin)
152
+ if (big) attempts.unshift(() => ffmpegThumb(input, width))
153
+ else attempts.push(() => ffmpegThumb(input, width))
154
+ } else {
155
+ attempts.push(() => ffmpegThumb(input, width))
156
+ }
157
+ const errors = []
158
+ for (const attempt of attempts) {
159
+ try {
160
+ return await attempt()
161
+ } catch (err) {
162
+ errors.push(err?.message ?? String(err))
163
+ }
164
+ }
165
+ throw new Boom(`could not generate image thumbnail (install sharp, @napi-rs/image or jimp, or ffmpeg): ${errors.join(' | ')}`)
166
+ }
@@ -1,7 +1,8 @@
1
1
  import { appendFileSync, existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
2
2
 
3
3
  const MAGIC = '{"nsql":1}'
4
- const COMPACT_MIN_BYTES = 1024 * 1024
4
+ const COMPACT_MIN_BYTES = 256 * 1024
5
+ const COMPACT_GROWTH_RATIO = 0.5
5
6
  const CONTROL = new Set(['begin', 'commit', 'rollback'])
6
7
  const TOKEN = /\s+|'((?:[^']|'')*)'|"([^"]*)"|`([^`]*)`|\[([^\]]*)\]|(\d+\.?\d*(?:[eE][+-]?\d+)?|\.\d+(?:[eE][+-]?\d+)?)|([A-Za-z_]\w*)|([(),;=?*.-])/y
7
8
 
@@ -16,6 +17,8 @@ const lower = name => name.toLowerCase()
16
17
 
17
18
  const keyOf = (table, row) => JSON.stringify(table.pk.map(i => row[i]))
18
19
 
20
+ const sameRow = (a, b) => a.length === b.length && a.every((v, i) => v === b[i])
21
+
19
22
  const bind = (count, params) => {
20
23
  if (params.length !== count) throw new SqlError(`expected ${count} parameters, got ${params.length}`)
21
24
  return params.map(value => {
@@ -361,7 +364,7 @@ export class SqlDatabase {
361
364
  const values = bind(stmt.paramCount, params)
362
365
  return this.#statement(() => {
363
366
  const result = this.#execute(stmt, values)
364
- if (stmt.write && result.changes) this.#pending.push([stmt.text, values])
367
+ if (stmt.write && result.changes && !result.noop) this.#pending.push([stmt.text, values])
365
368
  return result
366
369
  })
367
370
  }
@@ -533,6 +536,7 @@ export class SqlDatabase {
533
536
  if (action === 'nothing') return { changes: 0, rows: [] }
534
537
  if (action === 'update') return this.#upsertConflict(table, rowKey, existing, stmt.onConflict.sets, row, params)
535
538
  if (stmt.replace) {
539
+ if (sameRow(existing, row)) return { changes: 1, rows: [], noop: true }
536
540
  this.#storeRow(table, rowKey, row)
537
541
  return { changes: 1, rows: [] }
538
542
  }
@@ -548,6 +552,8 @@ export class SqlDatabase {
548
552
  }
549
553
  if (table.pk.some(i => next[i] !== existing[i])) throw new SqlError('primary key cannot be changed on conflict')
550
554
  this.#checkNotNull(table, next)
555
+ // rewriting identical data (e.g. saveCreds with unchanged creds) must not grow the log
556
+ if (sameRow(existing, next)) return { changes: 1, rows: [], noop: true }
551
557
  this.#storeRow(table, rowKey, next)
552
558
  return { changes: 1, rows: [] }
553
559
  }
@@ -653,8 +659,13 @@ export class SqlDatabase {
653
659
  for (const line of lines.slice(1)) this.#replay(line)
654
660
  this.#path = path
655
661
  this.#logBytes = this.#baseBytes = Buffer.byteLength(text)
656
- if (fresh) writeFileSync(path, text)
657
- else if (tail !== '') this.#compact()
662
+ if (fresh) {
663
+ writeFileSync(path, text)
664
+ } else if (tail !== '' || lines.length > 2) {
665
+ // torn write, or the log holds more than a single snapshot line: rewrite as a clean
666
+ // snapshot so baseBytes reflects live data and old bloated files shrink on first open
667
+ this.#compact()
668
+ }
658
669
  }
659
670
 
660
671
  #replay(line) {
@@ -678,7 +689,10 @@ export class SqlDatabase {
678
689
  }
679
690
 
680
691
  #maybeCompact() {
681
- if (this.#path === null || this.#logBytes < COMPACT_MIN_BYTES || this.#logBytes < 2 * this.#baseBytes) return
692
+ if (this.#path === null) return
693
+ // baseBytes is always the size of a clean snapshot, so garbage = logBytes - baseBytes
694
+ const garbage = this.#logBytes - this.#baseBytes
695
+ if (garbage < Math.max(COMPACT_MIN_BYTES, this.#baseBytes * COMPACT_GROWTH_RATIO)) return
682
696
  try {
683
697
  this.#compact()
684
698
  } catch {}
@@ -1066,6 +1066,9 @@ export const makeMessagesSocket = (config) => {
1066
1066
  else if (message.groupInviteMessage) {
1067
1067
  return 'url';
1068
1068
  }
1069
+ else if (message.albumMessage) {
1070
+ return 'collection';
1071
+ }
1069
1072
  return '';
1070
1073
  };
1071
1074
  const issuePrivacyTokens = async (jids, timestamp) => {
@@ -10,6 +10,7 @@ import { join } from 'node:path'
10
10
  import { Readable, Transform } from 'node:stream'
11
11
  import { proto } from '../../WAProto/index.js'
12
12
  import { Boom } from '../foundation/boom.js'
13
+ import { extractImageThumbFallback } from '../foundation/image-thumb.js'
13
14
  import { getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../binary/wa-binary.js'
14
15
  import { aesDecryptGCM, aesEncryptGCM, hkdf } from './wa-protocol-core.js'
15
16
  import { generateMessageIDV2 } from './wa-protocol-core.js'
@@ -75,8 +76,10 @@ const NEWSLETTER_MEDIA_PATH_MAP = {
75
76
  const getTmpFilesDirectory = () => tmpdir()
76
77
 
77
78
  let imageProcessingLibrary
79
+ let imageProcessingLibraryMissing = false
78
80
  export const getImageProcessingLibrary = async () => {
79
81
  if (imageProcessingLibrary) return imageProcessingLibrary
82
+ if (imageProcessingLibraryMissing) throw new Boom('No image processing library available')
80
83
  const [sharp, image, jimp] = await Promise.all([
81
84
  import('sharp').catch(() => {}),
82
85
  import('@napi-rs/image').catch(() => {}),
@@ -85,7 +88,10 @@ export const getImageProcessingLibrary = async () => {
85
88
  if (sharp) imageProcessingLibrary = { sharp }
86
89
  else if (image) imageProcessingLibrary = { image }
87
90
  else if (jimp) imageProcessingLibrary = { jimp }
88
- else throw new Boom('No image processing library available')
91
+ else {
92
+ imageProcessingLibraryMissing = true
93
+ throw new Boom('No image processing library available')
94
+ }
89
95
  return imageProcessingLibrary
90
96
  }
91
97
 
@@ -172,9 +178,7 @@ export const extractVideoThumb = async (path, time, size) => {
172
178
  return buffer
173
179
  }
174
180
 
175
- export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
176
- if (bufferOrFilePath instanceof Readable) bufferOrFilePath = await toBuffer(bufferOrFilePath)
177
- const lib = await getImageProcessingLibrary()
181
+ const thumbWithLibrary = async (lib, bufferOrFilePath, width) => {
178
182
  if ('sharp' in lib && lib.sharp?.default) {
179
183
  const img = lib.sharp.default(bufferOrFilePath)
180
184
  const dimensions = await img.metadata()
@@ -196,6 +200,24 @@ export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
196
200
  }
197
201
  }
198
202
 
203
+ // Never leave a media message without jpegThumbnail just because sharp / @napi-rs/image / jimp is not installed:
204
+ // fall back to the built-in decoder (JPEG/PNG) and ffmpeg (see foundation/image-thumb.js).
205
+ export const extractImageThumb = async (bufferOrFilePath, width = 32) => {
206
+ if (bufferOrFilePath instanceof Readable) bufferOrFilePath = await toBuffer(bufferOrFilePath)
207
+ let libraryError
208
+ try {
209
+ return await thumbWithLibrary(await getImageProcessingLibrary(), bufferOrFilePath, width)
210
+ } catch (err) {
211
+ libraryError = err
212
+ }
213
+ try {
214
+ return await extractImageThumbFallback(bufferOrFilePath, width)
215
+ } catch (err) {
216
+ if (libraryError && libraryError.message !== 'No image processing library available') err.message += ` (image library error: ${libraryError.message})`
217
+ throw err
218
+ }
219
+ }
220
+
199
221
  export const encodeBase64EncodedStringForUpload = b64 => encodeURIComponent(b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''))
200
222
 
201
223
  export const generateProfilePicture = async (mediaUpload, dimensions) => {
@@ -1,25 +0,0 @@
1
- Copyright (c) 2014, Eugene Ware
2
- All rights reserved.
3
-
4
- Redistribution and use in source and binary forms, with or without
5
- modification, are permitted provided that the following conditions are met:
6
-
7
- 1. Redistributions of source code must retain the above copyright
8
- notice, this list of conditions and the following disclaimer.
9
- 2. Redistributions in binary form must reproduce the above copyright
10
- notice, this list of conditions and the following disclaimer in the
11
- documentation and/or other materials provided with the distribution.
12
- 3. Neither the name of Eugene Ware nor the names of its contributors
13
- may be used to endorse or promote products derived from this software
14
- without specific prior written permission.
15
-
16
- THIS SOFTWARE IS PROVIDED BY EUGENE WARE ''AS IS'' AND ANY
17
- EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19
- DISCLAIMED. IN NO EVENT SHALL EUGENE WARE BE LIABLE FOR ANY
20
- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21
- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22
- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25
- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.