mukulhase / WebWhatsapp-Wrapper

An API for sending and receiving messages over web.whatsapp [Working as of 18th May 2018]
https://webwhatsapi.readthedocs.io/en/latest/
MIT License
2.02k stars 796 forks source link

Uncaught ReferenceError: WAPI is not defined #1150

Open bhatpatil opened 2 years ago

bhatpatil commented 2 years ago

Getting error while sending text message Uncaught ReferenceError: WAPI is not defined

andlb commented 2 years ago

Are you using Whatsapp Web MD?

This wapi.js code is working.

/**

/**

window.WAPI = { lastRead: {} };

window.WAPI._serializeRawObj = (obj) => { if (obj) { return obj.toJSON(); } return {} };

/**

window.WAPI._serializeChatObj = (obj) => { if (obj == undefined) { return null; }

return Object.assign(window.WAPI._serializeRawObj(obj), {
    kind: obj.kind,
    isGroup: obj.isGroup,
    contact: obj['contact'] ? window.WAPI._serializeContactObj(obj['contact']) : null,
    groupMetadata: obj["groupMetadata"] ? window.WAPI._serializeRawObj(obj["groupMetadata"]) : null,
    presence: obj["presence"] ? window.WAPI._serializeRawObj(obj["presence"]) : null,
    msgs: null
});

};

window.WAPI._serializeContactObj = (obj) => { if (obj == undefined) { return null; }

return Object.assign(window.WAPI._serializeRawObj(obj), {
    formattedName: obj.formattedName,
    isHighLevelVerified: obj.isHighLevelVerified,
    isMe: obj.isMe,
    isMyContact: obj.isMyContact,
    isPSA: obj.isPSA,
    isUser: obj.isUser,
    isVerified: obj.isVerified,
    isWAContact: obj.isWAContact,
    profilePicThumbObj: obj.profilePicThumb ? WAPI._serializeProfilePicThumb(obj.profilePicThumb) : {},
    statusMute: obj.statusMute,
    msgs: null
});

};

window.WAPI._serializeMessageObj = (obj) => { if (obj == undefined) { return null; }

return Object.assign(window.WAPI._serializeRawObj(obj), {
    id: obj.id._serialized,
    sender: obj["senderObj"] ? WAPI._serializeContactObj(obj["senderObj"]) : null,
    timestamp: obj["t"],
    content: obj["body"],
    isGroupMsg: obj.isGroupMsg,
    isLink: obj.isLink,
    isMMS: obj.isMMS,
    isMedia: obj.isMedia,
    isNotification: obj.isNotification,
    isPSA: obj.isPSA,
    type: obj.type,
    chat: WAPI._serializeChatObj(obj['chat']),
    chatId: obj.id.remote,
    quotedMsgObj: WAPI._serializeMessageObj(obj['_quotedMsgObj']),
    mediaData: window.WAPI._serializeRawObj(obj['mediaData'])
});

};

window.WAPI._serializeNumberStatusObj = (obj) => { if (obj == undefined) { return null; }

return Object.assign({}, {
    id: obj.jid,
    status: obj.status,
    isBusiness: (obj.biz === true),
    canReceiveMessage: (obj.status === 200)
});

};

window.WAPI._serializeProfilePicThumb = (obj) => { if (obj == undefined) { return null; }

return Object.assign({}, {
    eurl: obj.eurl,
    id: obj.id,
    img: obj.img,
    imgFull: obj.imgFull,
    raw: obj.raw,
    tag: obj.tag
});

}

window.WAPI.createGroup = function (name, contactsId) { if (!Array.isArray(contactsId)) { contactsId = [contactsId]; }

return window.Store.Wap.createGroup(name, contactsId);

};

window.WAPI.leaveGroup = function (groupId) { groupId = typeof groupId == "string" ? groupId : groupId._serialized; var group = WAPI.getChat(groupId); return group.sendExit() };

window.WAPI.getAllContacts = function (done) { const contacts = window.Store.Contact.map((contact) => WAPI._serializeContactObj(contact));

if (done !== undefined) done(contacts);
return contacts;

};

/**

/**

/**

window.WAPI.haveNewMsg = function (chat) { return chat.unreadCount > 0; };

window.WAPI.getAllChatsWithNewMsg = function (done) { const chats = window.Store.Chat.filter(window.WAPI.haveNewMsg).map((chat) => WAPI._serializeChatObj(chat));

if (done !== undefined) done(chats);
return chats;

};

/**

/**

/**

window.WAPI.getChatByName = function (name, done) { const found = window.WAPI.getAllChats().find(val => val.name.includes(name)) if (done !== undefined) done(found); return found; };

window.WAPI.sendImageFromDatabasePicBot = function (picId, chatId, caption) { var chatDatabase = window.WAPI.getChatByName('DATABASEPICBOT'); var msgWithImg = chatDatabase.msgs.find((msg) => msg.caption == picId);

if (msgWithImg === undefined) {
    return false;
}

// Nova versão Beta
if (WAPI.isMultiDeviceVersion()) {
    WAPI.getChat(chatId, chatSend => {
        if (chatSend === undefined) {
            return false;
        }
        const oldCaption = msgWithImg.caption;

        msgWithImg.id.id = window.WAPI.getNewId();
        msgWithImg.id.remote = chatId;
        msgWithImg.t = Math.ceil(new Date().getTime() / 1000);
        msgWithImg.to = chatId;

        if (caption !== undefined && caption !== '') {
            msgWithImg.caption = caption;
        } else {
            msgWithImg.caption = '';
        }

        msgWithImg.collection.send(msgWithImg).then(function (e) {
            msgWithImg.caption = oldCaption;
        });

        return true;
    });
} else {
    // Versão antiga
    var chatSend = WAPI.getChat(chatId);
    if (chatSend === undefined) {
        return false;
    }
    const oldCaption = msgWithImg.caption;

    msgWithImg.id.id = window.WAPI.getNewId();
    msgWithImg.id.remote = chatId;
    msgWithImg.t = Math.ceil(new Date().getTime() / 1000);
    msgWithImg.to = chatId;

    if (caption !== undefined && caption !== '') {
        msgWithImg.caption = caption;
    } else {
        msgWithImg.caption = '';
    }

    msgWithImg.collection.send(msgWithImg).then(function (e) {
        msgWithImg.caption = oldCaption;
    });

    return true;
}

};

window.WAPI.sendMessageWithThumb = function (thumb, url, title, description, text, chatId, done) { var chatSend = WAPI.getChat(chatId); if (chatSend === undefined) { if (done !== undefined) done(false); return false; } var linkPreview = { canonicalUrl: url, description: description, matchedText: url, title: title, thumbnail: thumb, compose: true }; chatSend.sendMessage(text, { linkPreview: linkPreview, mentionedJidList: [], quotedMsg: null, quotedMsgAdminGroupJid: null }); if (done !== undefined) done(true); return true; };

window.WAPI.getNewId = function () { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

for (var i = 0; i < 20; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;

};

window.WAPI.getChatById = function (id, done) { let found = WAPI.getChat(id); if (found) { found = WAPI._serializeChatObj(found); } else { found = false; }

if (done !== undefined) done(found);
return found;

};

/**

/**

/**

window.WAPI.asyncLoadAllEarlierMessages = function (id, done) { done(); window.WAPI.loadAllEarlierMessages(id); };

window.WAPI.areAllMessagesLoaded = function (id, done) { const found = WAPI.getChat(id); if (!found.msgs.msgLoadState.noEarlierMsgs) { if (done) done(false); return false } if (done) done(true); return true };

/**

window.WAPI.loadEarlierMessagesTillDate = function (id, lastMessage, done) { const found = WAPI.getChat(id); x = function () { if (found.msgs.models[0].t > lastMessage && !found.msgs.msgLoadState.noEarlierMsgs) { found.loadEarlierMsgs().then(x); } else { done(); } }; x(); };

/**

/**

};

/**

/**

window.WAPI.getGroupAdmins = async function (id, done) { const output = (await WAPI._getGroupParticipants(id)) .filter((participant) => participant.isAdmin) .map((admin) => admin.id);

if (done !== undefined) done(output);
return output;

};

/**

window.WAPI.isLoggedIn = function (done) { // Contact always exists when logged in const isLogged = window.Store.Contact && window.Store.Contact.checksum !== undefined;

if (done !== undefined) done(isLogged);
return isLogged;

};

window.WAPI.isConnected = function (done) { // Phone Disconnected icon appears when phone is disconnected from the tnternet const isConnected = document.querySelector('*[data-icon="alert-phone"]') !== null ? false : true;

if (done !== undefined) done(isConnected);
return isConnected;

};

window.WAPI.processMessageObj = function (messageObj, includeMe, includeNotifications) { if (messageObj.isNotification) { if (includeNotifications) { ret = WAPI._serializeMessageObj(messageObj); delete ret.waveform delete ret.mediaData.waveform if (ret.quotedMsg && ret.quotedMsg.waveform) delete ret.quotedMsg.waveform return ret } else { return; } // System message // (i.e. "Messages you send to this chat and calls are now secured with end-to-end encryption...") } else if (messageObj.id.fromMe === false || includeMe) { ret = WAPI._serializeMessageObj(messageObj); delete ret.waveform delete ret.mediaData.waveform if (ret.quotedMsg && ret.quotedMsg.waveform) delete ret.quotedMsg.waveform return ret } return; };

window.WAPI.getAllMessagesInChat = function (id, includeMe, includeNotifications, done) { const chat = WAPI.getChat(id); let output = []; const messages = chat.msgs._models;

for (const i in messages) {
    if (i === "remove") {
        continue;
    }
    const messageObj = messages[i];

    let message = WAPI.processMessageObj(messageObj, includeMe, includeNotifications)
    if (message)
        output.push(message);
}
if (done !== undefined) done(output);
return output;

};

window.WAPI.getAllMessageIdsInChat = function (id, includeMe, includeNotifications, done) { const chat = WAPI.getChat(id); let output = []; const messages = chat.msgs._models;

for (const i in messages) {
    if ((i === "remove")
        || (!includeMe && messages[i].isMe)
        || (!includeNotifications && messages[i].isNotification)) {
        continue;
    }
    output.push(messages[i].id._serialized);
}
if (done !== undefined) done(output);
return output;

};

window.WAPI.getMessageById = function (id, done) { let result = false; try { let msg = window.Store.Msg.get(id); if (msg) { result = WAPI.processMessageObj(msg, true, true); } } catch (err) { }

if (done !== undefined) {
    done(result);
} else {
    return result;
}

};

window.WAPI.ReplyMessage = function (idMessage, message, done) { var messageObject = window.Store.Msg.get(idMessage); if (messageObject === undefined) { if (done !== undefined) done(false); return false; } messageObject = messageObject.value();

const chat = WAPI.getChat(messageObject.chat.id)
if (chat !== undefined) {
    if (done !== undefined) {
        chat.sendMessage(message, null, messageObject).then(function () {
            function sleep(ms) {
                return new Promise(resolve => setTimeout(resolve, ms));
            }

            var trials = 0;

            function check() {
                for (let i = chat.msgs.models.length - 1; i >= 0; i--) {
                    let msg = chat.msgs.models[i];

                    if (!msg.senderObj.isMe || msg.body != message) {
                        continue;
                    }
                    done(WAPI._serializeMessageObj(msg));
                    return True;
                }
                trials += 1;
                console.log(trials);
                if (trials > 30) {
                    done(true);
                    return;
                }
                sleep(500).then(check);
            }
            check();
        });
        return true;
    } else {
        chat.sendMessage(message, null, messageObject);
        return true;
    }
} else {
    if (done !== undefined) done(false);
    return false;
}

};

window.WAPI.sendMessageToID = function (id, message, done) {

try {
    // Nova versão do WhatsApp Beta
    if (WAPI.isMultiDeviceVersion()) {
        console.log('Fluxo para Multdevice: ' + id);
        WAPI.getChat(id, chat => {
            if (chat) {
                chat.sendMessage(message);
                console.log('Mensagem enviada!');
                done(true);
                return true;
            } else {
                console.log('Mensagem NÃO enviada!');
                done(false);
                return false;
            }
        });
    } else {
        // Versão antiga do WhatsApp  para um só navegador
        try {
            window.getContact = (id) => {
                return Store.WapQuery.queryExist(id);
                //          return Store.WapQuery.SendPing().queryExist(id);
            }
            window.getContact(id).then(contact => {
                if (contact.status === 404) {
                    done(true);
                } else {
                    Store.Chat.find(contact.jid).then(chat => {
                        chat.sendMessage(message);
                        done(true);
                        return true;
                    }).catch(reject => {
                        if (WAPI.sendMessage(id, message)) {
                            done(true);
                            return true;
                        } else {
                            done(false);
                            return false;
                        }
                    });
                }
            });
        } catch (e) {
            // Quando ainda não é um contato
            if (window.Store.Chat.length === 0) {
                done(false);
                return false;
            }

            firstChat = Store.Chat.models[0];
            var originalID = firstChat.id;
            firstChat.id = typeof originalID === "string" ? id : new window.Store.UserConstructor(id, { intentionallyUsePrivateConstructor: true });
            if (done !== undefined) {
                firstChat.sendMessage(message).then(function () {
                    firstChat.id = originalID;
                    done(true);
                });
                return true;
            } else {
                firstChat.sendMessage(message);
                firstChat.id = originalID;
                done(true);
                return true;
            }
        }
        // Fim do fluxo antigo
    }
} catch (e) {
    console.log('Erro ao enviar a mensagem: ' + e.message);
    done(false);
    return false;
}

//   try {
//       if (WAPI.isMultiDeviceVersion()) {
//         console.log('Fluxo para Multdevice: ' + id);
//         var chat = WAPI.getChat(id);
//         console.chat('Chat: ');
//         // console.log(chat);
//         // chat.sendMessage(message);
//         console.log('Mensagem enviada!');
//         done(true);
//         return true;
//       } else {
//         window.getContact = (id) => {
//             return Store.WapQuery.queryExist(id);
// //           return Store.WapQuery.SendPing().queryExist(id);
//         }
//         window.getContact(id).then(contact => {
//             if (contact.status === 404) {
//                 done(true);
//             } else {
//                 Store.Chat.find(contact.jid).then(chat => {
//                     chat.sendMessage(message);
//                     return true;
//                 }).catch(reject => {
//                     if (WAPI.sendMessage(id, message)) {
//                         done(true);
//                         return true;
//                     }else{
//                         done(false);
//                         return false;
//                     }
//                 });
//             }
//         });
//       }
//   } catch (e) {
//       console.log('Caiu no fluxo antigo');
//       if (window.Store.Chat.length === 0)
//           return false;

//       firstChat = Store.Chat.models[0];
//       var originalID = firstChat.id;
//       firstChat.id = typeof originalID === "string" ? id : new window.Store.UserConstructor(id, { intentionallyUsePrivateConstructor: true });
//       if (done !== undefined) {
//           firstChat.sendMessage(message).then(function () {
//               firstChat.id = originalID;
//               done(true);
//           });
//           return true;
//       } else {
//           firstChat.sendMessage(message);
//           firstChat.id = originalID;
//           return true;
//       }
//   }
//   if (done !== undefined) done(false);
//   return false;

}

window.WAPI.sendMessage = function (id, message, done) { var chat = WAPI.getChat(id); if (chat !== undefined) { if (done !== undefined) { chat.sendMessage(message).then(function () { function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }

            var trials = 0;

            function check() {
                for (let i = chat.msgs.models.length - 1; i >= 0; i--) {
                    let msg = chat.msgs.models[i];

                    if (!msg.senderObj.isMe || msg.body != message) {
                        continue;
                    }
                    done(WAPI._serializeMessageObj(msg));
                    return True;
                }
                trials += 1;
                console.log(trials);
                if (trials > 30) {
                    done(true);
                    return;
                }
                sleep(500).then(check);
            }
            check();
        });
        return true;
    } else {
        chat.sendMessage(message);
        return true;
    }
} else {
    if (done !== undefined) done(false);
    return false;
}

};

window.WAPI.sendMessage2 = function (id, message, done) { var chat = WAPI.getChat(id); if (chat !== undefined) { try { if (done !== undefined) { chat.sendMessage(message).then(function () { done(true); }); } else { chat.sendMessage(message); } return true; } catch (error) { if (done !== undefined) done(false) return false; } } if (done !== undefined) done(false) return false; };

window.WAPI.sendSeen = function (id, done) { var chat = window.WAPI.getChat(id); if (chat !== undefined) { if (done !== undefined) { if (chat.getLastMsgKeyForAction === undefined) chat.getLastMsgKeyForAction = function () { }; Store.SendSeen(chat, false).then(function () { done(true); }); return true; } else { Store.SendSeen(chat, false); return true; } } if (done !== undefined) done(); return false; };

function isChatMessage(message) { if (message.isSentByMe) { return false; } if (message.isNotification) { return false; } if (!message.isUserCreatedType) { return false; } return true; }

window.WAPI.getUnreadMessages = function (includeMe, includeNotifications, use_unread_count, done) { const chats = window.Store.Chat.models; let output = [];

for (let chat in chats) {
    if (isNaN(chat)) {
        continue;
    }

    let messageGroupObj = chats[chat];
    let messageGroup = WAPI._serializeChatObj(messageGroupObj);

    messageGroup.messages = [];

    const messages = messageGroupObj.msgs._models;
    for (let i = messages.length - 1; i >= 0; i--) {
        let messageObj = messages[i];
        if (typeof (messageObj.isNewMsg) != "boolean" || messageObj.isNewMsg === false) {
            continue;
        } else {
            messageObj.isNewMsg = false;
            let message = WAPI.processMessageObj(messageObj, includeMe, includeNotifications);
            if (message) {
                messageGroup.messages.push(message);
            }
        }
    }

    if (messageGroup.messages.length > 0) {
        output.push(messageGroup);
    } else { // no messages with isNewMsg true
        if (use_unread_count) {
            let n = messageGroupObj.unreadCount; // will use unreadCount attribute to fetch last n messages from sender
            for (let i = messages.length - 1; i >= 0; i--) {
                let messageObj = messages[i];
                if (n > 0) {
                    if (!messageObj.isSentByMe) {
                        let message = WAPI.processMessageObj(messageObj, includeMe, includeNotifications);
                        messageGroup.messages.unshift(message);
                        n -= 1;
                    }
                } else if (n === -1) { // chat was marked as unread so will fetch last message as unread
                    if (!messageObj.isSentByMe) {
                        let message = WAPI.processMessageObj(messageObj, includeMe, includeNotifications);
                        messageGroup.messages.unshift(message);
                        break;
                    }
                } else { // unreadCount = 0
                    break;
                }
            }
            if (messageGroup.messages.length > 0) {
                messageGroupObj.unreadCount = 0; // reset unread counter
                output.push(messageGroup);
            }
        }
    }
}
if (done !== undefined) {
    done(output);
}
return output;

};

window.WAPI.getGroupOwnerID = async function (id, done) { const output = (await WAPI.getGroupMetadata(id)).owner.id; if (done !== undefined) { done(output); } return output;

};

window.WAPI.getCommonGroups = async function (id, done) { let output = [];

groups = window.WAPI.getAllGroups();

for (let idx in groups) {
    try {
        participants = await window.WAPI.getGroupParticipantIDs(groups[idx].id);
        if (participants.filter((participant) => participant == id).length) {
            output.push(groups[idx]);
        }
    } catch (err) {
        console.log("Error in group:");
        console.log(groups[idx]);
        console.log(err);
    }
}

if (done !== undefined) {
    done(output);
}
return output;

};

window.WAPI.getProfilePicSmallFromId = function (id, done) { window.Store.ProfilePicThumb.find(id).then(function (d) { if (d.img !== undefined) { window.WAPI.downloadFileWithCredentials(d.img, done); } else { done(false); } }, function (e) { done(false); }) };

window.WAPI.getProfilePicFromId = function (id, done) { window.Store.ProfilePicThumb.find(id).then(function (d) { if (d.imgFull !== undefined) { window.WAPI.downloadFileWithCredentials(d.imgFull, done); } else { done(false); } }, function (e) { done(false); }) };

window.WAPI.downloadFileWithCredentials = function (url, done) { let xhr = new XMLHttpRequest();

xhr.onload = function () {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            let reader = new FileReader();
            reader.readAsDataURL(xhr.response);
            reader.onload = function (e) {
                done(reader.result.substr(reader.result.indexOf(',') + 1))
            };
        } else {
            console.error(xhr.statusText);
        }
    } else {
        console.log(err);
        done(false);
    }
};

xhr.open("GET", url, true);
xhr.withCredentials = true;
xhr.responseType = 'blob';
xhr.send(null);

};

window.WAPI.downloadFile = function (url, done) { let xhr = new XMLHttpRequest();

xhr.onload = function () {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            let reader = new FileReader();
            reader.readAsDataURL(xhr.response);
            reader.onload = function (e) {
                done(reader.result.substr(reader.result.indexOf(',') + 1))
            };
        } else {
            console.error(xhr.statusText);
        }
    } else {
        console.log(err);
        done(false);
    }
};

xhr.open("GET", url, true);
xhr.responseType = 'blob';
xhr.send(null);

};

window.WAPI.getBatteryLevel = function (done) { if (window.Store.Conn.plugged) { if (done !== undefined) { done(100); } return 100; } output = window.Store.Conn.battery; if (done !== undefined) { done(output); } return output; };

window.WAPI.deleteConversation = function (chatId, done) { let userId = new window.Store.UserConstructor(chatId, { intentionallyUsePrivateConstructor: true }); let conversation = WAPI.getChat(userId);

if (!conversation) {
    if (done !== undefined) {
        done(false);
    }
    return false;
}

window.Store.sendDelete(conversation, false).then(() => {
    if (done !== undefined) {
        done(true);
    }
}).catch(() => {
    if (done !== undefined) {
        done(false);
    }
});

return true;

};

window.WAPI.deleteMessage = function (chatId, messageArray, revoke = false, done) { let userId = new window.Store.UserConstructor(chatId, { intentionallyUsePrivateConstructor: true }); let conversation = WAPI.getChat(userId);

if (!conversation) {
    if (done !== undefined) {
        done(false);
    }
    return false;
}

if (!Array.isArray(messageArray)) {
    messageArray = [messageArray];
}
let messagesToDelete = messageArray.map(msgId => window.Store.Msg.get(msgId));

if (revoke) {
    conversation.sendRevokeMsgs(messagesToDelete, conversation);
} else {
    conversation.sendDeleteMsgs(messagesToDelete, conversation);
}

if (done !== undefined) {
    done(true);
}

return true;

};

window.WAPI.isMultiDeviceVersion = function () { try { let resp = window.Store.FeatureChecker.GK.features['MD_BACKEND']; return resp; } catch { return true; } }

window.WAPI.getMyChatId = () => { return Store.GetMaybeMeUser.getMaybeMeUser(); }

window.WAPI.checkNumberStatus = function (id, done) { window.WAPI.findJidFromNumber(id).then((result) => { if (done !== undefined) { if (result.jid === undefined) throw 404; done(window.WAPI._serializeNumberStatusObj(result)); } }).catch((e) => { if (done !== undefined) { done(window.WAPI._serializeNumberStatusObj({ status: e, jid: id })); } });

return true;

};

window.WAPI.findJidFromNumber = (number) => { if (WAPI.isMultiDeviceVersion()) { return Store.QueryExist.queryExist(WAPI.tryFixNumber(number)).then(value => { return { status: 200, jid: value.wid } }); } else { if (!number.includes("@c.us")) number += "@c.us"; return Store.WapQuery.queryExist(number); } }

window.WAPI.tryFixNumber = (number) => { let firstNumbersMe = Store.GetMaybeMeUser.getMaybeMeUser().user.substring(0, 2); let firstNumbersContact = number.substring(0, 2); if (firstNumbersMe === firstNumbersContact) { return number.substring(2); } firstNumbersMe = Store.GetMaybeMeUser.getMaybeMeUser().user.substring(0, 3); firstNumbersContact = number.substring(0, 3); if (firstNumbersMe === firstNumbersContact) { return number.substring(3); } return number; }

/**

window.Store.Msg.off('add'); sessionStorage.removeItem('saved_msgs');

window.WAPI._newMessagesListener = window.Store.Msg.on('add', (newMessage) => { if (newMessage && newMessage.isNewMsg && !newMessage.isSentByMe) { let message = window.WAPI.processMessageObj(newMessage, false, false); if (message) { window.WAPI._newMessagesQueue.push(message); window.WAPI._newMessagesBuffer.push(message); }

    // Starts debouncer time to don't call a callback for each message if more than one message arrives
    // in the same second
    if (!window.WAPI._newMessagesDebouncer && window.WAPI._newMessagesQueue.length > 0) {
        window.WAPI._newMessagesDebouncer = setTimeout(() => {
            let queuedMessages = window.WAPI._newMessagesQueue;

            window.WAPI._newMessagesDebouncer = null;
            window.WAPI._newMessagesQueue = [];

            let removeCallbacks = [];

            window.WAPI._newMessagesCallbacks.forEach(function (callbackObj) {
                if (callbackObj.callback !== undefined) {
                    callbackObj.callback(queuedMessages);
                }
                if (callbackObj.rmAfterUse === true) {
                    removeCallbacks.push(callbackObj);
                }
            });

            // Remove removable callbacks.
            removeCallbacks.forEach(function (rmCallbackObj) {
                let callbackIndex = window.WAPI._newMessagesCallbacks.indexOf(rmCallbackObj);
                window.WAPI._newMessagesCallbacks.splice(callbackIndex, 1);
            });
        }, 1000);
    }
}

});

window.WAPI._unloadInform = (event) => { // Save in the buffer the ungot unreaded messages window.WAPI._newMessagesBuffer.forEach((message) => { Object.keys(message).forEach(key => message[key] === undefined ? delete message[key] : ''); }); sessionStorage.setItem("saved_msgs", JSON.stringify(window.WAPI._newMessagesBuffer));

// Inform callbacks that the page will be reloaded.
window.WAPI._newMessagesCallbacks.forEach(function (callbackObj) {
    if (callbackObj.callback !== undefined) {
        callbackObj.callback({ status: -1, message: 'page will be reloaded, wait and register callback again.' });
    }
});

};

window.addEventListener("unload", window.WAPI._unloadInform, false); window.addEventListener("beforeunload", window.WAPI._unloadInform, false); window.addEventListener("pageunload", window.WAPI._unloadInform, false);

/**

/**

window.WAPI.sendImage = function (imgBase64, chatid, filename, caption, done) { //var idUser = new window.Store.UserConstructor(chatid); var idUser = new window.Store.UserConstructor(chatid, { intentionallyUsePrivateConstructor: true }); // create new chat return Store.Chat.find(idUser).then((chat) => { var mediaBlob = window.WAPI.base64ImageToFile(imgBase64, filename); var mc = new Store.MediaCollection(chat); mc.processAttachments([{ file: mediaBlob }, 1], chat, 1).then(() => { var media = mc.models[0]; media.sendToChat(chat, { caption: caption }); if (done !== undefined) done(true); }); }); }

window.WAPI.base64ImageToFile = function (b64Data, filename) { var arr = b64Data.split(','); var mime = arr[0].match(/:(.*?);/)[1]; var bstr = atob(arr[1]); var n = bstr.length; var u8arr = new Uint8Array(n);

while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
}

return new File([u8arr], filename, { type: mime });

};

/**

/**

/**

/**

/**

/**

Elintondm commented 2 years ago

Hi, @andlb

Could you please attach your wapi.js here?

andlb commented 2 years ago

/**

/**

window.WAPI = { lastRead: {} };

window.WAPI._serializeRawObj = (obj) => { if (obj) { return obj.toJSON(); } return {} };

/**

window.WAPI._serializeChatObj = (obj) => { if (obj == undefined) { return null; }

return Object.assign(window.WAPI._serializeRawObj(obj), {
    kind: obj.kind,
    isGroup: obj.isGroup,
    contact: obj['contact'] ?

window.WAPI._serializeContactObj(obj['contact']) : null, groupMetadata: obj["groupMetadata"] ? window.WAPI._serializeRawObj(obj["groupMetadata"]) : null, presence: obj["presence"] ? window.WAPI._serializeRawObj(obj["presence"]) : null, msgs: null }); };

window.WAPI._serializeContactObj = (obj) => { if (obj == undefined) { return null; }

return Object.assign(window.WAPI._serializeRawObj(obj), {
    formattedName: obj.formattedName,
    isHighLevelVerified: obj.isHighLevelVerified,
    isMe: obj.isMe,
    isMyContact: obj.isMyContact,
    isPSA: obj.isPSA,
    isUser: obj.isUser,
    isVerified: obj.isVerified,
    isWAContact: obj.isWAContact,
    profilePicThumbObj: obj.profilePicThumb ?

WAPI._serializeProfilePicThumb(obj.profilePicThumb) : {}, statusMute: obj.statusMute, msgs: null }); };

window.WAPI._serializeMessageObj = (obj) => { if (obj == undefined) { return null; }

return Object.assign(window.WAPI._serializeRawObj(obj), {
    id: obj.id._serialized,
    sender: obj["senderObj"] ?

WAPI._serializeContactObj(obj["senderObj"]) : null, timestamp: obj["t"], content: obj["body"], isGroupMsg: obj.isGroupMsg, isLink: obj.isLink, isMMS: obj.isMMS, isMedia: obj.isMedia, isNotification: obj.isNotification, isPSA: obj.isPSA, type: obj.type, chat: WAPI._serializeChatObj(obj['chat']), chatId: obj.id.remote, quotedMsgObj: WAPI._serializeMessageObj(obj['_quotedMsgObj']), mediaData: window.WAPI._serializeRawObj(obj['mediaData']) }); };

window.WAPI._serializeNumberStatusObj = (obj) => { if (obj == undefined) { return null; }

return Object.assign({}, {
    id: obj.jid,
    status: obj.status,
    isBusiness: (obj.biz === true),
    canReceiveMessage: (obj.status === 200)
});

};

window.WAPI._serializeProfilePicThumb = (obj) => { if (obj == undefined) { return null; }

return Object.assign({}, {
    eurl: obj.eurl,
    id: obj.id,
    img: obj.img,
    imgFull: obj.imgFull,
    raw: obj.raw,
    tag: obj.tag
});

}

window.WAPI.createGroup = function (name, contactsId) { if (!Array.isArray(contactsId)) { contactsId = [contactsId]; }

return window.Store.Wap.createGroup(name, contactsId);

};

window.WAPI.leaveGroup = function (groupId) { groupId = typeof groupId == "string" ? groupId : groupId._serialized; var group = WAPI.getChat(groupId); return group.sendExit() };

window.WAPI.getAllContacts = function (done) { const contacts = window.Store.Contact.map((contact) => WAPI._serializeContactObj(contact));

if (done !== undefined) done(contacts);
return contacts;

};

/**

/**

/**

window.WAPI.haveNewMsg = function (chat) { return chat.unreadCount > 0; };

window.WAPI.getAllChatsWithNewMsg = function (done) { const chats = window.Store.Chat.filter(window.WAPI.haveNewMsg).map((chat) => WAPI._serializeChatObj(chat));

if (done !== undefined) done(chats);
return chats;

};

/**

/**

/**

window.WAPI.getChatByName = function (name, done) { const found = window.WAPI.getAllChats().find(val => val.name.includes(name)) if (done !== undefined) done(found); return found; };

window.WAPI.sendImageFromDatabasePicBot = function (picId, chatId, caption) { var chatDatabase = window.WAPI.getChatByName('DATABASEPICBOT'); var msgWithImg = chatDatabase.msgs.find((msg) => msg.caption == picId);

if (msgWithImg === undefined) {
    return false;
}

// Nova versão Beta
if (WAPI.isMultiDeviceVersion()) {
    WAPI.getChat(chatId, chatSend => {
        if (chatSend === undefined) {
            return false;
        }
        const oldCaption = msgWithImg.caption;

        msgWithImg.id.id = window.WAPI.getNewId();
        msgWithImg.id.remote = chatId;
        msgWithImg.t = Math.ceil(new Date().getTime() / 1000);
        msgWithImg.to = chatId;

        if (caption !== undefined && caption !== '') {
            msgWithImg.caption = caption;
        } else {
            msgWithImg.caption = '';
        }

        msgWithImg.collection.send(msgWithImg).then(function (e) {
            msgWithImg.caption = oldCaption;
        });

        return true;
    });
} else {
    // Versão antiga
    var chatSend = WAPI.getChat(chatId);
    if (chatSend === undefined) {
        return false;
    }
    const oldCaption = msgWithImg.caption;

    msgWithImg.id.id = window.WAPI.getNewId();
    msgWithImg.id.remote = chatId;
    msgWithImg.t = Math.ceil(new Date().getTime() / 1000);
    msgWithImg.to = chatId;

    if (caption !== undefined && caption !== '') {
        msgWithImg.caption = caption;
    } else {
        msgWithImg.caption = '';
    }

    msgWithImg.collection.send(msgWithImg).then(function (e) {
        msgWithImg.caption = oldCaption;
    });

    return true;
}

};

window.WAPI.sendMessageWithThumb = function (thumb, url, title, description, text, chatId, done) { var chatSend = WAPI.getChat(chatId); if (chatSend === undefined) { if (done !== undefined) done(false); return false; } var linkPreview = { canonicalUrl: url, description: description, matchedText: url, title: title, thumbnail: thumb, compose: true }; chatSend.sendMessage(text, { linkPreview: linkPreview, mentionedJidList: [], quotedMsg: null, quotedMsgAdminGroupJid: null }); if (done !== undefined) done(true); return true; };

window.WAPI.getNewId = function () { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

for (var i = 0; i < 20; i++)
    text += possible.charAt(Math.floor(Math.random() *

possible.length)); return text; };

window.WAPI.getChatById = function (id, done) { let found = WAPI.getChat(id); if (found) { found = WAPI._serializeChatObj(found); } else { found = false; }

if (done !== undefined) done(found);
return found;

};

/**

/**

/**

window.WAPI.asyncLoadAllEarlierMessages = function (id, done) { done(); window.WAPI.loadAllEarlierMessages(id); };

window.WAPI.areAllMessagesLoaded = function (id, done) { const found = WAPI.getChat(id); if (!found.msgs.msgLoadState.noEarlierMsgs) { if (done) done(false); return false } if (done) done(true); return true };

/**

window.WAPI.loadEarlierMessagesTillDate = function (id, lastMessage, done) { const found = WAPI.getChat(id); x = function () { if (found.msgs.models[0].t > lastMessage && !found.msgs.msgLoadState.noEarlierMsgs) { found.loadEarlierMsgs().then(x); } else { done(); } }; x(); };

/**

/**

};

/**

/**

window.WAPI.getGroupAdmins = async function (id, done) { const output = (await WAPI._getGroupParticipants(id)) .filter((participant) => participant.isAdmin) .map((admin) => admin.id);

if (done !== undefined) done(output);
return output;

};

/**

window.WAPI.isLoggedIn = function (done) { // Contact always exists when logged in const isLogged = window.Store.Contact && window.Store.Contact.checksum !== undefined;

if (done !== undefined) done(isLogged);
return isLogged;

};

window.WAPI.isConnected = function (done) { // Phone Disconnected icon appears when phone is disconnected from the tnternet const isConnected = document.querySelector('*[data-icon="alert-phone"]') !== null ? false : true;

if (done !== undefined) done(isConnected);
return isConnected;

};

window.WAPI.processMessageObj = function (messageObj, includeMe, includeNotifications) { if (messageObj.isNotification) { if (includeNotifications) { ret = WAPI._serializeMessageObj(messageObj); delete ret.waveform delete ret.mediaData.waveform if (ret.quotedMsg && ret.quotedMsg.waveform) delete ret.quotedMsg.waveform return ret } else { return; } // System message // (i.e. "Messages you send to this chat and calls are now secured with end-to-end encryption...") } else if (messageObj.id.fromMe === false || includeMe) { ret = WAPI._serializeMessageObj(messageObj); delete ret.waveform delete ret.mediaData.waveform if (ret.quotedMsg && ret.quotedMsg.waveform) delete ret.quotedMsg.waveform return ret } return; };

window.WAPI.getAllMessagesInChat = function (id, includeMe, includeNotifications, done) { const chat = WAPI.getChat(id); let output = []; const messages = chat.msgs._models;

for (const i in messages) {
    if (i === "remove") {
        continue;
    }
    const messageObj = messages[i];

    let message = WAPI.processMessageObj(messageObj, includeMe,

includeNotifications) if (message) output.push(message); } if (done !== undefined) done(output); return output; };

window.WAPI.getAllMessageIdsInChat = function (id, includeMe, includeNotifications, done) { const chat = WAPI.getChat(id); let output = []; const messages = chat.msgs._models;

for (const i in messages) {
    if ((i === "remove")
        || (!includeMe && messages[i].isMe)
        || (!includeNotifications && messages[i].isNotification)) {
        continue;
    }
    output.push(messages[i].id._serialized);
}
if (done !== undefined) done(output);
return output;

};

window.WAPI.getMessageById = function (id, done) { let result = false; try { let msg = window.Store.Msg.get(id); if (msg) { result = WAPI.processMessageObj(msg, true, true); } } catch (err) { }

if (done !== undefined) {
    done(result);
} else {
    return result;
}

};

window.WAPI.ReplyMessage = function (idMessage, message, done) { var messageObject = window.Store.Msg.get(idMessage); if (messageObject === undefined) { if (done !== undefined) done(false); return false; } messageObject = messageObject.value();

const chat = WAPI.getChat(messageObject.chat.id)
if (chat !== undefined) {
    if (done !== undefined) {
        chat.sendMessage(message, null, messageObject).then(function ()

{ function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }

            var trials = 0;

            function check() {
                for (let i = chat.msgs.models.length - 1; i >= 0; i--) {
                    let msg = chat.msgs.models[i];

                    if (!msg.senderObj.isMe || msg.body != message) {
                        continue;
                    }
                    done(WAPI._serializeMessageObj(msg));
                    return True;
                }
                trials += 1;
                console.log(trials);
                if (trials > 30) {
                    done(true);
                    return;
                }
                sleep(500).then(check);
            }
            check();
        });
        return true;
    } else {
        chat.sendMessage(message, null, messageObject);
        return true;
    }
} else {
    if (done !== undefined) done(false);
    return false;
}

};

window.WAPI.sendMessageToID = function (id, message, done) {

try {
    // Nova versão do WhatsApp Beta
    if (WAPI.isMultiDeviceVersion()) {
        console.log('Fluxo para Multdevice: ' + id);
        WAPI.getChat(id, chat => {
            if (chat) {
                chat.sendMessage(message);
                console.log('Mensagem enviada!');
                done(true);
                return true;
            } else {
                console.log('Mensagem NÃO enviada!');
                done(false);
                return false;
            }
        });
    } else {
        // Versão antiga do WhatsApp  para um só navegador
        try {
            window.getContact = (id) => {
                return Store.WapQuery.queryExist(id);
                //          return

Store.WapQuery.SendPing().queryExist(id); } window.getContact(id).then(contact => { if (contact.status === 404) { done(true); } else { Store.Chat.find(contact.jid).then(chat => { chat.sendMessage(message); done(true); return true; }).catch(reject => { if (WAPI.sendMessage(id, message)) { done(true); return true; } else { done(false); return false; } }); } }); } catch (e) { // Quando ainda não é um contato if (window.Store.Chat.length === 0) { done(false); return false; }

            firstChat = Store.Chat.models[0];
            var originalID = firstChat.id;
            firstChat.id = typeof originalID === "string" ? id : new

window.Store.UserConstructor(id, { intentionallyUsePrivateConstructor: true }); if (done !== undefined) { firstChat.sendMessage(message).then(function () { firstChat.id = originalID; done(true); }); return true; } else { firstChat.sendMessage(message); firstChat.id = originalID; done(true); return true; } } // Fim do fluxo antigo } } catch (e) { console.log('Erro ao enviar a mensagem: ' + e.message); done(false); return false; }

//   try {
//       if (WAPI.isMultiDeviceVersion()) {
//         console.log('Fluxo para Multdevice: ' + id);
//         var chat = WAPI.getChat(id);
//         console.chat('Chat: ');
//         // console.log(chat);
//         // chat.sendMessage(message);
//         console.log('Mensagem enviada!');
//         done(true);
//         return true;
//       } else {
//         window.getContact = (id) => {
//             return Store.WapQuery.queryExist(id);
// //           return Store.WapQuery.SendPing().queryExist(id);
//         }
//         window.getContact(id).then(contact => {
//             if (contact.status === 404) {
//                 done(true);
//             } else {
//                 Store.Chat.find(contact.jid).then(chat => {
//                     chat.sendMessage(message);
//                     return true;
//                 }).catch(reject => {
//                     if (WAPI.sendMessage(id, message)) {
//                         done(true);
//                         return true;
//                     }else{
//                         done(false);
//                         return false;
//                     }
//                 });
//             }
//         });
//       }
//   } catch (e) {
//       console.log('Caiu no fluxo antigo');
//       if (window.Store.Chat.length === 0)
//           return false;

//       firstChat = Store.Chat.models[0];
//       var originalID = firstChat.id;
//       firstChat.id = typeof originalID === "string" ? id : new

window.Store.UserConstructor(id, { intentionallyUsePrivateConstructor: true }); // if (done !== undefined) { // firstChat.sendMessage(message).then(function () { // firstChat.id = originalID; // done(true); // }); // return true; // } else { // firstChat.sendMessage(message); // firstChat.id = originalID; // return true; // } // } // if (done !== undefined) done(false); // return false; }

window.WAPI.sendMessage = function (id, message, done) { var chat = WAPI.getChat(id); if (chat !== undefined) { if (done !== undefined) { chat.sendMessage(message).then(function () { function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }

            var trials = 0;

            function check() {
                for (let i = chat.msgs.models.length - 1; i >= 0; i--) {
                    let msg = chat.msgs.models[i];

                    if (!msg.senderObj.isMe || msg.body != message) {
                        continue;
                    }
                    done(WAPI._serializeMessageObj(msg));
                    return True;
                }
                trials += 1;
                console.log(trials);
                if (trials > 30) {
                    done(true);
                    return;
                }
                sleep(500).then(check);
            }
            check();
        });
        return true;
    } else {
        chat.sendMessage(message);
        return true;
    }
} else {
    if (done !== undefined) done(false);
    return false;
}

};

window.WAPI.sendMessage2 = function (id, message, done) { var chat = WAPI.getChat(id); if (chat !== undefined) { try { if (done !== undefined) { chat.sendMessage(message).then(function () { done(true); }); } else { chat.sendMessage(message); } return true; } catch (error) { if (done !== undefined) done(false) return false; } } if (done !== undefined) done(false) return false; };

window.WAPI.sendSeen = function (id, done) { var chat = window.WAPI.getChat(id); if (chat !== undefined) { if (done !== undefined) { if (chat.getLastMsgKeyForAction === undefined) chat.getLastMsgKeyForAction = function () { }; Store.SendSeen(chat, false).then(function () { done(true); }); return true; } else { Store.SendSeen(chat, false); return true; } } if (done !== undefined) done(); return false; };

function isChatMessage(message) { if (message.isSentByMe) { return false; } if (message.isNotification) { return false; } if (!message.isUserCreatedType) { return false; } return true; }

window.WAPI.getUnreadMessages = function (includeMe, includeNotifications, use_unread_count, done) { const chats = window.Store.Chat.models; let output = [];

for (let chat in chats) {
    if (isNaN(chat)) {
        continue;
    }

    let messageGroupObj = chats[chat];
    let messageGroup = WAPI._serializeChatObj(messageGroupObj);

    messageGroup.messages = [];

    const messages = messageGroupObj.msgs._models;
    for (let i = messages.length - 1; i >= 0; i--) {
        let messageObj = messages[i];
        if (typeof (messageObj.isNewMsg) != "boolean" ||

messageObj.isNewMsg === false) { continue; } else { messageObj.isNewMsg = false; let message = WAPI.processMessageObj(messageObj, includeMe, includeNotifications); if (message) { messageGroup.messages.push(message); } } }

    if (messageGroup.messages.length > 0) {
        output.push(messageGroup);
    } else { // no messages with isNewMsg true
        if (use_unread_count) {
            let n = messageGroupObj.unreadCount; // will use

unreadCount attribute to fetch last n messages from sender for (let i = messages.length - 1; i >= 0; i--) { let messageObj = messages[i]; if (n > 0) { if (!messageObj.isSentByMe) { let message = WAPI.processMessageObj(messageObj, includeMe, includeNotifications); messageGroup.messages.unshift(message); n -= 1; } } else if (n === -1) { // chat was marked as unread so will fetch last message as unread if (!messageObj.isSentByMe) { let message = WAPI.processMessageObj(messageObj, includeMe, includeNotifications); messageGroup.messages.unshift(message); break; } } else { // unreadCount = 0 break; } } if (messageGroup.messages.length > 0) { messageGroupObj.unreadCount = 0; // reset unread counter output.push(messageGroup); } } } } if (done !== undefined) { done(output); } return output; };

window.WAPI.getGroupOwnerID = async function (id, done) { const output = (await WAPI.getGroupMetadata(id)).owner.id; if (done !== undefined) { done(output); } return output;

};

window.WAPI.getCommonGroups = async function (id, done) { let output = [];

groups = window.WAPI.getAllGroups();

for (let idx in groups) {
    try {
        participants = await

window.WAPI.getGroupParticipantIDs(groups[idx].id); if (participants.filter((participant) => participant == id).length) { output.push(groups[idx]); } } catch (err) { console.log("Error in group:"); console.log(groups[idx]); console.log(err); } }

if (done !== undefined) {
    done(output);
}
return output;

};

window.WAPI.getProfilePicSmallFromId = function (id, done) { window.Store.ProfilePicThumb.find(id).then(function (d) { if (d.img !== undefined) { window.WAPI.downloadFileWithCredentials(d.img, done); } else { done(false); } }, function (e) { done(false); }) };

window.WAPI.getProfilePicFromId = function (id, done) { window.Store.ProfilePicThumb.find(id).then(function (d) { if (d.imgFull !== undefined) { window.WAPI.downloadFileWithCredentials(d.imgFull, done); } else { done(false); } }, function (e) { done(false); }) };

window.WAPI.downloadFileWithCredentials = function (url, done) { let xhr = new XMLHttpRequest();

xhr.onload = function () {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            let reader = new FileReader();
            reader.readAsDataURL(xhr.response);
            reader.onload = function (e) {
                done(reader.result.substr(reader.result.indexOf(',') +

1)) }; } else { console.error(xhr.statusText); } } else { console.log(err); done(false); } };

xhr.open("GET", url, true);
xhr.withCredentials = true;
xhr.responseType = 'blob';
xhr.send(null);

};

window.WAPI.downloadFile = function (url, done) { let xhr = new XMLHttpRequest();

xhr.onload = function () {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            let reader = new FileReader();
            reader.readAsDataURL(xhr.response);
            reader.onload = function (e) {
                done(reader.result.substr(reader.result.indexOf(',') +

1)) }; } else { console.error(xhr.statusText); } } else { console.log(err); done(false); } };

xhr.open("GET", url, true);
xhr.responseType = 'blob';
xhr.send(null);

};

window.WAPI.getBatteryLevel = function (done) { if (window.Store.Conn.plugged) { if (done !== undefined) { done(100); } return 100; } output = window.Store.Conn.battery; if (done !== undefined) { done(output); } return output; };

window.WAPI.deleteConversation = function (chatId, done) { let userId = new window.Store.UserConstructor(chatId, { intentionallyUsePrivateConstructor: true }); let conversation = WAPI.getChat(userId);

if (!conversation) {
    if (done !== undefined) {
        done(false);
    }
    return false;
}

window.Store.sendDelete(conversation, false).then(() => {
    if (done !== undefined) {
        done(true);
    }
}).catch(() => {
    if (done !== undefined) {
        done(false);
    }
});

return true;

};

window.WAPI.deleteMessage = function (chatId, messageArray, revoke = false, done) { let userId = new window.Store.UserConstructor(chatId, { intentionallyUsePrivateConstructor: true }); let conversation = WAPI.getChat(userId);

if (!conversation) {
    if (done !== undefined) {
        done(false);
    }
    return false;
}

if (!Array.isArray(messageArray)) {
    messageArray = [messageArray];
}
let messagesToDelete = messageArray.map(msgId =>

window.Store.Msg.get(msgId));

if (revoke) {
    conversation.sendRevokeMsgs(messagesToDelete, conversation);
} else {
    conversation.sendDeleteMsgs(messagesToDelete, conversation);
}

if (done !== undefined) {
    done(true);
}

return true;

};

window.WAPI.isMultiDeviceVersion = function () { try { let resp = window.Store.FeatureChecker.GK.features['MD_BACKEND']; return resp; } catch { return true; } }

window.WAPI.getMyChatId = () => { return Store.GetMaybeMeUser.getMaybeMeUser(); }

window.WAPI.checkNumberStatus = function (id, done) { window.WAPI.findJidFromNumber(id).then((result) => { if (done !== undefined) { if (result.jid === undefined) throw 404; done(window.WAPI._serializeNumberStatusObj(result)); } }).catch((e) => { if (done !== undefined) { done(window.WAPI._serializeNumberStatusObj({ status: e, jid: id })); } });

return true;

};

window.WAPI.findJidFromNumber = (number) => { if (WAPI.isMultiDeviceVersion()) { return Store.QueryExist.queryExist(WAPI.tryFixNumber(number)).then(value => { return { status: 200, jid: value.wid } }); } else { if @.")) number += @."; return Store.WapQuery.queryExist(number); } }

window.WAPI.tryFixNumber = (number) => { let firstNumbersMe = Store.GetMaybeMeUser.getMaybeMeUser().user.substring(0, 2); let firstNumbersContact = number.substring(0, 2); if (firstNumbersMe === firstNumbersContact) { return number.substring(2); } firstNumbersMe = Store.GetMaybeMeUser.getMaybeMeUser().user.substring(0, 3); firstNumbersContact = number.substring(0, 3); if (firstNumbersMe === firstNumbersContact) { return number.substring(3); } return number; }

/**

window.Store.Msg.off('add'); sessionStorage.removeItem('saved_msgs');

window.WAPI._newMessagesListener = window.Store.Msg.on('add', (newMessage) => { if (newMessage && newMessage.isNewMsg && !newMessage.isSentByMe) { let message = window.WAPI.processMessageObj(newMessage, false, false); if (message) { window.WAPI._newMessagesQueue.push(message); window.WAPI._newMessagesBuffer.push(message); }

    // Starts debouncer time to don't call a callback for each message

if more than one message arrives // in the same second if (!window.WAPI._newMessagesDebouncer && window.WAPI._newMessagesQueue.length > 0) { window.WAPI._newMessagesDebouncer = setTimeout(() => { let queuedMessages = window.WAPI._newMessagesQueue;

            window.WAPI._newMessagesDebouncer = null;
            window.WAPI._newMessagesQueue = [];

            let removeCallbacks = [];

            window.WAPI._newMessagesCallbacks.forEach(function

(callbackObj) { if (callbackObj.callback !== undefined) { callbackObj.callback(queuedMessages); } if (callbackObj.rmAfterUse === true) { removeCallbacks.push(callbackObj); } });

            // Remove removable callbacks.
            removeCallbacks.forEach(function (rmCallbackObj) {
                let callbackIndex =

window.WAPI._newMessagesCallbacks.indexOf(rmCallbackObj); window.WAPI._newMessagesCallbacks.splice(callbackIndex, 1); }); }, 1000); } } });

window.WAPI._unloadInform = (event) => { // Save in the buffer the ungot unreaded messages window.WAPI._newMessagesBuffer.forEach((message) => { Object.keys(message).forEach(key => message[key] === undefined ? delete message[key] : ''); }); sessionStorage.setItem("saved_msgs", JSON.stringify(window.WAPI._newMessagesBuffer));

// Inform callbacks that the page will be reloaded.
window.WAPI._newMessagesCallbacks.forEach(function (callbackObj) {
    if (callbackObj.callback !== undefined) {
        callbackObj.callback({ status: -1, message: 'page will be

reloaded, wait and register callback again.' }); } }); };

window.addEventListener("unload", window.WAPI._unloadInform, false); window.addEventListener("beforeunload", window.WAPI._unloadInform, false); window.addEventListener("pageunload", window.WAPI._unloadInform, false);

/**

/**

window.WAPI.sendImage = function (imgBase64, chatid, filename, caption, done) { //var idUser = new window.Store.UserConstructor(chatid); var idUser = new window.Store.UserConstructor(chatid, { intentionallyUsePrivateConstructor: true }); // create new chat return Store.Chat.find(idUser).then((chat) => { var mediaBlob = window.WAPI.base64ImageToFile(imgBase64, filename); var mc = new Store.MediaCollection(chat); mc.processAttachments([{ file: mediaBlob }, 1], chat, 1).then(() => { var media = mc.models[0]; media.sendToChat(chat, { caption: caption }); if (done !== undefined) done(true); }); }); }

window.WAPI.base64ImageToFile = function (b64Data, filename) { var arr = b64Data.split(','); var mime = arr[0].match(/:(.*?);/)[1]; var bstr = atob(arr[1]); var n = bstr.length; var u8arr = new Uint8Array(n);

while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
}

return new File([u8arr], filename, { type: mime });

};

/**

/**

/**

/**

/**

/**

On Mon, May 30, 2022 at 8:29 AM Elintondm @.***> wrote:

Hi, @andlb https://github.com/andlb

Could you please attach your wapi.js here?

— Reply to this email directly, view it on GitHub https://github.com/mukulhase/WebWhatsapp-Wrapper/issues/1150#issuecomment-1141042294, or unsubscribe https://github.com/notifications/unsubscribe-auth/AG4WZ4OWCE2B5GAUXPBHSULVMSRBZANCNFSM5WHHILLA . You are receiving this because you were mentioned.Message ID: @.***>

--

Andre Luis Fone: +55 (17) 982098889 LinkedIn: www.linkedin.com/in/andreborgespaula