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

Newsletter support (absorbs #820 and #822) #961

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
7 changes: 0 additions & 7 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,6 @@
"@typescript-eslint/no-unnecessary-type-assertion": [
"warn"
],
"no-restricted-syntax": [
"warn",
{
"selector": "TSEnumDeclaration",
"message": "Don't declare enums, use literals instead"
}
],
"keyword-spacing": [
"warn"
]
Expand Down
65 changes: 61 additions & 4 deletions src/Socket/messages-recv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { randomBytes } from 'crypto'
import NodeCache from 'node-cache'
import { proto } from '../../WAProto'
import { DEFAULT_CACHE_TTLS, KEY_BUNDLE_TYPE, MIN_PREKEY_COUNT } from '../Defaults'
import { MessageReceiptType, MessageRelayOptions, MessageUserReceipt, SocketConfig, WACallEvent, WAMessageKey, WAMessageStatus, WAMessageStubType, WAPatchName } from '../Types'
import { MessageReceiptType, MessageRelayOptions, MessageUserReceipt, MexOperations, NewsletterSettingsUpdate, SocketConfig, SubscriberAction, WACallEvent, WAMessageKey, WAMessageStatus, WAMessageStubType, WAPatchName, XWAPaths } from '../Types'
import {
aesDecryptCTR,
aesEncryptGCM,
Expand Down Expand Up @@ -322,7 +322,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {

break
case 'membership_approval_mode':
const approvalMode: any = getBinaryNodeChild(child, 'group_join')
const approvalMode = getBinaryNodeChild(child, 'group_join')
if(approvalMode) {
msg.messageStubType = WAMessageStubType.GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE
msg.messageStubParameters = [ approvalMode.attrs.state ]
Expand All @@ -341,6 +341,57 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
}
}

const handleNewsletterNotification = (id: string, node: BinaryNode) => {
const messages = getBinaryNodeChild(node, 'messages')
const message = getBinaryNodeChild(messages, 'message')!

const serverId = message.attrs.server_id

const reactionsList = getBinaryNodeChild(message, 'reactions')
const viewsList = getBinaryNodeChildren(message, 'views_count')

if(reactionsList) {
const reactions = getBinaryNodeChildren(reactionsList, 'reaction')
if(reactions.length === 0) {
ev.emit('newsletter.reaction', { id, 'server_id': serverId, reaction: { removed: true } })
}

reactions.forEach(item => {
ev.emit('newsletter.reaction', { id, 'server_id': serverId, reaction: { code: item.attrs?.code, count: +item.attrs?.count } })
})
}

if(viewsList.length) {
viewsList.forEach(item => {
ev.emit('newsletter.view', { id, 'server_id': serverId, count: +item.attrs.count })
})
}
}

const handleMexNewsletterNotification = (id: string, node: BinaryNode) => {
const operation = node?.attrs.op_name
const content = JSON.parse(node?.content?.toString()!)

let contentPath

if(operation === MexOperations.UPDATE) {
contentPath = content.data[XWAPaths.METADATA_UPDATE]
ev.emit('newsletter-settings.update', { id, update: contentPath.thread_metadata.settings as NewsletterSettingsUpdate })
} else {
let action: SubscriberAction

if(operation === MexOperations.PROMOTE) {
action = 'promote'
contentPath = content.data[XWAPaths.PROMOTE]
} else {
action = 'demote'
contentPath = content.data[XWAPaths.DEMOTE]
}

ev.emit('newsletter-participants.update', { id, author: contentPath.actor.pn, user: contentPath.user.pn, 'new_role': contentPath.user_new_role, action })
}
}

const processNotification = async(node: BinaryNode) => {
const result: Partial<proto.IWebMessageInfo> = { }
const [child] = getAllBinaryNodeChildren(node)
Expand All @@ -362,6 +413,12 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
logger.debug({ jid }, 'got privacy token update')
}

break
case 'newsletter':
handleNewsletterNotification(node.attrs.from, child)
break
case 'mex':
handleMexNewsletterNotification(node.attrs.from, child)
break
case 'w:gp2':
handleGroupNotification(node.attrs.participant, child, result)
Expand Down Expand Up @@ -699,7 +756,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
}

const handleMessage = async(node: BinaryNode) => {
if(shouldIgnoreJid(node.attrs.from!) && node.attrs.from! !== '@s.whatsapp.net') {
if(shouldIgnoreJid(node.attrs.from) && node.attrs.from !== '@s.whatsapp.net') {
logger.debug({ key: node.attrs.key }, 'ignored message')
await sendMessageAck(node)
return
Expand Down Expand Up @@ -814,7 +871,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
}

const handleBadAck = async({ attrs }: BinaryNode) => {
const key: WAMessageKey = { remoteJid: attrs.from, fromMe: true, id: attrs.id }
const key: WAMessageKey = { remoteJid: attrs.from, fromMe: true, id: attrs.id, 'server_id': attrs?.server_id }
// current hypothesis is that if pash is sent in the ack
// it means -- the message hasn't reached all devices yet
// we'll retry sending the message here
Expand Down
20 changes: 15 additions & 5 deletions src/Socket/messages-send.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import NodeCache from 'node-cache'
import { proto } from '../../WAProto'
import { DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults'
import { AnyMessageContent, MediaConnInfo, MessageReceiptType, MessageRelayOptions, MiscMessageGenerationOptions, SocketConfig, WAMessageKey } from '../Types'
import { aggregateMessageKeysNotFromMe, assertMediaContent, bindWaitForEvent, decryptMediaRetryData, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, parseAndInjectE2ESessions, unixTimestampSeconds } from '../Utils'
import { aggregateMessageKeysNotFromMe, assertMediaContent, bindWaitForEvent, decryptMediaRetryData, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, generateMessageIDV2, generateWAMessage, getStatusCodeForMediaRetry, getUrlFromDirectPath, getWAUploadToServer, parseAndInjectE2ESessions, unixTimestampSeconds } from '../Utils'
import { getUrlInfo } from '../Utils/link-preview'
import { areJidsSameUser, BinaryNode, BinaryNodeAttributes, getBinaryNodeChild, getBinaryNodeChildren, isJidGroup, isJidUser, jidDecode, jidEncode, jidNormalizedUser, JidWithDevice, S_WHATSAPP_NET } from '../WABinary'
import { makeGroupsSocket } from './groups'
import { makeNewsletterSocket } from './newsletter'
import ListType = proto.Message.ListMessage.ListType;

export const makeMessagesSocket = (config: SocketConfig) => {
Expand All @@ -18,7 +18,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
options: axiosOptions,
patchMessageBeforeSending,
} = config
const sock = makeGroupsSocket(config)
const sock = makeNewsletterSocket(config)
const {
ev,
authState,
Expand Down Expand Up @@ -315,14 +315,15 @@ export const makeMessagesSocket = (config: SocketConfig) => {
const { user, server } = jidDecode(jid)!
const statusJid = 'status@broadcast'
const isGroup = server === 'g.us'
const isNewsletter = server === 'newsletter'
const isStatus = jid === statusJid
const isLid = server === 'lid'

msgId = msgId || generateMessageIDV2(sock.user?.id)
useUserDevicesCache = useUserDevicesCache !== false

const participants: BinaryNode[] = []
const destinationJid = (!isStatus) ? jidEncode(user, isLid ? 'lid' : isGroup ? 'g.us' : 's.whatsapp.net') : statusJid
const destinationJid = (!isStatus) ? jidEncode(user, isLid ? 'lid' : isGroup ? 'g.us' : isNewsletter ? 'newsletter' : 's.whatsapp.net') : statusJid
const binaryNodeContent: BinaryNode[] = []
const devices: JidWithDevice[] = []

Expand Down Expand Up @@ -431,6 +432,15 @@ export const makeMessagesSocket = (config: SocketConfig) => {
})

await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } })
} else if(isNewsletter) {
const patched = await patchMessageBeforeSending(message, [])
const bytes = encodeNewsletterMessage(patched)

binaryNodeContent.push({
tag: 'plaintext',
attrs: {},
content: bytes
})
} else {
const { user: meUser, device: meDevice } = jidDecode(meId)!

Expand Down Expand Up @@ -679,7 +689,7 @@ export const makeMessagesSocket = (config: SocketConfig) => {
}

content.directPath = media.directPath
content.url = getUrlFromDirectPath(content.directPath!)
content.url = getUrlFromDirectPath(content.directPath)

logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful')
} catch(err) {
Expand Down
Loading
Loading