Store: remove all mentions of window.Store (#127077)

* Store: remove all mentions of window.Store

* Apply suggestion from @BenyFilho

Co-authored-by: BenyFilho <168232825+BenyFilho@users.noreply.github.com>

* Apply suggestions from code review

Co-authored-by: BenyFilho <168232825+BenyFilho@users.noreply.github.com>

---------

Co-authored-by: BenyFilho <168232825+BenyFilho@users.noreply.github.com>
This commit is contained in:
Rajeh Taher 2026-03-01 21:49:21 +02:00 • committed by GitHub
commit 883d7e4eda
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 522 additions and 754 deletions

15
index.d.ts vendored
View file

@ -322,8 +322,7 @@ declare namespace WAWebJS {
on(event: 'auth_failure', listener: (message: string) => void): this
/** Emitted when authentication is successful */
on(event: 'authenticated', listener: (
) => void): this
on(event: 'authenticated', listener: () => void): this
/**
* Emitted when the battery percentage for the attached device changes
@ -563,7 +562,7 @@ declare namespace WAWebJS {
evalOnNewDoc?: Function,
/** Puppeteer launch options. View docs here: https://github.com/puppeteer/puppeteer/ */
puppeteer?: puppeteer.PuppeteerNodeLaunchOptions & puppeteer.ConnectOptions
/** Determines how to save and restore sessions. Otherwise, NoAuth will be used. */
/** Determines how to save and restore sessions. Will use LegacySessionAuth if options.session is set. Otherwise, NoAuth will be used. */
authStrategy?: AuthStrategy,
/** The version of WhatsApp Web to use. Use options.webVersionCache to configure how the version is retrieved. */
webVersion?: string,
@ -688,16 +687,6 @@ declare namespace WAWebJS {
extract: (options: { session: string, path: string }) => Promise<any> | any,
}
/**
* Represents a WhatsApp client session
*/
export interface ClientSession {
WABrowserId: string,
WASecretBundle: string,
WAToken1: string,
WAToken2: string,
}
/**
* @deprecated
*/

View file

@ -7,7 +7,6 @@ const Util = require('./util/Util');
const InterfaceController = require('./util/InterfaceController');
const { WhatsWebURL, DefaultOptions, Events, WAState, MessageTypes } = require('./util/Constants');
const { ExposeAuthStore } = require('./util/Injected/AuthStore/AuthStore');
const { ExposeStore } = require('./util/Injected/Store');
const { LoadUtils } = require('./util/Injected/Utils');
const ChatFactory = require('./factories/ChatFactory');
const ContactFactory = require('./factories/ContactFactory');
@ -20,7 +19,7 @@ const {exposeFunctionIfAbsent} = require('./util/Puppeteer');
* Starting point for interacting with the WhatsApp Web API
* @extends {EventEmitter}
* @param {object} options - Client options
* @param {AuthStrategy} options.authStrategy - Determines how to save and restore sessions. Otherwise, NoAuth will be used.
* @param {AuthStrategy} options.authStrategy - Determines how to save and restore sessions. If not set, NoAuth will be used.
* @param {string} options.webVersion - The version of WhatsApp Web to use. Use options.webVersionCache to configure how the version is retrieved.
* @param {object} options.webVersionCache - Determines how to retrieve the WhatsApp Web version. Defaults to a local cache (LocalWebCache) that falls back to latest if the requested version is not found.
* @param {number} options.authTimeoutMs - Timeout for authentication selector in puppeteer
@ -112,20 +111,20 @@ class Client extends EventEmitter {
await this.pupPage.evaluate(ExposeAuthStore);
const needAuthentication = await this.pupPage.evaluate(async () => {
let state = window.AuthStore.AppState.state;
let state = window.require('WAWebSocketModel').Socket.state;
if (state === 'OPENING' || state === 'UNLAUNCHED' || state === 'PAIRING') {
// wait till state changes
await new Promise(r => {
window.AuthStore.AppState.on('change:state', function waitTillInit(_AppState, state) {
window.require('WAWebSocketModel').Socket.on('change:state', function waitTillInit(_AppState, state) {
if (state !== 'OPENING' && state !== 'UNLAUNCHED' && state !== 'PAIRING') {
window.AuthStore.AppState.off('change:state', waitTillInit);
window.require('WAWebSocketModel').Socket.off('change:state', waitTillInit);
r();
}
});
});
}
state = window.AuthStore.AppState.state;
state = window.require('WAWebSocketModel').Socket.state;
return state == 'UNPAIRED' || state == 'UNPAIRED_IDLE';
});
@ -197,7 +196,7 @@ class Client extends EventEmitter {
await exposeFunctionIfAbsent(this.pupPage, 'onAuthAppStateChangedEvent', async (state) => {
if (state == 'UNPAIRED_IDLE' && !pairWithPhoneNumber.phoneNumber) {
// refresh qr code
window.Store.Cmd.refreshQR();
window.require('WAWebCmd').Cmd.refreshQR();
}
});
@ -210,7 +209,7 @@ class Client extends EventEmitter {
this.emit(Events.AUTHENTICATED, authEventPayload);
const injected = await this.pupPage.evaluate(async () => {
return typeof window.Store !== 'undefined' && typeof window.WWebJS !== 'undefined';
return typeof window.WWebJS !== 'undefined';
});
if (!injected) {
@ -221,13 +220,14 @@ class Client extends EventEmitter {
await webCache.persist(this.currentIndexHtml, version);
}
await this.pupPage.evaluate(ExposeStore);
//Load util functions (serializers, helper functions)
await this.pupPage.evaluate(LoadUtils);
let start = Date.now();
let res = false;
while(start > (Date.now() - 30000)){
// Check window.Store Injection
res = await this.pupPage.evaluate('window.Store != undefined');
// Check window.WWebJS Injection
res = await this.pupPage.evaluate('window.WWebJS != undefined');
if(res){break;}
await new Promise(r => setTimeout(r, 200));
}
@ -240,14 +240,11 @@ class Client extends EventEmitter {
* @type {ClientInfo}
*/
this.info = new ClientInfo(this, await this.pupPage.evaluate(() => {
return { ...window.Store.Conn.serialize(), wid: window.Store.User.getMaybeMePnUser() || window.Store.User.getMaybeMeLidUser() };
return { ...(window.require('WAWebConnModel').Conn).serialize(), wid: (window.require('WAWebUserPrefsMeUser')).getMaybeMePnUser() || (window.require('WAWebUserPrefsMeUser')).getMaybeMeLidUser() };
}));
this.interface = new InterfaceController(this);
//Load util functions (serializers, helper functions)
await this.pupPage.evaluate(LoadUtils);
await this.attachEventListeners();
}
/**
@ -269,15 +266,16 @@ class Client extends EventEmitter {
await this.pupPage.waitForNavigation({waitUntil: 'load', timeout: 5000}).catch((_) => _);
});
await this.pupPage.evaluate(() => {
window.AuthStore.AppState.on('change:state', (_AppState, state) => { window.onAuthAppStateChangedEvent(state); });
window.AuthStore.AppState.on('change:hasSynced', () => { window.onAppStateHasSyncedEvent(); });
window.AuthStore.Cmd.on('offline_progress_update_from_bridge', () => {
window.require('WAWebSocketModel').Socket.on('change:state', (_AppState, state) => { window.onAuthAppStateChangedEvent(state); });
window.require('WAWebSocketModel').Socket.on('change:hasSynced', () => { window.onAppStateHasSyncedEvent(); });
const Cmd = window.require('WAWebCmd').Cmd;
Cmd.on('offline_progress_update_from_bridge', () => {
window.onOfflineProgressUpdateEvent(window.AuthStore.OfflineMessageHandler.getOfflineDeliveryProgress());
});
window.AuthStore.Cmd.on('logout', async () => {
Cmd.on('logout', async () => {
await window.onLogoutEvent();
});
window.AuthStore.Cmd.on('logout_from_bridge', async () => {
Cmd.on('logout_from_bridge', async () => {
await window.onLogoutEvent();
});
});
@ -378,7 +376,8 @@ class Client extends EventEmitter {
clearInterval(window.codeInterval); // remove existing interval
}
window.codeInterval = setInterval(async () => {
if (window.AuthStore.AppState.state != 'UNPAIRED' && window.AuthStore.AppState.state != 'UNPAIRED_IDLE') {
const state = window.require('WAWebSocketModel').Socket.state;
if (state != 'UNPAIRED' && state != 'UNPAIRED_IDLE') {
clearInterval(window.codeInterval);
return;
}
@ -588,7 +587,7 @@ class Client extends EventEmitter {
if (state === WAState.CONFLICT) {
setTimeout(() => {
this.pupPage.evaluate(() => window.Store.AppState.takeover());
this.pupPage.evaluate(() => window.require('WAWebSocketModel').Socket.takeover());
}, this.options.takeoverTimeoutMs);
}
}
@ -721,21 +720,22 @@ class Client extends EventEmitter {
});
await this.pupPage.evaluate(() => {
window.Store.Msg.on('change', (msg) => { window.onChangeMessageEvent(window.WWebJS.getMessageModel(msg)); });
window.Store.Msg.on('change:type', (msg) => { window.onChangeMessageTypeEvent(window.WWebJS.getMessageModel(msg)); });
window.Store.Msg.on('change:ack', (msg, ack) => { window.onMessageAckEvent(window.WWebJS.getMessageModel(msg), ack); });
window.Store.Msg.on('change:isUnsentMedia', (msg, unsent) => { if (msg.id.fromMe && !unsent) window.onMessageMediaUploadedEvent(window.WWebJS.getMessageModel(msg)); });
window.Store.Msg.on('remove', (msg) => { if (msg.isNewMsg) window.onRemoveMessageEvent(window.WWebJS.getMessageModel(msg)); });
window.Store.Msg.on('change:body change:caption', (msg, newBody, prevBody) => { window.onEditMessageEvent(window.WWebJS.getMessageModel(msg), newBody, prevBody); });
window.Store.AppState.on('change:state', (_AppState, state) => { window.onAppStateChangedEvent(state); });
window.Store.Conn.on('change:battery', (state) => { window.onBatteryStateChangedEvent(state); });
const callCollection = (window.Store && window.Store.Call) || (window.Store && window.Store.WAWebCallCollection);
if (callCollection && typeof callCollection.on === 'function') {
callCollection.on('add', (call) => { window.onIncomingCall(call); });
const { Msg, Chat, WAWebCallCollection } = window.require('WAWebCollections');
const AppState = window.require('WAWebSocketModel').Socket;
Msg.on('change', (msg) => { window.onChangeMessageEvent(window.WWebJS.getMessageModel(msg)); });
Msg.on('change:type', (msg) => { window.onChangeMessageTypeEvent(window.WWebJS.getMessageModel(msg)); });
Msg.on('change:ack', (msg, ack) => { window.onMessageAckEvent(window.WWebJS.getMessageModel(msg), ack); });
Msg.on('change:isUnsentMedia', (msg, unsent) => { if (msg.id.fromMe && !unsent) window.onMessageMediaUploadedEvent(window.WWebJS.getMessageModel(msg)); });
Msg.on('remove', (msg) => { if (msg.isNewMsg) window.onRemoveMessageEvent(window.WWebJS.getMessageModel(msg)); });
Msg.on('change:body change:caption', (msg, newBody, prevBody) => { window.onEditMessageEvent(window.WWebJS.getMessageModel(msg), newBody, prevBody); });
AppState.on('change:state', (_AppState, state) => { window.onAppStateChangedEvent(state); });
(window.require('WAWebConnModel').Conn).on('change:battery', (state) => { window.onBatteryStateChangedEvent(state); });
if (WAWebCallCollection && typeof WAWebCallCollection.on === 'function') {
WAWebCallCollection.on('add', (call) => { window.onIncomingCall(call); });
}
window.Store.Chat.on('remove', async (chat) => { window.onRemoveChatEvent(await window.WWebJS.getChatModel(chat)); });
window.Store.Chat.on('change:archive', async (chat, currState, prevState) => { window.onArchiveChatEvent(await window.WWebJS.getChatModel(chat), currState, prevState); });
window.Store.Msg.on('add', (msg) => {
Chat.on('remove', async (chat) => { window.onRemoveChatEvent(await window.WWebJS.getChatModel(chat)); });
Chat.on('change:archive', async (chat, currState, prevState) => { window.onArchiveChatEvent(await window.WWebJS.getChatModel(chat), currState, prevState); });
Msg.on('add', (msg) => {
if (msg.isNewMsg) {
if(msg.type === 'ciphertext') {
// defer message event until ciphertext is resolved (type changed)
@ -746,11 +746,9 @@ class Client extends EventEmitter {
}
}
});
window.Store.Chat.on('change:unreadCount', (chat) => {window.onChatUnreadCountEvent(chat);});
Chat.on('change:unreadCount', (chat) => {window.onChatUnreadCountEvent(chat);});
const module = window.Store.AddonReactionTable;
const ogMethod = module.bulkUpsert;
module.bulkUpsert = ((...args) => {
window.WWebJS.injectToFunction({ module: 'WAWebAddonReactionTableMode', function: 'reactionTableMode.bulkUpsert'}, (module, origFunction, ...args) => {
window.onReaction(args[0].map(reaction => {
const msgKey = reaction.id;
const parentMsgKey = reaction.reactionParentKey;
@ -761,13 +759,10 @@ class Client extends EventEmitter {
return {...reaction, msgKey, parentMsgKey, senderUserJid, timestamp };
}));
return ogMethod(...args);
}).bind(module);
return origFunction.apply(module, args);
});
const pollVoteModule = window.Store.AddonPollVoteTable;
const ogPollVoteMethod = pollVoteModule.bulkUpsert;
pollVoteModule.bulkUpsert = (async (...args) => {
window.WWebJS.injectToFunction({ module: 'WAWebAddonPollVoteTableMode', function: 'pollVoteTableMode.bulkUpsert'}, async (module, origFunction, ...args) => {
const votes = await Promise.all(args[0].map(async vote => {
const msgKey = vote.id;
const parentMsgKey = vote.pollUpdateParentKey;
@ -775,9 +770,9 @@ class Client extends EventEmitter {
const sender = vote.author ?? vote.from;
const senderUserJid = sender._serialized;
let parentMessage = window.Store.Msg.get(parentMsgKey._serialized);
let parentMessage = Msg.get(parentMsgKey._serialized);
if (!parentMessage) {
const fetched = await window.Store.Msg.getMessagesById([parentMsgKey._serialized]);
const fetched = await Msg.getMessagesById([parentMsgKey._serialized]);
parentMessage = fetched?.messages?.[0] || null;
}
@ -794,8 +789,8 @@ class Client extends EventEmitter {
window.onPollVoteEvent(votes);
return ogPollVoteMethod.apply(pollVoteModule, args);
}).bind(pollVoteModule);
return origFunction.apply(module, args);
});
});
}
@ -846,9 +841,7 @@ class Client extends EventEmitter {
*/
async logout() {
await this.pupPage.evaluate(() => {
if (window.Store && window.Store.AppState && typeof window.Store.AppState.logout === 'function') {
return window.Store.AppState.logout();
}
return window.require('WAWebSocketModel').Socket.logout();
});
await this.pupBrowser.close();
@ -1072,15 +1065,16 @@ class Client extends EventEmitter {
*/
async sendChannelAdminInvite(chatId, channelId, options = {}) {
const response = await this.pupPage.evaluate(async (chatId, channelId, options) => {
const channelWid = window.Store.WidFactory.createWid(channelId);
const chatWid = window.Store.WidFactory.createWid(chatId);
const chat = window.Store.Chat.get(chatWid) || (await window.Store.Chat.find(chatWid));
const { createWid } = window.require('WAWebWidFactory');
const channelWid = createWid(channelId);
const chatWid = createWid(chatId);
const chat = window.require('WAWebCollections').Chat.get(chatWid) || (await (window.require('WAWebCollections')).Chat.find(chatWid));
if (!chatWid.isUser()) {
return false;
}
return await window.Store.SendChannelMessage.sendNewsletterAdminInviteMessage(
return await (window.require('WAWebNewsletterSendMsgAction')).sendNewsletterAdminInviteMessage(
chat,
{
newsletterWid: channelWid,
@ -1105,7 +1099,7 @@ class Client extends EventEmitter {
*/
async searchMessages(query, options = {}) {
const messages = await this.pupPage.evaluate(async (query, page, count, remote) => {
const { messages } = await window.Store.Msg.search(query, page, count, remote);
const { messages } = await (window.require('WAWebCollections')).Msg.search(query, page, count, remote);
return messages.map(msg => window.WWebJS.getMessageModel(msg));
}, query, options.page, options.limit, options.chatId);
@ -1204,13 +1198,13 @@ class Client extends EventEmitter {
*/
async getMessageById(messageId) {
const msg = await this.pupPage.evaluate(async messageId => {
let msg = window.Store.Msg.get(messageId);
let msg = (window.require('WAWebCollections')).Msg.get(messageId);
if(msg) return window.WWebJS.getMessageModel(msg);
const params = messageId.split('_');
if (params.length !== 3 && params.length !== 4) throw new Error('Invalid serialized message id specified');
let messagesObject = await window.Store.Msg.getMessagesById([messageId]);
let messagesObject = await (window.require('WAWebCollections')).Msg.getMessagesById([messageId]);
if (messagesObject && messagesObject.messages.length) msg = messagesObject.messages[0];
if(msg) return window.WWebJS.getMessageModel(msg);
@ -1227,16 +1221,16 @@ class Client extends EventEmitter {
*/
async getPinnedMessages(chatId) {
const pinnedMsgs = await this.pupPage.evaluate(async (chatId) => {
const chatWid = window.Store.WidFactory.createWid(chatId);
const chat = window.Store.Chat.get(chatWid) ?? await window.Store.Chat.find(chatWid);
const chatWid = window.require('WAWebWidFactory').createWid(chatId);
const chat = (window.require('WAWebCollections')).Chat.get(chatWid) ?? await (window.require('WAWebCollections')).Chat.find(chatWid);
if (!chat) return [];
const msgs = await window.Store.PinnedMsgUtils.getTable().equals(['chatId'], chatWid.toString());
const msgs = await (window.require('WAWebPinInChatSchema')).getTable().equals(['chatId'], chatWid.toString());
const pinnedMsgs = (
await Promise.all(
msgs.filter(msg => msg.pinType == 1).map(async (msg) => {
const res = await window.Store.Msg.getMessagesById([msg.parentMsgKey]);
const res = await (window.require('WAWebCollections')).Msg.getMessagesById([msg.parentMsgKey]);
return res?.messages?.[0];
})
)
@ -1257,7 +1251,7 @@ class Client extends EventEmitter {
*/
async getInviteInfo(inviteCode) {
return await this.pupPage.evaluate(inviteCode => {
return window.Store.GroupInvite.queryGroupInvite(inviteCode);
return (window.require('WAWebGroupQueryJob')).queryGroupInvite(inviteCode);
}, inviteCode);
}
@ -1268,7 +1262,7 @@ class Client extends EventEmitter {
*/
async acceptInvite(inviteCode) {
const res = await this.pupPage.evaluate(async inviteCode => {
return await window.Store.GroupInvite.joinGroupViaInvite(inviteCode);
return await (window.require('WAWebGroupQueryJob')).joinGroupViaInvite(inviteCode);
}, inviteCode);
return res.gid._serialized;
@ -1282,7 +1276,7 @@ class Client extends EventEmitter {
async acceptChannelAdminInvite(channelId) {
return await this.pupPage.evaluate(async (channelId) => {
try {
await window.Store.ChannelUtils.acceptNewsletterAdminInvite(channelId);
await (window.require('WAWebMexAcceptNewsletterAdminInviteJob')).acceptNewsletterAdminInvite(channelId);
return true;
} catch (err) {
if (err.name === 'ServerStatusCodeError') return false;
@ -1300,8 +1294,8 @@ class Client extends EventEmitter {
async revokeChannelAdminInvite(channelId, userId) {
return await this.pupPage.evaluate(async (channelId, userId) => {
try {
const userWid = window.Store.WidFactory.createWid(userId);
await window.Store.ChannelUtils.revokeNewsletterAdminInvite(channelId, userWid);
const userWid = window.require('WAWebWidFactory').createWid(userId);
await (window.require('WAWebMexRevokeNewsletterAdminInviteJob')).revokeNewsletterAdminInvite(channelId, userWid);
return true;
} catch (err) {
if (err.name === 'ServerStatusCodeError') return false;
@ -1319,8 +1313,8 @@ class Client extends EventEmitter {
async demoteChannelAdmin(channelId, userId) {
return await this.pupPage.evaluate(async (channelId, userId) => {
try {
const userWid = window.Store.WidFactory.createWid(userId);
await window.Store.ChannelUtils.demoteNewsletterAdmin(channelId, userWid);
const userWid = window.require('WAWebWidFactory').createWid(userId);
await (window.require('WAWebDemoteNewsletterAdminAction')).demoteNewsletterAdmin(channelId, userWid);
return true;
} catch (err) {
if (err.name === 'ServerStatusCodeError') return false;
@ -1339,8 +1333,8 @@ class Client extends EventEmitter {
if (inviteInfo.inviteCodeExp == 0) throw 'Expired invite code';
return this.pupPage.evaluate(async inviteInfo => {
let { groupId, fromId, inviteCode, inviteCodeExp } = inviteInfo;
let userWid = window.Store.WidFactory.createWid(fromId);
return await window.Store.GroupInviteV4.joinGroupViaInviteV4(inviteCode, String(inviteCodeExp), groupId, userWid);
let userWid = window.require('WAWebWidFactory').createWid(fromId);
return await (window.require('WAWebGroupInviteV4Job')).joinGroupViaInviteV4(inviteCode, String(inviteCodeExp), groupId, userWid);
}, inviteInfo);
}
@ -1350,7 +1344,7 @@ class Client extends EventEmitter {
*/
async setStatus(status) {
await this.pupPage.evaluate(async status => {
return await window.Store.StatusUtils.setMyStatus(status);
return await (window.require('WAWebContactStatusBridge')).setMyStatus(status);
}, status);
}
@ -1362,8 +1356,8 @@ class Client extends EventEmitter {
*/
async setDisplayName(displayName) {
const couldSet = await this.pupPage.evaluate(async displayName => {
if(!window.Store.Conn.canSetMyPushname()) return false;
await window.Store.Settings.setPushname(displayName);
if(!(window.require('WAWebConnModel').Conn).canSetMyPushname()) return false;
await (window.require('WAWebSetPushnameConnAction')).setPushname(displayName);
return true;
}, displayName);
@ -1376,8 +1370,7 @@ class Client extends EventEmitter {
*/
async getState() {
return await this.pupPage.evaluate(() => {
if(!window.Store) return null;
return window.Store.AppState.state;
return window.require('WAWebSocketModel').Socket.state ?? null;
});
}
@ -1386,7 +1379,7 @@ class Client extends EventEmitter {
*/
async sendPresenceAvailable() {
return await this.pupPage.evaluate(() => {
return window.Store.PresenceUtils.sendPresenceAvailable();
return window.require('WAWebPresenceChatAction').sendPresenceAvailable();
});
}
@ -1395,7 +1388,7 @@ class Client extends EventEmitter {
*/
async sendPresenceUnavailable() {
return await this.pupPage.evaluate(() => {
return window.Store.PresenceUtils.sendPresenceUnavailable();
return window.require('WAWebPresenceChatAction').sendPresenceUnavailable();
});
}
@ -1406,7 +1399,7 @@ class Client extends EventEmitter {
async archiveChat(chatId) {
return await this.pupPage.evaluate(async chatId => {
let chat = await window.WWebJS.getChat(chatId, { getAsModel: false });
await window.Store.Cmd.archiveChat(chat, true);
await (window.require('WAWebCmd').Cmd).archiveChat(chat, true);
return true;
}, chatId);
}
@ -1418,7 +1411,7 @@ class Client extends EventEmitter {
async unarchiveChat(chatId) {
return await this.pupPage.evaluate(async chatId => {
let chat = await window.WWebJS.getChat(chatId, { getAsModel: false });
await window.Store.Cmd.archiveChat(chat, false);
await (window.require('WAWebCmd').Cmd).archiveChat(chat, false);
return false;
}, chatId);
}
@ -1434,14 +1427,14 @@ class Client extends EventEmitter {
return true;
}
const MAX_PIN_COUNT = 3;
const chatModels = window.Store.Chat.getModelsArray();
const chatModels = (window.require('WAWebCollections')).Chat.getModelsArray();
if (chatModels.length > MAX_PIN_COUNT) {
let maxPinned = chatModels[MAX_PIN_COUNT - 1].pin;
if (maxPinned) {
return false;
}
}
await window.Store.Cmd.pinChat(chat, true);
await (window.require('WAWebCmd').Cmd).pinChat(chat, true);
return true;
}, chatId);
}
@ -1456,7 +1449,7 @@ class Client extends EventEmitter {
if (!chat.pin) {
return false;
}
await window.Store.Cmd.pinChat(chat, false);
await (window.require('WAWebCmd').Cmd).pinChat(chat, false);
return false;
}, chatId);
}
@ -1490,7 +1483,7 @@ class Client extends EventEmitter {
*/
async _muteUnmuteChat (chatId, action, unmuteDateTs) {
return this.pupPage.evaluate(async (chatId, action, unmuteDateTs) => {
const chat = window.Store.Chat.get(chatId) ?? await window.Store.Chat.find(chatId);
const chat = (window.require('WAWebCollections')).Chat.get(chatId) ?? await (window.require('WAWebCollections')).Chat.find(chatId);
action === 'MUTE'
? await chat.mute.mute({ expiration: unmuteDateTs, sendDevice: true })
: await chat.mute.unmute({ sendDevice: true });
@ -1505,7 +1498,7 @@ class Client extends EventEmitter {
async markChatUnread(chatId) {
await this.pupPage.evaluate(async chatId => {
let chat = await window.WWebJS.getChat(chatId, { getAsModel: false });
await window.Store.Cmd.markChatUnread(chat, true);
await (window.require('WAWebCmd').Cmd).markChatUnread(chat, true);
}, chatId);
}
@ -1517,8 +1510,10 @@ class Client extends EventEmitter {
async getProfilePicUrl(contactId) {
const profilePic = await this.pupPage.evaluate(async contactId => {
try {
const chatWid = window.Store.WidFactory.createWid(contactId);
return await window.Store.ProfilePic.requestProfilePicFromServer(chatWid);
const chatWid = window.require('WAWebWidFactory').createWid(contactId);
return window.WWebJS.compareWwebVersions(window.Debug.VERSION, '<', '2.3000.0')
? await window.require('WAWebContactProfilePicThumbBridge').profilePicFind(chatWid)
: await window.require('WAWebContactProfilePicThumbBridge').requestProfilePicFromServer(chatWid);
} catch (err) {
if(err.name === 'ServerStatusCodeError') return undefined;
throw err;
@ -1535,17 +1530,17 @@ class Client extends EventEmitter {
*/
async getCommonGroups(contactId) {
const commonGroups = await this.pupPage.evaluate(async (contactId) => {
let contact = window.Store.Contact.get(contactId);
let contact = (window.require('WAWebCollections')).Contact.get(contactId);
if (!contact) {
const wid = window.Store.WidFactory.createWid(contactId);
const chatConstructor = window.Store.Contact.getModelsArray().find(c=>!c.isGroup).constructor;
const wid = window.require('WAWebWidFactory').createWid(contactId);
const chatConstructor = (window.require('WAWebCollections')).Contact.getModelsArray().find(c=>!c.isGroup).constructor;
contact = new chatConstructor({id: wid});
}
if (contact.commonGroups) {
return contact.commonGroups.serialize();
}
const status = await window.Store.findCommonGroups(contact);
const status = await (window.require('WAWebFindCommonGroupsContactAction').findCommonGroups)(contact);
if (status) {
return contact.commonGroups.serialize();
}
@ -1563,7 +1558,7 @@ class Client extends EventEmitter {
*/
async resetState() {
await this.pupPage.evaluate(() => {
window.Store.AppState.reconnect();
window.require('WAWebSocketModel').Socket.reconnect();
});
}
@ -1588,8 +1583,8 @@ class Client extends EventEmitter {
}
return await this.pupPage.evaluate(async number => {
const wid = window.Store.WidFactory.createWid(number);
const result = await window.Store.QueryExist(wid);
const wid = window.require('WAWebWidFactory').createWid(number);
const result = await (window.require('WAWebQueryExistsJob').queryWidExists)(wid);
if (!result || result.wid === undefined) return null;
return result.wid;
}, number);
@ -1605,7 +1600,7 @@ class Client extends EventEmitter {
if (!number.includes('@s.whatsapp.net')) number = `${number}@s.whatsapp.net`;
return await this.pupPage.evaluate(async numberId => {
return window.Store.NumberInfo.formattedPhoneNumber(numberId);
return window.require('WAWebPhoneUtils').formattedPhoneNumber(numberId);
}, number);
}
@ -1618,7 +1613,7 @@ class Client extends EventEmitter {
number = number.replace(' ', '').replace('+', '').replace('@c.us', '');
return await this.pupPage.evaluate(async numberId => {
return window.Store.NumberInfo.findCC(numberId);
return window.require('WAPhoneFindCC').findCC(numberId);
}, number);
}
@ -1684,17 +1679,17 @@ class Client extends EventEmitter {
};
for (const participant of participants) {
const pWid = window.Store.WidFactory.createWid(participant);
if ((await window.Store.QueryExist(pWid))?.wid) {
const pWid = window.require('WAWebWidFactory').createWid(participant);
if ((await (window.require('WAWebQueryExistsJob').queryWidExists)(pWid))?.wid) {
participantWids.push({ phoneNumber: pWid });
}
else failedParticipants.push(participant);
}
parentGroupId && (parentGroupWid = window.Store.WidFactory.createWid(parentGroupId));
parentGroupId && (parentGroupWid = window.require('WAWebWidFactory').createWid(parentGroupId));
try {
createGroupResult = await window.Store.GroupUtils.createGroup(
createGroupResult = await (window.require('WAWebGroupCreateJob')).createGroup(
{
'addressingModeOverride': 'lid',
'memberAddMode': options.memberAddMode ?? false,
@ -1713,14 +1708,14 @@ class Client extends EventEmitter {
for (const participant of createGroupResult.participants) {
let isInviteV4Sent = false;
participant.wid.server == 'lid' && (participant.wid = window.Store.LidUtils.getPhoneNumber(participant.wid));
participant.wid.server == 'lid' && (participant.wid = window.require('WAWebApiContact').getPhoneNumber(participant.wid));
const participantId = participant.wid._serialized;
const statusCode = participant.error || 200;
if (autoSendInviteV4 && statusCode === 403) {
window.Store.Contact.gadd(participant.wid, { silent: true });
const addParticipantResult = await window.Store.GroupInviteV4.sendGroupInviteMessage(
window.Store.Chat.get(participant.wid) || await window.Store.Chat.find(participant.wid),
(window.require('WAWebCollections')).Contact.gadd(participant.wid, { silent: true });
const addParticipantResult = await (window.require('WAWebChatSendMessages')).sendGroupInviteMessage(
(window.require('WAWebCollections')).Chat.get(participant.wid) || await (window.require('WAWebCollections')).Chat.find(participant.wid),
createGroupResult.wid._serialized,
createGroupResult.subject,
participant.invite_code,
@ -1781,7 +1776,7 @@ class Client extends EventEmitter {
return await this.pupPage.evaluate(async (title, options) => {
let response, { description = null, picture = null } = options;
if (!window.Store.ChannelUtils.isNewsletterCreationEnabled()) {
if (!(window.require('WAWebNewsletterGatingUtils')).isNewsletterCreationEnabled()) {
return 'CreateChannelError: A channel creation is not enabled';
}
@ -1795,7 +1790,7 @@ class Client extends EventEmitter {
}
try {
response = await window.Store.ChannelUtils.createNewsletterQuery({
response = await (window.require('WAWebNewsletterCreateQueryJob')).createNewsletterQuery({
name: title,
description: description,
picture: picture,
@ -1809,7 +1804,7 @@ class Client extends EventEmitter {
return {
title: title,
nid: window.Store.JidToWid.newsletterJidToWid(response.idJid),
nid: window.require('WAWebJidToWid').newsletterJidToWid(response.idJid),
inviteLink: `https://whatsapp.com/channel/${response.newsletterInviteLinkMetadataMixin.inviteCode}`,
createdAtTs: response.newsletterCreationTimeMetadataMixin.creationTimeValue
};
@ -1862,17 +1857,17 @@ class Client extends EventEmitter {
async transferChannelOwnership(channelId, newOwnerId, options = {}) {
return await this.pupPage.evaluate(async (channelId, newOwnerId, options) => {
const channel = await window.WWebJS.getChat(channelId, { getAsModel: false });
const newOwner = window.Store.Contact.get(newOwnerId) || (await window.Store.Contact.find(newOwnerId));
const newOwner = (window.require('WAWebCollections')).Contact.get(newOwnerId) || (await (window.require('WAWebCollections')).Contact.find(newOwnerId));
if (!channel.newsletterMetadata) {
await window.Store.NewsletterMetadataCollection.update(channel.id);
await (window.require('WAWebCollections')).NewsletterMetadataCollection.update(channel.id);
}
try {
await window.Store.ChannelUtils.changeNewsletterOwnerAction(channel, newOwner);
await (window.require('WAWebChangeNewsletterOwnerAction')).changeNewsletterOwnerAction(channel, newOwner);
if (options.shouldDismissSelfAsAdmin) {
const meContact = window.Store.ContactCollection.getMeContact();
meContact && (await window.Store.ChannelUtils.demoteNewsletterAdminAction(channel, meContact));
const meContact = window.require('WAWebContactCollection').getMeContact();
meContact && (await (window.require('WAWebNewsletterDemoteAdminJob')).demoteNewsletterAdminAction(channel, meContact));
}
} catch (error) {
return false;
@ -1904,18 +1899,21 @@ class Client extends EventEmitter {
async searchChannels(searchOptions = {}) {
return await this.pupPage.evaluate(async ({
searchText = '',
countryCodes = [window.Store.ChannelUtils.currentRegion],
countryCodes = [],
skipSubscribedNewsletters = false,
view = 0,
limit = 50
}) => {
searchText = searchText.trim();
const currentRegion = window.Store.ChannelUtils.currentRegion;
const currentRegion = window.require('WAWebL10N').getRegion();
if (countryCodes.length === 0) countryCodes[0] = currentRegion;
if (![0, 1, 2, 3].includes(view)) view = 0;
const { countryCodesIso } = window.require('WAWebCountriesNativeCountryNames');
countryCodes = countryCodes.length === 1 && countryCodes[0] === currentRegion
? countryCodes
: countryCodes.filter((code) => Object.keys(window.Store.ChannelUtils.countryCodesIso).includes(code));
: countryCodes.filter((code) => Object.keys(countryCodesIso).includes(code));
const viewTypeMapping = {
0: 'RECOMMENDED',
@ -1933,12 +1931,12 @@ class Client extends EventEmitter {
cursorToken: ''
};
const originalFunction = window.Store.ChannelUtils.getNewsletterDirectoryPageSize;
limit !== 50 && (window.Store.ChannelUtils.getNewsletterDirectoryPageSize = () => limit);
const originalFunction = window.require('WAWebNewsletterGatingUtils').getNewsletterDirectoryPageSize;
limit !== 50 && (window.require('WAWebNewsletterGatingUtils').getNewsletterDirectoryPageSize = () => limit);
const channels = (await window.Store.ChannelUtils.fetchNewsletterDirectories(searchOptions)).newsletters;
const channels = (await (window.require('WAWebNewsletterDirectorySearchAction')).fetchNewsletterDirectories(searchOptions)).newsletters;
limit !== 50 && (window.Store.ChannelUtils.getNewsletterDirectoryPageSize = originalFunction);
limit !== 50 && (window.require('WAWebNewsletterGatingUtils').getNewsletterDirectoryPageSize = originalFunction);
return channels
? await Promise.all(channels.map((channel) => window.WWebJS.getChatModel(channel, { isChannel: true })))
@ -1956,7 +1954,7 @@ class Client extends EventEmitter {
const channel = await window.WWebJS.getChat(channelId, { getAsModel: false });
if (!channel) return false;
try {
await window.Store.ChannelUtils.deleteNewsletterAction(channel);
await (window.require('WAWebNewsletterDeleteAction')).deleteNewsletterAction(channel);
return true;
} catch (err) {
if (err.name === 'ServerStatusCodeError') return false;
@ -1997,9 +1995,9 @@ class Client extends EventEmitter {
const broadcast = await this.pupPage.evaluate(async (userId) => {
let status;
try {
status = window.Store.Status.get(userId);
status = (window.require('WAWebCollections')).Status.get(userId);
if (!status) {
status = await window.Store.Status.find(userId);
status = await (window.require('WAWebCollections')).Status.find(userId);
}
} catch {
status = null;
@ -2017,17 +2015,17 @@ class Client extends EventEmitter {
*/
async revokeStatusMessage(messageId) {
return await this.pupPage.evaluate(async (msgId) => {
const status = window.Store.Status.getMyStatus();
const status = (window.require('WAWebCollections')).Status.getMyStatus();
if (!status) return;
const msg =
window.Store.Msg.get(msgId) || (await window.Store.Msg.getMessagesById([msgId]))?.messages?.[0];
(window.require('WAWebCollections')).Msg.get(msgId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([msgId]))?.messages?.[0];
if (!msg) return;
if (!msg.id.fromMe || !msg.id.remote.isStatus())
throw 'Invalid usage! Can only revoke the message its from own status broadcast';
return await window.Store.StatusUtils.sendStatusRevokeMsgAction(status, msg);
return await (window.require('WAWebRevokeStatusAction')).sendStatusRevokeMsgAction(status, msg);
}, messageId);
}
@ -2064,7 +2062,7 @@ class Client extends EventEmitter {
*/
async getChatsByLabelId(labelId) {
const chatIds = await this.pupPage.evaluate(async (labelId) => {
const label = window.Store.Label.get(labelId);
const label = (window.require('WAWebCollections')).Label.get(labelId);
const labelItems = label.labelItemCollection.getModelsArray();
return labelItems.reduce((result, item) => {
if (item.parentType === 'Chat') {
@ -2083,7 +2081,7 @@ class Client extends EventEmitter {
*/
async getBlockedContacts() {
const blockedContacts = await this.pupPage.evaluate(() => {
let chatIds = window.Store.Blocklist.getModelsArray().map(a => a.id._serialized);
let chatIds = (window.require('WAWebCollections')).Blocklist.getModelsArray().map(a => a.id._serialized);
return Promise.all(chatIds.map(id => window.WWebJS.getContact(id)));
});
@ -2124,11 +2122,11 @@ class Client extends EventEmitter {
async addOrRemoveLabels(labelIds, chatIds) {
return this.pupPage.evaluate(async (labelIds, chatIds) => {
if (['smba', 'smbi'].indexOf(window.Store.Conn.platform) === -1) {
if (['smba', 'smbi'].indexOf((window.require('WAWebConnModel').Conn).platform) === -1) {
throw '[LT01] Only Whatsapp business';
}
const labels = window.WWebJS.getLabels().filter(e => labelIds.find(l => l == e.id) !== undefined);
const chats = window.Store.Chat.filter(e => chatIds.includes(e.id._serialized));
const chats = (window.require('WAWebCollections')).Chat.filter(e => chatIds.includes(e.id._serialized));
let actions = labels.map(label => ({id: label.id, type: 'add'}));
@ -2140,7 +2138,7 @@ class Client extends EventEmitter {
});
});
return await window.Store.Label.addOrRemoveLabels(actions, chats);
return await (window.require('WAWebCollections')).Label.addOrRemoveLabels(actions, chats);
}, labelIds, chatIds);
}
@ -2161,8 +2159,8 @@ class Client extends EventEmitter {
*/
async getGroupMembershipRequests(groupId) {
return await this.pupPage.evaluate(async (groupId) => {
const groupWid = window.Store.WidFactory.createWid(groupId);
return await window.Store.MembershipRequestUtils.getMembershipApprovalRequests(groupWid);
const groupWid = window.require('WAWebWidFactory').createWid(groupId);
return await (window.require('WAWebApiMembershipApprovalRequestStore')).getMembershipApprovalRequests(groupWid);
}, groupId);
}
@ -2214,11 +2212,11 @@ class Client extends EventEmitter {
*/
async setAutoDownloadAudio(flag) {
await this.pupPage.evaluate(async flag => {
const autoDownload = window.Store.Settings.getAutoDownloadAudio();
const autoDownload = (window.require('WAWebUserPrefsGeneral')).getAutoDownloadAudio();
if (autoDownload === flag) {
return flag;
}
await window.Store.Settings.setAutoDownloadAudio(flag);
await (window.require('WAWebUserPrefsGeneral')).setAutoDownloadAudio(flag);
return flag;
}, flag);
}
@ -2229,11 +2227,11 @@ class Client extends EventEmitter {
*/
async setAutoDownloadDocuments(flag) {
await this.pupPage.evaluate(async flag => {
const autoDownload = window.Store.Settings.getAutoDownloadDocuments();
const autoDownload = (window.require('WAWebUserPrefsGeneral')).getAutoDownloadDocuments();
if (autoDownload === flag) {
return flag;
}
await window.Store.Settings.setAutoDownloadDocuments(flag);
await (window.require('WAWebUserPrefsGeneral')).setAutoDownloadDocuments(flag);
return flag;
}, flag);
}
@ -2244,11 +2242,11 @@ class Client extends EventEmitter {
*/
async setAutoDownloadPhotos(flag) {
await this.pupPage.evaluate(async flag => {
const autoDownload = window.Store.Settings.getAutoDownloadPhotos();
const autoDownload = (window.require('WAWebUserPrefsGeneral')).getAutoDownloadPhotos();
if (autoDownload === flag) {
return flag;
}
await window.Store.Settings.setAutoDownloadPhotos(flag);
await (window.require('WAWebUserPrefsGeneral')).setAutoDownloadPhotos(flag);
return flag;
}, flag);
}
@ -2259,11 +2257,11 @@ class Client extends EventEmitter {
*/
async setAutoDownloadVideos(flag) {
await this.pupPage.evaluate(async flag => {
const autoDownload = window.Store.Settings.getAutoDownloadVideos();
const autoDownload = (window.require('WAWebUserPrefsGeneral')).getAutoDownloadVideos();
if (autoDownload === flag) {
return flag;
}
await window.Store.Settings.setAutoDownloadVideos(flag);
await (window.require('WAWebUserPrefsGeneral')).setAutoDownloadVideos(flag);
return flag;
}, flag);
}
@ -2276,11 +2274,11 @@ class Client extends EventEmitter {
*/
async setBackgroundSync(flag) {
return await this.pupPage.evaluate(async flag => {
const backSync = window.Store.Settings.getGlobalOfflineNotifications();
const backSync = (window.require('WAWebUserPrefsNotifications')).getGlobalOfflineNotifications();
if (backSync === flag) {
return flag;
}
await window.Store.Settings.setGlobalOfflineNotifications(flag);
await (window.require('WAWebUserPrefsNotifications')).setGlobalOfflineNotifications(flag);
return flag;
}, flag);
}
@ -2294,7 +2292,7 @@ class Client extends EventEmitter {
*/
async getContactDeviceCount(userId) {
return await this.pupPage.evaluate(async (userId) => {
const devices = await window.Store.DeviceList.getDeviceIds([window.Store.WidFactory.createWid(userId)]);
const devices = await (window.require('WAWebApiDeviceList')).getDeviceIds([window.require('WAWebWidFactory').createWid(userId)]);
if (devices && devices.length && devices[0] != null && typeof devices[0].devices == 'object') {
return devices[0].devices.length;
}
@ -2309,10 +2307,10 @@ class Client extends EventEmitter {
*/
async syncHistory(chatId) {
return await this.pupPage.evaluate(async (chatId) => {
const chatWid = window.Store.WidFactory.createWid(chatId);
const chat = window.Store.Chat.get(chatWid) ?? (await window.Store.Chat.find(chatWid));
const chatWid = window.require('WAWebWidFactory').createWid(chatId);
const chat = (window.require('WAWebCollections')).Chat.get(chatWid) ?? (await (window.require('WAWebCollections')).Chat.find(chatWid));
if (chat?.endOfHistoryTransferType === 0) {
await window.Store.HistorySync.sendPeerDataOperationRequest(3, {
await (window.require('WAWebSendNonMessageDataRequest')).sendPeerDataOperationRequest(3, {
chatId: chat.id
});
return true;
@ -2337,7 +2335,7 @@ class Client extends EventEmitter {
startTime = Math.floor(startTime.getTime() / 1000);
return await this.pupPage.evaluate(async (startTimeTs, callType) => {
const response = await window.Store.ScheduledEventMsgUtils.createEventCallLink(startTimeTs, callType);
const response = await (window.require('WAWebGenerateEventCallLink')).createEventCallLink(startTimeTs, callType);
return response ?? '';
}, startTime, callType);
}
@ -2352,10 +2350,10 @@ class Client extends EventEmitter {
if (![0, 1, 2, 3].includes(response)) return false;
return await this.pupPage.evaluate(async (response, msgId) => {
const eventMsg = window.Store.Msg.get(msgId) || (await window.Store.Msg.getMessagesById([msgId]))?.messages?.[0];
const eventMsg = (window.require('WAWebCollections')).Msg.get(msgId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([msgId]))?.messages?.[0];
if (!eventMsg) return false;
await window.Store.ScheduledEventMsgUtils.sendEventResponseMsg(response, eventMsg);
await (window.require('WAWebSendEventResponseMsgAction')).sendEventResponseMsg(response, eventMsg);
return true;
}, response, eventMessageId);
}
@ -2371,7 +2369,7 @@ class Client extends EventEmitter {
async saveOrEditAddressbookContact(phoneNumber, firstName, lastName, syncToAddressbook = false)
{
return await this.pupPage.evaluate(async (phoneNumber, firstName, lastName, syncToAddressbook) => {
return await window.Store.AddressbookContactUtils.saveContactAction({
return await (window.require('WAWebSaveContactAction')).saveContactAction({
'firstName' : firstName,
'lastName' : lastName,
'phoneNumber' : phoneNumber,
@ -2390,8 +2388,8 @@ class Client extends EventEmitter {
async deleteAddressbookContact(phoneNumber)
{
return await this.pupPage.evaluate(async (phoneNumber) => {
const wid = window.Store.WidFactory.createWid(phoneNumber);
return await window.Store.AddressbookContactUtils.deleteContactAction({phoneNumber: wid});
const wid = window.require('WAWebWidFactory').createWid(phoneNumber);
return await (window.require('WAWebDeleteContactAction')).deleteContactAction({phoneNumber: wid});
}, phoneNumber);
}
@ -2424,11 +2422,11 @@ class Client extends EventEmitter {
*/
async addOrEditCustomerNote(userId, note) {
return await this.pupPage.evaluate(async (userId, note) => {
if (!window.Store.BusinessGatingUtils.smbNotesV1Enabled()) return;
if (!(window.require('WAWebBizGatingUtils')).smbNotesV1Enabled()) return;
return window.Store.CustomerNoteUtils.noteAddAction(
return (window.require('WAWebNoteAction')).noteAddAction(
'unstructured',
window.Store.WidToJid.widToUserJid(window.Store.WidFactory.createWid(userId)),
window.require('WAWebWidToJid').widToUserJid(window.require('WAWebWidFactory').createWid(userId)),
note
);
}, userId, note);
@ -2449,17 +2447,17 @@ class Client extends EventEmitter {
*/
async getCustomerNote(userId) {
return await this.pupPage.evaluate(async (userId) => {
if (!window.Store.BusinessGatingUtils.smbNotesV1Enabled()) return null;
if (!(window.require('WAWebBizGatingUtils')).smbNotesV1Enabled()) return null;
const note = await window.Store.CustomerNoteUtils.retrieveOnlyNoteForChatJid(
window.Store.WidToJid.widToUserJid(window.Store.WidFactory.createWid(userId))
const note = await (window.require('WAWebNoteAction')).retrieveOnlyNoteForChatJid(
window.require('WAWebWidToJid').widToUserJid(window.require('WAWebWidFactory').createWid(userId))
);
let serialized = note?.serialize();
if (!serialized) return null;
serialized.chatId = window.Store.JidToWid.userJidToUserWid(serialized.chatJid)._serialized;
serialized.chatId = window.require('WAWebJidToWid').userJidToUserWid(serialized.chatJid)._serialized;
delete serialized.chatJid;
return serialized;
@ -2477,8 +2475,8 @@ class Client extends EventEmitter {
if (msg.type != MessageTypes.POLL_CREATION) throw 'Invalid usage! Can only be used with a pollCreation message';
const pollVotes = await this.pupPage.evaluate( async (msg) => {
const msgKey = window.Store.MsgKey.fromString(msg.id._serialized);
let pollVotes = await window.Store.PollsVotesSchema.getTable().equals(['parentMsgKey'], msgKey.toString());
const msgKey = (window.require('WAWebMsgKey')).fromString(msg.id._serialized);
let pollVotes = await (window.require('WAWebPollsVotesSchema')).getTable().equals(['parentMsgKey'], msgKey.toString());
return pollVotes.map(item => {
const typedArray = new Uint8Array(item.selectedOptionLocalIds);

View file

@ -103,9 +103,9 @@ class Channel extends Base {
return await this.client.pupPage.evaluate(async (channelId, limit) => {
const channel = await window.WWebJS.getChat(channelId, { getAsModel: false });
if (!channel) return [];
!limit && (limit = window.Store.ChannelUtils.getMaxSubscriberNumber());
const response = await window.Store.ChannelSubscribers.mexFetchNewsletterSubscribers(channelId, limit);
const contacts = window.Store.ChannelSubscribers.getSubscribersInContacts(response.subscribers);
!limit && (limit = window.require('WAWebNewsletterGatingUtils').getMaxSubscriberNumber());
const response = await (window.require('WAWebMexFetchNewsletterSubscribersJob')).mexFetchNewsletterSubscribers(channelId, limit);
const contacts = (window.require('WAWebNewsletterSubscriberListAction')).getSubscribersInContacts(response.subscribers);
return Promise.all(contacts.map((obj) => ({
...obj,
contact: window.WWebJS.getContactModel(obj.contact)
@ -303,7 +303,7 @@ class Channel extends Base {
if (searchOptions && searchOptions.limit > 0) {
while (msgs.length < searchOptions.limit) {
const loadedMessages = await window.Store.ConversationMsgs.loadEarlierMsgs(channel);
const loadedMessages = await (window.require('WAWebChatLoadMessages')).loadEarlierMsgs(channel);
if (!loadedMessages || !loadedMessages.length) break;
msgs = [...loadedMessages.filter(msgFilter), ...msgs];
}
@ -350,7 +350,7 @@ class Channel extends Base {
: null;
}
try {
await window.Store.ChannelUtils.editNewsletterMetadataAction(channel, property, value);
await (window.require('WAWebEditNewsletterMetadataAction')).editNewsletterMetadataAction(channel, property, value);
return true;
} catch (err) {
if (err.name === 'ServerStatusCodeError') return false;
@ -367,9 +367,11 @@ class Channel extends Base {
async _muteUnmuteChannel(action) {
return await this.client.pupPage.evaluate(async (channelId, action) => {
try {
action === 'MUTE'
? await window.Store.ChannelUtils.muteNewsletter([channelId])
: await window.Store.ChannelUtils.unmuteNewsletter([channelId]);
await (window.require('WAWebNewsletterUpdateUserSettingJob')).updateNewsletterUserSetting({
newsletterJid: window.require('WAJids').toNewsletterJid(channelId),
type: window.require('WAWebNewsletterModelUtils').ADMIN_NOTIFICATIONS,
muteExpirationValue: action === 'MUTE' ? window.require('WAWebNewsletterModelUtils').MUTED_STATE : window.require('WAWebNewsletterModelUtils').UNMUTED_STATE
});
return true;
} catch (err) {
if (err.name === 'ServerStatusCodeError') return false;

View file

@ -212,7 +212,7 @@ class Chat extends Base {
if (searchOptions && searchOptions.limit > 0) {
while (msgs.length < searchOptions.limit) {
const loadedMessages = await window.Store.ConversationMsgs.loadEarlierMsgs(chat,chat.msgs);
const loadedMessages = await (window.require('WAWebChatLoadMessages')).loadEarlierMsgs(chat,chat.msgs);
if (!loadedMessages || !loadedMessages.length) break;
msgs = [...loadedMessages.filter(msgFilter), ...msgs];
}

View file

@ -62,7 +62,7 @@ class ClientInfo extends Base {
*/
async getBatteryStatus() {
return await this.client.pupPage.evaluate(() => {
const { battery, plugged } = window.Store.Conn;
const { battery, plugged } = window.require('WAWebConnModel').Conn;
return { battery, plugged };
});
}

View file

@ -155,8 +155,8 @@ class Contact extends Base {
if(this.isGroup) return false;
await this.client.pupPage.evaluate(async (contactId) => {
const contact = window.Store.Contact.get(contactId);
await window.Store.BlockContact.blockContact({contact});
const contact = (window.require('WAWebCollections')).Contact.get(contactId);
await (window.require('WAWebBlockContactAction')).blockContact({contact});
}, this.id._serialized);
this.isBlocked = true;
@ -171,8 +171,8 @@ class Contact extends Base {
if(this.isGroup) return false;
await this.client.pupPage.evaluate(async (contactId) => {
const contact = window.Store.Contact.get(contactId);
await window.Store.BlockContact.unblockContact(contact);
const contact = (window.require('WAWebCollections')).Contact.get(contactId);
await (window.require('WAWebBlockContactAction')).unblockContact(contact);
}, this.id._serialized);
this.isBlocked = false;
@ -185,8 +185,8 @@ class Contact extends Base {
*/
async getAbout() {
const about = await this.client.pupPage.evaluate(async (contactId) => {
const wid = window.Store.WidFactory.createWid(contactId);
return window.Store.StatusUtils.getStatus({'token':'', 'wid': wid});
const wid = window.require('WAWebWidFactory').createWid(contactId);
return (window.require('WAWebContactStatusBridge')).getStatus({'token':'', 'wid': wid});
}, this.id._serialized);
if (typeof about.status !== 'string')

View file

@ -81,9 +81,9 @@ class GroupChat extends Chat {
const participantData = {};
!Array.isArray(participantIds) && (participantIds = [participantIds]);
const groupWid = window.Store.WidFactory.createWid(groupId);
const group = window.Store.Chat.get(groupWid) || (await window.Store.Chat.find(groupWid));
const participantWids = participantIds.map((p) => window.Store.WidFactory.createWid(p));
const groupWid = window.require('WAWebWidFactory').createWid(groupId);
const group = (window.require('WAWebCollections')).Chat.get(groupWid) || (await (window.require('WAWebCollections')).Chat.find(groupWid));
const participantWids = participantIds.map((p) => window.require('WAWebWidFactory').createWid(p));
const errorCodes = {
default: 'An unknown error occupied while adding a participant',
@ -98,7 +98,7 @@ class GroupChat extends Chat {
419: 'The participant can\'t be added because the group is full'
};
await window.Store.GroupQueryAndUpdate({ id: groupId });
await (window.require('WAWebGroupQueryJob')).queryAndUpdateGroupMetadataById({ id: groupId });
let groupParticipants = group.groupMetadata?.participants.serialize();
@ -111,7 +111,7 @@ class GroupChat extends Chat {
}
groupParticipants.map(({ id }) => {
return id.server === 'lid' ? window.Store.LidUtils.getPhoneNumber(id) : id;
return id.server === 'lid' ? window.require('WAWebApiContact').getPhoneNumber(id) : id;
});
const _getSleepTime = (sleep) => {
@ -127,7 +127,7 @@ class GroupChat extends Chat {
for (let pWid of participantWids) {
const pId = pWid._serialized;
pWid = pWid.server === 'lid' ? window.Store.LidUtils.getPhoneNumber(pWid) : pWid;
pWid = pWid.server === 'lid' ? window.require('WAWebApiContact').getPhoneNumber(pWid) : pWid;
participantData[pId] = {
code: undefined,
@ -141,7 +141,7 @@ class GroupChat extends Chat {
continue;
}
if (!(await window.Store.QueryExist(pWid))?.wid) {
if (!(await (window.require('WAWebQueryExistsJob').queryWidExists)(pWid))?.wid) {
participantData[pId].code = 404;
participantData[pId].message = errorCodes[404];
continue;
@ -157,12 +157,12 @@ class GroupChat extends Chat {
if (autoSendInviteV4 && rpcResultCode === 403) {
let userChat, isInviteV4Sent = false;
window.Store.Contact.gadd(pWid, { silent: true });
(window.require('WAWebCollections')).Contact.gadd(pWid, { silent: true });
if (rpcResult.name === 'ParticipantRequestCodeCanBeSent' &&
(userChat = window.Store.Chat.get(pWid) || (await window.Store.Chat.find(pWid)))) {
(userChat = (window.require('WAWebCollections')).Chat.get(pWid) || (await (window.require('WAWebCollections')).Chat.find(pWid)))) {
const groupName = group.formattedTitle || group.name;
const res = await window.Store.GroupInviteV4.sendGroupInviteMessage(
const res = await (window.require('WAWebChatSendMessages')).sendGroupInviteMessage(
userChat,
group.id._serialized,
groupName,
@ -201,7 +201,7 @@ class GroupChat extends Chat {
return chat.groupMetadata.participants.get(lid?._serialized) ||
chat.groupMetadata.participants.get(phone?._serialized);
}))).filter(Boolean);
await window.Store.GroupParticipants.removeParticipants(chat, participants);
await (window.require('WAWebModifyParticipantsGroupAction')).removeParticipants(chat, participants);
return { status: 200 };
}, this.id._serialized, participantIds);
}
@ -220,7 +220,7 @@ class GroupChat extends Chat {
return chat.groupMetadata.participants.get(lid?._serialized) ||
chat.groupMetadata.participants.get(phone?._serialized);
}))).filter(Boolean);
await window.Store.GroupParticipants.promoteParticipants(chat, participants);
await (window.require('WAWebModifyParticipantsGroupAction')).promoteParticipants(chat, participants);
return { status: 200 };
}, this.id._serialized, participantIds);
}
@ -239,7 +239,7 @@ class GroupChat extends Chat {
return chat.groupMetadata.participants.get(lid?._serialized) ||
chat.groupMetadata.participants.get(phone?._serialized);
}))).filter(Boolean);
await window.Store.GroupParticipants.demoteParticipants(chat, participants);
await (window.require('WAWebModifyParticipantsGroupAction')).demoteParticipants(chat, participants);
return { status: 200 };
}, this.id._serialized, participantIds);
}
@ -251,9 +251,9 @@ class GroupChat extends Chat {
*/
async setSubject(subject) {
const success = await this.client.pupPage.evaluate(async (chatId, subject) => {
const chatWid = window.Store.WidFactory.createWid(chatId);
const chatWid = window.require('WAWebWidFactory').createWid(chatId);
try {
await window.Store.GroupUtils.setGroupSubject(chatWid, subject);
await (window.require('WAWebGroupModifyInfoJob')).setGroupSubject(chatWid, subject);
return true;
} catch (err) {
if(err.name === 'ServerStatusCodeError') return false;
@ -273,12 +273,12 @@ class GroupChat extends Chat {
*/
async setDescription(description) {
const success = await this.client.pupPage.evaluate(async (chatId, description) => {
const chatWid = window.Store.WidFactory.createWid(chatId);
const chatWid = window.require('WAWebWidFactory').createWid(chatId);
const chat = await window.WWebJS.getChat(chatId, { getAsModel: false });
let descId = chat.groupMetadata.descId;
let newId = await window.Store.MsgKey.newId();
let newId = await (window.require('WAWebMsgKey')).newId();
try {
await window.Store.GroupUtils.setGroupDescription(chatWid, description, newId, descId);
await (window.require('WAWebGroupModifyInfoJob')).setGroupDescription(chatWid, description, newId, descId);
return true;
} catch (err) {
if(err.name === 'ServerStatusCodeError') return false;
@ -300,7 +300,7 @@ class GroupChat extends Chat {
const success = await this.client.pupPage.evaluate(async (groupId, adminsOnly) => {
const chat = await window.WWebJS.getChat(groupId, { getAsModel: false });
try {
await window.Store.GroupUtils.setGroupProperty(chat, 'member_add_mode', adminsOnly ? 0 : 1);
await (window.require('WAWebSetPropertyGroupAction')).setGroupProperty(chat, 'member_add_mode', adminsOnly ? 0 : 1);
return true;
} catch (err) {
if(err.name === 'ServerStatusCodeError') return false;
@ -321,7 +321,7 @@ class GroupChat extends Chat {
const success = await this.client.pupPage.evaluate(async (chatId, adminsOnly) => {
const chat = await window.WWebJS.getChat(chatId, { getAsModel: false });
try {
await window.Store.GroupUtils.setGroupProperty(chat, 'announcement', adminsOnly ? 1 : 0);
await (window.require('WAWebSetPropertyGroupAction')).setGroupProperty(chat, 'announcement', adminsOnly ? 1 : 0);
return true;
} catch (err) {
if(err.name === 'ServerStatusCodeError') return false;
@ -344,7 +344,7 @@ class GroupChat extends Chat {
const success = await this.client.pupPage.evaluate(async (chatId, adminsOnly) => {
const chat = await window.WWebJS.getChat(chatId, { getAsModel: false });
try {
await window.Store.GroupUtils.setGroupProperty(chat, 'restrict', adminsOnly ? 1 : 0);
await (window.require('WAWebSetPropertyGroupAction')).setGroupProperty(chat, 'restrict', adminsOnly ? 1 : 0);
return true;
} catch (err) {
if(err.name === 'ServerStatusCodeError') return false;
@ -390,7 +390,7 @@ class GroupChat extends Chat {
async getInviteCode() {
const codeRes = await this.client.pupPage.evaluate(async chatId => {
try {
return await window.Store.GroupInvite.fetchMexGroupInviteCode(chatId);
return await (window.require('WAWebMexFetchGroupInviteCodeJob')).fetchMexGroupInviteCode(chatId);
}
catch (err) {
if(err.name === 'ServerStatusCodeError') return undefined;
@ -409,8 +409,8 @@ class GroupChat extends Chat {
*/
async revokeInvite() {
const codeRes = await this.client.pupPage.evaluate(chatId => {
const chatWid = window.Store.WidFactory.createWid(chatId);
return window.Store.GroupInvite.resetGroupInviteCode(chatWid);
const chatWid = window.require('WAWebWidFactory').createWid(chatId);
return (window.require('WAWebGroupQueryJob')).resetGroupInviteCode(chatWid);
}, this.id._serialized);
return codeRes.code;
@ -474,7 +474,7 @@ class GroupChat extends Chat {
async leave() {
await this.client.pupPage.evaluate(async chatId => {
const chat = await window.WWebJS.getChat(chatId, { getAsModel: false });
return window.Store.GroupUtils.sendExitGroup(chat);
return (window.require('WAWebExitGroupAction')).sendExitGroup(chat);
}, this.id._serialized);
}

View file

@ -311,7 +311,7 @@ class Message extends Base {
*/
async reload() {
const newData = await this.client.pupPage.evaluate(async (msgId) => {
const msg = window.Store.Msg.get(msgId) || (await window.Store.Msg.getMessagesById([msgId]))?.messages?.[0];
const msg = (window.require('WAWebCollections')).Msg.get(msgId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([msgId]))?.messages?.[0];
if (!msg) return null;
return window.WWebJS.getMessageModel(msg);
}, this.id._serialized);
@ -370,8 +370,8 @@ class Message extends Base {
if (!this.hasQuotedMsg) return undefined;
const quotedMsg = await this.client.pupPage.evaluate(async (msgId) => {
const msg = window.Store.Msg.get(msgId) || (await window.Store.Msg.getMessagesById([msgId]))?.messages?.[0];
const quotedMsg = window.Store.QuotedMsg.getQuotedMsgObj(msg);
const msg = (window.require('WAWebCollections')).Msg.get(msgId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([msgId]))?.messages?.[0];
const quotedMsg = window.require('WAWebQuotedMsgModelUtils').getQuotedMsgObj(msg);
return window.WWebJS.getMessageModel(quotedMsg);
}, this.id._serialized);
@ -410,9 +410,9 @@ class Message extends Base {
await this.client.pupPage.evaluate(async (messageId, reaction) => {
if (!messageId) return null;
const msg =
window.Store.Msg.get(messageId) || (await window.Store.Msg.getMessagesById([messageId]))?.messages?.[0];
(window.require('WAWebCollections')).Msg.get(messageId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([messageId]))?.messages?.[0];
if(!msg) return null;
await window.Store.sendReactionToMsg(msg, reaction);
await (window.require('WAWebSendReactionMsgAction'))(msg, reaction);
}, this.id._serialized, reaction);
}
@ -448,7 +448,7 @@ class Message extends Base {
}
const result = await this.client.pupPage.evaluate(async (msgId) => {
const msg = window.Store.Msg.get(msgId) || (await window.Store.Msg.getMessagesById([msgId]))?.messages?.[0];
const msg = (window.require('WAWebCollections')).Msg.get(msgId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([msgId]))?.messages?.[0];
// REUPLOADING mediaStage means the media is expired and the download button is spinning, cannot be downloaded now
if (!msg || !msg.mediaData || msg.mediaData.mediaStage === 'REUPLOADING') {
@ -472,7 +472,7 @@ class Message extends Base {
addAnnotations: function() { return this; },
addPoint: function() { return this; }
};
const decryptedMedia = await window.Store.DownloadManager.downloadAndMaybeDecrypt({
const decryptedMedia = await (window.require('WAWebDownloadManager').downloadManager).downloadAndMaybeDecrypt({
directPath: msg.directPath,
encFilehash: msg.encFilehash,
filehash: msg.filehash,
@ -508,17 +508,23 @@ class Message extends Base {
*/
async delete(everyone, clearMedia = true) {
await this.client.pupPage.evaluate(async (msgId, everyone, clearMedia) => {
const msg = window.Store.Msg.get(msgId) || (await window.Store.Msg.getMessagesById([msgId]))?.messages?.[0];
const chat = window.Store.Chat.get(msg.id.remote) || (await window.Store.Chat.find(msg.id.remote));
const msg = (window.require('WAWebCollections')).Msg.get(msgId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([msgId]))?.messages?.[0];
const chat = (window.require('WAWebCollections')).Chat.get(msg.id.remote) || (await (window.require('WAWebCollections')).Chat.find(msg.id.remote));
const canRevoke =
window.Store.MsgActionChecks.canSenderRevokeMsg(msg) || window.Store.MsgActionChecks.canAdminRevokeMsg(msg);
window.require('WAWebMsgActionCapability').canSenderRevokeMsg(msg) || window.require('WAWebMsgActionCapability').canAdminRevokeMsg(msg);
const { Cmd } = window.require('WAWebCmd');
if (everyone && canRevoke) {
return window.Store.Cmd.sendRevokeMsgs(chat, { list: [msg], type: 'message' }, { clearMedia: clearMedia });
return window.WWebJS.compareWwebVersions(window.Debug.VERSION, '>=', '2.3000.0')
? Cmd.sendRevokeMsgs(chat, { list: [msg], type: 'message' }, { clearMedia: clearMedia })
: Cmd.sendRevokeMsgs(chat, [msg], { clearMedia: true, type: msg.id.fromMe ? 'Sender' : 'Admin' });
}
return window.Store.Cmd.sendDeleteMsgs(chat, { list: [msg], type: 'message' }, clearMedia);
return window.WWebJS.compareWwebVersions(window.Debug.VERSION, '>=', '2.3000.0')
? Cmd.sendDeleteMsgs(chat, { list: [msg], type: 'message' }, clearMedia)
: Cmd.sendDeleteMsgs(chat, [msg], clearMedia);
}, this.id._serialized, everyone, clearMedia);
}
@ -527,10 +533,10 @@ class Message extends Base {
*/
async star() {
await this.client.pupPage.evaluate(async (msgId) => {
const msg = window.Store.Msg.get(msgId) || (await window.Store.Msg.getMessagesById([msgId]))?.messages?.[0];
if (window.Store.MsgActionChecks.canStarMsg(msg)) {
let chat = await window.Store.Chat.find(msg.id.remote);
return window.Store.Cmd.sendStarMsgs(chat, [msg], false);
const msg = (window.require('WAWebCollections')).Msg.get(msgId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([msgId]))?.messages?.[0];
if (window.require('WAWebMsgActionCapability').canStarMsg(msg)) {
let chat = await (window.require('WAWebCollections')).Chat.find(msg.id.remote);
return (window.require('WAWebCmd').Cmd).sendStarMsgs(chat, [msg], false);
}
}, this.id._serialized);
}
@ -540,10 +546,10 @@ class Message extends Base {
*/
async unstar() {
await this.client.pupPage.evaluate(async (msgId) => {
const msg = window.Store.Msg.get(msgId) || (await window.Store.Msg.getMessagesById([msgId]))?.messages?.[0];
if (window.Store.MsgActionChecks.canStarMsg(msg)) {
let chat = await window.Store.Chat.find(msg.id.remote);
return window.Store.Cmd.sendUnstarMsgs(chat, [msg], false);
const msg = (window.require('WAWebCollections')).Msg.get(msgId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([msgId]))?.messages?.[0];
if (window.require('WAWebMsgActionCapability').canStarMsg(msg)) {
let chat = await (window.require('WAWebCollections')).Chat.find(msg.id.remote);
return (window.require('WAWebCmd').Cmd).sendUnstarMsgs(chat, [msg], false);
}
}, this.id._serialized);
}
@ -587,12 +593,12 @@ class Message extends Base {
*/
async getInfo() {
const info = await this.client.pupPage.evaluate(async (msgId) => {
const msg = window.Store.Msg.get(msgId) || (await window.Store.Msg.getMessagesById([msgId]))?.messages?.[0];
const msg = (window.require('WAWebCollections')).Msg.get(msgId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([msgId]))?.messages?.[0];
if (!msg || !msg.id.fromMe) return null;
return new Promise((resolve) => {
setTimeout(async () => {
resolve(await window.Store.getMsgInfo(msg.id));
resolve(await (window.require('WAWebApiMessageInfoStore').queryMsgInfo)(msg.id));
}, (Date.now() - msg.t * 1000 < 1250) && Math.floor(Math.random() * (1200 - 1100 + 1)) + 1100 || 0);
});
}, this.id._serialized);
@ -621,7 +627,7 @@ class Message extends Base {
async getPayment() {
if (this.type === MessageTypes.PAYMENT) {
const msg = await this.client.pupPage.evaluate(async (msgId) => {
const msg = window.Store.Msg.get(msgId) || (await window.Store.Msg.getMessagesById([msgId]))?.messages?.[0];
const msg = (window.require('WAWebCollections')).Msg.get(msgId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([msgId]))?.messages?.[0];
if(!msg) return null;
return msg.serialize();
}, this.id._serialized);
@ -650,7 +656,7 @@ class Message extends Base {
}
const reactions = await this.client.pupPage.evaluate(async (msgId) => {
const msgReactions = await window.Store.Reactions.find(msgId);
const msgReactions = await (window.require('WAWebCollections')).Reactions.find(msgId);
if (!msgReactions || !msgReactions.reactions.length) return null;
return msgReactions.reactions.serialize();
}, this.id._serialized);
@ -696,10 +702,10 @@ class Message extends Base {
return null;
}
const messageEdit = await this.client.pupPage.evaluate(async (msgId, message, options) => {
const msg = window.Store.Msg.get(msgId) || (await window.Store.Msg.getMessagesById([msgId]))?.messages?.[0];
const msg = (window.require('WAWebCollections')).Msg.get(msgId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([msgId]))?.messages?.[0];
if (!msg) return null;
let canEdit = window.Store.MsgActionChecks.canEditText(msg) || window.Store.MsgActionChecks.canEditCaption(msg);
let canEdit = window.require('WAWebMsgActionCapability').canEditText(msg) || window.require('WAWebMsgActionCapability').canEditCaption(msg);
if (canEdit) {
const msgEdit = await window.WWebJS.editMessage(msg, message, options);
return msgEdit.serialize();
@ -724,7 +730,7 @@ class Message extends Base {
}
const edittedEventMsg = await this.client.pupPage.evaluate(async (msgId, editedEventObject) => {
const msg = window.Store.Msg.get(msgId) || (await window.Store.Msg.getMessagesById([msgId]))?.messages?.[0];
const msg = (window.require('WAWebCollections')).Msg.get(msgId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([msgId]))?.messages?.[0];
if (!msg) return null;
const { name, startTimeTs, eventSendOptions } = editedEventObject;
@ -738,8 +744,8 @@ class Message extends Base {
isEventCanceled: eventSendOptions.isEventCanceled,
};
await window.Store.ScheduledEventMsgUtils.sendEventEditMessage(eventOptions, msg);
const editedMsg = window.Store.Msg.get(msg.id._serialized);
await (window.require('WAWebSendEventEditMsgAction')).sendEventEditMessage(eventOptions, msg);
const editedMsg = (window.require('WAWebCollections')).Msg.get(msg.id._serialized);
return editedMsg?.serialize();
}, this.id._serialized, editedEventObject);
@ -766,7 +772,7 @@ class Message extends Base {
if (!Array.isArray(votes)) votes = [votes];
let localIdSet = new Set();
const msg =
window.Store.Msg.get(messageId) || (await window.Store.Msg.getMessagesById([messageId]))?.messages?.[0];
(window.require('WAWebCollections')).Msg.get(messageId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([messageId]))?.messages?.[0];
if (!msg) return null;
msg.pollOptions.forEach(a => {
@ -775,7 +781,7 @@ class Message extends Base {
}
});
await window.Store.PollsSendVote.sendVote(msg, localIdSet);
await (window.require('WAWebPollsSendVoteMsgAction')).sendVote(msg, localIdSet);
}, this.id._serialized, selectedOptions);
}
}

View file

@ -7,7 +7,7 @@ exports.DefaultOptions = {
headless: true,
defaultViewport: null
},
webVersion: '2.3000.1030947950',
webVersion: '2.3000.1017054665',
webVersionCache: {
type: 'local',
},

View file

@ -1,266 +0,0 @@
'use strict';
exports.ExposeStore = () => {
/**
* Helper function that compares between two WWeb versions. Its purpose is to help the developer to choose the correct code implementation depending on the comparison value and the WWeb version.
* @param {string} lOperand The left operand for the WWeb version string to compare with
* @param {string} operator The comparison operator
* @param {string} rOperand The right operand for the WWeb version string to compare with
* @returns {boolean} Boolean value that indicates the result of the comparison
*/
window.compareWwebVersions = (lOperand, operator, rOperand) => {
if (!['>', '>=', '<', '<=', '='].includes(operator)) {
throw new class _ extends Error {
constructor(m) { super(m); this.name = 'CompareWwebVersionsError'; }
}('Invalid comparison operator is provided');
}
if (typeof lOperand !== 'string' || typeof rOperand !== 'string') {
throw new class _ extends Error {
constructor(m) { super(m); this.name = 'CompareWwebVersionsError'; }
}('A non-string WWeb version type is provided');
}
lOperand = lOperand.replace(/-beta$/, '');
rOperand = rOperand.replace(/-beta$/, '');
while (lOperand.length !== rOperand.length) {
lOperand.length > rOperand.length
? rOperand = rOperand.concat('0')
: lOperand = lOperand.concat('0');
}
lOperand = Number(lOperand.replace(/\./g, ''));
rOperand = Number(rOperand.replace(/\./g, ''));
return (
operator === '>' ? lOperand > rOperand :
operator === '>=' ? lOperand >= rOperand :
operator === '<' ? lOperand < rOperand :
operator === '<=' ? lOperand <= rOperand :
operator === '=' ? lOperand === rOperand :
false
);
};
window.Store = Object.assign({}, window.require('WAWebCollections'));
window.Store.AppState = window.require('WAWebSocketModel').Socket;
window.Store.BlockContact = window.require('WAWebBlockContactAction');
window.Store.Conn = window.require('WAWebConnModel').Conn;
window.Store.Cmd = window.require('WAWebCmd').Cmd;
window.Store.DownloadManager = window.require('WAWebDownloadManager').downloadManager;
window.Store.GroupQueryAndUpdate = window.require('WAWebGroupQueryJob').queryAndUpdateGroupMetadataById;
window.Store.MediaPrep = window.require('WAWebPrepRawMedia');
window.Store.MediaObject = window.require('WAWebMediaStorage');
window.Store.MediaTypes = window.require('WAWebMmsMediaTypes');
window.Store.MediaUpload = {
...window.require('WAWebMediaMmsV4Upload'),
...window.require('WAWebStartMediaUploadQpl')
};
window.Store.MediaUpdate = window.require('WAWebMediaUpdateMsg');
window.Store.MsgKey = window.require('WAWebMsgKey');
window.Store.OpaqueData = window.require('WAWebMediaOpaqueData');
window.Store.QueryProduct = window.require('WAWebBizProductCatalogBridge');
window.Store.QueryOrder = window.require('WAWebBizOrderBridge');
window.Store.SendClear = window.require('WAWebChatClearBridge');
window.Store.SendDelete = window.require('WAWebDeleteChatAction');
window.Store.SendMessage = window.require('WAWebSendMsgChatAction');
window.Store.EditMessage = window.require('WAWebSendMessageEditAction');
window.Store.MediaDataUtils = window.require('WAWebMediaDataUtils');
window.Store.BlobCache = window.require('WAWebMediaInMemoryBlobCache');
window.Store.SendSeen = window.require('WAWebUpdateUnreadChatAction');
window.Store.User = window.require('WAWebUserPrefsMeUser');
window.Store.ContactMethods = {
...window.require('WAWebContactGetters'),
...window.require('WAWebFrontendContactGetters')
};
window.Store.UserConstructor = window.require('WAWebWid');
window.Store.Validators = window.require('WALinkify');
window.Store.WidFactory = window.require('WAWebWidFactory');
window.Store.ProfilePic = window.require('WAWebContactProfilePicThumbBridge');
window.Store.PresenceUtils = window.require('WAWebPresenceChatAction');
window.Store.ChatState = window.require('WAWebChatStateBridge');
window.Store.findCommonGroups = window.require('WAWebFindCommonGroupsContactAction').findCommonGroups;
window.Store.ConversationMsgs = window.require('WAWebChatLoadMessages');
window.Store.sendReactionToMsg = window.require('WAWebSendReactionMsgAction').sendReactionToMsg;
window.Store.createOrUpdateReactionsModule = window.require('WAWebDBCreateOrUpdateReactions');
window.Store.EphemeralFields = window.require('WAWebGetEphemeralFieldsMsgActionsUtils');
window.Store.MsgActionChecks = window.require('WAWebMsgActionCapability');
window.Store.QuotedMsg = window.require('WAWebQuotedMsgModelUtils');
window.Store.LinkPreview = window.require('WAWebLinkPreviewChatAction');
window.Store.Socket = window.require('WADeprecatedSendIq');
window.Store.SocketWap = window.require('WAWap');
window.Store.SearchContext = window.require('WAWebChatMessageSearch');
window.Store.DrawerManager = window.require('WAWebDrawerManager').DrawerManager;
window.Store.LidUtils = window.require('WAWebApiContact');
window.Store.WidToJid = window.require('WAWebWidToJid');
window.Store.JidToWid = window.require('WAWebJidToWid');
window.Store.getMsgInfo = window.require('WAWebApiMessageInfoStore').queryMsgInfo;
window.Store.QueryExist = window.require('WAWebQueryExistsJob').queryWidExists;
window.Store.ReplyUtils = window.require('WAWebMsgReply');
window.Store.BotSecret = window.require('WAWebBotMessageSecret');
window.Store.BotProfiles = window.require('WAWebBotProfileCollection');
window.Store.ContactCollection = window.require('WAWebContactCollection').ContactCollection;
window.Store.DeviceList = window.require('WAWebApiDeviceList');
window.Store.HistorySync = window.require('WAWebSendNonMessageDataRequest');
window.Store.AddonReactionTable = window.require('WAWebAddonReactionTableMode').reactionTableMode;
window.Store.AddonPollVoteTable = window.require('WAWebAddonPollVoteTableMode').pollVoteTableMode;
window.Store.ChatGetters = window.require('WAWebChatGetters');
window.Store.UploadUtils = window.require('WAWebUploadManager');
window.Store.WAWebStreamModel = window.require('WAWebStreamModel');
window.Store.FindOrCreateChat = window.require('WAWebFindChatAction');
window.Store.CustomerNoteUtils = window.require('WAWebNoteAction');
window.Store.BusinessGatingUtils = window.require('WAWebBizGatingUtils');
window.Store.PollsVotesSchema = window.require('WAWebPollsVotesSchema');
window.Store.PollsSendVote = window.require('WAWebPollsSendVoteMsgAction');
window.Store.Settings = {
...window.require('WAWebUserPrefsGeneral'),
...window.require('WAWebUserPrefsNotifications'),
setPushname: window.require('WAWebSetPushnameConnAction').setPushname
};
window.Store.NumberInfo = {
...window.require('WAPhoneUtils'),
...window.require('WAPhoneFindCC'),
...window.require('WAWebPhoneUtils')
};
window.Store.ForwardUtils = {
...window.require('WAWebChatForwardMessage')
};
window.Store.PinnedMsgUtils = {
...window.require('WAWebPinInChatSchema'),
...window.require('WAWebSendPinMessageAction')
};
window.Store.ScheduledEventMsgUtils = {
...window.require('WAWebGenerateEventCallLink'),
...window.require('WAWebSendEventEditMsgAction'),
...window.require('WAWebSendEventResponseMsgAction')
};
window.Store.VCard = {
...window.require('WAWebFrontendVcardUtils'),
...window.require('WAWebVcardParsingUtils'),
...window.require('WAWebVcardGetNameFromParsed')
};
window.Store.StickerTools = {
...window.require('WAWebImageUtils'),
...window.require('WAWebAddWebpMetadata')
};
window.Store.GroupUtils = {
...window.require('WAWebGroupCreateJob'),
...window.require('WAWebGroupModifyInfoJob'),
...window.require('WAWebExitGroupAction'),
...window.require('WAWebContactProfilePicThumbBridge'),
...window.require('WAWebSetPropertyGroupAction')
};
window.Store.GroupParticipants = {
...window.require('WAWebModifyParticipantsGroupAction'),
...window.require('WASmaxGroupsAddParticipantsRPC')
};
window.Store.GroupInvite = {
...window.require('WAWebGroupInviteJob'),
...window.require('WAWebGroupQueryJob'),
...window.require('WAWebMexFetchGroupInviteCodeJob')
};
window.Store.GroupInviteV4 = {
...window.require('WAWebGroupInviteV4Job'),
...window.require('WAWebChatSendMessages')
};
window.Store.MembershipRequestUtils = {
...window.require('WAWebApiMembershipApprovalRequestStore'),
...window.require('WASmaxGroupsMembershipRequestsActionRPC')
};
window.Store.ChannelUtils = {
...window.require('WAWebLoadNewsletterPreviewChatAction'),
...window.require('WAWebNewsletterMetadataQueryJob'),
...window.require('WAWebNewsletterCreateQueryJob'),
...window.require('WAWebEditNewsletterMetadataAction'),
...window.require('WAWebNewsletterDeleteAction'),
...window.require('WAWebNewsletterSubscribeAction'),
...window.require('WAWebNewsletterUnsubscribeAction'),
...window.require('WAWebNewsletterDirectorySearchAction'),
...window.require('WAWebNewsletterGatingUtils'),
...window.require('WAWebNewsletterModelUtils'),
...window.require('WAWebMexAcceptNewsletterAdminInviteJob'),
...window.require('WAWebMexRevokeNewsletterAdminInviteJob'),
...window.require('WAWebChangeNewsletterOwnerAction'),
...window.require('WAWebDemoteNewsletterAdminAction'),
...window.require('WAWebNewsletterDemoteAdminJob'),
countryCodesIso: window.require('WAWebCountriesNativeCountryNames'),
currentRegion: window.require('WAWebL10N').getRegion(),
};
window.Store.SendChannelMessage = {
...window.require('WAWebNewsletterUpdateMsgsRecordsJob'),
...window.require('WAWebMsgDataFromModel'),
...window.require('WAWebNewsletterSendMessageJob'),
...window.require('WAWebNewsletterSendMsgAction'),
...window.require('WAMediaCalculateFilehash')
};
window.Store.ChannelSubscribers = {
...window.require('WAWebMexFetchNewsletterSubscribersJob'),
...window.require('WAWebNewsletterSubscriberListAction')
};
window.Store.AddressbookContactUtils = {
...window.require('WAWebSaveContactAction'),
...window.require('WAWebDeleteContactAction')
};
window.Store.StatusUtils = {
...window.require('WAWebContactStatusBridge'),
...window.require('WAWebSendStatusMsgAction'),
...window.require('WAWebRevokeStatusAction'),
...window.require('WAWebStatusGatingUtils')
};
if (!window.Store.Chat._find || !window.Store.Chat.findImpl) {
window.Store.Chat._find = e => {
const target = window.Store.Chat.get(e);
return target ? Promise.resolve(target) : Promise.resolve({
id: e
});
};
window.Store.Chat.findImpl = window.Store.Chat._find;
}
/**
* Target options object description
* @typedef {Object} TargetOptions
* @property {string|number} module The target module
* @property {string} function The function name to get from a module
*/
/**
* Function to modify functions
* @param {TargetOptions} target Options specifying the target function to search for modifying
* @param {Function} callback Modified function
*/
window.injectToFunction = (target, callback) => {
try {
let module = window.require(target.module);
if (!module) return;
const path = target.function.split('.');
const funcName = path.pop();
for (const key of path) {
if (!module[key]) return;
module = module[key];
}
const originalFunction = module[funcName];
if (typeof originalFunction !== 'function') return;
module[funcName] = (...args) => {
try {
return callback(originalFunction, ...args);
} catch {
return originalFunction(...args);
}
};
} catch {
return;
}
};
window.injectToFunction({ module: 'WAWebBackendJobsCommon', function: 'mediaTypeFromProtobuf' }, (func, ...args) => { const [proto] = args; return proto.locationMessage ? null : func(...args); });
window.injectToFunction({ module: 'WAWebE2EProtoUtils', function: 'typeAttributeFromProtobuf' }, (func, ...args) => { const [proto] = args; return proto.locationMessage || proto.groupInviteMessage ? 'text' : func(...args); });
};

View file

@ -3,29 +3,119 @@
exports.LoadUtils = () => {
window.WWebJS = {};
/**
* Helper function that compares between two WWeb versions. Its purpose is to help the developer to choose the correct code implementation depending on the comparison value and the WWeb version.
* @param {string} lOperand The left operand for the WWeb version string to compare with
* @param {string} operator The comparison operator
* @param {string} rOperand The right operand for the WWeb version string to compare with
* @returns {boolean} Boolean value that indicates the result of the comparison
*/
window.WWebJS.compareWwebVersions = (lOperand, operator, rOperand) => {
if (!['>', '>=', '<', '<=', '='].includes(operator)) {
throw new class _ extends Error {
constructor(m) { super(m); this.name = 'CompareWwebVersionsError'; }
}('Invalid comparison operator is provided');
}
if (typeof lOperand !== 'string' || typeof rOperand !== 'string') {
throw new class _ extends Error {
constructor(m) { super(m); this.name = 'CompareWwebVersionsError'; }
}('A non-string WWeb version type is provided');
}
lOperand = lOperand.replace(/-beta$/, '');
rOperand = rOperand.replace(/-beta$/, '');
while (lOperand.length !== rOperand.length) {
lOperand.length > rOperand.length
? rOperand = rOperand.concat('0')
: lOperand = lOperand.concat('0');
}
lOperand = Number(lOperand.replace(/\./g, ''));
rOperand = Number(rOperand.replace(/\./g, ''));
return (
operator === '>' ? lOperand > rOperand :
operator === '>=' ? lOperand >= rOperand :
operator === '<' ? lOperand < rOperand :
operator === '<=' ? lOperand <= rOperand :
operator === '=' ? lOperand === rOperand :
false
);
};
/**
* Target options object description
* @typedef {Object} TargetOptions
* @property {string|number} module The target module
* @property {string} function The function name to get from a module
*/
/**
* Function to modify functions
* @param {TargetOptions} target Options specifying the target function to search for modifying
* @param {Function} callback Modified function
*/
window.WWebJS.injectToFunction = (target, callback) => {
try {
let module = window.require(target.module);
if (!module) return;
const path = target.function.split('.');
const funcName = path.pop();
for (const key of path) {
if (!module[key]) return;
module = module[key];
}
const originalFunction = module[funcName];
if (typeof originalFunction !== 'function') return;
module[funcName] = ((...args) => {
try {
return callback(module, originalFunction, ...args);
} catch {
return originalFunction.apply(module, args);
}
}).bind(module);
} catch {
return;
}
};
window.WWebJS.injectToFunction({ module: 'WAWebBackendJobsCommon', function: 'mediaTypeFromProtobuf' }, (module, func, ...args) => { const [proto] = args; return proto.locationMessage ? null : func(...args); });
window.WWebJS.injectToFunction({ module: 'WAWebE2EProtoUtils', function: 'typeAttributeFromProtobuf' }, (module, func, ...args) => { const [proto] = args; return proto.locationMessage || proto.groupInviteMessage ? 'text' : func(...args); });
window.WWebJS.forwardMessage = async (chatId, msgId) => {
const msg = window.Store.Msg.get(msgId) || (await window.Store.Msg.getMessagesById([msgId]))?.messages?.[0];
const msg = (window.require('WAWebCollections')).Msg.get(msgId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([msgId]))?.messages?.[0];
const chat = await window.WWebJS.getChat(chatId, { getAsModel: false });
return await window.Store.ForwardUtils.forwardMessages({'chat': chat, 'msgs' : [msg], 'multicast': true, 'includeCaption': true, 'appendedText' : undefined});
return await (window.require('WAWebChatForwardMessage')).forwardMessages({'chat': chat, 'msgs' : [msg], 'multicast': true, 'includeCaption': true, 'appendedText' : undefined});
};
window.WWebJS.sendSeen = async (chatId) => {
const chat = await window.WWebJS.getChat(chatId, { getAsModel: false });
if (chat) {
window.Store.WAWebStreamModel.Stream.markAvailable();
await window.Store.SendSeen.sendSeen({
window.require('WAWebStreamModel').Stream.markAvailable();
await (window.require('WAWebUpdateUnreadChatAction')).sendSeen({
chat: chat,
threadId: undefined
});
window.Store.WAWebStreamModel.Stream.markUnavailable();
window.require('WAWebStreamModel').Stream.markUnavailable();
return true;
}
return false;
};
window.WWebJS.sendMessage = async (chat, content, options = {}) => {
const isChannel = window.Store.ChatGetters.getIsNewsletter(chat);
const isStatus = window.Store.ChatGetters.getIsBroadcast(chat);
const { getIsNewsletter, getIsBroadcast } = window.require('WAWebChatGetters');
const isChannel = getIsNewsletter(chat);
const isStatus = getIsBroadcast(chat);
const { findLink } = window.require('WALinkify');
let mediaOptions = {};
if (options.media) {
@ -49,12 +139,13 @@ exports.LoadUtils = () => {
let quotedMsgOptions = {};
if (options.quotedMessageId) {
let quotedMessage = window.Store.Msg.get(options.quotedMessageId);
!quotedMessage && (quotedMessage = (await window.Store.Msg.getMessagesById([options.quotedMessageId]))?.messages?.[0]);
let quotedMessage = (window.require('WAWebCollections')).Msg.get(options.quotedMessageId);
!quotedMessage && (quotedMessage = (await (window.require('WAWebCollections')).Msg.getMessagesById([options.quotedMessageId]))?.messages?.[0]);
if (quotedMessage) {
const canReply = window.Store.ReplyUtils
? window.Store.ReplyUtils.canReplyMsg(quotedMessage.unsafe())
const ReplyUtils = window.require('WAWebMsgReply');
const canReply = ReplyUtils
? ReplyUtils.canReplyMsg(quotedMessage.unsafe())
: quotedMessage.canReply();
if (canReply) {
@ -71,21 +162,21 @@ exports.LoadUtils = () => {
}
if (options.mentionedJidList) {
options.mentionedJidList = options.mentionedJidList.map((id) => window.Store.WidFactory.createWid(id));
options.mentionedJidList = options.mentionedJidList.map((id) => window.require('WAWebWidFactory').createWid(id));
options.mentionedJidList = options.mentionedJidList.filter(Boolean);
}
if (options.groupMentions) {
options.groupMentions = options.groupMentions.map((e) => ({
groupSubject: e.subject,
groupJid: window.Store.WidFactory.createWid(e.id)
groupJid: window.require('WAWebWidFactory').createWid(e.id)
}));
}
let locationOptions = {};
if (options.location) {
let { latitude, longitude, description, url } = options.location;
url = window.Store.Validators.findLink(url)?.href;
url = findLink(url)?.href;
url && !description && (description = url);
locationOptions = {
type: 'location',
@ -130,7 +221,7 @@ exports.LoadUtils = () => {
degreesLongitude: 0,
name: eventSendOptions.location
},
eventJoinLink: eventSendOptions.callType === 'none' ? null : await window.Store.ScheduledEventMsgUtils.createEventCallLink(
eventJoinLink: eventSendOptions.callType === 'none' ? null : await (window.require('WAWebGenerateEventCallLink')).createEventCallLink(
startTimeTs,
eventSendOptions.callType
),
@ -145,16 +236,16 @@ exports.LoadUtils = () => {
let vcardOptions = {};
if (options.contactCard) {
let contact = window.Store.Contact.get(options.contactCard);
let contact = (window.require('WAWebCollections')).Contact.get(options.contactCard);
vcardOptions = {
body: window.Store.VCard.vcardFromContactModel(contact).vcard,
body: window.require('WAWebFrontendVcardUtils').vcardFromContactModel(contact).vcard,
type: 'vcard',
vcardFormattedName: contact.formattedName
};
delete options.contactCard;
} else if (options.contactCardList) {
let contacts = options.contactCardList.map(c => window.Store.Contact.get(c));
let vcards = contacts.map(c => window.Store.VCard.vcardFromContactModel(c));
let contacts = options.contactCardList.map(c => (window.require('WAWebCollections')).Contact.get(c));
let vcards = contacts.map(c => window.require('WAWebFrontendVcardUtils').vcardFromContactModel(c));
vcardOptions = {
type: 'multi_vcard',
vcardList: vcards,
@ -165,11 +256,11 @@ exports.LoadUtils = () => {
delete options.parseVCards;
delete options.linkPreview;
try {
const parsed = window.Store.VCard.parseVcard(content);
const parsed = window.require('WAWebVcardParsingUtils').parseVcard(content);
if (parsed) {
vcardOptions = {
type: 'vcard',
vcardFormattedName: window.Store.VCard.vcardGetNameFromParsed(parsed)
vcardFormattedName: window.require('WAWebVcardGetNameFromParsed').vcardGetNameFromParsed(parsed)
};
}
} catch (_) {
@ -179,9 +270,9 @@ exports.LoadUtils = () => {
if (options.linkPreview) {
delete options.linkPreview;
const link = window.Store.Validators.findLink(content);
const link = findLink(content);
if (link) {
let preview = await window.Store.LinkPreview.getLinkPreview(link);
let preview = await (window.require('WAWebLinkPreviewChatAction')).getLinkPreview(link);
if (preview && preview.data) {
preview = preview.data;
preview.preview = true;
@ -215,7 +306,7 @@ exports.LoadUtils = () => {
let listOptions = {};
if (options.list) {
if (window.Store.Conn.platform === 'smba' || window.Store.Conn.platform === 'smbi') {
if ((window.require('WAWebConnModel').Conn).platform === 'smba' || (window.require('WAWebConnModel').Conn).platform === 'smbi') {
throw '[LT01] Whatsapp business can\'t send this yet';
}
listOptions = {
@ -234,28 +325,28 @@ exports.LoadUtils = () => {
const botOptions = {};
if (options.invokedBotWid) {
botOptions.messageSecret = window.crypto.getRandomValues(new Uint8Array(32));
botOptions.botMessageSecret = await window.Store.BotSecret.genBotMsgSecretFromMsgSecret(botOptions.messageSecret);
botOptions.invokedBotWid = window.Store.WidFactory.createWid(options.invokedBotWid);
botOptions.botPersonaId = window.Store.BotProfiles.BotProfileCollection.get(options.invokedBotWid).personaId;
botOptions.botMessageSecret = await (window.require('WAWebBotMessageSecret')).genBotMsgSecretFromMsgSecret(botOptions.messageSecret);
botOptions.invokedBotWid = window.require('WAWebWidFactory').createWid(options.invokedBotWid);
botOptions.botPersonaId = window.require('WAWebBotProfileCollection').BotProfileCollection.get(options.invokedBotWid).personaId;
delete options.invokedBotWid;
}
const lidUser = window.Store.User.getMaybeMeLidUser();
const meUser = window.Store.User.getMaybeMePnUser();
const newId = await window.Store.MsgKey.newId();
const { getMaybeMeLidUser, getMaybeMePnUser } = window.require('WAWebUserPrefsMeUser');
const lidUser = getMaybeMeLidUser();
const meUser = getMaybeMePnUser();
const newId = await (window.require('WAWebMsgKey')).newId();
let from = chat.id.isLid() ? lidUser : meUser;
let participant;
if (typeof chat.id?.isGroup === 'function' && chat.id.isGroup()) {
from = chat.groupMetadata && chat.groupMetadata.isLidAddressingMode ? lidUser : meUser;
participant = window.Store.WidFactory.asUserWidOrThrow(from);
participant = window.require('WAWebWidFactory').asUserWidOrThrow(from);
}
if (typeof chat.id?.isStatus === 'function' && chat.id.isStatus()) {
participant = window.Store.WidFactory.asUserWidOrThrow(from);
participant = window.require('WAWebWidFactory').asUserWidOrThrow(from);
}
const newMsgKey = new window.Store.MsgKey({
const newMsgKey = new (window.require('WAWebMsgKey'))({
from: from,
to: chat.id,
id: newId,
@ -266,7 +357,7 @@ exports.LoadUtils = () => {
const extraOptions = options.extraOptions || {};
delete options.extraOptions;
const ephemeralFields = window.Store.EphemeralFields.getEphemeralFields(chat);
const ephemeralFields = window.require('WAWebGetEphemeralFieldsMsgActionsUtils').getEphemeralFields(chat);
const message = {
...options,
@ -300,14 +391,14 @@ exports.LoadUtils = () => {
}
if (isChannel) {
const msg = new window.Store.Msg.modelClass(message);
const msgDataFromMsgModel = window.Store.SendChannelMessage.msgDataFromMsgModel(msg);
const msg = new (window.require('WAWebCollections')).Msg.modelClass(message);
const msgDataFromMsgModel = (window.require('WAWebMsgDataFromModel')).msgDataFromMsgModel(msg);
const isMedia = Object.keys(mediaOptions).length > 0;
await window.Store.SendChannelMessage.addNewsletterMsgsRecords([msgDataFromMsgModel]);
await (window.require('WAWebNewsletterUpdateMsgsRecordsJob')).addNewsletterMsgsRecords([msgDataFromMsgModel]);
chat.msgs.add(msg);
chat.t = msg.t;
const sendChannelMsgResponse = await window.Store.SendChannelMessage.sendNewsletterMessageJob({
const sendChannelMsgResponse = await (window.require('WAWebNewsletterSendMessageJob')).sendNewsletterMessageJob({
msg: msg,
type: message.type === 'chat' ? 'text' : isMedia ? 'media' : 'pollCreation',
newsletterJid: chat.id.toJid(),
@ -325,19 +416,19 @@ exports.LoadUtils = () => {
msg.serverId = sendChannelMsgResponse.serverId;
}
msg.updateAck(1, true);
await window.Store.SendChannelMessage.updateNewsletterMsgRecord(msg);
await (window.require('WAWebNewsletterUpdateMsgsRecordsJob')).updateNewsletterMsgRecord(msg);
return msg;
}
if (isStatus) {
const { backgroundColor, fontStyle } = extraOptions;
const isMedia = Object.keys(mediaOptions).length > 0;
const mediaUpdate = data => window.Store.MediaUpdate(data, mediaOptions);
const msg = new window.Store.Msg.modelClass({
const mediaUpdate = data => (window.require('WAWebMediaUpdateMsg'))(data, mediaOptions);
const msg = new (window.require('WAWebCollections')).Msg.modelClass({
...message,
author: participant ? participant : null,
messageSecret: window.crypto.getRandomValues(new Uint8Array(32)),
cannotBeRanked: window.Store.StatusUtils.canCheckStatusRankingPosterGating()
cannotBeRanked: (window.require('WAWebStatusGatingUtils')).canCheckStatusRankingPosterGating()
});
// for text only
@ -347,7 +438,7 @@ exports.LoadUtils = () => {
text: msg.body
};
await window.Store.StatusUtils[
await (window.require('WAWebSendStatusMsgAction'))[
isMedia ?
'sendStatusMediaMsgAction' : 'sendStatusTextMsgAction'
](
@ -360,12 +451,12 @@ exports.LoadUtils = () => {
return msg;
}
const [msgPromise, sendMsgResultPromise] = window.Store.SendMessage.addAndSendMsgToChat(chat, message);
const [msgPromise, sendMsgResultPromise] = (window.require('WAWebSendMsgChatAction')).addAndSendMsgToChat(chat, message);
await msgPromise;
if (options.waitUntilMsgSent) await sendMsgResultPromise;
return window.Store.Msg.get(newMsgKey._serialized);
return (window.require('WAWebCollections')).Msg.get(newMsgKey._serialized);
};
window.WWebJS.editMessage = async (msg, content, options = {}) => {
@ -373,22 +464,23 @@ exports.LoadUtils = () => {
delete options.extraOptions;
if (options.mentionedJidList) {
options.mentionedJidList = options.mentionedJidList.map((id) => window.Store.WidFactory.createWid(id));
options.mentionedJidList = options.mentionedJidList.map((id) => window.require('WAWebWidFactory').createWid(id));
options.mentionedJidList = options.mentionedJidList.filter(Boolean);
}
if (options.groupMentions) {
options.groupMentions = options.groupMentions.map((e) => ({
groupSubject: e.subject,
groupJid: window.Store.WidFactory.createWid(e.id)
groupJid: window.require('WAWebWidFactory').createWid(e.id)
}));
}
if (options.linkPreview) {
const { findLink } = window.require('WALinkify');
delete options.linkPreview;
const link = window.Store.Validators.findLink(content);
const link = findLink(content);
if (link) {
const preview = await window.Store.LinkPreview.getLinkPreview(link);
const preview = await (window.require('WAWebLinkPreviewChatAction')).getLinkPreview(link);
preview.preview = true;
preview.subtype = 'url';
options = { ...options, ...preview };
@ -401,15 +493,15 @@ exports.LoadUtils = () => {
...extraOptions
};
await window.Store.EditMessage.sendMessageEdit(msg, content, internalOptions);
return window.Store.Msg.get(msg.id._serialized);
await (window.require('WAWebSendMessageEditAction')).sendMessageEdit(msg, content, internalOptions);
return (window.require('WAWebCollections')).Msg.get(msg.id._serialized);
};
window.WWebJS.toStickerData = async (mediaInfo) => {
if (mediaInfo.mimetype == 'image/webp') return mediaInfo;
const file = window.WWebJS.mediaInfoToFile(mediaInfo);
const webpSticker = await window.Store.StickerTools.toWebpSticker(file);
const webpSticker = await (window.require('WAWebImageUtils')).toWebpSticker(file);
const webpBuffer = await webpSticker.arrayBuffer();
const data = window.WWebJS.arrayBufferToBase64(webpBuffer);
@ -427,12 +519,12 @@ exports.LoadUtils = () => {
let mediaKey = await window.WWebJS.generateHash(32);
const controller = new AbortController();
const uploadedInfo = await window.Store.UploadUtils.encryptAndUpload({
const uploadedInfo = await (window.require('WAWebUploadManager')).encryptAndUpload({
blob: file,
type: 'sticker',
signal: controller.signal,
mediaKey,
uploadQpl: window.Store.MediaUpload.startMediaUploadQpl({
uploadQpl: window.require('WAWebStartMediaUploadQpl').startMediaUploadQpl({
entryPoint: 'MediaUpload'
}),
});
@ -452,7 +544,8 @@ exports.LoadUtils = () => {
window.WWebJS.processMediaData = async (mediaInfo, { forceSticker, forceGif, forceVoice, forceDocument, forceMediaHd, sendToChannel, sendToStatus }) => {
const file = window.WWebJS.mediaInfoToFile(mediaInfo);
const opaqueData = await window.Store.OpaqueData.createFromData(file, mediaInfo.mimetype);
const OpaqueData = window.require('WAWebMediaOpaqueData');
const opaqueData = await OpaqueData.createFromData(file, mediaInfo.mimetype);
const mediaParams = {
asSticker: forceSticker,
asGif: forceGif,
@ -464,10 +557,10 @@ exports.LoadUtils = () => {
mediaParams.maxDimension = 2560;
}
const mediaPrep = window.Store.MediaPrep.prepRawMedia(opaqueData, mediaParams);
const mediaPrep = window.require('WAWebPrepRawMedia').prepRawMedia(opaqueData, mediaParams);
const mediaData = await mediaPrep.waitForPrep();
const mediaObject = window.Store.MediaObject.getOrCreateMediaObject(mediaData.filehash);
const mediaType = window.Store.MediaTypes.msgToMediaType({
const mediaObject = window.require('WAWebMediaStorage').getOrCreateMediaObject(mediaData.filehash);
const mediaType = window.require('WAWebMmsMediaTypes').msgToMediaType({
type: mediaData.type,
isGif: mediaData.isGif,
isNewsletter: sendToChannel,
@ -483,8 +576,8 @@ exports.LoadUtils = () => {
waveform || await window.WWebJS.generateWaveform(file);
}
if (!(mediaData.mediaBlob instanceof window.Store.OpaqueData)) {
mediaData.mediaBlob = await window.Store.OpaqueData.createFromData(
if (!(mediaData.mediaBlob instanceof OpaqueData)) {
mediaData.mediaBlob = await OpaqueData.createFromData(
mediaData.mediaBlob,
mediaData.mediaBlob.type
);
@ -494,24 +587,25 @@ exports.LoadUtils = () => {
mediaObject.consolidate(mediaData.toJSON());
mediaData.mediaBlob.autorelease();
const shouldUseMediaCache = window.Store.MediaDataUtils.shouldUseMediaCache(
window.Store.MediaTypes.castToV4(mediaObject.type)
const shouldUseMediaCache = (window.require('WAWebMediaDataUtils')).shouldUseMediaCache(
window.require('WAWebMmsMediaTypes').castToV4(mediaObject.type)
);
if (shouldUseMediaCache && mediaData.mediaBlob instanceof window.Store.OpaqueData) {
if (shouldUseMediaCache && mediaData.mediaBlob instanceof OpaqueData) {
const formData = mediaData.mediaBlob.formData();
window.Store.BlobCache.InMemoryMediaBlobCache.put(mediaObject.filehash, formData);
(window.require('WAWebMediaInMemoryBlobCache')).InMemoryMediaBlobCache.put(mediaObject.filehash, formData);
}
const dataToUpload = {
mimetype: mediaData.mimetype,
mediaObject,
mediaType,
...(sendToChannel ? { calculateToken: window.Store.SendChannelMessage.getRandomFilehash } : {})
...(sendToChannel ? { calculateToken: window.require('WAMediaCalculateFilehash').getRandomFilehash } : {})
};
const { uploadMedia, uploadUnencryptedMedia } = window.require('WAWebMediaMmsV4Upload');
const uploadedMedia = !sendToChannel
? await window.Store.MediaUpload.uploadMedia(dataToUpload)
: await window.Store.MediaUpload.uploadUnencryptedMedia(dataToUpload);
? await uploadMedia(dataToUpload)
: await uploadUnencryptedMedia(dataToUpload);
const mediaEntry = uploadedMedia.mediaEntry;
if (!mediaEntry) {
@ -539,9 +633,11 @@ exports.LoadUtils = () => {
window.WWebJS.getMessageModel = (message) => {
const msg = message.serialize();
const { findLinks } = window.require('WALinkify');
msg.isEphemeral = message.isEphemeral;
msg.isStatusV3 = message.isStatusV3;
msg.links = (window.Store.Validators.findLinks(message.mediaObject ? message.caption : message.body)).map((link) => ({
msg.links = findLinks(message.mediaObject ? message.caption : message.body).map((link) => ({
link: link.href,
isSuspicious: Boolean(link.suspiciousCharacters && link.suspiciousCharacters.size)
}));
@ -567,21 +663,21 @@ exports.LoadUtils = () => {
window.WWebJS.getChat = async (chatId, { getAsModel = true } = {}) => {
const isChannel = /@\w*newsletter\b/.test(chatId);
const chatWid = window.Store.WidFactory.createWid(chatId);
const chatWid = window.require('WAWebWidFactory').createWid(chatId);
let chat;
if (isChannel) {
try {
chat = window.Store.WAWebNewsletterCollection.get(chatId);
chat = (window.require('WAWebCollections')).WAWebNewsletterCollection.get(chatId);
if (!chat) {
await window.Store.ChannelUtils.loadNewsletterPreviewChat(chatId);
chat = await window.Store.WAWebNewsletterCollection.find(chatWid);
await (window.require('WAWebLoadNewsletterPreviewChatAction')).loadNewsletterPreviewChat(chatId);
chat = await (window.require('WAWebCollections')).WAWebNewsletterCollection.find(chatWid);
}
} catch (err) {
chat = null;
}
} else {
chat = window.Store.Chat.get(chatWid) || (await window.Store.FindOrCreateChat.findOrCreateLatestChat(chatWid))?.chat;
chat = (window.require('WAWebCollections')).Chat.get(chatWid) || (await (window.require('WAWebFindChatAction')).findOrCreateLatestChat(chatWid))?.chat;
}
return getAsModel && chat
@ -590,10 +686,11 @@ exports.LoadUtils = () => {
};
window.WWebJS.getChannelMetadata = async (inviteCode) => {
const role = (window.require('WAWebNewsletterModelUtils')).getRoleByIdentifier(inviteCode);
const response =
await window.Store.ChannelUtils.queryNewsletterMetadataByInviteCode(
await (window.require('WAWebNewsletterMetadataQueryJob')).queryNewsletterMetadataByInviteCode(
inviteCode,
window.Store.ChannelUtils.getRoleByIdentifier(inviteCode)
role
);
const picUrl = response.newsletterPictureMetadataMixin?.picture[0]?.queryPictureDirectPathOrEmptyResponseMixinGroup.value.directPath;
@ -610,7 +707,7 @@ exports.LoadUtils = () => {
updatedAtTs: response.newsletterDescriptionMetadataMixin.descriptionQueryDescriptionResponseMixin.updateTime
},
inviteLink: `https://whatsapp.com/channel/${response.newsletterInviteLinkMetadataMixin.inviteCode}`,
membershipType: window.Store.ChannelUtils.getRoleByIdentifier(inviteCode),
membershipType: role,
stateType: response.newsletterStateMetadataMixin.stateType,
pictureUrl: picUrl ? `https://pps.whatsapp.net${picUrl}` : null,
subscribersCount: response.newsletterSubscribersMetadataMixin.subscribersCount,
@ -619,13 +716,13 @@ exports.LoadUtils = () => {
};
window.WWebJS.getChats = async () => {
const chats = window.Store.Chat.getModelsArray();
const chats = (window.require('WAWebCollections')).Chat.getModelsArray();
const chatPromises = chats.map(chat => window.WWebJS.getChatModel(chat));
return await Promise.all(chatPromises);
};
window.WWebJS.getChannels = async () => {
const channels = window.Store.WAWebNewsletterCollection.getModelsArray();
const channels = (window.require('WAWebCollections')).WAWebNewsletterCollection.getModelsArray();
const channelPromises = channels?.map((channel) => window.WWebJS.getChatModel(channel, { isChannel: true }));
return await Promise.all(channelPromises);
};
@ -637,15 +734,15 @@ exports.LoadUtils = () => {
model.isGroup = false;
model.isMuted = chat.mute?.expiration !== 0;
if (isChannel) {
model.isChannel = window.Store.ChatGetters.getIsNewsletter(chat);
model.isChannel = (window.require('WAWebChatGetters')).getIsNewsletter(chat);
} else {
model.formattedTitle = chat.formattedTitle;
}
if (chat.groupMetadata) {
model.isGroup = true;
const chatWid = window.Store.WidFactory.createWid(chat.id._serialized);
const groupMetadata = window.Store.GroupMetadata || window.Store.WAWebGroupMetadataCollection;
const chatWid = window.require('WAWebWidFactory').createWid(chat.id._serialized);
const groupMetadata = (window.require('WAWebCollections')).GroupMetadata || (window.require('WAWebCollections')).WAWebGroupMetadataCollection;
await groupMetadata.update(chatWid);
chat.groupMetadata.participants._models
.filter(x => x.id?._serialized?.endsWith('@lid'))
@ -655,7 +752,7 @@ exports.LoadUtils = () => {
}
if (chat.newsletterMetadata) {
const newsletterMetadata = window.Store.NewsletterMetadataCollection || window.Store.WAWebNewsletterMetadataCollection;
const newsletterMetadata = (window.require('WAWebCollections')).NewsletterMetadataCollection || (window.require('WAWebCollections')).WAWebNewsletterMetadataCollection;
await newsletterMetadata.update(chat.id);
model.channelMetadata = chat.newsletterMetadata.serialize();
model.channelMetadata.createdAtTs = chat.newsletterMetadata.creationTime;
@ -664,7 +761,7 @@ exports.LoadUtils = () => {
model.lastMessage = null;
if (model.msgs && model.msgs.length) {
const lastMessage = chat.lastReceivedKey
? window.Store.Msg.get(chat.lastReceivedKey._serialized) || (await window.Store.Msg.getMessagesById([chat.lastReceivedKey._serialized]))?.messages?.[0]
? (window.require('WAWebCollections')).Msg.get(chat.lastReceivedKey._serialized) || (await (window.require('WAWebCollections')).Msg.getMessagesById([chat.lastReceivedKey._serialized]))?.messages?.[0]
: null;
lastMessage && (model.lastMessage = window.WWebJS.getMessageModel(lastMessage));
}
@ -684,37 +781,41 @@ exports.LoadUtils = () => {
res.businessProfile = contact.businessProfile.serialize();
}
res.isMe = window.Store.ContactMethods.getIsMe(contact);
res.isUser = window.Store.ContactMethods.getIsUser(contact);
res.isGroup = window.Store.ContactMethods.getIsGroup(contact);
res.isWAContact = window.Store.ContactMethods.getIsWAContact(contact);
res.isMyContact = window.Store.ContactMethods.getIsMyContact(contact);
res.isBlocked = contact.isContactBlocked;
res.userid = window.Store.ContactMethods.getUserid(contact);
res.isEnterprise = window.Store.ContactMethods.getIsEnterprise(contact);
res.verifiedName = window.Store.ContactMethods.getVerifiedName(contact);
res.verifiedLevel = window.Store.ContactMethods.getVerifiedLevel(contact);
res.statusMute = window.Store.ContactMethods.getStatusMute(contact);
res.name = window.Store.ContactMethods.getName(contact);
res.shortName = window.Store.ContactMethods.getShortName(contact);
res.pushname = window.Store.ContactMethods.getPushname(contact);
const ContactMethods = window.require('WAWebContactGetters');
res.isMe = ContactMethods.getIsMe(contact);
res.isUser = ContactMethods.getIsUser(contact);
res.isGroup = ContactMethods.getIsGroup(contact);
res.isWAContact = ContactMethods.getIsWAContact(contact);
res.userid = ContactMethods.getUserid(contact);
res.verifiedName = ContactMethods.getVerifiedName(contact);
res.verifiedLevel = ContactMethods.getVerifiedLevel(contact);
res.statusMute = ContactMethods.getStatusMute(contact);
res.name = ContactMethods.getName(contact);
res.shortName = ContactMethods.getShortName(contact);
res.pushname = ContactMethods.getPushname(contact);
const { getIsMyContact } = window.require('WAWebFrontendContactGetters');
res.isMyContact = getIsMyContact(contact);
res.isEnterprise = ContactMethods.getIsEnterprise(contact);
return res;
};
window.WWebJS.getContact = async contactId => {
const wid = window.Store.WidFactory.createWid(contactId);
let contact = await window.Store.Contact.find(wid);
const wid = window.require('WAWebWidFactory').createWid(contactId);
let contact = await (window.require('WAWebCollections')).Contact.find(wid);
if (contact.id._serialized.endsWith('@lid')) {
contact.id = contact.phoneNumber;
}
const bizProfile = await window.Store.BusinessProfile.fetchBizProfile(wid);
const bizProfile = await (window.require('WAWebCollections')).BusinessProfile.fetchBizProfile(wid);
bizProfile.profileOptions && (contact.businessProfile = bizProfile);
return window.WWebJS.getContactModel(contact);
};
window.WWebJS.getContacts = () => {
const contacts = window.Store.Contact.getModelsArray();
const contacts = (window.require('WAWebCollections')).Contact.getModelsArray();
return contacts.map(contact => window.WWebJS.getContactModel(contact));
};
@ -809,7 +910,7 @@ exports.LoadUtils = () => {
window.WWebJS.sendClearChat = async (chatId) => {
let chat = await window.WWebJS.getChat(chatId, { getAsModel: false });
if (chat !== undefined) {
await window.Store.SendClear.sendClear(chat, false);
await (window.require('WAWebChatClearBridge')).sendClear(chat, false);
return true;
}
return false;
@ -818,24 +919,25 @@ exports.LoadUtils = () => {
window.WWebJS.sendDeleteChat = async (chatId) => {
let chat = await window.WWebJS.getChat(chatId, { getAsModel: false });
if (chat !== undefined) {
await window.Store.SendDelete.sendDelete(chat);
await (window.require('WAWebDeleteChatAction')).sendDelete(chat);
return true;
}
return false;
};
window.WWebJS.sendChatstate = async (state, chatId) => {
chatId = window.Store.WidFactory.createWid(chatId);
chatId = window.require('WAWebWidFactory').createWid(chatId);
const ChatState = window.require('WAWebChatStateBridge');
switch (state) {
case 'typing':
await window.Store.ChatState.sendChatStateComposing(chatId);
await ChatState.sendChatStateComposing(chatId);
break;
case 'recording':
await window.Store.ChatState.sendChatStateRecording(chatId);
await ChatState.sendChatStateRecording(chatId);
break;
case 'stop':
await window.Store.ChatState.sendChatStatePaused(chatId);
await ChatState.sendChatStatePaused(chatId);
break;
default:
throw 'Invalid chatstate';
@ -852,12 +954,12 @@ exports.LoadUtils = () => {
};
window.WWebJS.getLabels = () => {
const labels = window.Store.Label.getModelsArray();
const labels = (window.require('WAWebCollections')).Label.getModelsArray();
return labels.map(label => window.WWebJS.getLabelModel(label));
};
window.WWebJS.getLabel = (labelId) => {
const label = window.Store.Label.get(labelId);
const label = (window.require('WAWebCollections')).Label.get(labelId);
return window.WWebJS.getLabelModel(label);
};
@ -867,13 +969,13 @@ exports.LoadUtils = () => {
};
window.WWebJS.getOrderDetail = async (orderId, token, chatId) => {
const chatWid = window.Store.WidFactory.createWid(chatId);
return window.Store.QueryOrder.queryOrder(chatWid, orderId, 80, 80, token);
const chatWid = window.require('WAWebWidFactory').createWid(chatId);
return (window.require('WAWebBizOrderBridge')).queryOrder(chatWid, orderId, 80, 80, token);
};
window.WWebJS.getProductMetadata = async (productId) => {
let sellerId = window.Store.Conn.wid;
let product = await window.Store.QueryProduct.queryProduct(sellerId, productId);
let sellerId = (window.require('WAWebConnModel').Conn).wid;
let product = await (window.require('WAWebBizProductCatalogBridge')).queryProduct(sellerId, productId);
if (product && product.data) {
return product.data;
}
@ -882,20 +984,20 @@ exports.LoadUtils = () => {
};
window.WWebJS.rejectCall = async (peerJid, id) => {
let userId = window.Store.User.getMaybeMePnUser()._serialized;
let userId = (window.require('WAWebUserPrefsMeUser')).getMaybeMePnUser()._serialized;
const stanza = window.Store.SocketWap.wap('call', {
id: window.Store.SocketWap.generateId(),
const stanza = window.require('WAWap').wap('call', {
id: window.require('WAWap').generateId(),
from: userId,
to: peerJid,
}, [
window.Store.SocketWap.wap('reject', {
window.require('WAWap').wap('reject', {
'call-id': id,
'call-creator': peerJid,
count: '0',
})
]);
await window.Store.Socket.deprecatedCastStanza(stanza);
await (window.require('WADeprecatedSendIq')).deprecatedCastStanza(stanza);
};
window.WWebJS.cropAndResizeImage = async (media, options = {}) => {
@ -940,12 +1042,12 @@ exports.LoadUtils = () => {
const thumbnail = await window.WWebJS.cropAndResizeImage(media, { asDataUrl: true, mimetype: 'image/jpeg', size: 96 });
const profilePic = await window.WWebJS.cropAndResizeImage(media, { asDataUrl: true, mimetype: 'image/jpeg', size: 640 });
const chatWid = window.Store.WidFactory.createWid(chatId);
const chatWid = window.require('WAWebWidFactory').createWid(chatId);
try {
const collection = window.Store.ProfilePicThumb.get(chatId) || await window.Store.ProfilePicThumb.find(chatId);
const collection = (window.require('WAWebCollections')).ProfilePicThumb.get(chatId) || await (window.require('WAWebCollections')).ProfilePicThumb.find(chatId);
if (!collection?.canSet()) return false;
const res = await window.Store.GroupUtils.sendSetPicture(chatWid, thumbnail, profilePic);
const res = await (window.require('WAWebContactProfilePicThumbBridge')).sendSetPicture(chatWid, thumbnail, profilePic);
return res ? res.status === 200 : false;
} catch (err) {
if (err.name === 'ServerStatusCodeError') return false;
@ -954,12 +1056,12 @@ exports.LoadUtils = () => {
};
window.WWebJS.deletePicture = async (chatid) => {
const chatWid = window.Store.WidFactory.createWid(chatid);
const chatWid = window.require('WAWebWidFactory').createWid(chatid);
try {
const collection = window.Store.ProfilePicThumb.get(chatid);
const collection = (window.require('WAWebCollections')).ProfilePicThumb.get(chatid);
if (!collection.canDelete()) return;
const res = await window.Store.GroupUtils.requestDeletePicture(chatWid);
const res = await (window.require('WAWebContactProfilePicThumbBridge')).requestDeletePicture(chatWid);
return res ? res.status === 200 : false;
} catch (err) {
if(err.name === 'ServerStatusCodeError') return false;
@ -968,7 +1070,7 @@ exports.LoadUtils = () => {
};
window.WWebJS.getProfilePicThumbToBase64 = async (chatWid) => {
const profilePicCollection = await window.Store.ProfilePicThumb.find(chatWid);
const profilePicCollection = await (window.require('WAWebCollections')).ProfilePicThumb.find(chatWid);
const _readImageAsBase64 = (imageBlob) => {
return new Promise((resolve) => {
@ -1002,10 +1104,10 @@ exports.LoadUtils = () => {
};
window.WWebJS.getAddParticipantsRpcResult = async (groupWid, participantWid) => {
const iqTo = window.Store.WidToJid.widToGroupJid(groupWid);
const iqTo = window.require('WAWebWidToJid').widToGroupJid(groupWid);
const participantArgs = [{
participantJid: window.Store.WidToJid.widToUserJid(participantWid)
participantJid: window.require('WAWebWidToJid').widToUserJid(participantWid)
}];
let rpcResult, resultArgs;
@ -1017,7 +1119,7 @@ exports.LoadUtils = () => {
};
try {
rpcResult = await window.Store.GroupParticipants.sendAddParticipantsRPC({ participantArgs, iqTo });
rpcResult = await (window.require('WASmaxGroupsAddParticipantsRPC')).sendAddParticipantsRPC({ participantArgs, iqTo });
resultArgs = rpcResult.value.addParticipant[0]
.addParticipantsParticipantAddedOrNonRegisteredWaUserParticipantErrorLidResponseMixinGroup
.value
@ -1049,20 +1151,20 @@ exports.LoadUtils = () => {
};
window.WWebJS.membershipRequestAction = async (groupId, action, requesterIds, sleep) => {
const groupWid = window.Store.WidFactory.createWid(groupId);
const group = await window.Store.Chat.find(groupWid);
const groupWid = window.require('WAWebWidFactory').createWid(groupId);
const group = await (window.require('WAWebCollections')).Chat.find(groupWid);
const toApprove = action === 'Approve';
let membershipRequests;
let response;
let result = [];
await window.Store.GroupQueryAndUpdate({ id: groupId });
await (window.require('WAWebGroupQueryJob')).queryAndUpdateGroupMetadataById({ id: groupId });
if (!requesterIds?.length) {
membershipRequests = group.groupMetadata.membershipApprovalRequests._models.map(({ id }) => id);
} else {
!Array.isArray(requesterIds) && (requesterIds = [requesterIds]);
membershipRequests = requesterIds.map(r => window.Store.WidFactory.createWid(r));
membershipRequests = requesterIds.map(r => window.require('WAWebWidFactory').createWid(r));
}
if (!membershipRequests.length) return [];
@ -1070,12 +1172,12 @@ exports.LoadUtils = () => {
const participantArgs = membershipRequests.map(m => ({
participantArgs: [
{
participantJid: window.Store.WidToJid.widToUserJid(m)
participantJid: window.require('WAWebWidToJid').widToUserJid(m)
}
]
}));
const groupJid = window.Store.WidToJid.widToGroupJid(groupWid);
const groupJid = window.require('WAWebWidToJid').widToGroupJid(groupWid);
const _getSleepTime = (sleep) => {
if (!Array.isArray(sleep) || (sleep.length === 2 && sleep[0] === sleep[1])) {
@ -1102,7 +1204,7 @@ exports.LoadUtils = () => {
try {
for (const participant of participantArgs) {
response = await window.Store.MembershipRequestUtils.sendMembershipRequestsActionRPC({
response = await (window.require('WASmaxGroupsMembershipRequestsActionRPC')).sendMembershipRequestsActionRPC({
iqTo: groupJid,
[toApprove ? 'approveArgs' : 'rejectArgs']: participant
});
@ -1117,7 +1219,7 @@ exports.LoadUtils = () => {
? value.participant[0].membershipRequestsActionAcceptParticipantMixins?.value.error
: value.participant[0].membershipRequestsActionRejectParticipantMixins?.value.error;
return {
requesterId: window.Store.WidFactory.createWid(p.jid)._serialized,
requesterId: window.require('WAWebWidFactory').createWid(p.jid)._serialized,
...(error
? { error: +error, message: membReqResCodes[error] || membReqResCodes.default }
: { message: `${toApprove ? 'Approved' : 'Rejected'} successfully` })
@ -1127,7 +1229,7 @@ exports.LoadUtils = () => {
}
} else {
result.push({
requesterId: window.Store.JidToWid.userJidToUserWid(participant.participantArgs[0].participantJid)._serialized,
requesterId: window.require('WAWebJidToWid').userJidToUserWid(participant.participantArgs[0].participantJid)._serialized,
message: 'ServerStatusCodeError'
});
}
@ -1151,9 +1253,9 @@ exports.LoadUtils = () => {
try {
if (action === 'Subscribe') {
await window.Store.ChannelUtils.subscribeToNewsletterAction(channel, options);
await (window.require('WAWebNewsletterSubscribeAction')).subscribeToNewsletterAction(channel, options);
} else if (action === 'Unsubscribe') {
await window.Store.ChannelUtils.unsubscribeFromNewsletterAction(channel, options);
await (window.require('WAWebNewsletterUnsubscribeAction')).unsubscribeFromNewsletterAction(channel, options);
} else return false;
return true;
} catch (err) {
@ -1163,7 +1265,7 @@ exports.LoadUtils = () => {
};
window.WWebJS.pinUnpinMsgAction = async (msgId, action, duration) => {
const message = window.Store.Msg.get(msgId) || (await window.Store.Msg.getMessagesById([msgId]))?.messages?.[0];
const message = (window.require('WAWebCollections')).Msg.get(msgId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([msgId]))?.messages?.[0];
if (!message) return false;
if (typeof duration !== 'number') return false;
@ -1171,7 +1273,7 @@ exports.LoadUtils = () => {
const originalFunction = window.require('WAWebPinMsgConstants').getPinExpiryDuration;
window.require('WAWebPinMsgConstants').getPinExpiryDuration = () => duration;
const response = await window.Store.PinnedMsgUtils.sendPinInChatMsg(message, action, duration);
const response = await (window.require('WAWebSendPinMessageAction')).sendPinInChatMsg(message, action, duration);
window.require('WAWebPinMsgConstants').getPinExpiryDuration = originalFunction;
@ -1185,27 +1287,27 @@ exports.LoadUtils = () => {
};
window.WWebJS.getAllStatuses = () => {
const statuses = window.Store.Status.getModelsArray();
const statuses = (window.require('WAWebCollections')).Status.getModelsArray();
return statuses.map(status => window.WWebJS.getStatusModel(status));
};
window.WWebJS.enforceLidAndPnRetrieval = async (userId) => {
const wid = window.Store.WidFactory.createWid(userId);
const wid = window.require('WAWebWidFactory').createWid(userId);
const isLid = wid.server === 'lid';
let lid = isLid ? wid : window.Store.LidUtils.getCurrentLid(wid);
let phone = isLid ? window.Store.LidUtils.getPhoneNumber(wid) : wid;
let lid = isLid ? wid : window.require('WAWebApiContact').getCurrentLid(wid);
let phone = isLid ? window.require('WAWebApiContact').getPhoneNumber(wid) : wid;
if (!isLid && !lid) {
const queryResult = await window.Store.QueryExist(wid);
const queryResult = await (window.require('WAWebQueryExistsJob').queryWidExists)(wid);
if (!queryResult?.wid) return {};
lid = window.Store.LidUtils.getCurrentLid(wid);
lid = window.require('WAWebApiContact').getCurrentLid(wid);
}
if (isLid && !phone) {
const queryResult = await window.Store.QueryExist(wid);
const queryResult = await (window.require('WAWebQueryExistsJob').queryWidExists)(wid);
if (!queryResult?.wid) return {};
phone = window.Store.LidUtils.getPhoneNumber(wid);
phone = window.require('WAWebApiContact').getPhoneNumber(wid);
}
return { lid, phone };

View file

@ -16,7 +16,7 @@ class InterfaceController {
async openChatWindow(chatId) {
return await this.pupPage.evaluate(async (chatId) => {
const chat = await window.WWebJS.getChat(chatId, { getAsModel: false });
return await window.Store.Cmd.openChatBottom({'chat':chat});
return await (window.require('WAWebCmd').Cmd).openChatBottom({'chat':chat});
}, chatId);
}
@ -27,7 +27,7 @@ class InterfaceController {
async openChatDrawer(chatId) {
await this.pupPage.evaluate(async chatId => {
let chat = await window.WWebJS.getChat(chatId, { getAsModel: false });
await window.Store.Cmd.openDrawerMid(chat);
await (window.require('WAWebCmd').Cmd).openDrawerMid(chat);
}, chatId);
}
@ -38,7 +38,7 @@ class InterfaceController {
async openChatSearch(chatId) {
await this.pupPage.evaluate(async chatId => {
let chat = await window.WWebJS.getChat(chatId, { getAsModel: false });
await window.Store.Cmd.chatSearch(chat);
await (window.require('WAWebCmd').Cmd).chatSearch(chat);
}, chatId);
}
@ -48,10 +48,10 @@ class InterfaceController {
*/
async openChatWindowAt(msgId) {
await this.pupPage.evaluate(async (msgId) => {
const msg = window.Store.Msg.get(msgId) || (await window.Store.Msg.getMessagesById([msgId]))?.messages?.[0];
const chat = window.Store.Chat.get(msg.id.remote) ?? await window.Store.Chat.find(msg.id.remote);
const searchContext = await window.Store.SearchContext.getSearchContext(chat, msg.id);
await window.Store.Cmd.openChatAt({ chat: chat, msgContext: searchContext });
const msg = (window.require('WAWebCollections')).Msg.get(msgId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([msgId]))?.messages?.[0];
const chat = (window.require('WAWebCollections')).Chat.get(msg.id.remote) ?? await (window.require('WAWebCollections')).Chat.find(msg.id.remote);
const searchContext = await (window.require('WAWebChatMessageSearch')).getSearchContext(chat, msg.id);
await (window.require('WAWebCmd').Cmd).openChatAt({ chat: chat, msgContext: searchContext });
}, msgId);
}
@ -61,8 +61,8 @@ class InterfaceController {
*/
async openMessageDrawer(msgId) {
await this.pupPage.evaluate(async msgId => {
const msg = window.Store.Msg.get(msgId) || (await window.Store.Msg.getMessagesById([msgId]))?.messages?.[0];
await window.Store.Cmd.msgInfoDrawer(msg);
const msg = (window.require('WAWebCollections')).Msg.get(msgId) || (await (window.require('WAWebCollections')).Msg.getMessagesById([msgId]))?.messages?.[0];
await (window.require('WAWebCmd').Cmd).msgInfoDrawer(msg);
}, msgId);
}
@ -71,7 +71,7 @@ class InterfaceController {
*/
async closeRightDrawer() {
await this.pupPage.evaluate(async () => {
await window.Store.DrawerManager.closeDrawerRight();
await window.require('WAWebDrawerManager').DrawerManager.closeDrawerRight();
});
}
@ -80,8 +80,8 @@ class InterfaceController {
*/
async getFeatures() {
return await this.pupPage.evaluate(() => {
if(!window.Store.Features) throw new Error('This version of Whatsapp Web does not support features');
return window.Store.Features.F;
if(!(window.require('WAWebCollections')).Features) throw new Error('This version of Whatsapp Web does not support features');
return (window.require('WAWebCollections')).Features.F;
});
}
@ -91,8 +91,8 @@ class InterfaceController {
*/
async checkFeatureStatus(feature) {
return await this.pupPage.evaluate((feature) => {
if(!window.Store.Features) throw new Error('This version of Whatsapp Web does not support features');
return window.Store.Features.supportsFeature(feature);
if(!(window.require('WAWebCollections')).Features) throw new Error('This version of Whatsapp Web does not support features');
return (window.require('WAWebCollections')).Features.supportsFeature(feature);
}, feature);
}
@ -102,9 +102,9 @@ class InterfaceController {
*/
async enableFeatures(features) {
await this.pupPage.evaluate((features) => {
if(!window.Store.Features) throw new Error('This version of Whatsapp Web does not support features');
if(!(window.require('WAWebCollections')).Features) throw new Error('This version of Whatsapp Web does not support features');
for (const feature in features) {
window.Store.Features.setFeature(features[feature], true);
(window.require('WAWebCollections')).Features.setFeature(features[feature], true);
}
}, features);
}
@ -115,9 +115,9 @@ class InterfaceController {
*/
async disableFeatures(features) {
await this.pupPage.evaluate((features) => {
if(!window.Store.Features) throw new Error('This version of Whatsapp Web does not support features');
if(!(window.require('WAWebCollections')).Features) throw new Error('This version of Whatsapp Web does not support features');
for (const feature in features) {
window.Store.Features.setFeature(features[feature], false);
(window.require('WAWebCollections')).Features.setFeature(features[feature], false);
}
}, features);
}

View file

@ -137,6 +137,7 @@ describe('Client', function() {
await client.initialize();
expect(authenticatedCallback.called).to.equal(true);
expect(readyCallback.called).to.equal(true);
expect(qrCallback.called).to.equal(false);
@ -163,71 +164,6 @@ describe('Client', function() {
console.log(`WA Version: ${version}`);
});
describe('Expose Store', function() {
it('exposes the store', async function() {
const exposed = await client.pupPage.evaluate(() => {
return Boolean(window.Store);
});
expect(exposed).to.equal(true);
});
it('exposes all required WhatsApp Web internal models', async function() {
const expectedModules = [
'AppState',
'BlockContact',
'Call',
'Chat',
'ChatState',
'Cmd',
'Conn',
'Contact',
'DownloadManager',
'EphemeralFields',
'Features',
'GroupMetadata',
'GroupParticipants',
'GroupUtils',
'Invite',
'InviteInfo',
'JoinInviteV4',
'Label',
'MediaObject',
'MediaPrep',
'MediaTypes',
'MediaUpload',
'MessageInfo',
'Msg',
'MsgKey',
'OpaqueData',
'QueryOrder',
'QueryProduct',
'PresenceUtils',
'ProfilePic',
'QueryExist',
'QueryProduct',
'QueryOrder',
'SendClear',
'SendDelete',
'SendMessage',
'SendSeen',
'StatusUtils',
'UploadUtils',
'UserConstructor',
'VCard',
'Validators',
'WidFactory',
'findCommonGroups',
'sendReactionToMsg',
];
const loadedModules = await client.pupPage.evaluate((expectedModules) => {
return expectedModules.filter(m => Boolean(window.Store[m]));
}, expectedModules);
expect(loadedModules).to.have.members(expectedModules);
});
});
describe('Send Messages', function () {
it('can send a message', async function() {

View file

@ -5,6 +5,7 @@ require('dotenv').config();
const remoteId = process.env.WWEBJS_TEST_REMOTE_ID;
if(!remoteId) throw new Error('The WWEBJS_TEST_REMOTE_ID environment variable has not been set.');
function createClient({authenticated, options: additionalOpts}={}) {
const options = {};