Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: new functions catalog business #255

Merged
merged 3 commits into from
Jun 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ session
session-*
src/app.ts
tokens
yarn.lock
4 changes: 2 additions & 2 deletions examples/basic/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ function start(client) {
client.onMessage((message) => {
if (message.body === 'Hi' && message.isGroupMsg === false) {
client
.sendText(message.from, 'Welcome Wppconnect 🕷')
.sendText(message.from, 'Welcome Wppconnect')
.then((result) => {
console.log('Result: ', result); //return object success
})
Expand All @@ -36,4 +36,4 @@ function start(client) {
});
}
});
}
}
41 changes: 41 additions & 0 deletions src/api/helpers/evaluate-and-return.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,48 @@ export async function evaluateAndReturn<T extends EvaluateFn>(
}
}

/**
* Polyfill async/await and promise converter
* See https://github.com/basarat/typescript-book/blob/master/docs/async-await.md
*/
const func = new Function(`
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var _this; // for arrow function
return Promise.resolve(
(${functionText}).apply(this, arguments)
).catch((error) => ({
Expand Down
26 changes: 20 additions & 6 deletions src/api/layers/business.layer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,39 @@

import { Page } from 'puppeteer';
import { ControlsLayer } from './controls.layer';
import { CreateConfig } from '../../config/create-config';
import { evaluateAndReturn } from '../helpers';

export class BusinessLayer extends ControlsLayer {
constructor(page: Page) {
super(page);
constructor(public page: Page, session?: string, options?: CreateConfig) {
super(page, session, options);
}

/**
* Querys product catalog
* @param id Buisness profile id ('00000@c.us')
*/
public async getBusinessProfilesProducts(id: string) {
return this.page.evaluate(
({ id }) => {
WAPI.getBusinessProfilesProducts(id);
},
return evaluateAndReturn(
this.page,
({ id }) => WAPI.getBusinessProfilesProducts(id),
{ id }
);
}

/**
* Querys order catalog
* @param messageId string
* @returns Message object
*/
public async getOrderbyMsg(messageId: string) {
return evaluateAndReturn(
this.page,
({ messageId }) => WAPI.getOrderbyMsg(messageId),
{ messageId }
);
}

/**
* Sends product with product image to given chat id
* @param to Chat id
Expand Down
4 changes: 2 additions & 2 deletions src/api/whatsapp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
*/

import { Page } from 'puppeteer';
import { ControlsLayer } from './layers/controls.layer';
import { BusinessLayer } from './layers/business.layer';
import { Message } from './model';
import { magix, timeout, makeOptions } from './helpers/decrypt';
import { useragentOverride } from '../config/WAuserAgente';
Expand All @@ -25,7 +25,7 @@ import axios from 'axios';
import treekill = require('tree-kill');
import { SocketState } from './model/enum';

export class Whatsapp extends ControlsLayer {
export class Whatsapp extends BusinessLayer {
constructor(public page: Page, session?: string, options?: CreateConfig) {
super(page, session, options);

Expand Down
32 changes: 20 additions & 12 deletions src/lib/wapi/business/get-business-profiles-products.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,23 @@
* along with WPPConnect. If not, see <https://www.gnu.org/licenses/>.
*/

window.WAPI.getBusinessProfilesProducts = function (id, done) {
return Store.Catalog.find(id)
.then((resp) => {
if (resp.msgProductCollection && resp.msgProductCollection._models.length)
done();
return resp.productCollection._models;
})
.catch((error) => {
done();
return error.model._products;
});
};
export async function getBusinessProfilesProducts(id) {
let catalog = window.Store.Catalog.get(id);
if (!catalog) {
catalog = await window.Store.Catalog.find(Store.WidFactory.createWid(id));
}

if (!catalog) {
throw {
error: true,
code: 'catalog_not_found',
message: 'Catalog not found',
};
}

if (catalog.productCollection) {
return catalog.productCollection.serialize();
}

return [];
}
54 changes: 54 additions & 0 deletions src/lib/wapi/business/get-order-by-msg.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* This file is part of WPPConnect.
*
* WPPConnect is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* WPPConnect is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with WPPConnect. If not, see <https://www.gnu.org/licenses/>.
*/

import { getMessageById } from '../functions/get-message-by-id';

export async function getOrderbyMsg(msgId) {
let msg = await getMessageById(msgId, null, false);
if (!msg) {
throw {
error: true,
code: 'message_not_found',
message: 'Message not found',
};
}
if (msg.type !== 'order') {
throw {
error: true,
code: 'message_is_not_an_order',
message: 'Message is not an order',
};
}
let order = window.Store.Order.get(msg.orderId);
if (!order) {
order = await window.Store.Order.findOrder(
msg.orderId,
msg.sellerJid,
msg.token
);
}

if (!order) {
throw {
error: true,
code: 'order_not_found',
message: 'Order not found',
};
}

return order.products;
}
2 changes: 2 additions & 0 deletions src/lib/wapi/business/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { getBusinessProfilesProducts } from './get-business-profiles-products';
export { getOrderbyMsg } from './get-order-by-msg';
5 changes: 5 additions & 0 deletions src/lib/wapi/wapi.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ import {
_serializeRawObj,
_profilePicfunc,
} from './serializers';
import { getBusinessProfilesProducts, getOrderbyMsg } from './business';
import { storeObjects } from './store/store-objects';

window['webpackJsonp'] = window['webpackJsonp'] || [];
Expand Down Expand Up @@ -332,6 +333,10 @@ if (typeof window.WAPI === 'undefined') {
window.WAPI.subscribePresence = subscribePresence;
window.WAPI.unsubscribePresence = unsubscribePresence;

// business functions
window.WAPI.getBusinessProfilesProducts = getBusinessProfilesProducts;
window.WAPI.getOrderbyMsg = getOrderbyMsg;

// Listeners initialization
window.WAPI._newMessagesQueue = [];
window.WAPI._newMessagesBuffer =
Expand Down
1 change: 1 addition & 0 deletions src/types/WAPI.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ interface WAPI {
getBatteryLevel: () => number;
getBlockList: () => Contact[];
getBusinessProfilesProducts: (to: string) => any;
getOrderbyMsg: (messageId: string) => any;
getChat: (contactId: string) => Chat;
getChatById: (contactId: string) => Chat;
getChatIsOnline: (chatId: string) => Promise<boolean>;
Expand Down