Skip to content

Commit

Permalink
Better wapi refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
danielcardeenas committed Apr 2, 2020
1 parent 7cd314a commit 9b0700d
Show file tree
Hide file tree
Showing 39 changed files with 2,336 additions and 625 deletions.
1 change: 0 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@
**/*.js
5 changes: 4 additions & 1 deletion src/controllers/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ async function initBrowser(session: string) {
// headless: true,
headless: false,
devtools: false,
userDataDir: path.join(process.cwd(), session),
userDataDir: path.join(
process.cwd(),
`session${session ? '-' + session : ''}`
),
args: [...puppeteerConfig.chroniumArgs],
});
return browser;
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/initializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const spinner = ora();
/**
* Should be called to initialize whatsapp client
*/
export async function create(session = 'session') {
export async function create(session?: string) {
spinner.start('Initializing whatsapp');
let waPage = await initWhatsapp(session);
spinner.succeed();
Expand Down
6 changes: 3 additions & 3 deletions src/lib/wapi/functions/create-group.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
* @param {string} name Group name
* @param {string[]} contactsId Contacts ids
*/
export function createGroup(name, contactsId) {
export async function createGroup(name, contactsId) {
if (!Array.isArray(contactsId)) {
contactsId = [contactsId];
}

return window.Store.Wap.createGroup(name, contactsId);
};
return await window.Store.WapQuery.createGroup(name, contactsId);
}
6 changes: 4 additions & 2 deletions src/lib/wapi/functions/get-all-chats-ids.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
* @param done Callback (optional)
* @returns {string[]} List of chat id's
*/
export const getAllChatIds = function(done) {
const chatIds = window.Store.Chat.map(chat => chat.id._serialized || chat.id);
export const getAllChatIds = function (done) {
const chatIds = window.Store.Chat.map(
(chat) => chat.id._serialized || chat.id
);

if (done !== undefined) done(chatIds);
return chatIds;
Expand Down
17 changes: 17 additions & 0 deletions src/lib/wapi/functions/get-all-chats-with-messages.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* Retrieves chats with messages
* @param {boolean} newOnly boolean
* @param {Function} done callback
*/
export async function getAllChatsWithMessages(newOnly, done) {
const x = [];
if (newOnly) {
x.push(
WAPI.getAllChatsWithNewMsg().map((c) => WAPI.getChat(c.id._serialized))
);
} else {
x.push(WAPI.getAllChatIds().map((c) => WAPI.getChat(c)));
}
const result = (await Promise.all(x)).flatMap((x) => x);
return JSON.stringify(result);
}
6 changes: 3 additions & 3 deletions src/lib/wapi/functions/get-all-chats.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
* @param done Callback (optional)
* @returns {Chat[]} Array of chat objects
*/
export const getAllChats = function(done) {
const chats = window.Store.Chat.map(chat => WAPI._serializeChatObj(chat));
export const getAllChats = function (done) {
const chats = window.Store.Chat.map((chat) => WAPI._serializeChatObj(chat));

if (done !== undefined) done(chats);
return chats;
};
};
4 changes: 2 additions & 2 deletions src/lib/wapi/functions/get-all-contacts.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
* @param {Function} done Callback function (optional)
* * @returns {Array} List of contacts
*/
export const getAllContacts = function(done) {
const contacts = window.Store.Contact.map(contact =>
export const getAllContacts = function (done) {
const contacts = window.Store.Contact.map((contact) =>
WAPI._serializeContactObj(contact)
);

Expand Down
11 changes: 11 additions & 0 deletions src/lib/wapi/functions/get-all-groups.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/**
* Retrieves all groups
* @param {Function} done callback
* @returns {Array} List of chats
*/
export function getAllGroups(done) {
const groups = window.Store.Chat.filter((chat) => chat.isGroup);

if (done !== undefined) done(groups);
return groups;
}
8 changes: 4 additions & 4 deletions src/lib/wapi/functions/get-all-new-messages.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { getAllChatsWithNewMessages } from "./get-chats-with-new-messages";
import { getAllChatsWithNewMessages } from './get-chats-with-new-messages';

/**
* Retrieves all new messages
* TODO: Test, seems to be written incorrectly
*/
export const getAllNewMessages = function() {
export const getAllNewMessages = function () {
return JSON.stringify(
getAllChatsWithNewMessages()
.map(c => WAPI.getChat(c.id._serialized))
.map(c => c.msgs._models.filter(x => x.isNewMsg)) || []
.map((c) => WAPI.getChat(c.id._serialized))
.map((c) => c.msgs._models.filter((x) => x.isNewMsg)) || []
);
};
15 changes: 15 additions & 0 deletions src/lib/wapi/functions/get-all-unread-messages.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { getAllChatsWithNewMessages } from './get-chats-with-new-messages';

/**
* Retrieves undread messages
* x.ack === -1
* TODO: Test this fn, seems incorrect, should not be async
*/
export const getAllUnreadMessages = async function () {
return JSON.stringify(
getAllChatsWithNewMessages()
.map((c) => WAPI.getChat(c.id._serialized))
.map((c) => c.msgs._models.filter((x) => x.ack === -1))
.flatMap((x) => x) || []
);
};
16 changes: 16 additions & 0 deletions src/lib/wapi/functions/get-chat-by-id.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* Retrieves a chat by given id
* @param {string} id
* @param {Function} done optional callback
*/
export function getChatById(id, done) {
let found = WAPI.getChat(id);
if (found) {
found = WAPI._serializeChatObj(found);
} else {
found = false;
}

if (done !== undefined) done(found);
return found;
}
10 changes: 10 additions & 0 deletions src/lib/wapi/functions/get-chat-by-name.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* Retrieves chat by its name
* @param {string} name Chat name
* @param {Function} done callback
*/
export function getChatByName(name, done) {
const found = window.Store.Chat.find((chat) => chat.name === name);
if (done !== undefined) done(found);
return found;
}
18 changes: 18 additions & 0 deletions src/lib/wapi/functions/get-chat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* Retrieves chat by its id
* @param {*} id Id of the chat
* @param {*} done Callback
* @returns {Chat} object
*/
export function getChat(id, done) {
id = typeof id == 'string' ? id : id._serialized;
const found = window.Store.Chat.get(id);
if (found)
found.sendMessage = found.sendMessage
? found.sendMessage
: function () {
return window.Store.sendMessage.apply(this, arguments);
};
if (done !== undefined) done(found);
return found;
}
8 changes: 4 additions & 4 deletions src/lib/wapi/functions/get-chats-with-new-messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ import { hasUndreadMessages } from './has-unread-messages';

/**
* Retrieves chats with undread/new messages
* @param {*} done
* @param {*} done
* @returns {Chat[]} chat list
*/
export const getAllChatsWithNewMessages = function(done) {
const chats = window.Store.Chat.filter(hasUndreadMessages).map(chat =>
export const getAllChatsWithNewMessages = function (done) {
const chats = window.Store.Chat.filter(hasUndreadMessages).map((chat) =>
WAPI._serializeChatObj(chat)
);

if (done !== undefined) done(chats);
return chats;
};
};
4 changes: 2 additions & 2 deletions src/lib/wapi/functions/get-contact.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
* @param {Function} done Callback (optional)
* @returns {Contact} contact object
*/
export const getContact = function(id, done) {
export const getContact = function (id, done) {
const found = window.Store.Contact.get(id);

if (done !== undefined) done(window.WAPI._serializeContactObj(found));
return window.WAPI._serializeContactObj(found);
};
};
10 changes: 10 additions & 0 deletions src/lib/wapi/functions/get-group-invite-link.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* Generates group invite link
* @param {string} chatId
*/
export async function getGroupInviteLink(chatId) {
var chat = Store.Chat.get(chatId);
if (!chat.isGroup) return false;
await Store.GroupInvite.queryGroupInviteCode(chat);
return `https://chat.whatsapp.com/${chat.inviteCode}`;
}
6 changes: 3 additions & 3 deletions src/lib/wapi/functions/get-my-contacts.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
* @param {Function} done Callback function (optional)
* @returns {Array} List of contacts
*/
export const getMyContacts = function(done) {
export const getMyContacts = function (done) {
const contacts = window.Store.Contact.filter(
contact => contact.isMyContact === true
).map(contact => WAPI._serializeContactObj(contact));
(contact) => contact.isMyContact === true
).map((contact) => WAPI._serializeContactObj(contact));
if (done !== undefined) done(contacts);
return contacts;
};
9 changes: 9 additions & 0 deletions src/lib/wapi/functions/get-new-id.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export function getNewId() {
var text = '';
var possible =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

for (var i = 0; i < 20; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
9 changes: 9 additions & 0 deletions src/lib/wapi/functions/get-status.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* Retrieves satus
* @param {string} to '[email protected]'
*
* TODO: Test this function
*/
export async function getStatus(id) {
return await Store.MyStatus.getStatus(id);
}
54 changes: 54 additions & 0 deletions src/lib/wapi/functions/get-unread-messages-in-chat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/**
* Retrieves unread messages from chat and mark them as read as a regular UX
* @param {string} id Chat id
* @param {boolean} includeMe Include user client messages
* @param {boolean} includeNotifications Include notifications
* @param {Function} done
*/
export function getUnreadMessagesInChat(
id,
includeMe,
includeNotifications,
done
) {
// get chat and its messages
let chat = WAPI.getChat(id);
let messages = chat.msgs._models;

// initialize result list
let output = [];

// look for unread messages, newest is at the end of array
for (let i = messages.length - 1; i >= 0; i--) {
// system message: skip it
if (i === 'remove') {
continue;
}

// get message
let messageObj = messages[i];

// found a read message: stop looking for others
if (
typeof messageObj.isNewMsg !== 'boolean' ||
messageObj.isNewMsg === false
) {
continue;
} else {
messageObj.isNewMsg = false;
// process it
let message = WAPI.processMessageObj(
messageObj,
includeMe,
includeNotifications
);

// save processed message on result list
if (message) output.push(message);
}
}
// callback was passed: run it
if (done !== undefined) done(output);
// return result list
return output;
}
35 changes: 27 additions & 8 deletions src/lib/wapi/functions/index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,31 @@
export { sendMessage } from './send-message';
export { sendMessage2 } from './send-message2';
export { createGroup } from './create-group';
export { leaveGroup } from './leave-group';
export { getAllChats } from './get-all-chats';
export { getAllChatIds } from './get-all-chats-ids';
export { getAllContacts } from './get-all-contacts';
export { getMyContacts } from './get-my-contacts';
export { getAllNewMessages } from './get-all-new-messages';
export { getAllUnreadMessages } from './get-all-unread-messages';
export { getAllChatsWithNewMessages } from './get-chats-with-new-messages';
export { getContact } from './get-contact';
export { getAllChats } from './get-all-chats';
export { getMyContacts } from './get-my-contacts';
export { hasUndreadMessages } from './has-unread-messages';
export { getAllChatsWithNewMessages } from './get-chats-with-new-messages';
export { getAllChatIds } from './get-all-chats-ids';
export { getAllNewMessages } from './get-all-new-messages';
export { leaveGroup } from './leave-group';
export { sendMessage } from './send-message';
export { sendMessage2 } from './send-message2';
export { getAllChatsWithMessages } from './get-all-chats-with-messages';
export { getAllGroups } from './get-all-groups';
export { sendChatstate } from './send-chat-state';
export { getChat } from './get-chat';
export { getStatus } from './get-status';
export { getChatByName } from './get-chat-by-name';
export { sendMessageWithThumb } from './send-message-with-thumb';
export { getGroupInviteLink } from './get-group-invite-link';
export { getNewId } from './get-new-id';
export { getChatById } from './get-chat-by-id';
export { getUnreadMessagesInChat } from './get-unread-messages-in-chat';
export { processMessageObj } from './process-message-object';
export { loadChatEarlierMessages } from './load-earlier-chat-messages';
export {
loadAllEarlierMessages,
asyncLoadAllEarlierMessages,
} from './load-all-earlier-chat-messages';
export { isLoggedIn } from './is-logged-in';
12 changes: 12 additions & 0 deletions src/lib/wapi/functions/is-logged-in.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* @param {Function} done Optional callback
* @returns {boolean} true if logged in, false otherwise
*/
export function isLoggedIn(done) {
// Contact always exists when logged in
const isLogged =
window.Store.Contact && window.Store.Contact.checksum !== undefined;

if (done !== undefined) done(isLogged);
return isLogged;
}
9 changes: 5 additions & 4 deletions src/lib/wapi/functions/leave-group.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
/**
* Leaves group
* @param {string} groupId The group id
* @returns Promise
*/
export function leaveGroup(groupId) {
groupId = typeof groupId == "string" ? groupId : groupId._serialized;
export async function leaveGroup(groupId) {
groupId = typeof groupId == 'string' ? groupId : groupId._serialized;
var group = WAPI.getChat(groupId);
return group.sendExit();
};
return Store.GroupActions.sendExitGroup(group);
}
Loading

0 comments on commit 9b0700d

Please sign in to comment.