fraddyrad

engine.v3.js

Mar 25th, 2022
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * This script contains WAPI functions that need to be run in the context of the webpage
  3.  */
  4.  
  5. /**
  6.  * Auto discovery the webpack object references of instances that contains all functions used by the WAPI
  7.  * functions and creates the Store object.
  8.  */
  9. if (!window.Store) {
  10.     (function () {
  11.         function getStore(modules) {
  12.         let foundCount = 0;
  13.         let neededObjects = [
  14.                 { id: "Store", conditions: (module) => (module.default && module.default.Chat && module.default.Msg) ? module.default : null },
  15.                 { id: "MediaCollection", conditions: (module) => (module.default && module.default.prototype && module.default.prototype.processAttachments) ? module.default : null },
  16.                 { id: "MediaProcess", conditions: (module) => (module.BLOB) ? module : null },
  17.                 { id: "Wap", conditions: (module) => (module.createGroup) ? module : null },
  18.                 { id: "ServiceWorker", conditions: (module) => (module.default && module.default.killServiceWorker) ? module : null },
  19.                 { id: "State", conditions: (module) => (module.STATE && module.STREAM) ? module : null },
  20.                 { id: "WapDelete", conditions: (module) => (module.sendConversationDelete && module.sendConversationDelete.length == 2) ? module : null },
  21.                 { id: "Conn", conditions: (module) => (module.default && module.default.ref && module.default.refTTL) ? module.default : null },
  22.                 { id: "WapQuery", conditions: (module) => (module.default && module.default.queryExist) ? module.default : null },
  23.                 { id: "CryptoLib", conditions: (module) => (module.decryptE2EMedia) ? module : null },
  24.                 { id: "OpenChat", conditions: (module) => (module.default && module.default.prototype && module.default.prototype.openChat) ? module.default : null },
  25.                 { id: "UserConstructor", conditions: (module) => (module.default && module.default.prototype && module.default.prototype.isServer && module.default.prototype.isUser) ? module.default : null },
  26.                 { id: "SendTextMsgToChat", conditions: (module) => (module.sendTextMsgToChat) ? module.sendTextMsgToChat : null },
  27.                 { id: "SendSeen", conditions: (module) => (module.sendSeen) ? module.sendSeen : null },
  28.                 { id: "sendDelete", conditions: (module) => (module.sendDelete) ? module.sendDelete : null },
  29.                 { id: 'FindChat', conditions: (module) => (module && module.findChat)? module : null}
  30.             ];
  31.         for (let idx in modules) {
  32.             if ((typeof modules[idx] === "object") && (modules[idx] !== null)) {
  33.                 neededObjects.forEach((needObj) => {
  34.                     if (!needObj.conditions || needObj.foundedModule)
  35.                         return;
  36.                     let neededModule = needObj.conditions(modules[idx]);
  37.                     if (neededModule !== null) {
  38.                         foundCount++;
  39.                         needObj.foundedModule = neededModule;
  40.                     }
  41.                 });
  42.  
  43.                 if (foundCount == neededObjects.length) {
  44.                     break;
  45.                 }
  46.             }
  47.         }
  48.  
  49.         let neededStore = neededObjects.find((needObj) => needObj.id === "Store");
  50.         window.Store = neededStore.foundedModule ? neededStore.foundedModule : {};
  51.         neededObjects.splice(neededObjects.indexOf(neededStore), 1);
  52.         neededObjects.forEach((needObj) => {
  53.             if (needObj.foundedModule) {
  54.                 window.Store[needObj.id] = needObj.foundedModule;
  55.             }
  56.         });
  57.        
  58.         window.Store.Chat.modelClass.prototype.sendMessage = function (e) {
  59.             window.Store.SendTextMsgToChat(this, ...arguments);
  60.         }      
  61.        
  62.         return window.Store;
  63.     }
  64.  
  65.         if (typeof webpackJsonp === 'function') {
  66.             webpackJsonp([], {'parasite': (x, y, z) => getStore(z)}, ['parasite']);
  67.         } else {
  68.             let tag = new Date().getTime();
  69.             webpackChunkwhatsapp_web_client.push([
  70.                 ["parasite" + tag],
  71.                 {
  72.  
  73.                 },
  74.                 function (o, e, t) {
  75.                     let modules = [];
  76.                     for (let idx in o.m) {
  77.                         let module = o(idx);
  78.                         modules.push(module);
  79.                     }
  80.                     getStore(modules);
  81.                 }
  82.             ]);
  83.         }
  84.  
  85.     })();
  86. }
  87.  
  88. window.WAPI = {
  89.     lastRead: {}
  90. };
  91.  
  92. window.WAPI._serializeRawObj = (obj) => {
  93.     if (obj) {
  94.         return obj.toJSON();
  95.     }
  96.     return {}
  97. };
  98.  
  99. /**
  100.  * Serializes a chat object
  101.  *
  102.  * @param rawChat Chat object
  103.  * @returns {{}}
  104.  */
  105.  
  106. window.WAPI._serializeChatObj = (obj) => {
  107.     if (obj == undefined) {
  108.         return null;
  109.     }
  110.  
  111.     return Object.assign(window.WAPI._serializeRawObj(obj), {
  112.         kind         : obj.kind,
  113.         isGroup      : obj.isGroup,
  114.         contact      : obj['contact'] ? window.WAPI._serializeContactObj(obj['contact'])        : null,
  115.         groupMetadata: obj["groupMetadata"] ? window.WAPI._serializeRawObj(obj["groupMetadata"]): null,
  116.         presence     : obj["presence"] ? window.WAPI._serializeRawObj(obj["presence"])          : null,
  117.         msgs         : null
  118.     });
  119. };
  120.  
  121. window.WAPI._serializeContactObj = (obj) => {
  122.     if (obj == undefined) {
  123.         return null;
  124.     }
  125.  
  126.     return Object.assign(window.WAPI._serializeRawObj(obj), {
  127.         formattedName      : obj.formattedName,
  128.         isHighLevelVerified: obj.isHighLevelVerified,
  129.         isMe               : obj.isMe,
  130.         isMyContact        : obj.isMyContact,
  131.         isPSA              : obj.isPSA,
  132.         isUser             : obj.isUser,
  133.         isVerified         : obj.isVerified,
  134.         isWAContact        : obj.isWAContact,
  135.         profilePicThumbObj : obj.profilePicThumb ? WAPI._serializeProfilePicThumb(obj.profilePicThumb): {},
  136.         statusMute         : obj.statusMute,
  137.         msgs               : null
  138.     });
  139. };
  140.  
  141. window.WAPI._serializeMessageObj = (obj) => {
  142.     if (obj == undefined) {
  143.         return null;
  144.     }
  145.  
  146.     return Object.assign(window.WAPI._serializeRawObj(obj), {
  147.         id            : obj.id._serialized,
  148.         sender        : obj["senderObj"] ? WAPI._serializeContactObj(obj["senderObj"]): null,
  149.         timestamp     : obj["t"],
  150.         content       : obj["body"],
  151.         isGroupMsg    : obj.isGroupMsg,
  152.         isLink        : obj.isLink,
  153.         isMMS         : obj.isMMS,
  154.         isMedia       : obj.isMedia,
  155.         isNotification: obj.isNotification,
  156.         isPSA         : obj.isPSA,
  157.         type          : obj.type,
  158.         chat          : WAPI._serializeChatObj(obj['chat']),
  159.         chatId        : obj.id.remote,
  160.         quotedMsgObj  : WAPI._serializeMessageObj(obj['_quotedMsgObj']),
  161.         mediaData     : window.WAPI._serializeRawObj(obj['mediaData'])
  162.     });
  163. };
  164.  
  165. window.WAPI._serializeNumberStatusObj = (obj) => {
  166.     if (obj == undefined) {
  167.         return null;
  168.     }
  169.  
  170.     return Object.assign({}, {
  171.         id               : obj.jid,
  172.         status           : obj.status,
  173.         isBusiness       : (obj.biz === true),
  174.         canReceiveMessage: (obj.status === 200)
  175.     });
  176. };
  177.  
  178. window.WAPI._serializeProfilePicThumb = (obj) => {
  179.     if (obj == undefined) {
  180.         return null;
  181.     }
  182.  
  183.     return Object.assign({}, {
  184.         eurl   : obj.eurl,
  185.         id     : obj.id,
  186.         img    : obj.img,
  187.         imgFull: obj.imgFull,
  188.         raw    : obj.raw,
  189.         tag    : obj.tag
  190.     });
  191. }
  192.  
  193. window.WAPI.createGroup = function (name, contactsId) {
  194.     if (!Array.isArray(contactsId)) {
  195.         contactsId = [contactsId];
  196.     }
  197.  
  198.     return window.Store.Wap.createGroup(name, contactsId);
  199. };
  200.  
  201. window.WAPI.leaveGroup = function (groupId) {
  202.     groupId = typeof groupId == "string" ? groupId : groupId._serialized;
  203.     var group = WAPI.getChat(groupId);
  204.     return group.sendExit()
  205. };
  206.  
  207.  
  208. window.WAPI.getAllContacts = function (done) {
  209.     const contacts = window.Store.Contact.map((contact) => WAPI._serializeContactObj(contact));
  210.  
  211.     if (done !== undefined) done(contacts);
  212.     return contacts;
  213. };
  214.  
  215. /**
  216.  * Fetches all contact objects from store, filters them
  217.  *
  218.  * @param done Optional callback function for async execution
  219.  * @returns {Array|*} List of contacts
  220.  */
  221. window.WAPI.getMyContacts = function (done) {
  222.     const contacts = window.Store.Contact.filter((contact) => contact.isMyContact === true).map((contact) => WAPI._serializeContactObj(contact));
  223.     if (done !== undefined) done(contacts);
  224.     return contacts;
  225. };
  226.  
  227. /**
  228.  * Fetches contact object from store by ID
  229.  *
  230.  * @param id ID of contact
  231.  * @param done Optional callback function for async execution
  232.  * @returns {T|*} Contact object
  233.  */
  234. window.WAPI.getContact = function (id, done) {
  235.     const found = window.Store.Contact.get(id);
  236.  
  237.     if (done !== undefined) done(window.WAPI._serializeContactObj(found))
  238.     return window.WAPI._serializeContactObj(found);
  239. };
  240.  
  241. /**
  242.  * Fetches all chat objects from store
  243.  *
  244.  * @param done Optional callback function for async execution
  245.  * @returns {Array|*} List of chats
  246.  */
  247. window.WAPI.getAllChats = function (done) {
  248.     const chats = window.Store.Chat.map((chat) => WAPI._serializeChatObj(chat));
  249.  
  250.     if (done !== undefined) done(chats);
  251.     return chats;
  252. };
  253.  
  254. window.WAPI.haveNewMsg = function (chat) {
  255.     return chat.unreadCount > 0;
  256. };
  257.  
  258. window.WAPI.getAllChatsWithNewMsg = function (done) {
  259.     const chats = window.Store.Chat.filter(window.WAPI.haveNewMsg).map((chat) => WAPI._serializeChatObj(chat));
  260.  
  261.     if (done !== undefined) done(chats);
  262.     return chats;
  263. };
  264.  
  265. /**
  266.  * Fetches all chat IDs from store
  267.  *
  268.  * @param done Optional callback function for async execution
  269.  * @returns {Array|*} List of chat id's
  270.  */
  271. window.WAPI.getAllChatIds = function (done) {
  272.     const chatIds = window.Store.Chat.map((chat) => chat.id._serialized || chat.id);
  273.  
  274.     if (done !== undefined) done(chatIds);
  275.     return chatIds;
  276. };
  277.  
  278. /**
  279.  * Fetches all groups objects from store
  280.  *
  281.  * @param done Optional callback function for async execution
  282.  * @returns {Array|*} List of chats
  283.  */
  284. window.WAPI.getAllGroups = function (done) {
  285.     const groups = window.Store.Chat.filter((chat) => chat.isGroup);
  286.  
  287.     if (done !== undefined) done(groups);
  288.     return groups;
  289. };
  290.  
  291. /**
  292.  * Fetches chat object from store by ID
  293.  *
  294.  * @param id ID of chat
  295.  * @param done Optional callback function for async execution
  296.  * @returns {T|*} Chat object
  297.  */
  298. window.WAPI.getChat = function (id, done) {
  299.     id = typeof id == "string" ? id : id._serialized;
  300.     const found = window.Store.Chat.get(id);
  301.     //found.sendMessage = (found.sendMessage) ? found.sendMessage : function () { return window.Store.sendMessage.apply(this, arguments); };
  302.    if (!found) {
  303.     const ConstructChat = new Store.UserConstructor(id, {intentionallyUsePrivateConstructor: true});
  304.    
  305.     chat = Store.Chat.find(ConstructChat);
  306. }
  307.    if (done !== undefined) done(found);
  308.     return found;
  309.    
  310.    
  311.  
  312. }
  313.  
  314. window.WAPI.getChatByName = function (name, done) {
  315.     const found = window.WAPI.getAllChats().find(val => val.name.includes(name))
  316.     if (done !== undefined) done(found);
  317.     return found;
  318. };
  319.  
  320. window.WAPI.sendImageFromDatabasePicBot = function (picId, chatId, caption) {
  321.     var chatDatabase = window.WAPI.getChatByName('DATABASEPICBOT');
  322.     var msgWithImg   = chatDatabase.msgs.find((msg) => msg.caption == picId);
  323.  
  324.     if (msgWithImg === undefined) {
  325.         return false;
  326.     }
  327.     var chatSend = WAPI.getChat(chatId);
  328.     if (chatSend === undefined) {
  329.         return false;
  330.     }
  331.     const oldCaption = msgWithImg.caption;
  332.  
  333.     msgWithImg.id.id     = window.WAPI.getNewId();
  334.     msgWithImg.id.remote = chatId;
  335.     msgWithImg.t         = Math.ceil(new Date().getTime() / 1000);
  336.     msgWithImg.to        = chatId;
  337.  
  338.     if (caption !== undefined && caption !== '') {
  339.         msgWithImg.caption = caption;
  340.     } else {
  341.         msgWithImg.caption = '';
  342.     }
  343.  
  344.     msgWithImg.collection.send(msgWithImg).then(function (e) {
  345.         msgWithImg.caption = oldCaption;
  346.     });
  347.  
  348.     return true;
  349. };
  350.  
  351. window.WAPI.sendMessageWithThumb = function (thumb, url, title, description, text, chatId, done) {
  352.     var chatSend = WAPI.getChat(chatId);
  353.     if (chatSend === undefined) {
  354.         if (done !== undefined) done(false);
  355.         return false;
  356.     }
  357.     var linkPreview = {
  358.         canonicalUrl: url,
  359.         description : description,
  360.         matchedText : url,
  361.         title       : title,
  362.         thumbnail   : thumb,
  363.         compose: true
  364.     };
  365.     chatSend.sendMessage(text, { linkPreview: linkPreview,
  366.                                 mentionedJidList: [],
  367.                                 quotedMsg: null,
  368.                                 quotedMsgAdminGroupJid: null });
  369.     if (done !== undefined) done(true);
  370.     return true;
  371. };
  372.  
  373. window.WAPI.getNewId = function () {
  374.     var text     = "";
  375.     var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  376.  
  377.     for (var i = 0; i < 20; i++)
  378.         text += possible.charAt(Math.floor(Math.random() * possible.length));
  379.     return text;
  380. };
  381.  
  382. window.WAPI.getChatById = function (id, done) {
  383.     let found = WAPI.getChat(id);
  384.     if (found) {
  385.         found = WAPI._serializeChatObj(found);
  386.     } else {
  387.         found = false;
  388.     }
  389.  
  390.     if (done !== undefined) done(found);
  391.     return found;
  392. };
  393.  
  394.  
  395. /**
  396.  * I return all unread messages from an asked chat and mark them as read.
  397.  *
  398.  * :param id: chat id
  399.  * :type  id: string
  400.  *
  401.  * :param includeMe: indicates if user messages have to be included
  402.  * :type  includeMe: boolean
  403.  *
  404.  * :param includeNotifications: indicates if notifications have to be included
  405.  * :type  includeNotifications: boolean
  406.  *
  407.  * :param done: callback passed by selenium
  408.  * :type  done: function
  409.  *
  410.  * :returns: list of unread messages from asked chat
  411.  * :rtype: object
  412.  */
  413. window.WAPI.getUnreadMessagesInChat = function (id, includeMe, includeNotifications, done) {
  414.     // get chat and its messages
  415.     let chat     = WAPI.getChat(id);
  416.     let messages = chat.msgs._models;
  417.  
  418.     // initialize result list
  419.     let output = [];
  420.  
  421.     // look for unread messages, newest is at the end of array
  422.     for (let i = messages.length - 1; i >= 0; i--) {
  423.         // system message: skip it
  424.         if (i === "remove") {
  425.             continue;
  426.         }
  427.  
  428.         // get message
  429.         let messageObj = messages[i];
  430.  
  431.         // found a read message: stop looking for others
  432.         if (typeof (messageObj.isNewMsg) !== "boolean" || messageObj.isNewMsg === false) {
  433.             continue;
  434.         } else {
  435.             messageObj.isNewMsg = false;
  436.             // process it
  437.             let message = WAPI.processMessageObj(messageObj,
  438.                     includeMe,
  439.                     includeNotifications);
  440.  
  441.             // save processed message on result list
  442.             if (message)
  443.                 output.push(message);
  444.         }
  445.     }
  446.     // callback was passed: run it
  447.     if (done !== undefined) done(output);
  448.     // return result list
  449.     return output;
  450. }
  451. ;
  452.  
  453.  
  454. /**
  455.  * Load more messages in chat object from store by ID
  456.  *
  457.  * @param id ID of chat
  458.  * @param done Optional callback function for async execution
  459.  * @returns None
  460.  */
  461. window.WAPI.loadEarlierMessages = function (id, done) {
  462.     const found = WAPI.getChat(id);
  463.     if (done !== undefined) {
  464.         found.loadEarlierMsgs().then(function () {
  465.             done()
  466.         });
  467.     } else {
  468.         found.loadEarlierMsgs();
  469.     }
  470. };
  471.  
  472. /**
  473.  * Load more messages in chat object from store by ID
  474.  *
  475.  * @param id ID of chat
  476.  * @param done Optional callback function for async execution
  477.  * @returns None
  478.  */
  479. window.WAPI.loadAllEarlierMessages = function (id, done) {
  480.     const found = WAPI.getChat(id);
  481.     x = function () {
  482.         if (!found.msgs.msgLoadState.noEarlierMsgs) {
  483.             found.loadEarlierMsgs().then(x);
  484.         } else if (done) {
  485.             done();
  486.         }
  487.     };
  488.     x();
  489. };
  490.  
  491. window.WAPI.asyncLoadAllEarlierMessages = function (id, done) {
  492.     done();
  493.     window.WAPI.loadAllEarlierMessages(id);
  494. };
  495.  
  496. window.WAPI.areAllMessagesLoaded = function (id, done) {
  497.     const found = WAPI.getChat(id);
  498.     if (!found.msgs.msgLoadState.noEarlierMsgs) {
  499.         if (done) done(false);
  500.         return false
  501.     }
  502.     if (done) done(true);
  503.     return true
  504. };
  505.  
  506. /**
  507.  * Load more messages in chat object from store by ID till a particular date
  508.  *
  509.  * @param id ID of chat
  510.  * @param lastMessage UTC timestamp of last message to be loaded
  511.  * @param done Optional callback function for async execution
  512.  * @returns None
  513.  */
  514.  
  515. window.WAPI.loadEarlierMessagesTillDate = function (id, lastMessage, done) {
  516.     const found = WAPI.getChat(id);
  517.     x = function () {
  518.         if (found.msgs.models[0].t > lastMessage && !found.msgs.msgLoadState.noEarlierMsgs) {
  519.             found.loadEarlierMsgs().then(x);
  520.         } else {
  521.             done();
  522.         }
  523.     };
  524.     x();
  525. };
  526.  
  527.  
  528. /**
  529.  * Fetches all group metadata objects from store
  530.  *
  531.  * @param done Optional callback function for async execution
  532.  * @returns {Array|*} List of group metadata
  533.  */
  534. window.WAPI.getAllGroupMetadata = function (done) {
  535.     const groupData = window.Store.GroupMetadata.map((groupData) => groupData.all);
  536.  
  537.     if (done !== undefined) done(groupData);
  538.     return groupData;
  539. };
  540.  
  541. /**
  542.  * Fetches group metadata object from store by ID
  543.  *
  544.  * @param id ID of group
  545.  * @param done Optional callback function for async execution
  546.  * @returns {T|*} Group metadata object
  547.  */
  548. window.WAPI.getGroupMetadata = async function (id, done) {
  549.     let output = window.Store.GroupMetadata.get(id);
  550.  
  551.     if (output !== undefined) {
  552.         if (output.stale) {
  553.             await window.Store.GroupMetadata.update(id);
  554.         }
  555.     }
  556.  
  557.     if (done !== undefined) done(output);
  558.     return output;
  559.  
  560. };
  561.  
  562.  
  563. /**
  564.  * Fetches group participants
  565.  *
  566.  * @param id ID of group
  567.  * @returns {Promise.<*>} Yields group metadata
  568.  * @private
  569.  */
  570. window.WAPI._getGroupParticipants = async function (id) {
  571.     const metadata = await WAPI.getGroupMetadata(id);
  572.     return metadata.participants;
  573. };
  574.  
  575. /**
  576.  * Fetches IDs of group participants
  577.  *
  578.  * @param id ID of group
  579.  * @param done Optional callback function for async execution
  580.  * @returns {Promise.<Array|*>} Yields list of IDs
  581.  */
  582. window.WAPI.getGroupParticipantIDs = async function (id, done) {
  583.     const output = (await WAPI._getGroupParticipants(id))
  584.             .map((participant) => participant.id);
  585.  
  586.     if (done !== undefined) done(output);
  587.     return output;
  588. };
  589.  
  590. window.WAPI.getGroupAdmins = async function (id, done) {
  591.     const output = (await WAPI._getGroupParticipants(id))
  592.             .filter((participant) => participant.isAdmin)
  593.             .map((admin) => admin.id);
  594.  
  595.     if (done !== undefined) done(output);
  596.     return output;
  597. };
  598.  
  599. /**
  600.  * Gets object representing the logged in user
  601.  *
  602.  * @returns {Array|*|$q.all}
  603.  */
  604. window.WAPI.getMe = function (done) {
  605.     const rawMe = window.Store.Contact.get(window.Store.Conn.me);
  606.  
  607.     if (done !== undefined) done(rawMe.all);
  608.     return rawMe.all;
  609. };
  610.  
  611. window.WAPI.isLoggedIn = function (done) {
  612.     // Contact always exists when logged in
  613.     const isLogged = window.Store.Contact && window.Store.Contact.checksum !== undefined;
  614.  
  615.     if (done !== undefined) done(isLogged);
  616.  
  617.     return isLogged;
  618. };
  619. window.WAPI.logstatus ='';
  620. window.WAPI.isConnected = function (done) {
  621.     // Phone Disconnected icon appears when phone is disconnected from the tnternet
  622.     const isConnected = document.querySelector('*[data-icon="alert-phone"]') !== null ? false : true;
  623.  
  624.     if (done !== undefined) done(isConnected);
  625.     if(isConnected === true)
  626.     {
  627.          WAPI.logstatus = { sendStatus:1, description:'na' }
  628.     }
  629.     else
  630.     {
  631.          WAPI.logstatus = { sendStatus:0, description:'na' }
  632.     }
  633.     return isConnected;
  634. };
  635.  
  636. window.WAPI.processMessageObj = function (messageObj, includeMe, includeNotifications) {
  637.     if (messageObj.isNotification) {
  638.         if (includeNotifications)
  639.             return WAPI._serializeMessageObj(messageObj);
  640.         else
  641.             return;
  642.         // System message
  643.         // (i.e. "Messages you send to this chat and calls are now secured with end-to-end encryption...")
  644.     } else if (messageObj.id.fromMe === false || includeMe) {
  645.         return WAPI._serializeMessageObj(messageObj);
  646.     }
  647.     return;
  648. };
  649.  
  650. window.WAPI.getAllMessagesInChat = function (id, includeMe, includeNotifications, done) {
  651.     const chat     = WAPI.getChat(id);
  652.     let   output   = [];
  653.     const messages = chat.msgs._models;
  654.  
  655.     for (const i in messages) {
  656.         if (i === "remove") {
  657.             continue;
  658.         }
  659.         const messageObj = messages[i];
  660.  
  661.         let message = WAPI.processMessageObj(messageObj, includeMe, includeNotifications)
  662.         if (message)
  663.             output.push(message);
  664.     }
  665.     if (done !== undefined) done(output);
  666.     return output;
  667. };
  668.  
  669. window.WAPI.getAllMessageIdsInChat = function (id, includeMe, includeNotifications, done) {
  670.     const chat     = WAPI.getChat(id);
  671.     let   output   = [];
  672.     const messages = chat.msgs._models;
  673.  
  674.     for (const i in messages) {
  675.         if ((i === "remove")
  676.                 || (!includeMe && messages[i].isMe)
  677.                 || (!includeNotifications && messages[i].isNotification)) {
  678.             continue;
  679.         }
  680.         output.push(messages[i].id._serialized);
  681.     }
  682.     if (done !== undefined) done(output);
  683.     return output;
  684. };
  685.  
  686. window.WAPI.getMessageById = function (id, done) {
  687.     let result = false;
  688.     try {
  689.         let msg = window.Store.Msg.get(id);
  690.         if (msg) {
  691.             result = WAPI.processMessageObj(msg, true, true);
  692.         }
  693.     } catch (err) { }
  694.  
  695.     if (done !== undefined) {
  696.         done(result);
  697.     } else {
  698.         return result;
  699.     }
  700. };
  701.  
  702. window.WAPI.ReplyMessage = function (idMessage, message, done) {
  703.     var messageObject = window.Store.Msg.get(idMessage);
  704.     if (messageObject === undefined) {
  705.         if (done !== undefined) done(false);
  706.         return false;
  707.     }
  708.     messageObject = messageObject.value();
  709.  
  710.     const chat = WAPI.getChat(messageObject.chat.id)
  711.     if (chat !== undefined) {
  712.         if (done !== undefined) {
  713.             chat.sendMessage(message, null, messageObject).then(function () {
  714.                 function sleep(ms) {
  715.                     return new Promise(resolve => setTimeout(resolve, ms));
  716.                 }
  717.  
  718.                 var trials = 0;
  719.  
  720.                 function check() {
  721.                     for (let i = chat.msgs.models.length - 1; i >= 0; i--) {
  722.                         let msg = chat.msgs.models[i];
  723.  
  724.                         if (!msg.senderObj.isMe || msg.body != message) {
  725.                             continue;
  726.                         }
  727.                         done(WAPI._serializeMessageObj(msg));
  728.                         return True;
  729.                     }
  730.                     trials += 1;
  731.                     console.log(trials);
  732.                     if (trials > 30) {
  733.                         done(true);
  734.                         return;
  735.                     }
  736.                     sleep(500).then(check);
  737.                 }
  738.                 check();
  739.             });
  740.             return true;
  741.         } else {
  742.             chat.sendMessage(message, null, messageObject);
  743.             return true;
  744.         }
  745.     } else {
  746.         if (done !== undefined) done(false);
  747.         return false;
  748.     }
  749. };
  750.  
  751. window.WAPI.sendMessageToID = function (id, message, done) {
  752.     try {
  753.         window.getContact = (id) => {
  754.             return Store.WapQuery.queryExist(id);
  755.         }
  756.         window.getContact(id).then(contact => {
  757.             if (contact.status === 404) {
  758.                 done(true);
  759.             } else {
  760.                 Store.FindChat.findChat(contact.jid).then(chat => {
  761.                     chat.sendMessage(message);
  762.                     return true;
  763.                 }).catch(reject => {
  764.                     if (WAPI.sendMessage(id, message)) {
  765.                         done(true);
  766.                         return true;
  767.                     }else{
  768.                         done(true);
  769.                         return true;
  770.                     }
  771.                 });
  772.             }
  773.         });
  774.     } catch (e) {
  775.         if (window.Store.Chat.length === 0)
  776.             return false;
  777.  
  778.         firstChat = Store.Chat.models[0];
  779.         var originalID = firstChat.id;
  780.         firstChat.id = typeof originalID === "string" ? id : new window.Store.UserConstructor(id, { intentionallyUsePrivateConstructor: true });
  781.         if (done !== undefined) {
  782.             firstChat.sendMessage(message).then(function () {
  783.                 firstChat.id = originalID;
  784.                 done(true);
  785.             });
  786.             return true;
  787.         } else {
  788.             firstChat.sendMessage(message);
  789.             firstChat.id = originalID;
  790.             return true;
  791.         }
  792.     }
  793.     if (done !== undefined) done(false);
  794.     return false;
  795. }
  796.  
  797. window.WAPI.sendMessage = function (id, message, done) {
  798.     var chat = WAPI.getChat(id);
  799.     if (chat !== undefined) {
  800.         if (done !== undefined) {
  801.             chat.sendMessage(message).then(function () {
  802.                 function sleep(ms) {
  803.                     return new Promise(resolve => setTimeout(resolve, ms));
  804.                 }
  805.  
  806.                 var trials = 0;
  807.  
  808.                 function check() {
  809.                     for (let i = chat.msgs.models.length - 1; i >= 0; i--) {
  810.                         let msg = chat.msgs.models[i];
  811.  
  812.                         if (!msg.senderObj.isMe || msg.body != message) {
  813.                             continue;
  814.                         }
  815.                         done(WAPI._serializeMessageObj(msg));
  816.                         return True;
  817.                     }
  818.                     trials += 1;
  819.                     console.log(trials);
  820.                     if (trials > 30) {
  821.                         done(true);
  822.                         return;
  823.                     }
  824.                     sleep(500).then(check);
  825.                 }
  826.                 check();
  827.             });
  828.             return true;
  829.         } else {
  830.             chat.sendMessage(message);
  831.             return true;
  832.         }
  833.     } else {
  834.         if (done !== undefined) done(false);
  835.         return false;
  836.     }
  837. };
  838. window.WAPI.newRMessages=[];
  839. window.WAPI.msgstatus ='';
  840. window.WAPI.send = function (_id,_msg) {
  841.     var today = Date(Date.now());
  842. console.log(today);
  843.  WAPI.msgstatus = {id:_id, message:_msg, sendDate:today, sendStatus:0, err:404 , description:'na' }
  844.  
  845.  if (WAPI.isLoggedIn() === true) {
  846.     WAPI.checkNumberStatus(_id, id=>{
  847.         if (id.status===200){
  848.             WAPI.sendMessageToID(_id,_msg);
  849.             console.log('Message queded' );
  850.             WAPI.msgstatus = {id:_id, message:_msg, sendDate:today, sendStatus:1, err:200 , description:'Message queded' }
  851.         }
  852.         else{
  853.             WAPI.msgstatus = {id:_id, message:_msg, sendDate:today, sendStatus:0, err:404 , description:'Account do not exsist' }
  854.                 console.log('Account do not exsist' );
  855.         }
  856.     });
  857.  
  858.  } else {
  859.     WAPI.msgstatus = {id:_id, message:_msg, sendDate:today, sendStatus:0, err:401 , description:'Not loggedin' }
  860.   }
  861.  
  862. }
  863.  
  864. window.WAPI.sendMessage2 = function (id, message, done) {
  865.     var chat = WAPI.getChat(id);
  866.      var today = Date(Date.now());
  867.     console.log(today);
  868.      WAPI.msgstatus = {id:id, message:message, sendDate:today, sendStatus:0, err:404 , description:'na' }
  869.      
  870.      var today = Date(Date.now());
  871.     if (chat !== undefined) {
  872.         try {
  873.             if (done !== undefined) {
  874.                 chat.sendMessage(message).then(function () {
  875.                     //console.log('message Sent' );
  876.                     done(true);
  877.                 });
  878.             } else {
  879.                 chat.sendMessage(message);
  880.                 //console.log('message Sent 2' );
  881.             }
  882.               WAPI.msgstatus = {id:id, message:message, sendDate:today, sendStatus:1, err:200 , description:'Message queded' }
  883.  
  884.             return true;
  885.         } catch (error) {
  886.             if (done !== undefined)
  887.             {
  888.                 done(false)
  889.                         console.log('message Sent undefined' );
  890.                      WAPI.msgstatus = {id:id, message:message, sendDate:today, sendStatus:0, err:404 , description:'Account do not exsist' }
  891.             return false;
  892.             }              
  893.         }
  894.     }
  895.     if (done !== undefined)
  896.     {
  897.         done(false)
  898.          WAPI.msgstatus = {id:id, message:message, sendDate:today, sendStatus:0, err:404 , description:'Account do not exsist' }
  899.     }      
  900.        
  901.     return false;
  902. };
  903.  
  904. window.WAPI.sendSeen = function (id, done) {
  905.     var chat = window.WAPI.getChat(id);
  906.     if (chat !== undefined) {
  907.         if (done !== undefined) {
  908.             if (chat.getLastMsgKeyForAction === undefined)
  909.                 chat.getLastMsgKeyForAction = function () { };
  910.             Store.SendSeen(chat, false).then(function () {
  911.                 done(true);
  912.             });
  913.             return true;
  914.         } else {
  915.             Store.SendSeen(chat, false);
  916.             return true;
  917.         }
  918.     }
  919.     if (done !== undefined) done();
  920.     return false;
  921. };
  922.  
  923. function isChatMessage(message) {
  924.     if (message.isSentByMe) {
  925.         return false;
  926.     }
  927.     if (message.isNotification) {
  928.         return false;
  929.     }
  930.     if (!message.isUserCreatedType) {
  931.         return false;
  932.     }
  933.     return true;
  934. }
  935.  
  936.  
  937. window.WAPI.getUnreadMessages = function (includeMe, includeNotifications, use_unread_count, done) {
  938.     const chats  = window.Store.Chat.models;
  939.     let   output = [];
  940.  
  941.     for (let chat in chats) {
  942.         if (isNaN(chat)) {
  943.             continue;
  944.         }
  945.  
  946.         let messageGroupObj = chats[chat];
  947.         let messageGroup    = WAPI._serializeChatObj(messageGroupObj);
  948.  
  949.         messageGroup.messages = [];
  950.  
  951.         const messages = messageGroupObj.msgs._models;
  952.         for (let i = messages.length - 1; i >= 0; i--) {
  953.             let messageObj = messages[i];
  954.             if (typeof (messageObj.isNewMsg) != "boolean" || messageObj.isNewMsg === false) {
  955.                 continue;
  956.             } else {
  957.                 messageObj.isNewMsg = false;
  958.                 let message = WAPI.processMessageObj(messageObj, includeMe, includeNotifications);
  959.                 if (message) {
  960.                     messageGroup.messages.push(message);
  961.                 }
  962.             }
  963.         }
  964.  
  965.         if (messageGroup.messages.length > 0) {
  966.             output.push(messageGroup);
  967.         } else { // no messages with isNewMsg true
  968.             if (use_unread_count) {
  969.                 let n = messageGroupObj.unreadCount; // will use unreadCount attribute to fetch last n messages from sender
  970.                 for (let i = messages.length - 1; i >= 0; i--) {
  971.                     let messageObj = messages[i];
  972.                     if (n > 0) {
  973.                         if (!messageObj.isSentByMe) {
  974.                             let message = WAPI.processMessageObj(messageObj, includeMe, includeNotifications);
  975.                             messageGroup.messages.unshift(message);
  976.                             n -= 1;
  977.                         }
  978.                     } else if (n === -1) { // chat was marked as unread so will fetch last message as unread
  979.                         if (!messageObj.isSentByMe) {
  980.                             let message = WAPI.processMessageObj(messageObj, includeMe, includeNotifications);
  981.                             messageGroup.messages.unshift(message);
  982.                             break;
  983.                         }
  984.                     } else { // unreadCount = 0
  985.                         break;
  986.                     }
  987.                 }
  988.                 if (messageGroup.messages.length > 0) {
  989.                     messageGroupObj.unreadCount = 0; // reset unread counter
  990.                     output.push(messageGroup);
  991.                 }
  992.             }
  993.         }
  994.     }
  995.     if (done !== undefined) {
  996.         done(output);
  997.     }
  998.     return output;
  999. };
  1000.  
  1001. window.WAPI.getGroupOwnerID = async function (id, done) {
  1002.     const output = (await WAPI.getGroupMetadata(id)).owner.id;
  1003.     if (done !== undefined) {
  1004.         done(output);
  1005.     }
  1006.     return output;
  1007.  
  1008. };
  1009.  
  1010. window.WAPI.getCommonGroups = async function (id, done) {
  1011.     let output = [];
  1012.  
  1013.     groups = window.WAPI.getAllGroups();
  1014.  
  1015.     for (let idx in groups) {
  1016.         try {
  1017.             participants = await window.WAPI.getGroupParticipantIDs(groups[idx].id);
  1018.             if (participants.filter((participant) => participant == id).length) {
  1019.                 output.push(groups[idx]);
  1020.             }
  1021.         } catch (err) {
  1022.             console.log("Error in group:");
  1023.             console.log(groups[idx]);
  1024.             console.log(err);
  1025.         }
  1026.     }
  1027.  
  1028.     if (done !== undefined) {
  1029.         done(output);
  1030.     }
  1031.     return output;
  1032. };
  1033.  
  1034.  
  1035. window.WAPI.getProfilePicSmallFromId = function (id, done) {
  1036.     window.Store.ProfilePicThumb.find(id).then(function (d) {
  1037.         if (d.img !== undefined) {
  1038.             window.WAPI.downloadFileWithCredentials(d.img, done);
  1039.         } else {
  1040.             done(false);
  1041.         }
  1042.     }, function (e) {
  1043.         done(false);
  1044.     })
  1045. };
  1046.  
  1047. window.WAPI.getProfilePicFromId = function (id, done) {
  1048.     window.Store.ProfilePicThumb.find(id).then(function (d) {
  1049.         if (d.imgFull !== undefined) {
  1050.             window.WAPI.downloadFileWithCredentials(d.imgFull, done);
  1051.         } else {
  1052.             done(false);
  1053.         }
  1054.     }, function (e) {
  1055.         done(false);
  1056.     })
  1057. };
  1058.  
  1059. window.WAPI.downloadFileWithCredentials = function (url, done) {
  1060.     let xhr = new XMLHttpRequest();
  1061.  
  1062.     xhr.onload = function () {
  1063.         if (xhr.readyState == 4) {
  1064.             if (xhr.status == 200) {
  1065.                 let reader = new FileReader();
  1066.                 reader.readAsDataURL(xhr.response);
  1067.                 reader.onload = function (e) {
  1068.                     done(reader.result.substr(reader.result.indexOf(',') + 1))
  1069.                 };
  1070.             } else {
  1071.                 console.error(xhr.statusText);
  1072.             }
  1073.         } else {
  1074.             console.log(err);
  1075.             done(false);
  1076.         }
  1077.     };
  1078.  
  1079.     xhr.open("GET", url, true);
  1080.     xhr.withCredentials = true;
  1081.     xhr.responseType = 'blob';
  1082.     xhr.send(null);
  1083. };
  1084.  
  1085.  
  1086. window.WAPI.downloadFile = function (url, done) {
  1087.     let xhr = new XMLHttpRequest();
  1088.  
  1089.  
  1090.     xhr.onload = function () {
  1091.         if (xhr.readyState == 4) {
  1092.             if (xhr.status == 200) {
  1093.                 let reader = new FileReader();
  1094.                 reader.readAsDataURL(xhr.response);
  1095.                 reader.onload = function (e) {
  1096.                     done(reader.result.substr(reader.result.indexOf(',') + 1))
  1097.                 };
  1098.             } else {
  1099.                 console.error(xhr.statusText);
  1100.             }
  1101.         } else {
  1102.             console.log(err);
  1103.             done(false);
  1104.         }
  1105.     };
  1106.  
  1107.     xhr.open("GET", url, true);
  1108.     xhr.responseType = 'blob';
  1109.     xhr.send(null);
  1110. };
  1111.  
  1112. window.WAPI.getBatteryLevel = function (done) {
  1113.     if (window.Store.Conn.plugged) {
  1114.         if (done !== undefined) {
  1115.             done(100);
  1116.         }
  1117.         return 100;
  1118.     }
  1119.     output = window.Store.Conn.battery;
  1120.     if (done !== undefined) {
  1121.         done(output);
  1122.     }
  1123.     return output;
  1124. };
  1125.  
  1126. window.WAPI.deleteConversation = function (chatId, done) {
  1127.     let userId       = new window.Store.UserConstructor(chatId, {intentionallyUsePrivateConstructor: true});
  1128.     let conversation = WAPI.getChat(userId);
  1129.  
  1130.     if (!conversation) {
  1131.         if (done !== undefined) {
  1132.             done(false);
  1133.         }
  1134.         return false;
  1135.     }
  1136.  
  1137.     window.Store.sendDelete(conversation, false).then(() => {
  1138.         if (done !== undefined) {
  1139.             done(true);
  1140.         }
  1141.     }).catch(() => {
  1142.         if (done !== undefined) {
  1143.             done(false);
  1144.         }
  1145.     });
  1146.  
  1147.     return true;
  1148. };
  1149.  
  1150. window.WAPI.deleteMessage = function (chatId, messageArray, revoke=false, done) {
  1151.     let userId       = new window.Store.UserConstructor(chatId, {intentionallyUsePrivateConstructor: true});
  1152.     let conversation = WAPI.getChat(userId);
  1153.  
  1154.     if(!conversation) {
  1155.         if(done !== undefined) {
  1156.             done(false);
  1157.         }
  1158.         return false;
  1159.     }
  1160.  
  1161.     if (!Array.isArray(messageArray)) {
  1162.         messageArray = [messageArray];
  1163.     }
  1164.     let messagesToDelete = messageArray.map(msgId => window.Store.Msg.get(msgId));
  1165.  
  1166.     if (revoke) {
  1167.         conversation.sendRevokeMsgs(messagesToDelete, conversation);
  1168.     } else {
  1169.         conversation.sendDeleteMsgs(messagesToDelete, conversation);
  1170.     }
  1171.  
  1172.  
  1173.     if (done !== undefined) {
  1174.         done(true);
  1175.     }
  1176.  
  1177.     return true;
  1178. };
  1179.  
  1180. window.WAPI.checkNumberStatus = function (id, done) {
  1181.     window.Store.WapQuery.queryExist(id).then((result) => {
  1182.         if( done !== undefined) {
  1183.             if (result.jid === undefined) throw 404;
  1184.             done(window.WAPI._serializeNumberStatusObj(result));
  1185.         }
  1186.     }).catch((e) => {
  1187.         if (done !== undefined) {
  1188.             done(window.WAPI._serializeNumberStatusObj({
  1189.                 status: e,
  1190.                 jid   : id
  1191.             }));
  1192.         }
  1193.     });
  1194.  
  1195.     return true;
  1196. };
  1197.  
  1198. /**
  1199.  * New messages observable functions.
  1200.  */
  1201. window.WAPI._newMessagesQueue     = [];
  1202. window.WAPI._newMessagesBuffer    = (sessionStorage.getItem('saved_msgs') != null) ? JSON.parse(sessionStorage.getItem('saved_msgs')) : [];
  1203. window.WAPI._newMessagesDebouncer = null;
  1204. window.WAPI._newMessagesCallbacks = [];
  1205.  
  1206. window.Store.Msg.off('add');
  1207. sessionStorage.removeItem('saved_msgs');
  1208.  
  1209. window.WAPI._newMessagesListener = window.Store.Msg.on('add', (newMessage) => {
  1210.     if (newMessage && newMessage.isNewMsg && !newMessage.isSentByMe) {
  1211.         let message = window.WAPI.processMessageObj(newMessage, false, false);
  1212.         if (message) {
  1213.             window.WAPI._newMessagesQueue.push(message);
  1214.             window.WAPI._newMessagesBuffer.push(message);
  1215.         }
  1216.  
  1217.         // Starts debouncer time to don't call a callback for each message if more than one message arrives
  1218.         // in the same second
  1219.         if (!window.WAPI._newMessagesDebouncer && window.WAPI._newMessagesQueue.length > 0) {
  1220.             window.WAPI._newMessagesDebouncer = setTimeout(() => {
  1221.                 let queuedMessages = window.WAPI._newMessagesQueue;
  1222.  
  1223.                 window.WAPI._newMessagesDebouncer = null;
  1224.                 window.WAPI._newMessagesQueue     = [];
  1225.  
  1226.                 let removeCallbacks = [];
  1227.  
  1228.                 window.WAPI._newMessagesCallbacks.forEach(function (callbackObj) {
  1229.                     if (callbackObj.callback !== undefined) {
  1230.                         callbackObj.callback(queuedMessages);
  1231.                     }
  1232.                     if (callbackObj.rmAfterUse === true) {
  1233.                         removeCallbacks.push(callbackObj);
  1234.                     }
  1235.                 });
  1236.  
  1237.                 // Remove removable callbacks.
  1238.                 removeCallbacks.forEach(function (rmCallbackObj) {
  1239.                     let callbackIndex = window.WAPI._newMessagesCallbacks.indexOf(rmCallbackObj);
  1240.                     window.WAPI._newMessagesCallbacks.splice(callbackIndex, 1);
  1241.                 });
  1242.             }, 1000);
  1243.         }
  1244.     }
  1245. });
  1246.  
  1247. window.WAPI._unloadInform = (event) => {
  1248.     // Save in the buffer the ungot unreaded messages
  1249.     window.WAPI._newMessagesBuffer.forEach((message) => {
  1250.         Object.keys(message).forEach(key => message[key] === undefined ? delete message[key] : '');
  1251.     });
  1252.     sessionStorage.setItem("saved_msgs", JSON.stringify(window.WAPI._newMessagesBuffer));
  1253.  
  1254.     // Inform callbacks that the page will be reloaded.
  1255.     window.WAPI._newMessagesCallbacks.forEach(function (callbackObj) {
  1256.         if (callbackObj.callback !== undefined) {
  1257.             callbackObj.callback({ status: -1, message: 'page will be reloaded, wait and register callback again.' });
  1258.         }
  1259.     });
  1260. };
  1261.  
  1262. window.addEventListener("unload", window.WAPI._unloadInform, false);
  1263. window.addEventListener("beforeunload", window.WAPI._unloadInform, false);
  1264. window.addEventListener("pageunload", window.WAPI._unloadInform, false);
  1265.  
  1266. /**
  1267.  * Registers a callback to be called when a new message arrives the WAPI.
  1268.  * @param rmCallbackAfterUse - Boolean - Specify if the callback need to be executed only once
  1269.  * @param done - function - Callback function to be called when a new message arrives.
  1270.  * @returns {boolean}
  1271.  */
  1272. window.WAPI.waitNewMessages = function (rmCallbackAfterUse = true, done) {
  1273.     window.WAPI._newMessagesCallbacks.push({ callback: done, rmAfterUse: rmCallbackAfterUse });
  1274.     return true;
  1275. };
  1276.  
  1277. /**
  1278.  * Reads buffered new messages.
  1279.  * @param done - function - Callback function to be called contained the buffered messages.
  1280.  * @returns {Array}
  1281.  */
  1282. window.WAPI.getBufferedNewMessages = function (done) {
  1283.     let bufferedMessages = window.WAPI._newMessagesBuffer;
  1284.     window.WAPI._newMessagesBuffer = [];
  1285.     if (done !== undefined) {
  1286.         done(bufferedMessages);
  1287.     }
  1288.     return bufferedMessages;
  1289. };
  1290. /** End new messages observable functions **/
  1291.  
  1292. window.WAPI.sendImage = function (imgBase64, chatid, filename, caption, done) {
  1293. //var idUser = new window.Store.UserConstructor(chatid);
  1294. var idUser = new window.Store.UserConstructor(chatid, { intentionallyUsePrivateConstructor: true });
  1295. // create new chat
  1296. return Store.FindChat.findChat(idUser).then((chat) => {
  1297.     var mediaBlob = window.WAPI.base64ImageToFile(imgBase64, filename);
  1298.     var mc = new Store.MediaCollection(chat);
  1299.     mc.processAttachments([{file: mediaBlob}, 1], chat, 1).then(() => {
  1300.         var media = mc.models[0];
  1301.         media.sendToChat(chat, { caption: caption });
  1302.         if (done !== undefined) done(true);
  1303.     });
  1304. });
  1305. }
  1306.  
  1307. window.WAPI.base64ImageToFile = function (b64Data, filename) {
  1308.     var arr   = b64Data.split(',');
  1309.     var mime  = arr[0].match(/:(.*?);/)[1];
  1310.     var bstr  = atob(arr[1]);
  1311.     var n     = bstr.length;
  1312.     var u8arr = new Uint8Array(n);
  1313.  
  1314.     while (n--) {
  1315.         u8arr[n] = bstr.charCodeAt(n);
  1316.     }
  1317.  
  1318.     return new File([u8arr], filename, {type: mime});
  1319. };
  1320.  
  1321. /**
  1322.  * Send contact card to a specific chat using the chat ids
  1323.  *
  1324.  * @param {string} to '000000000000@c.us'
  1325.  * @param {string|array} contact '111111111111@c.us' | ['222222222222@c.us', '333333333333@c.us, ... 'nnnnnnnnnnnn@c.us']
  1326.  */
  1327. window.WAPI.sendContact = function (to, contact) {
  1328.     if (!Array.isArray(contact)) {
  1329.         contact = [contact];
  1330.     }
  1331.     contact = contact.map((c) => {
  1332.         return WAPI.getChat(c).__x_contact;
  1333.     });
  1334.  
  1335.     if (contact.length > 1) {
  1336.         window.WAPI.getChat(to).sendContactList(contact);
  1337.     } else if (contact.length === 1) {
  1338.         window.WAPI.getChat(to).sendContact(contact[0]);
  1339.     }
  1340. };
  1341.  
  1342. /**
  1343.  * Create an chat ID based in a cloned one
  1344.  *
  1345.  * @param {string} chatId '000000000000@c.us'
  1346.  */
  1347. window.WAPI.getNewMessageId = function (chatId) {
  1348.     var newMsgId = Store.Msg.models[0].__x_id.clone();
  1349.  
  1350.     newMsgId.fromMe      = true;
  1351.     newMsgId.id          = WAPI.getNewId().toUpperCase();
  1352.     newMsgId.remote      = chatId;
  1353.     newMsgId._serialized = `${newMsgId.fromMe}_${newMsgId.remote}_${newMsgId.id}`
  1354.  
  1355.     return newMsgId;
  1356. };
  1357.  
  1358. /**
  1359.  * Send Customized VCard without the necessity of contact be a Whatsapp Contact
  1360.  *
  1361.  * @param {string} chatId '000000000000@c.us'
  1362.  * @param {object|array} vcard { displayName: 'Contact Name', vcard: 'BEGIN:VCARD\nVERSION:3.0\nN:;Contact Name;;;\nEND:VCARD' } | [{ displayName: 'Contact Name 1', vcard: 'BEGIN:VCARD\nVERSION:3.0\nN:;Contact Name 1;;;\nEND:VCARD' }, { displayName: 'Contact Name 2', vcard: 'BEGIN:VCARD\nVERSION:3.0\nN:;Contact Name 2;;;\nEND:VCARD' }]
  1363.  */
  1364. window.WAPI.sendVCard = function (chatId, vcard) {
  1365.     var chat    = Store.Chat.get(chatId);
  1366.     var tempMsg = Object.create(Store.Msg.models.filter(msg => msg.__x_isSentByMe)[0]);
  1367.     var newId   = window.WAPI.getNewMessageId(chatId);
  1368.  
  1369.     var extend = {
  1370.         ack     : 0,
  1371.         id      : newId,
  1372.         local   : !0,
  1373.         self    : "out",
  1374.         t       : parseInt(new Date().getTime() / 1000),
  1375.         to      : chatId,
  1376.         isNewMsg: !0,
  1377.     };
  1378.  
  1379.     if (Array.isArray(vcard)) {
  1380.         Object.assign(extend, {
  1381.             type     : "multi_vcard",
  1382.             vcardList: vcard
  1383.         });
  1384.  
  1385.         delete extend.body;
  1386.     } else {
  1387.         Object.assign(extend, {
  1388.             type   : "vcard",
  1389.             subtype: vcard.displayName,
  1390.             body   : vcard.vcard
  1391.         });
  1392.  
  1393.         delete extend.vcardList;
  1394.     }
  1395.  
  1396.     Object.assign(tempMsg, extend);
  1397.  
  1398.     chat.addAndSendMsg(tempMsg);
  1399. };
  1400. /**
  1401.  * Block contact
  1402.  * @param {string} id '000000000000@c.us'
  1403.  * @param {*} done - function - Callback function to be called when a new message arrives.
  1404.  */
  1405. window.WAPI.contactBlock = function (id, done) {
  1406.     const contact = window.Store.Contact.get(id);
  1407.     if (contact !== undefined) {
  1408.         contact.setBlock(!0);
  1409.         done(true);
  1410.         return true;
  1411.     }
  1412.     done(false);
  1413.     return false;
  1414. }
  1415. /**
  1416.  * unBlock contact
  1417.  * @param {string} id '000000000000@c.us'
  1418.  * @param {*} done - function - Callback function to be called when a new message arrives.
  1419.  */
  1420. window.WAPI.contactUnblock = function (id, done) {
  1421.     const contact = window.Store.Contact.get(id);
  1422.     if (contact !== undefined) {
  1423.         contact.setBlock(!1);
  1424.         done(true);
  1425.         return true;
  1426.     }
  1427.     done(false);
  1428.     return false;
  1429. }
  1430.  
  1431. /**
  1432.  * Remove participant of Group
  1433.  * @param {*} idGroup '0000000000-00000000@g.us'
  1434.  * @param {*} idParticipant '000000000000@c.us'
  1435.  * @param {*} done - function - Callback function to be called when a new message arrives.
  1436.  */
  1437. window.WAPI.removeParticipantGroup = function (idGroup, idParticipant, done) {
  1438.     window.Store.WapQuery.removeParticipants(idGroup, [idParticipant]).then(() => {
  1439.         const metaDataGroup = window.Store.GroupMetadata.get(id)
  1440.         checkParticipant = metaDataGroup.participants._index[idParticipant];
  1441.         if (checkParticipant === undefined) {
  1442.             done(true); return true;
  1443.         }
  1444.     })
  1445. }
  1446.  
  1447. /**
  1448.  * Promote Participant to Admin in Group
  1449.  * @param {*} idGroup '0000000000-00000000@g.us'
  1450.  * @param {*} idParticipant '000000000000@c.us'
  1451.  * @param {*} done - function - Callback function to be called when a new message arrives.
  1452.  */
  1453. window.WAPI.promoteParticipantAdminGroup = function (idGroup, idParticipant, done) {
  1454.     window.Store.WapQuery.promoteParticipants(idGroup, [idParticipant]).then(() => {
  1455.         const metaDataGroup = window.Store.GroupMetadata.get(id)
  1456.         checkParticipant = metaDataGroup.participants._index[idParticipant];
  1457.         if (checkParticipant !== undefined && checkParticipant.isAdmin) {
  1458.             done(true); return true;
  1459.         }
  1460.         done(false); return false;
  1461.     })
  1462. }
  1463.  
  1464. /**
  1465.  * Demote Admin of Group
  1466.  * @param {*} idGroup '0000000000-00000000@g.us'
  1467.  * @param {*} idParticipant '000000000000@c.us'
  1468.  * @param {*} done - function - Callback function to be called when a new message arrives.
  1469.  */
  1470. window.WAPI.demoteParticipantAdminGroup = function (idGroup, idParticipant, done) {
  1471.     window.Store.WapQuery.demoteParticipants(idGroup, [idParticipant]).then(() => {
  1472.         const metaDataGroup = window.Store.GroupMetadata.get(id)
  1473.         if (metaDataGroup === undefined) {
  1474.             done(false); return false;
  1475.         }
  1476.         checkParticipant = metaDataGroup.participants._index[idParticipant];
  1477.         if (checkParticipant !== undefined && checkParticipant.isAdmin) {
  1478.             done(false); return false;
  1479.         }
  1480.         done(true); return true;
  1481.     })
  1482. }
  1483.  
  1484. window.WAPI.sendStatus = false;
  1485. window.WAPI.sendSafe = function (id, message) {
  1486.  
  1487.    
  1488.    if (!id.includes("@g.us"))
  1489.    {
  1490.    Store.WapQuery.queryExist(id).then((e) => {
  1491.  
  1492.         if (e.status === 200) {
  1493.             try {
  1494.                 WAPI.sendStatus = WAPI.sendMessage(id, message);
  1495.             }
  1496.             catch (err) {
  1497.                 WAPI.sendStatus = false;
  1498.             }
  1499.         }
  1500.     })
  1501.    }else
  1502.    {
  1503.            WAPI.sendStatus = WAPI.sendMessage(id, message);
  1504.    }
  1505.    
  1506.  
  1507. }
  1508. window.WAPI.sendUnsafe = function (id, message) {
  1509.        if (!id.includes("@g.us"))
  1510.        {
  1511.     Store.WapQuery.queryExist(id).then((e) => {
  1512.         if (e.status === 200) {
  1513.             WAPI.sendMessageToID(id, message);
  1514.             window.WAPI.sendStatus = true;
  1515.         } else {
  1516.             window.WAPI.sendStatus = false;
  1517.  
  1518.         }
  1519.  
  1520.     })
  1521.        }else
  1522.        {
  1523.             WAPI.sendMessageToID(id, message);
  1524.             window.WAPI.sendStatus = true;
  1525.        }
  1526.        
  1527.  
  1528. }
Add Comment
Please, Sign In to add comment