Skip to content

Commit

Permalink
fix: function fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
jonalan7 committed May 19, 2023
1 parent 066b189 commit 9105c06
Show file tree
Hide file tree
Showing 65 changed files with 1,443 additions and 79 deletions.
1 change: 1 addition & 0 deletions src/api/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ export { deleteFiles } from './delete-file';
export { callbackWile } from './callback-wile';
export { checkingCloses } from './closes-browser';
export { loadForceConnect } from './force-connect';
export { sleep } from './sleep';
10 changes: 10 additions & 0 deletions src/api/helpers/sleep.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* Pauses the execution for a specified amount of time.
* @param time The duration to sleep in milliseconds.
*/
export function sleep(time: number) {
try {
// Create a promise that resolves after the specified time
return new Promise((resolve) => setTimeout(resolve, time));
} catch {}
}
34 changes: 34 additions & 0 deletions src/api/inject/webpack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Page, Browser } from 'puppeteer';
import * as path from 'path';
//import { SenderLayer } from '../api/layes/sender.layes';
//import { CreateOptions, defaultConfig } from '../model/interface';

// export class webPack extends SenderLayer {
// constructor(
// public page: Page,
// public browser: Browser,
// public options: CreateOptions,
// public ev: any
// ) {
// super(page, browser, options, ev);
// this.initService();

// this.page.on('load', async () => {
// await this.initService();
// });
// }

// async initService() {
// try {
// await this.page
// .waitForFunction('webpackChunkwhatsapp_web_client.length')
// .catch();
// await this.page
// .addScriptTag({
// path: require.resolve(path.join(__dirname, '../assets/', 'api.js'))
// })
// .catch();
// this.initLitener();
// } catch {}
// }
// }
72 changes: 72 additions & 0 deletions src/api/layers/callback-on.layes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { onMode } from '../model/enum';
import { sleep } from '../helpers';

/**
* attribution and behavior change of a given event
*/
export class CallbackOnStatus {
public statusFind: any;
constructor() {
this.statusFind = '';
}

/**
* waiting for event change
* @param event returns event status
*/
async onChange(event: (status: any) => void) {
let change = null;
while (true) {
if (this.statusFind !== change) {
change = this.statusFind;
event && event(change);
}
await sleep(50);
}
}

/**
* here you can monitor user events
* @param type types of monitoring
* @param callback returns of monitoring
*/
public async on(type: onMode, callback: (state: any) => void) {
switch (type) {
case onMode.interfaceChange:
this.onChange((event) => {
if (event.onType === onMode.interfaceChange) {
callback(event);
}
});
break;
case onMode.newOnAck:
this.onChange((event) => {
if (event.onType === onMode.newOnAck) {
callback(event);
}
});
break;
case onMode.newMessage:
this.onChange((event) => {
if (event.onType === onMode.newMessage) {
callback(event);
}
});
break;
case onMode.qrcode:
this.onChange((event) => {
if (event.onType === onMode.qrcode) {
callback(event);
}
});
break;
case onMode.connection:
this.onChange((event) => {
if (event.onType === onMode.connection) {
callback(event);
}
});
break;
}
}
}
1 change: 1 addition & 0 deletions src/api/layers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { CallbackOnStatus } from './callback-on.layes';
9 changes: 6 additions & 3 deletions src/api/layers/listener.layer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,16 @@ export class ListenerLayer extends ProfileLayer {
.evaluate(() => {
let isHeroEqual = {};
// try {
window.Store.Msg.on('add', (newMessage) => {
window.Store.Msg.on('add', async (newMessage) => {
if (!Object.is(isHeroEqual, newMessage)) {
isHeroEqual = newMessage;
if (newMessage && newMessage.isNewMsg) {
window.onAnyMessage(
window.WAPI.processMessageObj(newMessage, true, false)
const processMessageObj = await window.WAPI.processMessageObj(
newMessage,
true,
false
);
window.onAnyMessage(processMessageObj);
}
}
});
Expand Down
1 change: 1 addition & 0 deletions src/api/model/enum/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ export { GroupNotificationType } from './group-notification-type';
export { SocketState, SocketStream } from './socket-state';
export { MessageType, MediaType } from './message-type';
export { GroupSettings } from './group-settings';
export { onMode } from './mode.enum';
export * from './interface-mode';
export * from './interface-state';
31 changes: 31 additions & 0 deletions src/api/model/enum/mode.enum.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
export enum onMode {
/**
* Indicates a change in the user interface.
* @description Used to receive information about the current interface the user is on.
*/
interfaceChange = 'interfaceChange',

/**
* Monitors new messages.
* @description Used to receive notifications when a new message is received.
*/
newMessage = 'newMessage',

/**
* Receives QR code updates.
* @description Used to receive updated information about the QR code.
*/
qrcode = 'qrcode',

/**
* User connection information.
* @description Used to obtain information about the user's connection.
*/
connection = 'connection',

/**
* Monitors the status of a message.
* @description Used to receive notifications about the delivery status of a message.
*/
newOnAck = 'newOnAck'
}
2 changes: 1 addition & 1 deletion src/config/create-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ export const defaultOptions: CreateConfig = {
addBrowserArgs: [],
puppeteerOptions: {},
disableSpins: false,
disableWelcome: false,
disableWelcome: true,
updatesLog: true,
autoClose: 120000,
createPathFileToken: true,
Expand Down
1 change: 1 addition & 0 deletions src/controllers/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ export async function initBrowser(

// Set the executable path to the path of the Chrome binary or the executable path provided
const executablePath = getChrome() ?? puppeteer.executablePath();
console.log('Path Chrome: ', executablePath);
const extras = { executablePath };

// Use stealth plugin to avoid being detected as a bot
Expand Down
4 changes: 3 additions & 1 deletion src/controllers/init.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { Browser, Page } from 'puppeteer';
import { checkUpdates } from './check-up-to-date';
import { options, defaultOptions } from '../config';
import { initWhatsapp, initBrowser, statusLog } from './browser';
import { initWhatsapp, initBrowser } from './browser';
import { CallbackOnStatus } from '../api/layers';

export async function connect(options?: options);

export async function connect(options?: options) {
const event = new CallbackOnStatus();
const mergeOptionsDefault = { ...defaultOptions, ...options };

if (!!mergeOptionsDefault.session && mergeOptionsDefault.session.length) {
Expand Down
4 changes: 0 additions & 4 deletions src/controllers/initializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -391,10 +391,6 @@ export async function create(
client
.onStateChange(async (state) => {
if (state === SocketState.PAIRING) {
await page.evaluate(async () => {
await window?.Store?.Login?.triggerCriticalSyncLogout();
});

if (statusFind) {
statusFind('deviceNotConnected', session);
}
Expand Down
109 changes: 109 additions & 0 deletions src/lib/wapi/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import {
sleep,
injectConfig,
injectParasiteSnake,
processFiles,
base64ToFile,
generateMediaKey,
arrayBufferToBase64,
encryptAndUploadFile,
getFileHash
} from './help';

import {
getChat,
scope,
getNewId,
getNewMessageId,
sendExist,
checkNumberStatus,
isMD,
sendCheckType,
addChatWapi
} from './functions/help';

import {
sendMessage,
baseSendMessage,
getAllContacts,
createGroup,
addParticipant,
setGroupDescription,
getHost,
setGroupImage
} from './functions';

import {
serializeMessageObj,
serializeChatObj,
serializeContactObj,
serializeProfilePicThumb,
serializeRawObj,
serializeMeObj
} from './serialize';

//initialized scrap webpack
(async () => {
window[injectConfig.webpack] = window[injectConfig.webpack] || [];
window.Store = {};
while (true) {
try {
const webPackLast = window[injectConfig.webpack].length - 1;
if (
!window[injectConfig.webpack][webPackLast][0].includes(
injectConfig.parasite
)
) {
await injectParasiteSnake();
return;
}
} catch {
await sleep(1000);
}
}
})();

if (typeof window.WAPI === 'undefined') {
window.WAPI = {};

// Helps
window.WAPI.getChat = getChat;
window.WAPI.scope = scope;
window.WAPI.getNewId = getNewId;
window.WAPI.getNewMessageId = getNewMessageId;
window.WAPI.sendExist = sendExist;
window.WAPI.checkNumberStatus = checkNumberStatus;
window.WAPI.isMD = isMD;
window.WAPI.baseSendMessage = baseSendMessage;
window.WAPI.processFiles = processFiles;
window.WAPI.base64ToFile = base64ToFile;
window.WAPI.generateMediaKey = generateMediaKey;
window.WAPI.arrayBufferToBase64 = arrayBufferToBase64;
window.WAPI.encryptAndUploadFile = encryptAndUploadFile;
window.WAPI.getFileHash = getFileHash;
window.WAPI.sendCheckType = sendCheckType;
window.WAPI.addChatWapi = addChatWapi;

// Functions

// Send
window.WAPI.sendMessage = sendMessage;

// Host
window.WAPI.getAllContacts = getAllContacts;
window.WAPI.getHost = getHost;

// Group
window.WAPI.createGroup = createGroup;
window.WAPI.addParticipant = addParticipant;
window.WAPI.setGroupDescription = setGroupDescription;
window.WAPI.setGroupImage = setGroupImage;

// Serialize
window.WAPI.serializeMessageObj = serializeMessageObj;
window.WAPI.serializeChatObj = serializeChatObj;
window.WAPI.serializeContactObj = serializeContactObj;
window.WAPI.serializeProfilePicThumb = serializeProfilePicThumb;
window.WAPI.serializeRawObj = serializeRawObj;
window.WAPI.serializeMeObj = serializeMeObj;
}
2 changes: 1 addition & 1 deletion src/lib/wapi/functions/get-all-messages-in-chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export async function getAllMessagesInChat(
}
const messageObj = messages[i];

let message = WAPI.processMessageObj(
let message = await WAPI.processMessageObj(
messageObj,
includeMe,
includeNotifications
Expand Down
5 changes: 3 additions & 2 deletions src/lib/wapi/functions/get-all-new-messages.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { getAllChatsWithNewMessages } from './get-chats-with-new-messages';

export const getAllNewMessages = function () {
export const getAllNewMessages = async function () {
const serializeMessageObj = await WAPI._serializeMessageObj;
const _newMessages =
getAllChatsWithNewMessages()
.map((c) => WAPI.getChat(c.id))
.flatMap((c) => c.msgs._models.filter((x) => x.isNewMsg))
.map(WAPI._serializeMessageObj) || [];
.map(serializeMessageObj) || [];

return _newMessages;
};
4 changes: 2 additions & 2 deletions src/lib/wapi/functions/get-data-messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export async function getAllMessagesDate(
if (chat && chat.status != 404) {
const statusMsg = chat.msgs.msgLoadState.noEarlierMsgs;
if (statusMsg === false) {
await chat.loadEarlierMsgs();
await chat.onEmptyMRM();
}

let messages = chat.msgs._models;
Expand Down Expand Up @@ -93,7 +93,7 @@ export async function getAllMessagesDate(
}
if (output.length < limit || limit === 0) {
const messageObj = messages[i];
const message = WAPI._serializeMessageObj(messageObj);
const message = await WAPI._serializeMessageObj(messageObj);
if (message.id && idCheck.includes(message.id) === true) {
continue;
}
Expand Down
5 changes: 3 additions & 2 deletions src/lib/wapi/functions/get-message-by-id.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ export async function getMessageById(key, done, serialize = true) {
}

//If not message not found, load latest messages of chat
await chat.loadEarlierMsgs();
await chat.onEmptyMRM();
await WAPI.sleep(100);
msg = window.Store.Msg.get(key);

if (!msg) {
Expand All @@ -36,7 +37,7 @@ export async function getMessageById(key, done, serialize = true) {

if (serialize) {
try {
result = WAPI.processMessageObj(msg, true, true);
result = await WAPI.processMessageObj(msg, true, true);
} catch (err) {}
} else {
result = msg;
Expand Down
Loading

0 comments on commit 9105c06

Please sign in to comment.