Skip to content

Commit

Permalink
feat: Added onStreamChange method
Browse files Browse the repository at this point in the history
  • Loading branch information
jonalan7 committed Jan 22, 2021
1 parent b910e92 commit 1236dbb
Show file tree
Hide file tree
Showing 11 changed files with 123 additions and 55 deletions.
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -763,6 +763,21 @@ client.onStateChange((state) => {
if ('UNPAIRED'.includes(state)) console.log('logout');
});

// DISCONNECTED
// SYNCING
// RESUMING
// CONNECTED
let time = 0;
client.onStreamChange((state) => {
console.log('State Connection Stream: ' + state);
clearTimeout(time);
if (state === 'DISCONNECTED' || state === 'SYNCING') {
time = setTimeout(() => {
client.close();
}, 80000);
}
});

// function to detect incoming call
client.onIncomingCall(async (call) => {
console.log(call);
Expand Down
1 change: 1 addition & 0 deletions src/api/helpers/exposed.enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export enum ExposedFn {
onAck = 'onAck',
onParticipantsChanged = 'onParticipantsChanged',
onStateChange = 'onStateChange',
onStreamChange = 'onStreamChange',
onIncomingCall = 'onIncomingCall',
onInterfaceChange = 'onInterfaceChange',
}
56 changes: 40 additions & 16 deletions src/api/layers/listener.layer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ import { Page } from 'puppeteer';
import { CreateConfig } from '../../config/create-config';
import { ExposedFn } from '../helpers/exposed.enum';
import { Ack, Chat, LiveLocation, Message, ParticipantEvent } from '../model';
import { SocketState } from '../model/enum';
import { SocketState, SocketStream } from '../model/enum';
import { InterfaceMode } from '../model/enum/interface-mode';
import { InterfaceState } from '../model/enum/interface-state';
import { ProfileLayer } from './profile.layer';
Expand All @@ -67,6 +67,7 @@ declare global {
onMessage: any;
onAnyMessage: any;
onStateChange: any;
onStreamChange: any;
onIncomingCall: any;
onAck: any;
}
Expand Down Expand Up @@ -117,6 +118,10 @@ export class ListenerLayer extends ProfileLayer {
window.WAPI.onStateChange(window['onStateChange']);
window['onStateChange'].exposed = true;
}
if (!window['onStreamChange'].exposed) {
window.WAPI.onStreamChange(window['onStreamChange']);
window['onStreamChange'].exposed = true;
}
if (!window['onAddedToGroup'].exposed) {
window.WAPI.onAddedToGroup(window['onAddedToGroup']);
window['onAddedToGroup'].exposed = true;
Expand All @@ -138,8 +143,9 @@ export class ListenerLayer extends ProfileLayer {
* @returns Observable stream of messages
*/
public async onMessage(fn: (message: Message) => void) {
this.listenerEmitter.on(ExposedFn.OnMessage, fn);

this.listenerEmitter.on(ExposedFn.OnMessage, (state: Message) => {
fn(state);
});
return {
dispose: () => {
this.listenerEmitter.off(ExposedFn.OnMessage, fn);
Expand All @@ -153,8 +159,9 @@ export class ListenerLayer extends ProfileLayer {
* @fires Message
*/
public async onAnyMessage(fn: (message: Message) => void) {
this.listenerEmitter.on(ExposedFn.OnAnyMessage, fn);

this.listenerEmitter.on(ExposedFn.OnAnyMessage, (state: Message) => {
fn(state);
});
return {
dispose: () => {
this.listenerEmitter.off(ExposedFn.OnAnyMessage, fn);
Expand All @@ -163,19 +170,34 @@ export class ListenerLayer extends ProfileLayer {
}

/**
* @event Listens to messages received
* @returns Observable stream of messages
* @event Listens List of mobile states
* @returns Observable status flow
*/
public async onStateChange(fn: (state: SocketState) => void) {
this.listenerEmitter.on(ExposedFn.onStateChange, fn);

this.listenerEmitter.on(ExposedFn.onStateChange, (state: SocketState) => {
fn(state);
});
return {
dispose: () => {
this.listenerEmitter.off(ExposedFn.onStateChange, fn);
},
};
}

/**
* @returns Returns the current state of the connection
*/
public async onStreamChange(fn: (state: SocketStream) => void) {
this.listenerEmitter.on(ExposedFn.onStreamChange, (state: SocketStream) => {
fn(state);
});
return {
dispose: () => {
this.listenerEmitter.off(ExposedFn.onStreamChange, fn);
},
};
}

/**
* @event Listens to interface mode change See {@link InterfaceState} and {@link InterfaceMode} for details
* @returns A disposable object to cancel the event
Expand All @@ -184,7 +206,6 @@ export class ListenerLayer extends ProfileLayer {
fn: (state: { displayInfo: InterfaceState; mode: InterfaceMode }) => void
) {
this.listenerEmitter.on(ExposedFn.onInterfaceChange, fn);

return {
dispose: () => {
this.listenerEmitter.off(ExposedFn.onInterfaceChange, fn);
Expand All @@ -197,8 +218,9 @@ export class ListenerLayer extends ProfileLayer {
* @returns Observable stream of messages
*/
public async onAck(fn: (ack: Ack) => void) {
this.listenerEmitter.on(ExposedFn.onAck, fn);

this.listenerEmitter.on(ExposedFn.onAck, (state: Ack) => {
fn(state);
});
return {
dispose: () => {
this.listenerEmitter.off(ExposedFn.onAck, fn);
Expand Down Expand Up @@ -266,8 +288,9 @@ export class ListenerLayer extends ProfileLayer {
* @returns Observable stream of Chats
*/
public async onAddedToGroup(fn: (chat: Chat) => any) {
this.listenerEmitter.on('onAddedToGroup', fn);

this.listenerEmitter.on('onAddedToGroup', (state: Chat) => {
fn(state);
});
return {
dispose: () => {
this.listenerEmitter.off('onAddedToGroup', fn);
Expand All @@ -280,8 +303,9 @@ export class ListenerLayer extends ProfileLayer {
* @returns Observable stream of messages
*/
public async onIncomingCall(fn: (call: any) => any) {
this.listenerEmitter.on('onIncomingCall', fn);

this.listenerEmitter.on('onIncomingCall', (state: any) => {
fn(state);
});
return {
dispose: () => {
this.listenerEmitter.off('onIncomingCall', fn);
Expand Down
2 changes: 1 addition & 1 deletion src/api/model/enum/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export { AckType } from './ack-type';
export { ChatState } from './chat-state';
export { GroupChangeEvent } from './group-change-event';
export { GroupNotificationType } from './group-notification-type';
export { SocketState } from './socket-state';
export { SocketState, SocketStream } from './socket-state';
export { MessageType, MediaType } from './message-type';
export * from './interface-mode';
export * from './interface-state';
5 changes: 3 additions & 2 deletions src/api/model/enum/socket-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNMMNNNMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
*/
export enum SocketState {
// for state
CONFLICT = 'CONFLICT',
CONNECTED = 'CONNECTED',
DEPRECATED_VERSION = 'DEPRECATED_VERSION',
Expand All @@ -66,7 +65,9 @@ export enum SocketState {
UNLAUNCHED = 'UNLAUNCHED',
UNPAIRED = 'UNPAIRED',
UNPAIRED_IDLE = 'UNPAIRED_IDLE',
// for stream
}
export enum SocketStream {
CONNECTED = 'CONNECTED',
DISCONNECTED = 'DISCONNECTED',
RESUMING = 'RESUMING',
SYNCING = 'SYNCING',
Expand Down
66 changes: 40 additions & 26 deletions src/controllers/initializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ export async function create(
options?: CreateConfig,
browserSessionToken?: tokenSession
): Promise<Whatsapp>;

export async function create(
sessionOrOption: string | CreateOptions,
catchQR?: CatchQR,
Expand Down Expand Up @@ -240,35 +241,48 @@ export async function create(
});
}

if (mergedOptions.waitForLogin) {
const isLogged = await client.waitForLogin(catchQR, statusFind);
if (!isLogged) {
throw 'Not Logged';
}
let LocalLogin = JSON.parse(
await waPage.evaluate(() => {
return JSON.stringify(window.localStorage);
})
);

let waitLoginPromise = null;
client.onStateChange(async (state) => {
if (
state === SocketState.UNPAIRED ||
state === SocketState.UNPAIRED_IDLE
) {
logger.info('Session Unpaired', { session });
if (statusFind) {
statusFind('desconnectedMobile', session);
}
deleteFiles(mergedOptions, session, logger);
let CheckLogin =
LocalLogin.WASecretBundle && LocalLogin.WAToken1 && LocalLogin.WAToken2
? true
: false;

if (!waitLoginPromise) {
waitLoginPromise = client
.waitForLogin(catchQR, statusFind)
.catch(() => {})
.finally(() => {
waitLoginPromise = null;
});
}
await waitLoginPromise;
if (!CheckLogin) {
if (mergedOptions.waitForLogin) {
const isLogged = await client.waitForLogin(catchQR, statusFind);
if (!isLogged) {
throw 'Not Logged';
}
});

let waitLoginPromise = null;
client.onStateChange(async (state) => {
if (
state === SocketState.UNPAIRED ||
state === SocketState.UNPAIRED_IDLE
) {
logger.info('Session Unpaired', { session });
if (statusFind) {
statusFind('desconnectedMobile', session);
}
deleteFiles(mergedOptions, session, logger);

if (!waitLoginPromise) {
waitLoginPromise = client
.waitForLogin(catchQR, statusFind)
.catch(() => {})
.finally(() => {
waitLoginPromise = null;
});
}
await waitLoginPromise;
}
});
}
}

if (mergedOptions.debug) {
Expand Down
9 changes: 1 addition & 8 deletions src/controllers/welcome.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,14 @@ export function welcomeScreen() {
}
welcomeShown = true;
logger.info(`
▐█ ██ █░▐█▀▀▀░▐█ ▄█▀▀█▄ ▄█▀▀█▄ ▐██ ██▌ ▓█▀▀▀░
█▌▐██▄▓█ ▐█▄▄▄ ▐█ ▐█ █▒ ▐█▄▐█▀▌ ▐▌█▌ ▓█▄▄▄
▐██ ▐██░ ▐█ ▐█ ▐█▄ ▄▀ █▌ ▐█ ▐█ █▓█ █▌ ██
▀▀ ▀▀ ▀▀▀▀▀░▐▀▀▀▀▀ ▀▀▀▀ ▀▀▀▀ ▐▀ ▀ ▀▀ ▀▀▀▀▀
▄▄░ ▄ ▄▄▄▄▄▄▄▄▄▄▄▄▄ ██ ▄▄ ▄▄▄▄ ░
░██▄ ██ ███▀▀▀▀▀▀▀▀█▌ ███▌ ██▄ ▄▄█▀▀▀▀▀▀█▄ ▓█▄ ▄█░
░██▄ ░██▀ ███ ██▀██▄ ██▄ ▄█░ ▀█▄ ▓███▄ ░████░
██▌ ▄██░ ▄███▄▄▄▄ ██ ▓██▄ ██▄▐█ ▐█ ▓█▌▀██▄ ▄███░██░
██▌ ▄██░ ▀███▀▀▀▀ ██ ▐██▌ ██▄▐█ ▐█░▓█▌ ▀█████░ ██░
▓████ ███ ██ ▀██▄██▄ █▌ ██ ▓█▌ ▀█░ ██░
▀██ ███ █▌ ██ ▀███▄ ▀█▄ ▄▄█▀ ▓█▌ ██░
▀ ▀███████████▌ ██ ░██▄ ▀▀███▀▀░ ▀█▌ ▓█░
▀░ \n`);
▀ ▀███████████▌ ██ ░██▄ ▀▀███▀▀░ ▀█▌ ▓█░`);
}

export async function checkUpdates() {
Expand Down
19 changes: 18 additions & 1 deletion src/lib/wapi/listeners/add-on-state-change.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM

export function addOnStateChange() {
let initialized = false;
const getData = () => {
let getData = () => {
return window.Store.State.default.state;
};

Expand All @@ -70,3 +70,20 @@ export function addOnStateChange() {
return true;
};
}

export function addOnStreamChange() {
let initialized = false;
let getData = () => {
return window.Store.State.default.stream;
};
window.WAPI.onStreamChange = function (callback) {
window.WAPI.waitForStore('State', () => {
window.Store.State.default.on('change:stream', () => callback(getData()));
if (!initialized) {
initialized = true;
callback(getData());
}
});
return true;
};
}
2 changes: 1 addition & 1 deletion src/lib/wapi/listeners/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
export { initNewMessagesListener } from './init-listeners';
export { addNewMessagesListener } from './add-new-messages';
export { allNewMessagesListener } from './add-all-new-messages';
export { addOnStateChange } from './add-on-state-change';
export { addOnStateChange, addOnStreamChange } from './add-on-state-change';
export { addOnNewAcks } from './add-on-new-ack';
export { addOnLiveLocation } from './add-on-live-location';
export { addOnParticipantsChange } from './add-on-participants-change';
Expand Down
2 changes: 2 additions & 0 deletions src/lib/wapi/wapi.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ import {
addOnNewAcks,
addOnParticipantsChange,
addOnStateChange,
addOnStreamChange,
allNewMessagesListener,
initNewMessagesListener,
} from './listeners';
Expand Down Expand Up @@ -586,6 +587,7 @@ if (typeof window.WAPI === 'undefined') {
return await all;
};

addOnStreamChange();
addOnStateChange();
initNewMessagesListener();
addNewMessagesListener();
Expand Down
1 change: 1 addition & 0 deletions src/types/WAPI.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ interface WAPI {
onLiveLocation: (chatId: string, callback: Function) => any;
onParticipantsChanged: (groupId: string, callback: Function) => any;
onStateChange: (callback: Function) => void;
onStreamChange: (callback: Function) => void;
openChat: (chatId: string) => boolean;
openChatAt: (
chatId: string,
Expand Down

1 comment on commit 1236dbb

@jonalan7
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.