Archive bug fix + Delete bug fix + assert deprecation update

This commit is contained in:
Adhiraj Singh
2020-11-30 19:21:10 +05:30
parent 196be24e4f
commit 84edfe1ca0
11 changed files with 42 additions and 44 deletions

View File

@@ -354,7 +354,7 @@ setTimeout (() => {
conn.modifyChat (jid, ChatModification.unmute) conn.modifyChat (jid, ChatModification.unmute)
}, 5000) // unmute after 5 seconds }, 5000) // unmute after 5 seconds
await conn.deleteChat (jid) // will delete the chat (can be a group or broadcast list as well) await conn.modifyChat (jid, ChatModification.delete) // will delete the chat (can be a group or broadcast list as well)
``` ```
**Note:** to unmute or unpin a chat, one must pass the timestamp of the pinning or muting. This is returned by the pin & mute functions. This is also available in the `WAChat` objects of the respective chats, as a `mute` or `pin` property. **Note:** to unmute or unpin a chat, one must pass the timestamp of the pinning or muting. This is returned by the pin & mute functions. This is also available in the `WAChat` objects of the respective chats, as a `mute` or `pin` property.

View File

@@ -60,13 +60,13 @@ export const WAConnectionTest = (name: string, func: (conn: WAConnection) => voi
) )
export const assertChatDBIntegrity = (conn: WAConnection) => { export const assertChatDBIntegrity = (conn: WAConnection) => {
conn.chats.all ().forEach (chat => ( conn.chats.all ().forEach (chat => (
assert.deepEqual ( assert.deepStrictEqual (
[...chat.messages.all()].sort ((m1, m2) => waMessageKey.compare(waMessageKey.key(m1), waMessageKey.key(m2))), [...chat.messages.all()].sort ((m1, m2) => waMessageKey.compare(waMessageKey.key(m1), waMessageKey.key(m2))),
chat.messages.all() chat.messages.all()
) )
)) ))
conn.chats.all ().forEach (chat => ( conn.chats.all ().forEach (chat => (
assert.deepEqual ( assert.deepStrictEqual (
chat.messages.all().filter (m => chat.messages.all().filter(m1 => m1.key.id === m.key.id).length > 1), chat.messages.all().filter (m => chat.messages.all().filter(m1 => m1.key.id === m.key.id).length > 1),
[] []
) )

View File

@@ -79,10 +79,10 @@ describe('Binary Coding Tests', () => {
const buff = Buffer.from(pair[0], 'hex') const buff = Buffer.from(pair[0], 'hex')
const decoded = decoder.read(buff) const decoded = decoder.read(buff)
//console.log((decoded[2][0][2])) //console.log((decoded[2][0][2]))
assert.deepEqual(decoded, pair[1]) assert.deepStrictEqual(decoded, pair[1])
const encoded = encoder.write(decoded) const encoded = encoder.write(decoded)
assert.deepEqual(encoded, buff) assert.deepStrictEqual(encoded, buff)
}) })
console.log('all coding tests passed') console.log('all coding tests passed')
}) })

View File

@@ -72,7 +72,7 @@ describe('Test Connect', () => {
const conn = makeConnection () const conn = makeConnection ()
conn.logger.level = 'debug' conn.logger.level = 'debug'
await conn.loadAuthInfo('./auth_info.json').connect () await conn.loadAuthInfo('./auth_info.json').connect ()
assert.equal (conn.phoneConnected, true) assert.strictEqual (conn.phoneConnected, true)
try { try {
const waitForEvent = expect => new Promise (resolve => { const waitForEvent = expect => new Promise (resolve => {
@@ -217,7 +217,7 @@ describe ('Reconnects', () => {
conn.autoReconnect = ReconnectMode.onConnectionLost conn.autoReconnect = ReconnectMode.onConnectionLost
await conn.loadAuthInfo('./auth_info.json').connect () await conn.loadAuthInfo('./auth_info.json').connect ()
assert.equal (conn.phoneConnected, true) assert.strictEqual (conn.phoneConnected, true)
try { try {
const closeConn = () => conn['conn']?.terminate () const closeConn = () => conn['conn']?.terminate ()
@@ -269,7 +269,7 @@ describe ('Reconnects', () => {
conn.autoReconnect = ReconnectMode.onConnectionLost conn.autoReconnect = ReconnectMode.onConnectionLost
await conn.loadAuthInfo('./auth_info.json').connect () await conn.loadAuthInfo('./auth_info.json').connect ()
assert.equal (conn.phoneConnected, true) assert.strictEqual (conn.phoneConnected, true)
await delay (30*1000) await delay (30*1000)

View File

@@ -9,7 +9,7 @@ WAConnectionTest('Groups', (conn) => {
assert.ok (conn.chats.get(response.gid)) assert.ok (conn.chats.get(response.gid))
const {chats} = await conn.loadChats(10, null) const {chats} = await conn.loadChats(10, null)
assert.equal (chats[0].jid, response.gid) // first chat should be new group assert.strictEqual (chats[0].jid, response.gid) // first chat should be new group
gid = response.gid gid = response.gid
@@ -54,14 +54,14 @@ WAConnectionTest('Groups', (conn) => {
const loaded = await conn.loadMessages(gid, 10) const loaded = await conn.loadMessages(gid, 10)
const message = loaded.messages.find (m => m.key.id === response.key.id)?.message?.extendedTextMessage const message = loaded.messages.find (m => m.key.id === response.key.id)?.message?.extendedTextMessage
assert.ok(message) assert.ok(message)
assert.equal (message.contextInfo.stanzaId, quotableMessage.key.id) assert.strictEqual (message.contextInfo.stanzaId, quotableMessage.key.id)
}) })
it('should update the subject', async () => { it('should update the subject', async () => {
const subject = 'Baileyz ' + Math.floor(Math.random()*5) const subject = 'Baileyz ' + Math.floor(Math.random()*5)
const waitForEvent = new Promise (resolve => { const waitForEvent = new Promise (resolve => {
conn.once ('chat-update', ({jid, name}) => { conn.once ('chat-update', ({jid, name}) => {
if (jid === gid) { if (jid === gid) {
assert.equal (name, subject) assert.strictEqual (name, subject)
resolve () resolve ()
} }
}) })
@@ -77,7 +77,7 @@ WAConnectionTest('Groups', (conn) => {
const waitForEvent = new Promise (resolve => { const waitForEvent = new Promise (resolve => {
conn.once ('group-update', ({jid, announce}) => { conn.once ('group-update', ({jid, announce}) => {
if (jid === gid) { if (jid === gid) {
assert.equal (announce, 'true') assert.strictEqual (announce, 'true')
resolve () resolve ()
} }
}) })
@@ -127,7 +127,7 @@ WAConnectionTest('Groups', (conn) => {
const waitForEvent = new Promise (resolve => { const waitForEvent = new Promise (resolve => {
conn.once ('chat-update', ({jid, read_only}) => { conn.once ('chat-update', ({jid, read_only}) => {
if (jid === gid) { if (jid === gid) {
assert.equal (read_only, 'true') assert.strictEqual (read_only, 'true')
resolve () resolve ()
} }
}) })
@@ -141,7 +141,7 @@ WAConnectionTest('Groups', (conn) => {
const waitForEvent = new Promise (resolve => { const waitForEvent = new Promise (resolve => {
conn.once ('chat-update', ({jid, archive}) => { conn.once ('chat-update', ({jid, archive}) => {
if (jid === gid) { if (jid === gid) {
assert.equal (archive, 'true') assert.strictEqual (archive, 'true')
resolve () resolve ()
} }
}) })
@@ -153,12 +153,12 @@ WAConnectionTest('Groups', (conn) => {
const waitForEvent = new Promise (resolve => { const waitForEvent = new Promise (resolve => {
conn.once ('chat-update', (chat) => { conn.once ('chat-update', (chat) => {
if (chat.jid === gid) { if (chat.jid === gid) {
assert.equal (chat['delete'], 'true') assert.strictEqual (chat['delete'], 'true')
resolve () resolve ()
} }
}) })
}) })
await conn.deleteChat(gid) await conn.modifyChat(gid, 'delete')
await waitForEvent await waitForEvent
}) })
}) })

View File

@@ -29,7 +29,7 @@ WAConnectionTest('Messages', conn => {
messages = (await conn.loadMessages (testJid, 1)).messages messages = (await conn.loadMessages (testJid, 1)).messages
const message = messages.slice (-1)[0] const message = messages.slice (-1)[0]
const content = message.message[ Object.keys(message.message)[0] ] const content = message.message[ Object.keys(message.message)[0] ]
assert.equal (content?.contextInfo?.isForwarded, true) assert.strictEqual (content?.contextInfo?.isForwarded, true)
}) })
it('should send a link preview', async () => { it('should send a link preview', async () => {
const text = 'hello this is from https://www.github.com/adiwajshing/Baileys' const text = 'hello this is from https://www.github.com/adiwajshing/Baileys'
@@ -78,7 +78,7 @@ WAConnectionTest('Messages', conn => {
const message = await sendAndRetreiveMessage(conn, content, MessageType.audio, { mimetype: Mimetype.mp4Audio, ptt: true }) const message = await sendAndRetreiveMessage(conn, content, MessageType.audio, { mimetype: Mimetype.mp4Audio, ptt: true })
assert.ok (message.message.audioMessage.seconds > 0) assert.ok (message.message.audioMessage.seconds > 0)
assert.equal (message.message?.audioMessage?.ptt, true) assert.strictEqual (message.message?.audioMessage?.ptt, true)
await conn.downloadAndSaveMediaMessage(message,'./Media/received_aud') await conn.downloadAndSaveMediaMessage(message,'./Media/received_aud')
}) })
it('should send an image', async () => { it('should send an image', async () => {
@@ -176,7 +176,7 @@ WAConnectionTest('Messages', conn => {
conn.on ('message-status-update', async update => { conn.on ('message-status-update', async update => {
if (update.to === JID) { if (update.to === JID) {
assert.equal (update.type, WA_MESSAGE_STATUS_TYPE.ERROR) assert.strictEqual (update.type, WA_MESSAGE_STATUS_TYPE.ERROR)
await conn.deleteChat (JID) await conn.deleteChat (JID)
done () done ()
} }
@@ -188,16 +188,16 @@ WAConnectionTest('Messages', conn => {
conn.loadMessages (testJid, 50), conn.loadMessages (testJid, 50),
conn.loadMessages (testJid, 50) conn.loadMessages (testJid, 50)
]) ])
assert.equal (results[0].messages.length, results[1].messages.length) assert.strictEqual (results[0].messages.length, results[1].messages.length)
for (let i = 0; i < results[1].messages.length;i++) { for (let i = 0; i < results[1].messages.length;i++) {
assert.deepEqual (results[0].messages[i], results[1].messages[i], `failed equal at ${i}`) assert.deepStrictEqual (results[0].messages[i], results[1].messages[i], `failed equal at ${i}`)
} }
assert.ok (results[0].messages.length <= 50) assert.ok (results[0].messages.length <= 50)
// check if messages match server // check if messages match server
let msgs = await conn.fetchMessagesFromWA (testJid, 50) let msgs = await conn.fetchMessagesFromWA (testJid, 50)
for (let i = 0; i < results[1].messages.length;i++) { for (let i = 0; i < results[1].messages.length;i++) {
assert.deepEqual (results[0].messages[i].key, msgs[i].key, `failed equal at ${i}`) assert.deepStrictEqual (results[0].messages[i].key, msgs[i].key, `failed equal at ${i}`)
} }
// check with some arbitary cursors // check with some arbitary cursors
let cursor = results[0].messages.slice(-1)[0].key let cursor = results[0].messages.slice(-1)[0].key
@@ -205,7 +205,7 @@ WAConnectionTest('Messages', conn => {
msgs = await conn.fetchMessagesFromWA (testJid, 20, cursor) msgs = await conn.fetchMessagesFromWA (testJid, 20, cursor)
let {messages} = await conn.loadMessages (testJid, 20, cursor) let {messages} = await conn.loadMessages (testJid, 20, cursor)
for (let i = 0; i < messages.length;i++) { for (let i = 0; i < messages.length;i++) {
assert.deepEqual (messages[i].key, msgs[i].key, `failed equal at ${i}`) assert.deepStrictEqual (messages[i].key, msgs[i].key, `failed equal at ${i}`)
} }
for (let i = 0; i < 3;i++) { for (let i = 0; i < 3;i++) {
cursor = results[0].messages[i].key cursor = results[0].messages[i].key
@@ -213,7 +213,7 @@ WAConnectionTest('Messages', conn => {
msgs = await conn.fetchMessagesFromWA (testJid, 20, cursor) msgs = await conn.fetchMessagesFromWA (testJid, 20, cursor)
messages = (await conn.loadMessages (testJid, 20, cursor)).messages messages = (await conn.loadMessages (testJid, 20, cursor)).messages
for (let i = 0; i < messages.length;i++) { for (let i = 0; i < messages.length;i++) {
assert.deepEqual (messages[i].key, msgs[i].key, `failed equal at ${i}`) assert.deepStrictEqual (messages[i].key, msgs[i].key, `failed equal at ${i}`)
} }
cursor = msgs[0].key cursor = msgs[0].key
@@ -221,7 +221,7 @@ WAConnectionTest('Messages', conn => {
msgs = await conn.fetchMessagesFromWA (testJid, 20, cursor) msgs = await conn.fetchMessagesFromWA (testJid, 20, cursor)
messages = (await conn.loadMessages (testJid, 20, cursor)).messages messages = (await conn.loadMessages (testJid, 20, cursor)).messages
for (let i = 0; i < messages.length;i++) { for (let i = 0; i < messages.length;i++) {
assert.deepEqual (messages[i].key, msgs[i].key, `failed equal at ${i}`) assert.deepStrictEqual (messages[i].key, msgs[i].key, `failed equal at ${i}`)
} }
} }
}) })

View File

@@ -1,4 +1,4 @@
import { Presence, ChatModification, delay, DEFAULT_ORIGIN } from '../WAConnection/WAConnection' import { Presence, ChatModification, delay } from '../WAConnection/WAConnection'
import { promises as fs } from 'fs' import { promises as fs } from 'fs'
import * as assert from 'assert' import * as assert from 'assert'
import fetch from 'node-fetch' import fetch from 'node-fetch'
@@ -22,7 +22,7 @@ WAConnectionTest('Misc', (conn) => {
const waitForEvent = new Promise (resolve => { const waitForEvent = new Promise (resolve => {
conn.on ('user-status-update', ({jid, status}) => { conn.on ('user-status-update', ({jid, status}) => {
if (jid === conn.user.jid) { if (jid === conn.user.jid) {
assert.equal (status, newStatus) assert.strictEqual (status, newStatus)
conn.removeAllListeners ('user-status-update') conn.removeAllListeners ('user-status-update')
resolve () resolve ()
} }
@@ -36,7 +36,7 @@ WAConnectionTest('Misc', (conn) => {
await conn.setStatus (newStatus) await conn.setStatus (newStatus)
const response2 = await conn.getStatus() const response2 = await conn.getStatus()
assert.equal (response2.status, newStatus) assert.strictEqual (response2.status, newStatus)
await waitForEvent await waitForEvent
@@ -132,7 +132,7 @@ WAConnectionTest('Misc', (conn) => {
const {messages} = await conn.loadMessages (testJid, 25) const {messages} = await conn.loadMessages (testJid, 25)
for (var message of messages) { for (var message of messages) {
const loaded = await conn.loadMessage (testJid, message.key.id) const loaded = await conn.loadMessage (testJid, message.key.id)
assert.equal (loaded.key.id, message.key.id, `loaded message ${JSON.stringify(message)} incorrectly`) assert.strictEqual (loaded.key.id, message.key.id, `loaded message ${JSON.stringify(message)} incorrectly`)
await delay (500) await delay (500)
} }
}) })

View File

@@ -67,7 +67,7 @@ describe ('garbage', () => {
[...Array(duplicates)].map(() => stuff.myKeyedFunction (key)) [...Array(duplicates)].map(() => stuff.myKeyedFunction (key))
)) ))
) )
assert.deepEqual ( assert.deepStrictEqual (
results.slice(0, duplicates).filter (r => r !== results[0]), results.slice(0, duplicates).filter (r => r !== results[0]),
[] []
) )
@@ -103,7 +103,7 @@ describe ('garbage', () => {
const diff = new Date ().getTime()-start.getTime() const diff = new Date ().getTime()-start.getTime()
assert.ok (diff < WAIT*FUNCS*1.1) assert.ok (diff < WAIT*FUNCS*1.1)
assert.equal ( assert.strictEqual (
results.filter (r => r === 'failed').length, results.filter (r => r === 'failed').length,
FUNCS/2 // half should fail FUNCS/2 // half should fail
) )

View File

@@ -108,16 +108,6 @@ export class WAConnection extends Base {
} }
/** Query broadcast list info */ /** Query broadcast list info */
async getBroadcastListInfo(jid: string) { return this.query({json: ['query', 'contact', jid], expect200: true }) as Promise<WABroadcastListInfo> } async getBroadcastListInfo(jid: string) { return this.query({json: ['query', 'contact', jid], expect200: true }) as Promise<WABroadcastListInfo> }
/** Delete the chat of a given ID */
async deleteChat (jid: string) {
const response = await this.setQuery ([ ['chat', {type: 'delete', jid: jid}, null] ], [12, WAFlag.ignore])
const chat = this.chats.get (jid)
if (chat) {
this.chats.delete (chat)
this.emit ('chat-update', { jid, delete: 'true' })
}
return response
}
/** /**
* Load chats in a paginated manner + gets the profile picture * Load chats in a paginated manner + gets the profile picture
* @param before chats before the given cursor * @param before chats before the given cursor

View File

@@ -334,13 +334,20 @@ export class WAConnection extends Base {
await this.relayWAMessage (waMessage) await this.relayWAMessage (waMessage)
return waMessage return waMessage
} }
/**
* Delete the chat of a given ID
* @deprecated -- use `modifyChat(jid, 'delete')` instead
* */
deleteChat (jid: string) {
return this.modifyChat(jid, 'delete')
}
/** /**
* Modify a given chat (archive, pin etc.) * Modify a given chat (archive, pin etc.)
* @param jid the ID of the person/group you are modifiying * @param jid the ID of the person/group you are modifiying
* @param durationMs only for muting, how long to mute the chat for * @param durationMs only for muting, how long to mute the chat for
*/ */
@Mutex ((jid, type) => jid+type) @Mutex ((jid, type) => jid+type)
async modifyChat (jid: string, type: ChatModification, durationMs?: number) { async modifyChat (jid: string, type: ChatModification | (keyof typeof ChatModification), durationMs?: number) {
jid = whatsappID (jid) jid = whatsappID (jid)
const chat = this.assertChatGet (jid) const chat = this.assertChatGet (jid)
@@ -373,7 +380,7 @@ export class WAConnection extends Base {
chatAttrs.owner = msg.key.fromMe.toString() chatAttrs.owner = msg.key.fromMe.toString()
} }
if (isGroupID(jid)) { if (isGroupID(jid)) {
chatAttrs.participant = this.user?.jid chatAttrs.participant = whatsappID(msg.participant || msg.key.participant)
} }
break break
} }

View File

@@ -310,7 +310,8 @@ export enum ChatModification {
pin='pin', pin='pin',
unpin='unpin', unpin='unpin',
mute='mute', mute='mute',
unmute='unmute' unmute='unmute',
delete='delete'
} }
export const HKDFInfoKeys = { export const HKDFInfoKeys = {
[MessageType.image]: 'WhatsApp Image Keys', [MessageType.image]: 'WhatsApp Image Keys',