Skip to content

Commit

Permalink
Add more modular functions to wapi
Browse files Browse the repository at this point in the history
  • Loading branch information
danielcardeenas committed Apr 3, 2020
1 parent 6ee66e1 commit bf7e60b
Show file tree
Hide file tree
Showing 14 changed files with 208 additions and 229 deletions.
Binary file added cv_en.pdf
Binary file not shown.
2 changes: 1 addition & 1 deletion src/api/functions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ export { getConnectionState } from './get-connection-state';
export { sendTextWithTags } from './send-text-with-tags';
export { sendMessageWithThumb } from './send-message-with-thumb';
export { reply } from './reply';
export { sendFile, sendFileFromPath } from './send-file';
export { sendFile, sendFileFromBase64 } from './send-file';
8 changes: 4 additions & 4 deletions src/api/functions/send-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ declare module WAPI {
*/
export async function sendFile(
to: string,
base64: string,
path: string,
filename: string,
caption?: string
) {
const base64 = await fileToBase64(path);
return await this.page.evaluate(
({ to, base64, filename, caption }) => {
WAPI.sendFile(base64, to, filename, caption);
Expand All @@ -37,13 +38,12 @@ export async function sendFile(
* @param filename
* @param caption
*/
export async function sendFileFromPath(
export async function sendFileFromBase64(
to: string,
path: string,
base64: string,
filename: string,
caption?: string
) {
const base64 = await fileToBase64(path);
return await this.page.evaluate(
({ to, base64, filename, caption }) => {
WAPI.sendFile(base64, to, filename, caption);
Expand Down
40 changes: 40 additions & 0 deletions src/api/model/host-device.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
export interface HostDevice {
id: string;
ref: string;
refTTL: number;
wid: Me;
connected: boolean;
me: Me;
protoVersion: number[];
clientToken: string;
serverToken: string;
isResponse: string;
battery: number;
plugged: boolean;
lc: string;
lg: string;
locales: string;
is24h: boolean;
platform: string;
phone: Phone;
tos: number;
smbTos: number;
pushname: string;
blockStoreAdds: boolean;
}

export interface Me {
server: string;
user: string;
_serialized: string;
}

export interface Phone {
wa_version: string;
mcc: string;
mnc: string;
os_version: string;
device_manufacturer: string;
device_model: string;
os_build_number: string;
}
1 change: 1 addition & 0 deletions src/api/model/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ export { ParticipantEvent } from './participant-event';
export { PartialMessage } from './partial-message';
export { Ack } from './ack';
export { AckType } from './enum/ack-type';
export { HostDevice } from './host-device';
57 changes: 20 additions & 37 deletions src/api/whatsapp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
setChatState,
setProfileName,
setProfileStatus,
sendFileFromPath,
sendFileFromBase64,
} from './functions';
import { sendText } from './functions/send-text';
import { base64MimeType } from './helpers';
Expand All @@ -22,6 +22,7 @@ import {
Id,
PartialMessage,
ParticipantEvent,
HostDevice,
} from './model';
import { SocketState } from './model/enum/socket-state';
import { LiveLocation } from './model/live-location';
Expand Down Expand Up @@ -59,12 +60,6 @@ declare module WAPI {
const deleteConversation: (chatId: string) => boolean;
const clearChat: (chatId: string) => void;
const getGroupInviteLink: (chatId: string) => Promise<string> | boolean;
const sendImage: (
base64: string,
to: string,
filename: string,
caption: string
) => void;
const getBusinessProfilesProducts: (to: string) => any;
const sendImageWithProduct: (
base64: string,
Expand All @@ -73,12 +68,6 @@ declare module WAPI {
bizNumber: string,
productId: string
) => any;
const sendFile: (
base64: string,
to: string,
filename: string,
caption: string
) => void;
const sendVideoAsGif: (
base64: string,
to: string,
Expand All @@ -87,8 +76,7 @@ declare module WAPI {
) => void;
const getAllContacts: () => Contact[];
const getWAVersion: () => String;
const getMe: () => any;
const getHost: () => any;
const getHost: () => HostDevice;
const getAllUnreadMessages: () => PartialMessage[];
const getAllChatsWithMessages: (withNewMessageOnly?: boolean) => any;
const getAllChats: () => Chat[];
Expand All @@ -110,7 +98,8 @@ declare module WAPI {
onlyLocal: boolean
) => any;
const sendContact: (to: string, contact: string | string[]) => any;
const simulateTyping: (to: string, on: boolean) => void;
const startTyping: (to: string) => void;
const stopTyping: (to: string) => void;
const isConnected: () => Boolean;
const loadEarlierMessages: (contactId: string) => Message[];
const loadAllEarlierMessages: (contactId: string) => void;
Expand Down Expand Up @@ -340,7 +329,7 @@ export class Whatsapp {
* @param filename
* @param caption
*/
public sendFile = sendFile;
public sendFileFromBase64 = sendFileFromBase64;

/**
* Sends file from path
Expand All @@ -349,7 +338,7 @@ export class Whatsapp {
* @param filename
* @param caption
*/
public sendFileFromPath = sendFileFromPath;
public sendFile = sendFile;

/**
* Sends a video to given chat as a gif, with caption or not, using base64
Expand All @@ -375,17 +364,7 @@ export class Whatsapp {
/**
* Returns an object with all of your host device details
*/
public async getMe() {
return await this.page.evaluate(() =>
//@ts-ignore
window.Store.Contact.get(window.Store.Conn.me)
);
}

/**
* Returns an object with all of your host device details
*/
public async getHost() {
public async getHostDevice() {
return await this.page.evaluate(() => WAPI.getHost());
}

Expand Down Expand Up @@ -443,15 +422,19 @@ export class Whatsapp {
}

/**
* Simulate '...typing' in chat
* @param {string} to '[email protected]'
* @param {boolean} on turn on similated typing, false to turn it off you need to manually turn this off.
* Simulates '...typing' state
* @param {string} to Chat id
*/
public async simulateTyping(to: string, on: boolean) {
return await this.page.evaluate(
({ to, on }) => WAPI.simulateTyping(to, on),
{ to, on }
);
public async startTyping(to: string) {
return await this.page.evaluate(({ to }) => WAPI.startTyping(to), { to });
}

/**
* Stops typing
* @param to Chat id
*/
public async stopTyping(to: string) {
return await this.page.evaluate(({ to }) => WAPI.stopTyping(to), { to });
}

/**
Expand Down
10 changes: 5 additions & 5 deletions src/lib/wapi/functions/encrypt-and-upload-file.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import { generateMediaKey, getFileHash } from '../helper';
* @param {Blob} blob
*/
export async function encryptAndUploadFile(type, blob) {
let filehash = await getFileHash(blob);
let mediaKey = generateMediaKey(32);
let controller = new AbortController();
let signal = controller.signal;
let encrypted = await window.Store.UploadUtils.encryptAndUpload({
const filehash = await getFileHash(blob);
const mediaKey = generateMediaKey(32);
const controller = new AbortController();
const signal = controller.signal;
const encrypted = await window.Store.UploadUtils.encryptAndUpload({
blob,
type,
signal,
Expand Down
24 changes: 24 additions & 0 deletions src/lib/wapi/functions/forward-messages.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Forwards array of messages (could be ids or message objects)
* @param {string} to Chat id
* @param {string[] | Message[]} messages Array of messages to be forwarded
* @param {boolean} skipMyMessages
*/
export async function forwardMessages(to, messages, skipMyMessages) {
if (!Array.isArray(messages)) {
messages = [messages];
}
const toForward = messages
.map((msg) => {
if (typeof msg === 'string') {
return window.Store.Msg.get(msg);
} else {
return window.Store.Msg.get(msg.id);
}
})
.filter((msg) => (skipMyMessages ? !msg.__x_isSentByMe : true));

// const userId = new window.Store.UserConstructor(to);
const conversation = window.Store.Chat.get(to);
return conversation.forwardMessages(toForward);
}
15 changes: 15 additions & 0 deletions src/lib/wapi/functions/get-new-message-id.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* Generates new message id based on given chat
* @param {*} chatId Chat id
*/
export function getNewMessageId(chatId) {
const newMsgId = new Store.MsgKey(
Object.assign({}, Store.Msg.models[0].__x_id)
);

newMsgId.fromMe = true;
newMsgId.id = WAPI.getNewId().toUpperCase();
newMsgId.remote = chatId;
newMsgId._serialized = `${newMsgId.fromMe}_${newMsgId.remote}_${newMsgId.id}`;
return newMsgId;
}
5 changes: 5 additions & 0 deletions src/lib/wapi/functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,8 @@ export { sendSticker } from './send-sticker';
export { sendVideoAsGif } from './send-video-as-gif';
export { setMyName } from './set-my-name';
export { setMyStatus } from './set-my-status';
export { forwardMessages } from './forward-messages';
export { sendContact } from './send-contact';
export { getNewMessageId } from './get-new-message-id';
export { reply } from './reply';
export { startTyping, stopTyping } from './simulate-typing';
37 changes: 37 additions & 0 deletions src/lib/wapi/functions/reply.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { getNewMessageId } from './get-new-message-id';

/**
* Replys to message of given chat id
* @param {string} chatId
* @param {string} body
* @param {string | Message} quotedMsg Message id or message object
*/
export async function reply(chatId, body, quotedMsg) {
if (typeof quotedMsg !== 'object') {
quotedMsg = Store.Msg.get(quotedMsg);
}

const chat = Store.Chat.get(chatId);
const extras = {
quotedParticipant: quotedMsg.author || quotedMsg.from,
quotedStanzaID: quotedMsg.id.id,
};

let tempMsg = Object.create(chat.msgs.filter((msg) => msg.__x_isSentByMe)[0]);
const newId = getNewMessageId(chatId);
const extend = {
ack: 0,
id: newId,
local: !0,
self: 'out',
t: parseInt(new Date().getTime() / 1000),
to: chatId,
isNewMsg: !0,
type: 'chat',
quotedMsg,
body,
...extras,
};
Object.assign(tempMsg, extend);
await Store.addAndSendMsgToChat(chat, tempMsg);
}
20 changes: 20 additions & 0 deletions src/lib/wapi/functions/send-contact.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* Sends contact card to iven chat id
* @param {string} to Chat id
* @param {string | string[]} contact Example: [email protected] | [[email protected], [email protected]]
*/
export function sendContact(to, contact) {
if (!Array.isArray(contact)) {
contact = [contact];
}

contact = contact.map((c) => {
return WAPI.getChat(c).__x_contact;
});

if (contact.length > 1) {
window.WAPI.getChat(to).sendContactList(contact);
} else if (contact.length === 1) {
window.WAPI.getChat(to).sendContact(contact[0]);
}
}
15 changes: 15 additions & 0 deletions src/lib/wapi/functions/simulate-typing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* Starts typing
* @param {string} chatId
*/
export async function startTyping(chatId) {
await Store.ChatStates.sendChatStateComposing(chatId);
}

/**
* Stops typing
* @param {string} chatId
*/
export async function stopTyping(chatId) {
await Store.ChatStates.sendChatStatePaused(chatId);
}
Loading

0 comments on commit bf7e60b

Please sign in to comment.