diff --git a/CHANGELOG.md b/CHANGELOG.md index ad63eb3..5c82c33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,26 @@ # Change Log +## [4.16.0](https://github.com/plivo/plivo-node/releases/tag/v4.16.0)(2021-04-19) +- Added SDK support for Voice MultiPartyCall APIs and XML + +## [4.15.0](https://github.com/plivo/plivo-node/releases/tag/v4.15.0)(2021-04-19) +- Add support for Regulatory Compliance APIs. +- Add "npanxx" and "local_calling_area" support for Search Phone Number. + +## [4.14.3](https://github.com/plivo/plivo-node/releases/tag/v4.14.3)(2021-03-26) +- Fix bug on stopRecording and all voice API flows post Typescript changes. + +## [4.14.2](https://github.com/plivo/plivo-node/releases/tag/v4.14.2)(2021-02-17) +- Fix duplicate call issue for make call API. + +## [4.14.1](https://github.com/plivo/plivo-node/releases/tag/v4.14.1)(2021-02-09) +- Fix Buy Number API & env variables support for TypeScript. + +## [4.14.0](https://github.com/plivo/plivo-node/releases/tag/v4.14.0)(2021-01-29) +- Add axios as HTTP client library. + +## [4.13.0](https://github.com/plivo/plivo-node/releases/tag/v4.13.0)(2021-01-19) +- Add TypeScript support. ## [4.12.0](https://github.com/plivo/plivo-node/releases/tag/v4.12.0)(2020-11-17) - Add number_priority support for Powerpack API. diff --git a/examples/complianceApplications.js b/examples/complianceApplications.js new file mode 100644 index 0000000..9efebe6 --- /dev/null +++ b/examples/complianceApplications.js @@ -0,0 +1,45 @@ +var Plivo = require('../dist/rest/client.js'); +var client = new Plivo.Client(); + +var createParams = { + countryIso2: "US", + numberType: "local", + endUserType: "individual" +}; + +var listParams = { + countryIso2: "US", + numberType: "local", + endUserType: "individual", + limit: 10, + offset: 5 +}; + +var updateParams = { + documentIds: [ "test-1", "test-2"], +}; + +client.complianceApplications.create(createParams) + .then(function(complianceApplication) { + console.log("\n============ created ===========\n", complianceApplication) + return client.complianceApplications.update(complianceApplication.id, updateParams); + }) + .then(function(complianceApplication) { + console.log("\n============ updated ===========\n", complianceApplication) + return client.complianceApplications.get(complianceApplication.id); + }) + .then(function(complianceApplication){ + console.log("\n============ list with id ===========\n", complianceApplication) + return complianceApplications.delete(complianceApplication.id); + }) + .then(function(result){ + console.log("\n============ deleted ===========\n", result) + return client.complianceApplications.list(listParams) + }) + .then(function(complianceApplications){ + console.log("\n============ list all ===========\n", complianceApplications) + }) + .catch(function(response) { + console.log("\n============ Error :: ===========\n", response); + }); + diff --git a/examples/complianceDocumentTypes.js b/examples/complianceDocumentTypes.js new file mode 100644 index 0000000..288eb6d --- /dev/null +++ b/examples/complianceDocumentTypes.js @@ -0,0 +1,21 @@ +var Plivo = require('../dist/rest/client.js'); +var client = new Plivo.Client(); + +var listParams = { + documentName: "Test", + proofRequired: "passport" +}; + +client.complianceDocumentTypes.get("some-fake-id") + .then(function(complianceDocumentType) { + console.log("\n============ Fetch by ID ===========\n", complianceDocumentType) + return client.complianceDocumentTypes.list(listParams); + }) + .then(function(complianceDocumentTypes) { + console.log("\n============ list all ===========\n", complianceDocumentTypes) + }) + .catch(function(response) { + console.log("\n============ Error :: ===========\n", response); + }); + + \ No newline at end of file diff --git a/examples/complianceDocuments.js b/examples/complianceDocuments.js new file mode 100644 index 0000000..fab3008 --- /dev/null +++ b/examples/complianceDocuments.js @@ -0,0 +1,34 @@ +var Plivo = require('../dist/rest/client.js'); +var client = new Plivo.Client(); + +var createParams = { + alias: "testing", + documentTypeId: "testing", + complianceDocumentId: "test", + metaInformation: "test meta", + file: "test path to file" +}; + +var updateDocument = { + alias: "alias update" +}; + +client.complianceDocuments.create(createParams) + .then(function(complianceDocument) { + console.log("\n============ created ===========\n", complianceDocument) + return client.complianceDocuments.update(complianceDocument.id, updateDocument); + }) + .then(function(complianceDocument){ + return complianceDocuments.delete(); + }) + .then(function(result){ + console.log("\n============ deleted ===========\n", result) + return client.complianceDocuments.list() + }) + .then(function(complianceDocuments){ + console.log("\n============ list all ===========\n", complianceDocuments) + }) + .catch(function(response) { + console.log("\n============ Error :: ===========\n", response); + }); + diff --git a/examples/complianceRequirements.js b/examples/complianceRequirements.js new file mode 100644 index 0000000..fb72f3b --- /dev/null +++ b/examples/complianceRequirements.js @@ -0,0 +1,22 @@ +var Plivo = require('../dist/rest/client.js'); +var client = new Plivo.Client(); + +var listParams = { + countryIso2: "US", + numberType: "local", + endUserType: "individual" +}; + +client.complianceRequirements.get("some-fake-id") + .then(function(complianceRequirement) { + console.log("\n============ Fetch by ID ===========\n", complianceRequirement) + return client.complianceRequirements.list(listParams); + }) + .then(function(complianceRequirements) { + console.log("\n============ list all ===========\n", complianceRequirements) + }) + .catch(function(response) { + console.log("\n============ Error :: ===========\n", response); + }); + + \ No newline at end of file diff --git a/examples/endUsers.js b/examples/endUsers.js new file mode 100644 index 0000000..eb9a152 --- /dev/null +++ b/examples/endUsers.js @@ -0,0 +1,37 @@ +var Plivo = require('../dist/rest/client.js'); +var client = new Plivo.Client(); + +var createParams = { + name: "testing name", + lastName: "testing lastname", + endUserType: "business" +}; + +var updateParams = { + endUserType: "individual" +}; + +client.endUsers.create(createParams) + .then(function(endUser) { + console.log("\n============ created ===========\n", endUser) + return client.endUsers.update(endUser.id, updateParams); + }) + .then(function(endUser) { + console.log("\n============ updated ===========\n", endUser) + return client.endUsers.get(endUser.id); + }) + .then(function(endUser){ + console.log("\n============ list with id ===========\n", endUser) + return endUsers.delete(); + }) + .then(function(result){ + console.log("\n============ deleted ===========\n", result) + return client.endUsers.list() + }) + .then(function(endUsers){ + console.log("\n============ list all ===========\n", endUsers) + }) + .catch(function(response) { + console.log("\n============ Error :: ===========\n", response); + }); + diff --git a/gulpfile.js b/gulpfile.js index f272484..36f37db 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -10,6 +10,7 @@ var babel = require('gulp-babel'); var del = require('del'); var isparta = require('isparta'); +const merge = require("merge-stream"); // Initialize the babel transpiler so ES2015 files gets compiled // when they're loaded require('babel-register'); @@ -73,9 +74,13 @@ gulp.task('coveralls', ['test'], function () { }); gulp.task('babel', ['clean'], function () { - return gulp.src('lib/**/*.js') + return merge([ + gulp.src('types/**/*.d.ts') + .pipe(gulp.dest('dist/')), + gulp.src('lib/**/*.js') .pipe(babel()) - .pipe(gulp.dest('dist')); + .pipe(gulp.dest('dist')) +]); }); gulp.task('lintFix', function () { diff --git a/lib/base.js b/lib/base.js index 98d0f49..d6ba0d7 100644 --- a/lib/base.js +++ b/lib/base.js @@ -4,115 +4,150 @@ let actionKey = Symbol('api action'); let klassKey = Symbol('constructor'); let idKey = Symbol('id filed'); let clientKey = Symbol('make api call'); +let secondaryActionKey = Symbol('api action'); +let secondaryKlassKey = Symbol('constructor'); +let secondaryIdKey = Symbol('id filed'); export class PlivoGenericResponse { constructor(params, idString) { - params = params || {}; - if (typeof idString !== 'undefined' && (idString in params)) { - this.id = params[idString]; - } else if ('request_uuid' in params) { - this.id = params.request_uuid; - } - extend(this, params); + params = params || {}; + if (typeof idString !== 'undefined' && (idString in params)) { + this.id = params[idString]; + } else if ('request_uuid' in params) { + this.id = params.request_uuid; + } + extend(this, params); } } export class PlivoResource { constructor(action, klass, idField, request) { + this[actionKey] = action; + this[klassKey] = klass; + this[idKey] = idField; + this[clientKey] = request; + } + + update(params, id) { + let client = this[clientKey]; + let action = this[actionKey]; + let that = this; + id = typeof id !== 'undefined' ? id : that.id; + + return new Promise((resolve, reject) => { + client('POST', action + id + '/', params) + .then(response => { + extend(that, response.body); + if (params.hasOwnProperty('isVoiceRequest')) { + delete params.isVoiceRequest; + } + extend(that, params); + resolve(that); + }) + .catch(error => { + reject(error); + }); + }); + } + + delete(params) { + let client = this[clientKey]; + let action = this[actionKey]; + let id = this.id; + + return new Promise((resolve, reject) => { + client('DELETE', action + id + '/', params) + .then(() => { + resolve(true); + }) + .catch(error => { + reject(error); + }); + }); + } + + executeAction(task = '', method = 'GET', params = {}, action) { + let client = this[clientKey]; + action = action == null ? this[actionKey] : action; + let idField = this[idKey]; + + return new Promise((resolve, reject) => { + client(method, action + task, params) + .then(response => { + resolve(new PlivoGenericResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } + + + customexecuteAction(url, method = 'GET', params = {}) { + let client = this[clientKey]; + let idField = this[idKey]; + return new Promise((resolve, reject) => { + client(method, url, params) + .then(response => { + resolve(new PlivoGenericResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } + customexecuteGetNumberAction(url, method = 'GET', params = {}) { + let client = this[clientKey]; + let idField = this[idKey]; + let number = ""; + let promise = client(method, url, params).then(response => { + number = response.body.objects[0].number; + return number; + }).catch(error => { + console.log(error); + return error; + }); + return promise; + } + getMetaResponse(url, method = 'GET', params = {}) { + let client = this[clientKey]; + let idField = this[idKey]; + let count = 0; + return new Promise((resolve, reject) => { + client(method, url, params) + .then(response => { + count = response.body.meta.totalCount; + resolve(count); + }) + .catch(error => { + reject(error); + }); + }); + } +} + +export class PlivoSecondaryResource { + constructor(action, klass, idField, secondaryAction, secondaryKlass, secondaryIdField, request) { this[actionKey] = action; this[klassKey] = klass; this[idKey] = idField; this[clientKey] = request; + this[secondaryActionKey] = secondaryAction; + this[secondaryKlassKey] = secondaryKlass; + this[secondaryIdKey] = secondaryIdField; } - update(params, id) { - let client = this[clientKey]; - let action = this[actionKey]; - let that = this; - id = typeof id !== 'undefined' ? id : that.id; - - return new Promise((resolve, reject) => { - client('POST', action + id + '/', params) - .then(response => { - extend(that, response.body); - if (params.hasOwnProperty('isVoiceRequest')){ - delete params.isVoiceRequest; - } - extend(that, params); - resolve(that); - }) - .catch(error => { - reject(error); - }); - }); - } - - delete(params) { - let client = this[clientKey]; - let action = this[actionKey]; - let id = this.id; - - return new Promise((resolve, reject) => { - client('DELETE', action + id + '/', params) - .then(() => { - resolve(true); - }) - .catch(error => { - reject(error); - }); - }); - } - - executeAction(task = '', method = 'GET', params = {}, action) { + executeAction(task = '', secondaryTask = '', method = 'GET', params = {}, action, secondaryAction) { let client = this[clientKey]; action = action == null ? this[actionKey] : action; let idField = this[idKey]; + secondaryAction = secondaryAction == null ? this[secondaryActionKey] : secondaryAction; + let secondaryIdField = this[secondaryIdKey] return new Promise((resolve, reject) => { - client(method, action + task, params) + client(method, action + task + '/' + secondaryAction + secondaryTask + '/', params) .then(response => { - resolve(new PlivoGenericResponse(response.body, idField)); - }) - .catch(error => { - reject(error); - }); - }); - } - customexecuteAction(url, method = 'GET', params = {}) { - let client = this[clientKey]; - let idField = this[idKey]; - return new Promise((resolve, reject) => { - client(method, url, params) - .then(response => { - resolve(new PlivoGenericResponse(response.body, idField)); - }) - .catch(error => { - reject(error); - }); - }); - } - customexecuteGetNumberAction(url, method = 'GET', params = {}) { - let client = this[clientKey]; - let idField = this[idKey]; - let number = ""; - let promise = client(method, url, params).then(response => { - number = response.body.objects[0].number; - return number; - }).catch(error => { - console.log(error); - return error; - }); - return promise; - } - getMetaResponse(url, method = 'GET', params = {}) { - let client = this[clientKey]; - let idField = this[idKey]; - let count = 0; - return new Promise((resolve, reject) => { - client(method, url, params) - .then(response => { - count = response.body.meta.totalCount; - resolve(count); + resolve(new PlivoGenericResponse(response.body, secondaryIdField)); }) .catch(error => { reject(error); @@ -123,66 +158,69 @@ export class PlivoResource { export class PlivoResourceInterface { constructor(action, klass, idField, request) { - this[actionKey] = action; - this[klassKey] = klass; - this[idKey] = idField; - this[clientKey] = request; + this[actionKey] = action; + this[klassKey] = klass; + this[idKey] = idField; + this[clientKey] = request; } get(id, params = {}) { - let client = this[clientKey]; - let action = this[actionKey]; - let Klass = this[klassKey]; + let client = this[clientKey]; + let action = this[actionKey]; + let Klass = this[klassKey]; - return new Promise((resolve, reject) => { - if (action !== '' && !id) { - reject(new Error(this[idKey] + ' must be set')); - } + return new Promise((resolve, reject) => { + if (action !== '' && !id) { + reject(new Error(this[idKey] + ' must be set')); + } - client('GET', action + (id ? id + '/' : ''), params) - .then(response => { - resolve(new Klass(client, response.body)); - }) - .catch(error => { - reject(error); - }); - }); + client('GET', action + (id ? id + '/' : ''), params) + .then(response => { + resolve(new Klass(client, response.body)); + }) + .catch(error => { + reject(error); + }); + }); } list(params) { - let client = this[clientKey]; - let action = this[actionKey]; - let Klass = this[klassKey]; + let client = this[clientKey]; + let action = this[actionKey]; + let Klass = this[klassKey]; - return new Promise((resolve, reject) => { - client('GET', action, params) - .then(response => { - let objects = []; - Object.defineProperty(objects, 'meta', { value: response.body.meta, enumerable: true }); - response.body.objects.forEach(item => { - objects.push(new Klass(client, item)); - }); - resolve(objects); - }) - .catch(error => { - reject(error); - }); - }); + return new Promise((resolve, reject) => { + client('GET', action, params) + .then(response => { + let objects = []; + Object.defineProperty(objects, 'meta', { + value: response.body.meta, + enumerable: true + }); + response.body.objects.forEach(item => { + objects.push(new Klass(client, item)); + }); + resolve(objects); + }) + .catch(error => { + reject(error); + }); + }); } create(params) { - let client = this[clientKey]; - let idField = this[idKey]; - let action = this[actionKey] + (this.id ? this.id + '/' : ''); + let client = this[clientKey]; + let idField = this[idKey]; + let action = this[actionKey] + (this.id ? this.id + '/' : ''); - return new Promise((resolve, reject) => { - client('POST', action, params) - .then(response => { - resolve(new PlivoGenericResponse(response.body, idField)); - }) - .catch(error => { - reject(error); - }); - }); + return new Promise((resolve, reject) => { + client('POST', action, params) + .then(response => { + resolve(new PlivoGenericResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); } } diff --git a/lib/resources/accounts.js b/lib/resources/accounts.js index c40b9e7..6446c8b 100644 --- a/lib/resources/accounts.js +++ b/lib/resources/accounts.js @@ -1,8 +1,8 @@ -import {extend, validate} from '../utils/common.js'; import {PlivoResource, PlivoResourceInterface} from '../base'; +import {extend, validate} from '../utils/common.js'; const clientKey = Symbol(); -const action = ''; +const action = 'Subaccount/'; const idField = 'authId'; /** @@ -11,10 +11,77 @@ const idField = 'authId'; * @param {function} client - make api call * @param {object} [data] - data of call */ + +export class GetAccountDetails +{ + constructor(params) { + params = params || {}; + this.accountType= params.accountType; + this.address = params.address; + this.apiId = params.apiId; + this.autoRecharge = params.autoRecharge; + this.billingMode = params.billingMode; + this.cashCredits = params.cashCredits; + this.city = params.city; + this.name = params.name; + this.resourceUri = params.resourceUri; + this.state = params.state; + this.timezone = params.timezone; + } + +} + +export class CreateSubAccountResponse +{ + constructor(params) { + params = params || {}; + this.apiId= params.apiId; + this.authId = params.authId; + this.authToken = params.authToken; + this.message = params.message; + } + +} + +export class UpdateSubAccountDetails +{ + constructor(params) { + params = params || {}; + this.apiId= params.apiId; + this.message = params.message; + } + +} + +export class UpdateAccountDetailsResponse +{ + constructor(params) { + params = params || {}; + this.apiId= params.apiId; + this.message = params.message; + } + +} + +export class GetSubAccountDetails { + constructor(params) { + params = params || {}; + this.account= params.account; + this.apiId = params.apiId; + this.authId = params.authId; + this.authToken = params.authToken; + this.created = params.created; + this.enabled = params.enabled; + this.modified = params.modified; + this.name = params.name; + this.resourceUri = params.resourceUri; + + } +} export class Subaccount extends PlivoResource { constructor(client, data = {}) { super('Subaccount/', Subaccount, idField, client); - + this[clientKey] = client; if (idField in data) { this.id = data[idField]; } @@ -47,7 +114,22 @@ export class Subaccount extends PlivoResource { params.enabled = enabled.toString(); } - return super.update(params); + let client = this[clientKey]; + let that = this; + return new Promise((resolve, reject) => { + client('POST', action + that.id + '/', params) + .then(response => { + extend(that, response.body); + if (params.hasOwnProperty('isVoiceRequest')){ + delete params.isVoiceRequest; + } + extend(that, params); + resolve(new UpdateSubAccountDetails(that)); + }) + .catch(error => { + reject(error); + }); + }); } /** @@ -57,18 +139,29 @@ export class Subaccount extends PlivoResource { * @promise {boolean} return true if subaccount deleted * @fail {Error} return Error */ - delete(cascade) { + delete(cascade) + { let params = {}; if (typeof cascade === 'boolean') { params.cascade = cascade.toString(); } - - return super.delete(params); + let client = this[clientKey]; + let id = this.id; + + return new Promise((resolve, reject) => { + client('DELETE', action + id + '/', params) + .then(() => { + resolve(true); + }) + .catch(error => { + reject(error); + }); + }); } - } + /** * Represents a Subaccount Interface * @constructor @@ -98,7 +191,20 @@ export class SubaccountInterface extends PlivoResourceInterface { if (errors) { return errors; } - return super.get(id); + let client = this[clientKey]; + + return new Promise((resolve, reject) => { + if (action !== '' && !id) { + reject(new Error(this[idKey] + ' must be set')); + } + client('GET', action + (id ? id + '/' : '')) + .then(response => { + resolve(new GetSubAccountDetails(response.body,client)); + }) + .catch(error => { + reject(error); + }); + }); } /** @@ -125,8 +231,16 @@ export class SubaccountInterface extends PlivoResourceInterface { if (typeof enabled === 'boolean') { params.enabled = enabled.toString(); } - - return super.create(params); + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('POST', action + (this.id ? this.id + '/' : ''), params) + .then(response => { + resolve(new CreateSubAccountResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }) } /** @@ -197,10 +311,12 @@ export class Account extends PlivoResource { * @promise {PlivoGenericResponse} return PlivoGenericResponse object * @fail {Error} return Error */ - get() { - return new AccountInterface(this[clientKey]) - .get(); - } +get() { + return new AccountInterface(this[clientKey]) + .get(); +} + + /** * update account detail @@ -213,7 +329,23 @@ export class Account extends PlivoResource { * @fail {Error} return Error */ update(params) { - return super.update(params, ''); + + let client = this[clientKey]; + let that = this; + return new Promise((resolve, reject) => { + client('POST', '/', params) + .then(response => { + extend(that, response.body); + if (params.hasOwnProperty('isVoiceRequest')){ + delete params.isVoiceRequest; + } + extend(that, params); + resolve(new UpdateAccountDetailsResponse(that)); + }) + .catch(error => { + reject(error); + }); + }); } } @@ -238,8 +370,17 @@ export class AccountInterface extends PlivoResourceInterface { * @fail {Error} return Error */ get() { - return super.get(); - } + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('GET', '/') + .then(response => { + resolve(new GetAccountDetails(response.body, client)); + }) + .catch(error => { + reject(error); + }); + }); +} /** * update account detail diff --git a/lib/resources/applications.js b/lib/resources/applications.js index a06355a..8f01b3a 100644 --- a/lib/resources/applications.js +++ b/lib/resources/applications.js @@ -1,5 +1,11 @@ -import {extend, validate} from '../utils/common.js'; -import {PlivoResource, PlivoResourceInterface} from '../base'; +import { + PlivoResource, + PlivoResourceInterface +} from '../base'; +import { + extend, + validate +} from '../utils/common.js'; const clientKey = Symbol(); const action = 'Application/'; @@ -11,60 +17,145 @@ const idField = 'appId'; * @param {function} client - make api call * @param {object} [data] - data of call */ -export class Application extends PlivoResource { - constructor(client, data = {}) { - super(action, Application, idField, client); - if (idField in data) { - this.id = data[idField]; + +export class UpdateApplicationResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.message = params.message; } - - extend(this, data); - } - -/** - * update application - * @method - * @param {object} params - to update application - * @param {string} [params.answerUrl] The URL invoked by Plivo when a call executes this application. - * @param {string} [params.answerMethod] The method used to call the answer_url. Defaults to POST. - * @param {string} [params.hangupUrl] The URL that is notified by Plivo when the call hangs up. - * @param {string} [params.hangupMethod] The method used to call the hangup_url. Defaults to POST - * @param {string} [params.fallbackAnswerUrl] Invoked by Plivo only if answer_url is unavailable or the XML response is invalid. Should contain a XML response. - * @param {string} [params.fallbackMethod] The method used to call the fallback_answer_url. Defaults to POST. - * @param {string} [params.messageUrl] The URL that is notified by Plivo when an inbound message is received. Defaults not set. - * @param {string} [params.messageMethod] The method used to call the message_url. Defaults to POST. - * @param {boolean} [params.defaultNumberApp] If set to true, associates all newly created Plivo numbers that have not specified an app_id, to this application. - * @param {boolean} [params.defaultEndpointApp] If set to true, associates all newly created Plivo endpoints that have not specified an app_id, to this application. - * @param {string} [params.subaccount] Id of the subaccount, in case only subaccount applications are needed. - * @param {boolean} [params.logIncomingMessages] flag to control incoming message logs. - - * @promise {object} return {@link Application} object - * @fail {Error} return Error - */ - update(params) { - params.isVoiceRequest = 'true'; - return super.update(params); - } - -/** - * delete application - * @method - * @param {object} params - params to delete application - * @param {boolean} [params.cascade] - delete associated endpoints - * @param {string} [params.newEndpointApplication] - link associated endpoints with app - * @promise {object} return true on success - * @fail {Error} return Error - */ - delete(params) { - if (typeof params.cascade === 'boolean') { - params.cascade = params.cascade.toString(); - } - params.isVoiceRequest = 'true'; - return super.delete(params); - } - } + +export class CreateApplicationResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.appId = params.appId; + this.message = params.message; + } +} + +export class RetrieveApplicationResponse { + constructor(params) { + params = params || {}; + this.answerMethod = params.answerMethod; + this.answerUrl = params.answerUrl; + this.apiId = params.apiId; + this.appId = params.appId; + this.appName = params.appName; + this.applicationType = params.applicationType; + this.defaultApp = params.defaultApp; + this.defaultEndpointApp = params.defaultEndpointApp; + this.enabled = params.enabled; + this.fallbackAnswerUrl = params.fallbackAnswerUrl; + this.fallbackMethod = params.fallbackMethod; + this.hangupMethod = params.hangupMethod; + this.logIncomingMessage = params.logIncomingMessage; + this.messageMethod = params.messageMethod; + this.resourceUri = params.resourceUri; + this.sipUri = params.sipUri; + this.subAccount = params.subAccount; + } +} +export class ListAllApplicationResponse { + constructor(params) { + params = params || {}; + this.answerMethod = params.answerMethod; + this.answerUrl = params.answerUrl; + this.apiId = params.apiId; + this.appId = params.appId; + this.appName = params.appName; + this.applicationType = params.applicationType; + this.defaultApp = params.defaultApp; + this.defaultEndpointApp = params.defaultEndpointApp; + this.enabled = params.enabled; + this.fallbackAnswerUrl = params.fallbackAnswerUrl; + this.fallbackMethod = params.fallbackMethod; + this.hangupMethod = params.hangupMethod; + this.logIncomingMessage = params.logIncomingMessage; + this.messageMethod = params.messageMethod; + this.resourceUri = params.resourceUri; + this.sipUri = params.sipUri; + this.subAccount = params.subAccount; + } +} + +export class Application extends PlivoResource { + constructor(client, data = {}) { + super(action, Application, idField, client); + if (idField in data) { + this.id = data[idField]; + } + this[clientKey] = client; + extend(this, data); + } + + /** + * update application + * @method + * @param {object} params - to update application + * @param {string} [params.answerUrl] The URL invoked by Plivo when a call executes this application. + * @param {string} [params.answerMethod] The method used to call the answer_url. Defaults to POST. + * @param {string} [params.hangupUrl] The URL that is notified by Plivo when the call hangs up. + * @param {string} [params.hangupMethod] The method used to call the hangup_url. Defaults to POST + * @param {string} [params.fallbackAnswerUrl] Invoked by Plivo only if answer_url is unavailable or the XML response is invalid. Should contain a XML response. + * @param {string} [params.fallbackMethod] The method used to call the fallback_answer_url. Defaults to POST. + * @param {string} [params.messageUrl] The URL that is notified by Plivo when an inbound message is received. Defaults not set. + * @param {string} [params.messageMethod] The method used to call the message_url. Defaults to POST. + * @param {boolean} [params.defaultNumberApp] If set to true, associates all newly created Plivo numbers that have not specified an app_id, to this application. + * @param {boolean} [params.defaultEndpointApp] If set to true, associates all newly created Plivo endpoints that have not specified an app_id, to this application. + * @param {string} [params.subaccount] Id of the subaccount, in case only subaccount applications are needed. + * @param {boolean} [params.logIncomingMessages] flag to control incoming message logs. + + * @promise {object} return {@link Application} object + * @fail {Error} return Error + */ + update(params) { + params.isVoiceRequest = 'true'; + let client = this[clientKey]; + let that = this; + return new Promise((resolve, reject) => { + client('POST', action + that.id + '/', params) + .then(response => { + extend(that, response.body); + if (params.hasOwnProperty('isVoiceRequest')) { + delete params.isVoiceRequest; + } + extend(that, params); + resolve(new UpdateApplicationResponse(that)); + }) + .catch(error => { + reject(error); + }); + }); + + } + + /** + * delete application + * @method + * @param {object} params - params to delete application + * @param {boolean} [params.cascade] - delete associated endpoints + * @param {string} [params.newEndpointApplication] - link associated endpoints with app + * @promise {object} return true on success + * @fail {Error} return Error + */ + delete(params, id) { + let client = this[clientKey]; + params.isVoiceRequest = 'true'; + return new Promise((resolve, reject) => { + client('DELETE', action + id + '/', params) + .then(() => { + resolve(true); + }) + .catch(error => { + reject(error); + }); + }); + } +} + /** * Represents a Application interface * @constructor @@ -73,126 +164,167 @@ export class Application extends PlivoResource { */ export class ApplicationInterface extends PlivoResourceInterface { - constructor(client, data = {}) { - super(action, Application, idField, client); - extend(this, data); - - this[clientKey] = client; - } - -/** - * get application by given id - * @method - * @param {string} id - id of application - * @promise {object} return {@link Application} object - * @fail {Error} return Error - */ - get(id) { - let params = {} - params.isVoiceRequest = 'true' - return super.get(id, params); - } - - /** - * list applications - * @method - * @param {object} params - params to list applications - * @param {string} [params.subaccount] - ID of the subaccount if present - * @param {integer} [params.limit] - To display no of results per page - * @param {integer} [params.offset] - No of value items by which results should be offset - */ - list(params= {}) { - params.isVoiceRequest = 'true'; - return super.list(params); - } - -/** - * create Application - * @method - * @param {string} appName - name of application - * @param {object} params - params to create application - * @param {string} [params.answerUrl] - answer url - * @param {string} [params.appName] The name of your application - * @param {string} [params.answerUrl] The URL invoked by Plivo when a call executes this application. - * @param {string} [params.answerMethod] The method used to call the answer_url. Defaults to POST. - * @param {string} [params.hangupUrl] The URL that is notified by Plivo when the call hangs up. - * @param {string} [params.hangupMethod] The method used to call the hangup_url. Defaults to POST - * @param {string} [params.fallbackAnswerUrl] Invoked by Plivo only if answer_url is unavailable or the XML response is invalid. Should contain a XML response. - * @param {string} [params.fallbackMethod] The method used to call the fallback_answer_url. Defaults to POST. - * @param {string} [params.messageUrl] The URL that is notified by Plivo when an inbound message is received. Defaults not set. - * @param {string} [params.messageMethod] The method used to call the message_url. Defaults to POST. - * @param {boolean} [params.defaultNumberApp] If set to true, associates all newly created Plivo numbers that have not specified an app_id, to this application. - * @param {boolean} [params.defaultEndpointApp] If set to true, associates all newly created Plivo endpoints that have not specified an app_id, to this application. - * @param {string} [params.subaccount] Id of the subaccount, in case only subaccount applications are needed. - * @param {boolean} [params.logIncomingMessages] flag to control incoming message logs. - * @promise {object} return {@link PlivoGenericResponse} object - * @fail {Error} return Error - */ - create(appName, params = {}) { - - let errors = validate([ - {field: 'app_name', value: appName, validators: ['isRequired', 'isString']} - ]); - - if (errors) { - return errors; + constructor(client, data = {}) { + super(action, Application, idField, client); + extend(this, data); + this[clientKey] = client; } - params.app_name = appName; - params.isVoiceRequest = 'true'; - return super.create(params); - } + /** + * get application by given id + * @method + * @param {string} id - id of application + * @promise {object} return {@link Application} object + * @fail {Error} return Error + */ + get(id) { + let params = {} + params.isVoiceRequest = 'true' + let client = this[clientKey]; -/** - * update Application - * @method - * @param {string} id - id of application - * @param {object} params - to update application - * @param {string} [params.answerUrl] The URL invoked by Plivo when a call executes this application. - * @param {string} [params.answerMethod] The method used to call the answer_url. Defaults to POST. - * @param {string} [params.hangupUrl] The URL that is notified by Plivo when the call hangs up. - * @param {string} [params.hangupMethod] The method used to call the hangup_url. Defaults to POST - * @param {string} [params.fallbackAnswerUrl] Invoked by Plivo only if answer_url is unavailable or the XML response is invalid. Should contain a XML response. - * @param {string} [params.fallbackMethod] The method used to call the fallback_answer_url. Defaults to POST. - * @param {string} [params.messageUrl] The URL that is notified by Plivo when an inbound message is received. Defaults not set. - * @param {string} [params.messageMethod] The method used to call the message_url. Defaults to POST. - * @param {boolean} [params.defaultNumberApp] If set to true, associates all newly created Plivo numbers that have not specified an app_id, to this application. - * @param {boolean} [params.defaultEndpointApp] If set to true, associates all newly created Plivo endpoints that have not specified an app_id, to this application. - * @param {string} [params.subaccount] Id of the subaccount, in case only subaccount applications are needed. - * @param {boolean} [params.logIncomingMessages] flag to control incoming message logs. - * @promise {object} return {@link Application} object - * @fail {Error} return Error - */ - update(id, params) { - let errors = validate([ - {field: 'id', value: id, validators: ['isRequired']} - ]); - - if (errors) { - return errors; - } - return new Application(this[clientKey], { - id: id - }).update(params); - } - -/** - * delete Application - * @method - * @param {string} id - id of application - * @param {object} params - params to delete application - * @param {boolean} [params.cascade] - delete associated endpoints - * @param {string} [params.newEndpointApplication] - link associated endpoints with app - * @promise {object} return true on success - * @fail {Error} return Error - */ - delete(id, params = {}) { - if (typeof params.cascade === 'boolean') { - params.cascade = params.cascade.toString(); + return new Promise((resolve, reject) => { + if (action !== '' && !id) { + reject(new Error(this[idKey] + ' must be set')); + } + client('GET', action + (id ? id + '/' : ''), params) + .then(response => { + resolve(new RetrieveApplicationResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); + }); } - return new Application(this[clientKey], { - id: id - }).delete(params); - } + /** + * list applications + * @method + * @param {object} params - params to list applications + * @param {string} [params.subaccount] - ID of the subaccount if present + * @param {integer} [params.limit] - To display no of results per page + * @param {integer} [params.offset] - No of value items by which results should be offset + */ + list(params = {}) { + let client = this[clientKey]; + params.isVoiceRequest = true; + return new Promise((resolve, reject) => { + client('GET', action, params) + .then(response => { + let objects = []; + Object.defineProperty(objects, 'meta', { + value: response.body.meta, + enumerable: true + }); + response.body.objects.forEach(item => { + objects.push(new ListAllApplicationResponse(item, client)); + }); + resolve(objects); + }) + .catch(error => { + reject(error); + }); + }); + } + + /** + * create Application + * @method + * @param {string} appName - name of application + * @param {object} params - params to create application + * @param {string} [params.answerUrl] - answer url + * @param {string} [params.appName] The name of your application + * @param {string} [params.answerUrl] The URL invoked by Plivo when a call executes this application. + * @param {string} [params.answerMethod] The method used to call the answer_url. Defaults to POST. + * @param {string} [params.hangupUrl] The URL that is notified by Plivo when the call hangs up. + * @param {string} [params.hangupMethod] The method used to call the hangup_url. Defaults to POST + * @param {string} [params.fallbackAnswerUrl] Invoked by Plivo only if answer_url is unavailable or the XML response is invalid. Should contain a XML response. + * @param {string} [params.fallbackMethod] The method used to call the fallback_answer_url. Defaults to POST. + * @param {string} [params.messageUrl] The URL that is notified by Plivo when an inbound message is received. Defaults not set. + * @param {string} [params.messageMethod] The method used to call the message_url. Defaults to POST. + * @param {boolean} [params.defaultNumberApp] If set to true, associates all newly created Plivo numbers that have not specified an app_id, to this application. + * @param {boolean} [params.defaultEndpointApp] If set to true, associates all newly created Plivo endpoints that have not specified an app_id, to this application. + * @param {string} [params.subaccount] Id of the subaccount, in case only subaccount applications are needed. + * @param {boolean} [params.logIncomingMessages] flag to control incoming message logs. + * @promise {object} return {@link PlivoGenericResponse} object + * @fail {Error} return Error + */ + create(appName, params = {}) { + + let errors = validate([{ + field: 'app_name', + value: appName, + validators: ['isRequired', 'isString'] + }]); + + if (errors) { + return errors; + } + params.app_name = appName; + params.isVoiceRequest = 'true'; + let client = this[clientKey]; + return new Promise((resolve, reject) => { + console.log(action, params) + client('POST', action, params) + .then(response => { + resolve(new CreateApplicationResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }) + } + + /** + * update Application + * @method + * @param {string} id - id of application + * @param {object} params - to update application + * @param {string} [params.answerUrl] The URL invoked by Plivo when a call executes this application. + * @param {string} [params.answerMethod] The method used to call the answer_url. Defaults to POST. + * @param {string} [params.hangupUrl] The URL that is notified by Plivo when the call hangs up. + * @param {string} [params.hangupMethod] The method used to call the hangup_url. Defaults to POST + * @param {string} [params.fallbackAnswerUrl] Invoked by Plivo only if answer_url is unavailable or the XML response is invalid. Should contain a XML response. + * @param {string} [params.fallbackMethod] The method used to call the fallback_answer_url. Defaults to POST. + * @param {string} [params.messageUrl] The URL that is notified by Plivo when an inbound message is received. Defaults not set. + * @param {string} [params.messageMethod] The method used to call the message_url. Defaults to POST. + * @param {boolean} [params.defaultNumberApp] If set to true, associates all newly created Plivo numbers that have not specified an app_id, to this application. + * @param {boolean} [params.defaultEndpointApp] If set to true, associates all newly created Plivo endpoints that have not specified an app_id, to this application. + * @param {string} [params.subaccount] Id of the subaccount, in case only subaccount applications are needed. + * @param {boolean} [params.logIncomingMessages] flag to control incoming message logs. + * @promise {object} return {@link Application} object + * @fail {Error} return Error + */ + update(id, params) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); + + if (errors) { + return errors; + } + return new Application(this[clientKey], { + id: id + }).update(params); + } + + /** + * delete Application + * @method + * @param {string} id - id of application + * @param {object} params - params to delete application + * @param {boolean} [params.cascade] - delete associated endpoints + * @param {string} [params.newEndpointApplication] - link associated endpoints with app + * @promise {object} return true on success + * @fail {Error} return Error + */ + delete(id, params = {}) { + if (typeof params.cascade === 'boolean') { + params.cascade = params.cascade.toString(); + } + return new Application(this[clientKey], { + id: id + }).delete(params, id); + } } diff --git a/lib/resources/call.js b/lib/resources/call.js index 655c0ac..625c375 100644 --- a/lib/resources/call.js +++ b/lib/resources/call.js @@ -1,12 +1,167 @@ - -import {extend, validate} from '../utils/common.js'; -import {PlivoResource, PlivoResourceInterface} from '../base'; import * as _ from "lodash"; +import { + PlivoResource, + PlivoResourceInterface +} from '../base'; +import { + extend, + validate +} from '../utils/common.js'; + const clientKey = Symbol(); const action = 'Call/'; const idField = 'callUuid'; +export class CallTransferResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.callUuids = params.callUuids; + this.message = params.message; + + } +} +export class ListAllQueuedCalls { + constructor(params) { + params = params || {}; + this.apiId = params.id; + this.calls = params.calls; + } +} +export class ListAllLiveCallResponse { + constructor(params) { + params = params || {}; + this.apiId = params.id; + this.callUuid = params.callUuid; + } +} + +export class CreateCallResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.message = params.message; + this.requestUuid = params.requestUuid; + + } +} + + +export class GetQueuedCallResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.direction = params.direction; + this.from = params.from; + this.callStatus = params.callStatus; + this.to = params.to; + this.callerName = params.callerName; + this.callUuid = params.callUuid; + this.requestUuid = params.requestUuid; + } +} + + +export class GetLiveCallResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.callStatus = params.callStatus; + this.callUuid = params.callUuid; + this.callerName = params.callerName; + this.direction = params.direction; + this.from = params.from; + this.requestUuid = params.requestUuid; + this.sessionStart = params.sessionStart; + this.to = params.to; + } +} +export class RetrieveCallResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.answerTime = params.answerTime; + this.billDuration = params.billDuration; + this.billedDuration = params.billedDuration; + this.callDirection = params.callDirection; + this.callDuration = params.callDuration; + this.callState = params.callState; + this.callUuid = params.callUuid; + this.conferenceUuid = params.conferenceUuid; + this.endTime = params.endTime; + this.fromNumber = params.fromNumber; + this.hangupCauseCode = params.hangupCauseCode; + this.hangupCauseName = params.hangupCauseName; + this.hangupSource = params.hangupSource; + this.initiationTime = params.initiationTime; + this.parentCallUuid = params.parentCallUuid; + this.resourceUri = params.resourceUri; + this.toNumber = params.toNumber; + this.totalAmount = params.totalAmount; + this.totalRate = params.totalRate; + } +} + +export class ListAllCallsResponse { + constructor(params) { + params = params || {}; + this.answerTime = params.answerTime; + this.billDuration = params.billDuration; + this.billedDuration = params.billedDuration; + this.callDirection = params.callDirection; + this.callDuration = params.callDuration; + this.callState = params.callState; + this.callUuid = params.callUuid; + this.conferenceUuid = params.conferenceUuid; + this.endTime = params.endTime; + this.fromNumber = params.fromNumber; + this.hangupCauseCode = params.hangupCauseCode; + this.hangupCauseName = params.hangupCauseName; + this.hangupSource = params.hangupSource; + this.initiationTime = params.initiationTime; + this.parentCallUuid = params.parentCallUuid; + this.resourceUri = params.resourceUri; + this.toNumber = params.toNumber; + this.totalAmount = params.totalAmount; + this.totalRate = params.totalRate; + } +} + +export class StartPlayingMusicResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.message = params.message; + } +} + +export class StartSpeakingTextResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.message = params.message; + } +} + +export class SendDigitsResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.message = params.message; + } +} + +export class RecordCallResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.message = params.message; + this.recordingId = params.recordingId; + this.url = params.url; + } +} + /** * Represents a Call * @constructor @@ -14,203 +169,269 @@ const idField = 'callUuid'; * @param {object} [data] - data of call */ export class Call extends PlivoResource { - constructor(client, data = {}) { - super(action, Call, idField, client); + constructor(client, data = {}) { + super(action, Call, idField, client); - if (idField in data) { - this.id = data[idField]; + if (idField in data) { + this.id = data[idField]; + } + + extend(this, data); + this[clientKey] = client; } - extend(this, data); - this[clientKey] = client; - } - -/** - * hangup call - * @method - * @promise {Boolean} return true if call hung up - * @fail {Error} return Error - */ - hangup() { - let params = {} - params.isVoiceRequest = 'true'; - return super.delete(params); - } - -/** - * transfer call - * @method - * @param {object} params - optional params to transfer a call - * @param {string} [params.legs] aleg, bleg or both Defaults to aleg. aleg will transfer call_uuid ; bleg will transfer the bridged leg (if found) of call_uuid ; both will transfer call_uuid and bridged leg of call_uuid - * @param {string} [params.alegUrl] URL to transfer for aleg, if legs is aleg or both, then aleg_url has to be specified. - * @param {string} [params.alegMethod] HTTP method to invoke aleg_url. Defaults to POST. - * @param {string} [params.blegUrl] URL to transfer for bridged leg, if legs is bleg or both, then bleg_url has to be specified. - * @param {string} [params.blegMethod] HTTP method to invoke bleg_url. Defaults to POST. - * @promise {object} return call object - * @fail {Error} return Error - */ - transfer(params) { - params.isVoiceRequest = 'true'; - return super.update(params); - } -/** - * record call - * @method - * @param {object} params - to record call - * @promise {object} return PlivoGenericResponse Object - * @fail {Error} return Error - */ - record(params) { - return this.startRecording(params); - } - -/** - * record call - * @method - * @param {object} params - to record call - * @promise {object} return PlivoGenericResponse Object - * @fail {Error} return Error - */ - startRecording(params) { - params.isVoiceRequest = 'true'; - return super.executeAction(this.id + '/Record/', 'POST', params); - } -/** - * stop recording call - * @method - * @param {object} params - to stop recording call - * @promise {object} return PlivoGenericResponse Object - * @fail {Error} return Error - */ - stopRecording(params) { - params.isVoiceRequest = 'true'; - return super.executeAction(this.id + '/Record/', 'DELETE', params); - } - -/** - * play music for call - * @method - * @param {string} url - url which contains audio to play for call - * @param {object} optionalParams - to stop recording call - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - playMusic(url, optionalParams) { - return this.startPlayingMusic(url, optionalParams); - } -/** - * play music for call - * @method - * @param {string} url - url which contains audio to play for call - * @param {object} optionalParams - to stop recording call - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - startPlayingMusic(urls, optionalParams) { - let params = optionalParams || {}; - params.urls = urls; - params.isVoiceRequest = 'true'; - - let errors = validate([ - {field: 'urls', value: urls, validators: ['isRequired', 'isString']} - ]); - - if (errors) { - return errors; - } - return super.executeAction(this.id + '/Play/', 'POST', params); - } - -/** - * stop playing music for call - * @method - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - stopPlayingMusic() { - let params = {} - params.isVoiceRequest = 'true' - return super.executeAction(this.id + '/Play/', 'DELETE', params); - } - -/** - * speak text for call - * @method - * @param {string} text - text to speak for call - * @param {object} optionalParams - to speak for call - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - speakText(text, optionalParams) { - return this.startSpeakingText(text, optionalParams); - } - -/** - * speak text for call - * @method - * @param {string} text - text to speak for call - * @param {object} optionalParams - to speak for call - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - startSpeakingText(text, optionalParams) { - let errors = validate([{field: 'text', value: text, validators: ['isRequired', 'isString']}]); - - if (errors) { - return errors; + /** + * hangup call + * @method + * @promise {Boolean} return true if call hung up + * @fail {Error} return Error + */ + hangup() { + let params = {} + params.isVoiceRequest = 'true'; + return super.delete(params); } - let params = optionalParams || {}; - params.text = text; - params.isVoiceRequest = 'true'; + /** + * transfer call + * @method + * @param {object} params - optional params to transfer a call + * @param {string} [params.legs] aleg, bleg or both Defaults to aleg. aleg will transfer call_uuid ; bleg will transfer the bridged leg (if found) of call_uuid ; both will transfer call_uuid and bridged leg of call_uuid + * @param {string} [params.alegUrl] URL to transfer for aleg, if legs is aleg or both, then aleg_url has to be specified. + * @param {string} [params.alegMethod] HTTP method to invoke aleg_url. Defaults to POST. + * @param {string} [params.blegUrl] URL to transfer for bridged leg, if legs is bleg or both, then bleg_url has to be specified. + * @param {string} [params.blegMethod] HTTP method to invoke bleg_url. Defaults to POST. + * @promise {object} return call object + * @fail {Error} return Error + */ + transfer(params, callUUID) { + params.isVoiceRequest = 'true'; + let client = this[clientKey]; + let that = this; + callUUID = typeof callUUID !== 'undefined' ? callUUID : that.callUUID; - return super.executeAction(this.id + '/Speak/', 'POST', params); - } - -/** - * stop speaking text for call - * @method - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - stopSpeakingText() { - let params = {} - params.isVoiceRequest = 'true'; - return super.executeAction(this.id + '/Speak/', 'DELETE', params); - } - -/** - * Send digits on a call - * @method - * @param {number} digits - digits to be send - * @param {object} optionalParams - to send digits for call - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - sendDigits(digits, optionalParams) { - let errors = validate([{field: 'digits', value: digits, validators: ['isRequired']}]); - - if (errors) { - return errors; + return new Promise((resolve, reject) => { + client('POST', action + callUUID + '/', params) + .then(response => { + extend(that, response.body); + if (params.hasOwnProperty('isVoiceRequest')) { + delete params.isVoiceRequest; + } + extend(that, params); + resolve(new CallTransferResponse(that)); + }) + .catch(error => { + reject(error); + }); + }); + } + /** + * record call + * @method + * @param {object} params - to record call + * @promise {object} return PlivoGenericResponse Object + * @fail {Error} return Error + */ + record(params= {}) { + params.isVoiceRequest = 'true'; + return this.startRecording(params); } - let params = optionalParams || {}; - params.digits = digits; - params.isVoiceRequest = 'true'; - return super.executeAction(this.id + '/DTMF/', 'POST', params); - } + /** + * record call + * @method + * @param {object} params - to record call + * @promise {object} return PlivoGenericResponse Object + * @fail {Error} return Error + */ + startRecording(params) { + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('POST', action + this.id + '/Record/', params) + .then(response => { + resolve(new RecordCallResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } + /** + * stop recording call + * @method + * @param {object} params - to stop recording call + * @promise {object} return PlivoGenericResponse Object + * @fail {Error} return Error + */ + stopRecording(params= {}) { + params.isVoiceRequest = 'true'; + return super.executeAction(this.id + '/Record/', 'DELETE', params); + } -/** - * Hangup a Call Request - * @method - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - cancel() { - let params = {}; - params.isVoiceRequest = 'true'; - return super.executeAction('Request/' + this.id + '/', 'DELETE', params, ''); - } + /** + * play music for call + * @method + * @param {string} url - url which contains audio to play for call + * @param {object} optionalParams - to stop recording call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + playMusic(url, optionalParams) { + return this.startPlayingMusic(url, optionalParams); + } + /** + * play music for call + * @method + * @param {string} url - url which contains audio to play for call + * @param {object} optionalParams - to stop recording call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + startPlayingMusic(urls, optionalParams) { + let params = optionalParams || {}; + params.urls = urls; + params.isVoiceRequest = 'true'; + + let errors = validate([{ + field: 'urls', + value: urls, + validators: ['isRequired', 'isString'] + }]); + + if (errors) { + return errors; + } + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('POST', action + this.id + '/Play/', params) + .then(response => { + resolve(new StartPlayingMusicResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } + + /** + * stop playing music for call + * @method + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + stopPlayingMusic() { + let params = {} + params.isVoiceRequest = 'true' + return super.executeAction(this.id + '/Play/', 'DELETE', params); + } + + /** + * speak text for call + * @method + * @param {string} text - text to speak for call + * @param {object} optionalParams - to speak for call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + speakText(text, optionalParams) { + return this.startSpeakingText(text, optionalParams); + } + + /** + * speak text for call + * @method + * @param {string} text - text to speak for call + * @param {object} optionalParams - to speak for call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + startSpeakingText(text, optionalParams) { + let errors = validate([{ + field: 'text', + value: text, + validators: ['isRequired', 'isString'] + }]); + + if (errors) { + return errors; + } + + let params = optionalParams || {}; + params.text = text; + params.isVoiceRequest = 'true'; + + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('POST', action + this.id + '/Speak/', params) + .then(response => { + resolve(new StartSpeakingTextResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } + + /** + * stop speaking text for call + * @method + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + stopSpeakingText() { + let params = {} + params.isVoiceRequest = 'true'; + return super.executeAction(this.id + '/Speak/', 'DELETE', params); + } + + /** + * Send digits on a call + * @method + * @param {number} digits - digits to be send + * @param {object} optionalParams - to send digits for call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + sendDigits(digits, optionalParams) { + let errors = validate([{ + field: 'digits', + value: digits, + validators: ['isRequired'] + }]); + + if (errors) { + return errors; + } + + let params = optionalParams || {}; + params.digits = digits; + params.isVoiceRequest = 'true'; + + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('POST', action + this.id + '/DTMF/', params) + .then(response => { + resolve(new SendDigitsResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + + + } + + /** + * Hangup a Call Request + * @method + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + cancel() { + let params = {}; + params.isVoiceRequest = 'true'; + return super.executeAction('Request/' + this.id + '/', 'DELETE', params, ''); + } } const liveCallInterfaceKey = Symbol('liveCallInterface'); @@ -224,350 +445,440 @@ const queuedCallInterfaceKey = Symbol('queuedCallInterface'); */ export class CallInterface extends PlivoResourceInterface { - constructor(client, data = {}) { - super(action, Call, idField, client); - extend(this, data); + constructor(client, data = {}) { + super(action, Call, idField, client); + extend(this, data); - this[clientKey] = client; - this[liveCallInterfaceKey] = new LiveCallInterface(client); - this[queuedCallInterfaceKey] = new QueuedCallInterface(client); - } - -/** - * Get A Call Detail - * @method - * @param {string} id - call uuid to get information of. - * @promise {object} returns Call Object - * @fail {Error} returns Error - */ - get(id) { - let errors = validate([{field: 'id', value: id, validators: ['isRequired']}]); - - if (errors) { - return errors; + this[clientKey] = client; + this[liveCallInterfaceKey] = new LiveCallInterface(client); + this[queuedCallInterfaceKey] = new QueuedCallInterface(client); } - let params = {} - params.isVoiceRequest = 'true'; - return super.get(id, params); - } -/** - * Get All Call Detail - * @method - * @param {object} params - params to get all call details. - * @promise {object[]} returns list of Call Object - * @fail {Error} returns Error - */ - list(params) { - params.isVoiceRequest = 'true'; - return super.list(params); - } + /** + * Get A Call Detail + * @method + * @param {string} id - call uuid to get information of. + * @promise {object} returns Call Object + * @fail {Error} returns Error + */ + get(id) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); -/** - * Create a call - * @method - * @param {string} from - The phone number to be used as the caller id (with the country code).For e.g, a USA caller id number could be, 15677654321, with '1' for the country code. - * @param {string} to - The regular number(s) or sip endpoint(s) to call. Regular number must be prefixed with country code but without the + sign). For e.g, to dial a number in the USA, the number could be, 15677654321, with '1' for the country code. Multiple numbers can be sent by using a delimiter. For e.g. 15677654321<12077657621<12047657621. Sip endpoints must be prefixed with sip: E.g., sip:john1234@phone.plivo.com. To make bulk calls, the delimiter < is used. For example, 15677654321<15673464321 0(in seconds). - * @param {number} [params.hangupOnRing] Schedules the call for hangup at a specified time after the call starts ringing. Value should be an integer >= 0 (in seconds). - * @param {string} [params.machineDetection] Used to detect if the call has been answered by a machine. The valid values are true and hangup. - * @param {number} [params.machineDetectionTime] Time allotted to analyze if the call has been answered by a machine. It should be an integer >= 2000 and <= 10000 and the unit is ms. The default value is 5000 ms. - * @param {string} [params.machineDetectionUrl] A URL where machine detection parameters will be sent by Plivo. This parameter should be used to make machine detection asynchronous - * @param {string} [params.machineDetectionMethod] The HTTP method which will be used by Plivo to request the machine_detection_url. Defaults to POST. - * @param {string} [params.sipHeaders] List of SIP headers in the form of 'key=value' pairs, separated by commas. - * @param {number} [params.ringTimeout] Determines the time in seconds the call should ring. If the call is not answered within the ring_timeout value or the default value of 120s, it is canceled. - * @param {string} [params.parentCallUuid] The call_uuid of the first leg in an ongoing conference call. It is recommended to use this parameter in scenarios where a member who is already present in the conference intends to add new members by initiating outbound API calls. - * @param {boolean} [params.errorIfParentNotFound] if set to true and the parent_call_uuid cannot be found, the API request would return an error. If set to false, the outbound call API request will be executed even if the parent_call_uuid is not found. Defaults to false. - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - create(from, to, answerUrl, params = {}) { - let errors = validate([ - {field: 'from', value: from, validators: ['isRequired']}, - {field: 'to', value: to, validators: ['isRequired']}, - {field: 'answer_url', value: answerUrl, validators: ['isRequired']} - ]); + if (errors) { + return errors; + } + let params = {} + params.isVoiceRequest = 'true'; + let client = this[clientKey]; + return new Promise((resolve, reject) => { + if (action !== '' && !id) { + reject(new Error(this[idKey] + ' must be set')); + } + client('GET', action + (id ? id + '/' : ''), params) + .then(response => { + resolve(new RetrieveCallResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); + }); - if (errors) { - return errors; } - params.from = from; - params.to = _.isArray(to) ? _.join(to, '<') : to; - params.answer_url = answerUrl; - params.isVoiceRequest = 'true'; - return super.create(params); - } + /** + * Get All Call Detail + * @method + * @param {object} params - params to get all call details. + * @promise {object[]} returns list of Call Object + * @fail {Error} returns Error + */ + list(params = {}) { + params.isVoiceRequest = 'true'; + let client = this[clientKey]; -/** - * Hangup A Specific Call - * @method - * @param {string} callUUID - call uuid to hangup call - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - hangup(callUUID) { - let errors = validate([ - {field: 'call_uuid', value: callUUID, validators: ['isRequired']} - ]); - - if (errors) { - return errors; + return new Promise((resolve, reject) => { + client('GET', action, params) + .then(response => { + let objects = []; + Object.defineProperty(objects, 'meta', { + value: response.body.meta, + enumerable: true + }); + response.body.objects.forEach(item => { + objects.push(new ListAllCallsResponse(item, client)); + }); + resolve(objects); + }) + .catch(error => { + reject(error); + }); + }); } - return new Call(this[clientKey], { - id: callUUID - }).hangup(); - } -/** - * Transfer a Call - * @method - * @param {string} callUUID - call uuid to transfer call - * @param {object} params - optional params to transfer a call - * @param {string} [params.legs] aleg, bleg or both Defaults to aleg. aleg will transfer call_uuid ; bleg will transfer the bridged leg (if found) of call_uuid ; both will transfer call_uuid and bridged leg of call_uuid - * @param {string} [params.alegUrl] URL to transfer for aleg, if legs is aleg or both, then aleg_url has to be specified. - * @param {string} [params.alegMethod] HTTP method to invoke aleg_url. Defaults to POST. - * @param {string} [params.blegUrl] URL to transfer for bridged leg, if legs is bleg or both, then bleg_url has to be specified. - * @param {string} [params.blegMethod] HTTP method to invoke bleg_url. Defaults to POST. - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - transfer(callUUID, params) { - let errors = validate([ - {field: 'call_uuid', value: callUUID, validators: ['isRequired']} - ]); - if (errors) { - return errors; + /** + * Create a call + * @method + * @param {string} from - The phone number to be used as the caller id (with the country code).For e.g, a USA caller id number could be, 15677654321, with '1' for the country code. + * @param {string} to - The regular number(s) or sip endpoint(s) to call. Regular number must be prefixed with country code but without the + sign). For e.g, to dial a number in the USA, the number could be, 15677654321, with '1' for the country code. Multiple numbers can be sent by using a delimiter. For e.g. 15677654321<12077657621<12047657621. Sip endpoints must be prefixed with sip: E.g., sip:john1234@phone.plivo.com. To make bulk calls, the delimiter < is used. For example, 15677654321<15673464321 0(in seconds). + * @param {number} [params.hangupOnRing] Schedules the call for hangup at a specified time after the call starts ringing. Value should be an integer >= 0 (in seconds). + * @param {string} [params.machineDetection] Used to detect if the call has been answered by a machine. The valid values are true and hangup. + * @param {number} [params.machineDetectionTime] Time allotted to analyze if the call has been answered by a machine. It should be an integer >= 2000 and <= 10000 and the unit is ms. The default value is 5000 ms. + * @param {string} [params.machineDetectionUrl] A URL where machine detection parameters will be sent by Plivo. This parameter should be used to make machine detection asynchronous + * @param {string} [params.machineDetectionMethod] The HTTP method which will be used by Plivo to request the machine_detection_url. Defaults to POST. + * @param {string} [params.sipHeaders] List of SIP headers in the form of 'key=value' pairs, separated by commas. + * @param {number} [params.ringTimeout] Determines the time in seconds the call should ring. If the call is not answered within the ring_timeout value or the default value of 120s, it is canceled. + * @param {string} [params.parentCallUuid] The call_uuid of the first leg in an ongoing conference call. It is recommended to use this parameter in scenarios where a member who is already present in the conference intends to add new members by initiating outbound API calls. + * @param {boolean} [params.errorIfParentNotFound] if set to true and the parent_call_uuid cannot be found, the API request would return an error. If set to false, the outbound call API request will be executed even if the parent_call_uuid is not found. Defaults to false. + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + create(from, to, answerUrl, params = {}) { + let errors = validate([{ + field: 'from', + value: from, + validators: ['isRequired'] + }, + { + field: 'to', + value: to, + validators: ['isRequired'] + }, + { + field: 'answer_url', + value: answerUrl, + validators: ['isRequired'] + } + ]); + + if (errors) { + return errors; + } + params.from = from; + params.to = _.isArray(to) ? _.join(to, '<') : to; + params.answer_url = answerUrl; + params.isVoiceRequest = 'true'; + + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('POST', action, params) + .then(response => { + resolve(new CreateCallResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); } - return new Call(this[clientKey], { - id: callUUID - }).transfer(params); - } -/** - * Record a Call - * @method - * @param {string} callUUID - call uuid to record call - * @param {object} optionalParams - optional params to record a call - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - record(callUUID, optionalParams) { - let errors = validate([ - {field: 'call_uuid', value: callUUID, validators: ['isRequired']} - ]); + /** + * Hangup A Specific Call + * @method + * @param {string} callUUID - call uuid to hangup call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + hangup(callUUID) { + let errors = validate([{ + field: 'call_uuid', + value: callUUID, + validators: ['isRequired'] + }]); - if (errors) { - return errors; + if (errors) { + return errors; + } + return new Call(this[clientKey], { + id: callUUID + }).hangup(); } - return new Call(this[clientKey], { - id: callUUID - }).record(optionalParams); - } + /** + * Transfer a Call + * @method + * @param {string} callUUID - call uuid to transfer call + * @param {object} params - optional params to transfer a call + * @param {string} [params.legs] aleg, bleg or both Defaults to aleg. aleg will transfer call_uuid ; bleg will transfer the bridged leg (if found) of call_uuid ; both will transfer call_uuid and bridged leg of call_uuid + * @param {string} [params.alegUrl] URL to transfer for aleg, if legs is aleg or both, then aleg_url has to be specified. + * @param {string} [params.alegMethod] HTTP method to invoke aleg_url. Defaults to POST. + * @param {string} [params.blegUrl] URL to transfer for bridged leg, if legs is bleg or both, then bleg_url has to be specified. + * @param {string} [params.blegMethod] HTTP method to invoke bleg_url. Defaults to POST. + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + transfer(callUUID, params) { + let errors = validate([{ + field: 'call_uuid', + value: callUUID, + validators: ['isRequired'] + }]); -/** - * Stop Recording a Call - * @method - * @param {string} callUUID - call uuid to stop recording a call - * @param {object} optionalParams - optional params to stop recording a call - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - stopRecording(callUUID, optionalParams) { - let errors = validate([ - {field: 'call_uuid', value: callUUID, validators: ['isRequired']} - ]); - - if (errors) { - return errors; + if (errors) { + return errors; + } + return new Call(this[clientKey], { + id: callUUID + }).transfer(params, callUUID); } - return new Call(this[clientKey], { - id: callUUID - }).stopRecording(optionalParams); - } -/** - * Play a music file - * @method - * @param {string} callUUID - call uuid to play music file - * @param {string} url - A single URL or a list of comma separated URLs linking to an mp3 or wav file. - * @param {object} optionalParams - optional params to play music file. - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - playMusic(callUUID, urls, optionalParams) { - let errors = validate([ - {field: 'call_uuid', value: callUUID, validators: ['isRequired']}, - {field: 'urls', value: urls, validators: ['isRequired', 'isString']} - ]); + /** + * Record a Call + * @method + * @param {string} callUUID - call uuid to record call + * @param {object} optionalParams - optional params to record a call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + record(callUUID, optionalParams = {}) { + let errors = validate([{ + field: 'call_uuid', + value: callUUID, + validators: ['isRequired'] + }]); - if (errors) { - return errors; + if (errors) { + return errors; + } + return new Call(this[clientKey], { + id: callUUID + }).record(optionalParams); } - return new Call(this[clientKey], { - id: callUUID - }).playMusic(urls, optionalParams); - } -/** - * Stop Playing a music file - * @method - * @param {string} callUUID - call uuid to stop plaing music file - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - stopPlayingMusic(callUUID) { - let errors = validate([ - {field: 'call_uuid', value: callUUID, validators: ['isRequired']} - ]); + /** + * Stop Recording a Call + * @method + * @param {string} callUUID - call uuid to stop recording a call + * @param {object} optionalParams - optional params to stop recording a call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + stopRecording(callUUID, optionalParams= {}) { + let errors = validate([{ + field: 'call_uuid', + value: callUUID, + validators: ['isRequired'] + }]); - if (errors) { - return errors; + if (errors) { + return errors; + } + return new Call(this[clientKey], { + id: callUUID + }).stopRecording(optionalParams); } - return new Call(this[clientKey], { - id: callUUID - }).stopPlayingMusic(); - } -/** - * Speak text during a call - * @method - * @param {string} callUUID - call uuid to speak text during a call - * @param {string} text - text to be played. - * @param {object} optionalParams - optional params to speak text during a call - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - speakText(callUUID, text, optionalParams) { - let errors = validate([ - {field: 'call_uuid', value: callUUID, validators: ['isRequired']}, - {field: 'text', value: text, validators: ['isRequired', 'isString']} - ]); + /** + * Play a music file + * @method + * @param {string} callUUID - call uuid to play music file + * @param {string} url - A single URL or a list of comma separated URLs linking to an mp3 or wav file. + * @param {object} optionalParams - optional params to play music file. + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + playMusic(callUUID, urls, optionalParams) { + let errors = validate([{ + field: 'call_uuid', + value: callUUID, + validators: ['isRequired'] + }, + { + field: 'urls', + value: urls, + validators: ['isRequired', 'isString'] + } + ]); - if (errors) { - return errors; + if (errors) { + return errors; + } + return new Call(this[clientKey], { + id: callUUID + }).playMusic(urls, optionalParams); } - return new Call(this[clientKey], { - id: callUUID - }).speakText(text, optionalParams); - } -/** - * Stop Speaking text during a call - * @method - * @param {string} callUUID - call uuid to stop speaking text during a call - * @param {object} optionalParams - optional params to stop speaking text during a call - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - stopSpeakingText(callUUID) { - let errors = validate([ - {field: 'call_uuid', value: callUUID, validators: ['isRequired']} - ]); + /** + * Stop Playing a music file + * @method + * @param {string} callUUID - call uuid to stop plaing music file + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + stopPlayingMusic(callUUID) { + let errors = validate([{ + field: 'call_uuid', + value: callUUID, + validators: ['isRequired'] + }]); - if (errors) { - return errors; + if (errors) { + return errors; + } + return new Call(this[clientKey], { + id: callUUID + }).stopPlayingMusic(); } - return new Call(this[clientKey], { - id: callUUID - }).stopSpeakingText(); - } -/** - * Send digits on a call - * @method - * @param {string} callUUID - call uuid to send digits on a call - * @param {number} digits - digits to be send - * @param {object} optionalParams - optional params to send digits - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - sendDigits(callUUID, digits, optionalParams) { - let errors = validate([ - {field: 'call_uuid', value: callUUID, validators: ['isRequired']}, - {field: 'digits', value: digits, validators: ['isRequired']} - ]); + /** + * Speak text during a call + * @method + * @param {string} callUUID - call uuid to speak text during a call + * @param {string} text - text to be played. + * @param {object} optionalParams - optional params to speak text during a call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + speakText(callUUID, text, optionalParams) { + let errors = validate([{ + field: 'call_uuid', + value: callUUID, + validators: ['isRequired'] + }, + { + field: 'text', + value: text, + validators: ['isRequired', 'isString'] + } + ]); - if (errors) { - return errors; + if (errors) { + return errors; + } + return new Call(this[clientKey], { + id: callUUID + }).speakText(text, optionalParams); } - return new Call(this[clientKey], { - id: callUUID - }).sendDigits(digits, optionalParams); - } -/** - * Hangup a call request - * @method - * @param {string} callUUID - call uuid to send digits on a call - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - cancel(id) { - let errors = validate([ - {field: 'call_uuid', value: id, validators: ['isRequired']} - ]); + /** + * Stop Speaking text during a call + * @method + * @param {string} callUUID - call uuid to stop speaking text during a call + * @param {object} optionalParams - optional params to stop speaking text during a call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + stopSpeakingText(callUUID) { + let errors = validate([{ + field: 'call_uuid', + value: callUUID, + validators: ['isRequired'] + }]); - if (errors) { - return errors; + if (errors) { + return errors; + } + return new Call(this[clientKey], { + id: callUUID + }).stopSpeakingText(); } - return new Call(this[clientKey], { - id: id - }).cancel(); - } - listLiveCalls(params) { - return this[liveCallInterfaceKey].list(params); - } + /** + * Send digits on a call + * @method + * @param {string} callUUID - call uuid to send digits on a call + * @param {number} digits - digits to be send + * @param {object} optionalParams - optional params to send digits + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + sendDigits(callUUID, digits, optionalParams) { + let errors = validate([{ + field: 'call_uuid', + value: callUUID, + validators: ['isRequired'] + }, + { + field: 'digits', + value: digits, + validators: ['isRequired'] + } + ]); - getLiveCall(id) { - return this[liveCallInterfaceKey].get(id); - } + if (errors) { + return errors; + } + return new Call(this[clientKey], { + id: callUUID + }).sendDigits(digits, optionalParams); + } - listQueuedCalls() { - return this[queuedCallInterfaceKey].list(); - } + /** + * Hangup a call request + * @method + * @param {string} callUUID - call uuid to send digits on a call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + cancel(id) { + let errors = validate([{ + field: 'call_uuid', + value: id, + validators: ['isRequired'] + }]); - getQueuedCall(id) { - return this[queuedCallInterfaceKey].get(id); - } + if (errors) { + return errors; + } + return new Call(this[clientKey], { + id: id + }).cancel(); + } + + listLiveCalls(params) { + return this[liveCallInterfaceKey].list(params); + } + + getLiveCall(id) { + return this[liveCallInterfaceKey].get(id); + } + + listQueuedCalls() { + return this[queuedCallInterfaceKey].list(); + } + + getQueuedCall(id) { + return this[queuedCallInterfaceKey].get(id); + } } export class LiveCallResource extends PlivoResource { - constructor(client, data = {}) { - super(action, LiveCallResource, idField, client); + constructor(client, data = {}) { + super(action, LiveCallResource, idField, client); - if (idField in data) { - this.id = data[idField]; + if (idField in data) { + this.id = data[idField]; + } + + extend(this, data); + this[clientKey] = client; } - - extend(this, data); - this[clientKey] = client; - } } export class QueuedCallResource extends PlivoResource { - constructor(client, data = {}) { - super(action, QueuedCallResource, idField, client); + constructor(client, data = {}) { + super(action, QueuedCallResource, idField, client); - if (idField in data) { - this.id = data[idField]; + if (idField in data) { + this.id = data[idField]; + } + + extend(this, data); + this[clientKey] = client; } - - extend(this, data); - this[clientKey] = client; - } } /** @@ -577,55 +888,71 @@ export class QueuedCallResource extends PlivoResource { * @param {object} [data] - data of call */ class LiveCallInterface extends PlivoResourceInterface { - constructor(client, data = {}) { - super(action, LiveCallResource, idField, client); - extend(this, data); + constructor(client, data = {}) { + super(action, LiveCallResource, idField, client); + extend(this, data); - this[clientKey] = client; - } - - /** - * Get A Live Call Detail - * @method - * @param {string} id - call uuid to get information of. - * @promise {object} returns LiveCallResource Object - * @fail {Error} returns Error - */ - get(id) { - let errors = validate([{field: 'id', value: id, validators: ['isRequired']}]); - - if (errors) { - return errors; + this[clientKey] = client; } - return super.get(id, { - status: 'live', - isVoiceRequest: 'true' - }); - } - list(params) { - let client = this[clientKey]; - if (params === undefined){ - params = {} - } - params.status = 'live' - params.isVoiceRequest = 'true' - return new Promise((resolve, reject) => { - client('GET', action, params) - .then(response => { - let calls = []; - response.body.calls.forEach(callUuid => { - calls.push(new LiveCallResource(client, { - callUuid: callUuid - })); - }); - resolve(calls); - }) - .catch(error => { - reject(error); + /** + * Get A Live Call Detail + * @method + * @param {string} id - call uuid to get information of. + * @promise {object} returns LiveCallResource Object + * @fail {Error} returns Error + */ + get(id) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); + + if (errors) { + return errors; + } + let client = this[clientKey]; + return new Promise((resolve, reject) => { + if (action !== '' && !id) { + reject(new Error(this[idKey] + ' must be set')); + } + client('GET', action + (id ? id + '/?status=live' : '') , { + isVoiceRequest: 'true' + }) + .then(response => { + resolve(new GetLiveCallResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); }); - }); - } + } + + //List all Live calls + list(params) { + let client = this[clientKey]; + if (params === undefined) { + params = {} + } + params.status = 'live' + params.isVoiceRequest = 'true'; + return new Promise((resolve, reject) => { + client('GET', action+'?status=live', params) + .then(response => { + let calls = []; + response.body.calls.forEach(callUuid => { + calls.push(new LiveCallResource(client, { + callUuid: callUuid + })); + }); + resolve(calls); + }) + .catch(error => { + reject(error); + }); + }); + } } @@ -636,49 +963,70 @@ class LiveCallInterface extends PlivoResourceInterface { * @param {object} [data] - data of call */ class QueuedCallInterface extends PlivoResourceInterface { - constructor(client, data = {}) { - super(action, QueuedCallResource, idField, client); - extend(this, data); + constructor(client, data = {}) { + super(action, QueuedCallResource, idField, client); + extend(this, data); - this[clientKey] = client; - } - - /** - * Get A Queued Call Detail - * @method - * @param {string} id - call uuid to get information of. - * @promise {object} returns QueuedCallResource Object - * @fail {Error} returns Error - */ - get(id) { - let errors = validate([{field: 'id', value: id, validators: ['isRequired']}]); - - if (errors) { - return errors; + this[clientKey] = client; } - return super.get(id, { - status: 'queued', - isVoiceRequest: 'true' - }); - } - list() { - let client = this[clientKey]; + /** + * Get A Queued Call Detail + * @method + * @param {string} id - call uuid to get information of. + * @promise {object} returns QueuedCallResource Object + * @fail {Error} returns Error + */ + get(id) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); - return new Promise((resolve, reject) => { - client('GET', action, {status: 'queued', isVoiceRequest: 'true'}) - .then(response => { - let calls = []; - response.body.calls.forEach(callUuid => { - calls.push(new QueuedCallResource(client, { - callUuid: callUuid - })); - }); - resolve(calls); - }) - .catch(error => { - reject(error); + if (errors) { + return errors; + } + let client = this[clientKey]; + + return new Promise((resolve, reject) => { + if (action !== '' && !id) { + reject(new Error(this[idKey] + ' must be set')); + } + + client('GET', action + (id ? id + '/?status=queued' : ''), { + isVoiceRequest: 'true' + }) + .then(response => { + resolve(new GetQueuedCallResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); }); - }); - } + + + } + + list() { + let client = this[clientKey]; + + return new Promise((resolve, reject) => { + client('GET', action+'?status=queued', { + isVoiceRequest: 'true' + }) + .then(response => { + let calls = []; + response.body.calls.forEach(callUuid => { + calls.push(new QueuedCallResource(client, { + callUuid: callUuid + })); + }); + resolve(calls); + }) + .catch(error => { + reject(error); + }); + }); + } } diff --git a/lib/resources/callFeedback.js b/lib/resources/callFeedback.js index 0bfa535..1037dd0 100644 --- a/lib/resources/callFeedback.js +++ b/lib/resources/callFeedback.js @@ -1,7 +1,24 @@ -import {extend, validate} from '../utils/common.js'; -import {PlivoResource, PlivoResourceInterface} from '../base'; import * as _ from "lodash"; +import { + PlivoResource, + PlivoResourceInterface +} from '../base'; +import { + extend, + validate +} from '../utils/common.js'; + +export class CallFeedbackResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.message = params.message; + this.status = params.status; + + } +} + const clientKey = Symbol(); const action = 'Call/'; const idField = 'callUuid'; @@ -10,14 +27,14 @@ const CALLINSIGHTS_BASE_URL = 'https://stats.plivo.com/' export class CallFeedback extends PlivoResource { constructor(client, data = {}) { super(action, Call, idField, client); - + if (idField in data) { - this.id = data[idField]; + this.id = data[idField]; } - + extend(this, data); this[clientKey] = client; - } + } } /** @@ -30,15 +47,22 @@ export class CallFeedbackInterface extends PlivoResourceInterface { constructor(client, data = {}) { super(action, CallFeedback, idField, client); extend(this, data); - + this[clientKey] = client; - } - - create(callUUID, rating, issues=[], notes="") { - let errors = validate([ - {field: 'callUUId', value: callUUID, validators: ['isRequired']}, - {field: 'rating', value: rating, validators: ['isRequired']} - ]); + } + + create(callUUID, rating, issues = [], notes = "") { + let errors = validate([{ + field: 'callUUId', + value: callUUID, + validators: ['isRequired'] + }, + { + field: 'rating', + value: rating, + validators: ['isRequired'] + } + ]); if (errors) { return errors; @@ -55,7 +79,17 @@ export class CallFeedbackInterface extends PlivoResourceInterface { params.isCallInsightsRequest = ""; params.CallInsightsBaseUrl = CALLINSIGHTS_BASE_URL; params.CallInsightsRequestPath = `v1/Call/${callUUID}/Feedback/`; - return super.create(params); + + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('POST', action, params) + .then(response => { + resolve(new CallFeedbackResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); } - + } \ No newline at end of file diff --git a/lib/resources/complianceApplications.js b/lib/resources/complianceApplications.js new file mode 100644 index 0000000..14c16b8 --- /dev/null +++ b/lib/resources/complianceApplications.js @@ -0,0 +1,281 @@ +import { + PlivoResource, + PlivoResourceInterface +} from '../base'; +import { + extend, + validate +} from '../utils/common.js'; + +const clientKey = Symbol(); +const action = 'ComplianceApplication/'; +const idField = 'complianceApplicationId'; + +export class ComplianceApplicationResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.complianceApplicationId = params.complianceApplicationId; + this.alias = params.alias; + this.status = params.status; + this.endUserType = params.endUserType; + this.endUserId = params.endUserId; + this.countryIso2 = params.countryIso2; + this.numberType = params.numberType; + this.complianceRequirementId= params.complianceRequirementId; + this.documents = params.documents; + this.createdAt = params.createdAt; + } +} + +export class CreateComplianceApplicationResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.complianceApplicationId = params.complianceApplicationId; + this.alias = params.alias; + this.status = params.status; + this.endUserType = params.endUserType; + this.endUserId = params.endUserId; + this.countryIso2 = params.countryIso2; + this.numberType = params.numberType; + this.message = params.message; + this.complianceRequirementId= params.complianceRequirementId; + this.documents = params.documents; + this.createdAt = params.createdAt; + } +} + +export class ListComplianceApplicationResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.meta = params.meta; + this.objects = params.objects; + } +} + +export class UpdateComplianceApplicationResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.message = params.message; + } +} + +export class ComplianceApplication extends PlivoResource { + constructor(client, data = {}) { + super(action, ComplianceApplication, idField, client); + if (idField in data) { + this.id = data[idField]; + } + this[clientKey] = client; + extend(this, data); + } + + /** + * update ComplianceApplication + * @method + * @param {string} id - id to update + * @param {object} params + * @param {string} [params.documentIds] - Document IDs + * @promise {object} return {@link ComplianceApplication} object if success + * @fail {Error} return Error + */ + update(params, id) { + let client = this[clientKey]; + let that = this; + return new Promise((resolve, reject) => { + client('POST', action + id + '/', params) + .then(response => { + extend(that, response.body); + extend(that, params); + resolve(new UpdateComplianceApplicationResponse(that)); + }) + .catch(error => { + reject(error); + }); + }); + + } + + /** + * delete an Compliance application + * @method + * @param {string} id - id to delete + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + delete() { + let client = this[clientKey]; + let id = this.id; + + return new Promise((resolve, reject) => { + client('DELETE', action + id + '/') + .then(() => { + resolve(true); + }) + .catch(error => { + reject(error); + }); + }); + } +} + +/** + * Represents a Compliance Application interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class ComplianceApplicationInterface extends PlivoResourceInterface { + + constructor(client, data = {}) { + super(action, ComplianceApplication, idField, client); + extend(this, data); + this[clientKey] = client; + } + + /** + * get application by given id + * @method + * @param {string} id - id of application + * @promise {object} return {@link EndUser} object + * @fail {Error} return Error + */ + get(id) { + let client = this[clientKey]; + + return new Promise((resolve, reject) => { + if (action !== '' && !id) { + reject(new Error(this[idKey] + ' must be set')); + } + client('GET', action + (id ? id + '/' : '')) + .then(response => { + resolve(new ComplianceApplicationResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); + }); + } + + /** + * list all applications + * @method + * @param {object} params - params to list endusers + * @param {string} [params.status] - Status of the application + * @param {string} [params.endUserId] - End user ID related to application + * @param {string} [params.numberType] -Number Type related to application + * @param {integer} [params.offset] - No of value items by which results should be offset + * @param {integer} [params.limit] - No of value items by which results should be offset + */ + list(params = {}) { + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('GET', action, params) + .then(response => { + resolve(new ListComplianceApplicationResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); + }); + } + + /** + * Create a complaince application + * @method + * @param {object} params + * @param {string} [params.complianceRequirementId] - compliance requirement ID. + * @param {string} [params.endUserId] - End user ID. + * @param {string} [params.alias] - Alias + * @param {string} [params.documentIds] - Document IDs + * @param {string} [params.endUserType] - End user type + * @param {string} [params.countryIso2] - CountryISo2 + * @param {string} [params.numberType] - Number Type + * @fail {Error} return Error + */ + create(params = {}) { + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('POST', action, params) + .then(response => { + resolve(new CreateComplianceApplicationResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }) + } + + /** + * update ComplianceApplication + * @method + * @param {string} id - id to update + * @param {object} params + * @param {string} [params.documentIds] - Document IDs + * @promise {object} return {@link ComplianceApplication} object if success + * @fail {Error} return Error + */ + update(id, params) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); + + if (errors) { + return errors; + } + return new ComplianceApplication(this[clientKey], { + id: id + }).update(params, id); + } + + /** + * delete ComplianceApplication + * @method + * @param {string} id - id to delete + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + delete(id) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); + + if (errors) { + return errors; + } + return new ComplianceApplication(this[clientKey], { + id: id + }).delete(); + } + + /** + * submit an application by given id + * @method + * @param {string} id - id of application + * @fail {Error} return Error + */ + submit(id) { + let client = this[clientKey]; + + return new Promise((resolve, reject) => { + if (action !== '' && !id) { + reject(new Error(this[idKey] + ' must be set')); + } + + client('POST', action + (id ? id + '/Submit/' : '')) + .then(response => { + resolve(new ComplianceApplicationResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); + }); + } +} \ No newline at end of file diff --git a/lib/resources/complianceDocumentTypes.js b/lib/resources/complianceDocumentTypes.js new file mode 100644 index 0000000..5324e5c --- /dev/null +++ b/lib/resources/complianceDocumentTypes.js @@ -0,0 +1,110 @@ +import { + PlivoResource, + PlivoResourceInterface +} from '../base'; +import { + extend, + validate +} from '../utils/common.js'; + +const clientKey = Symbol(); +const action = 'ComplianceDocumentType/'; +const idField = 'documentTypeID'; + +export class ComplianceDocumentTypeResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.documentTypeId = params.documentTypeId; + this.documentName = params.documentName; + this.description = params.description; + this.information = params.information; + this.proofRequired = params.proofRequired; + this.createdAt = params.createdAt; + } +} + +export class ListComplianceDocumentTypeResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.meta = params.meta; + this.objects = params.objects; + } +} + +export class ComplianceDocumentType extends PlivoResource { + constructor(client, data = {}) { + super(action, ComplianceDocumentType, idField, client); + if (idField in data) { + this.id = data[idField]; + } + this[clientKey] = client; + extend(this, data); + } +} + +/** + * Represents a Compliance Document Type interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class ComplianceDocumentTypeInterface extends PlivoResourceInterface { + + constructor(client, data = {}) { + super(action, ComplianceDocumentType, idField, client); + extend(this, data); + this[clientKey] = client; + } + + /** + * get compliance document types by id + * @method + * @param {string} id - id of the compliane document type. + * @promise {object} return {@link ComplianceDocumentType} object + * @fail {Error} return Error + */ + get(id) { + let params = {} + params.isVoiceRequest = 'false' + let client = this[clientKey]; + + return new Promise((resolve, reject) => { + if (action !== '' && !id) { + reject(new Error(this[idKey] + ' must be set')); + } + + client('GET', action + (id ? id + '/' : '')) + .then(response => { + resolve(new ComplianceDocumentTypeResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); + }); + } + + /** + * list compliance document types + * @method + * @param {object} params - params to list endusers + * @param {string} [params.documentTypeID] - Document Type ID of the document id. + * @param {string} [params.documentName] - Document name of the document if present. + * @param {string} [params.description] - Description of the document type. + * @param {string} [params.information] - Information about the document type. + * @param {string} [params.proofRequired] - Proofs required for the document. + */ + list(params = {}) { + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('GET', action, params) + .then(response => { + resolve(new ListComplianceDocumentTypeResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); + }); + } +} \ No newline at end of file diff --git a/lib/resources/complianceDocuments.js b/lib/resources/complianceDocuments.js new file mode 100644 index 0000000..8235554 --- /dev/null +++ b/lib/resources/complianceDocuments.js @@ -0,0 +1,264 @@ +import { + PlivoResource, + PlivoResourceInterface +} from '../base'; +import { + extend, + validate +} from '../utils/common.js'; + +const clientKey = Symbol(); +const action = 'ComplianceDocument/'; +const idField = 'complianceDocumentId'; + +export class ComplianceDocumentResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.documentTypeId = params.documentTypeId; + this.documentId = params.documentId; + this.endUserId = params.endUserId; + this.alias = params.alias; + this.metaInformation = params.metaInformation; + this.fileName = params.fileName, + this.createdAt = params.createdAt; + } +} + +export class CreateComplianceDocumentResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.documentTypeId = params.documentTypeId; + this.documentId = params.documentId; + this.endUserId = params.endUserId; + this.alias = params.alias; + this.message = params.message; + this.metaInformation = params.metaInformation; + this.fileName = params.fileName, + this.createdAt = params.createdAt; + } +} + +export class ListComplianceDocumentsResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.meta = params.meta; + this.objects = params.objects; + } +} + +export class UpdateComplianceDocumentResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.message = params.message; + } +} + +export class ComplianceDocument extends PlivoResource { + constructor(client, data = {}) { + super(action, ComplianceDocument, idField, client); + if (idField in data) { + this.id = data[idField]; + } + this[clientKey] = client; + extend(this, data); + } + + /** + * update Compliance Document + * @method + * @param {string} id - compliance document id of the document. + * @param {object} params - optional params array of updated values + * @promise {object} return {@link ComplianceDocument} object if success + * @fail {Error} return Error + */ + update(params, id) { + let client = this[clientKey]; + let that = this; + return new Promise((resolve, reject) => { + if ((params.file) != 'undefined') { + params.multipart = true; + } + + client('POST', action + id + '/', params) + .then(response => { + extend(that, response.body); + extend(that, params); + resolve(new UpdateComplianceDocumentResponse(that)); + }) + .catch(error => { + reject(error); + }); + }); + + } + + /** + * delete an Compliance Document + * @method + * @param {string} id - id to delete + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + delete() { + let client = this[clientKey]; + let id = this.id; + return new Promise((resolve, reject) => { + client('DELETE', action + id + '/') + .then(() => { + resolve(true); + }) + .catch(error => { + reject(error); + }); + }); + } +} + +/** + * Represents a Compliance Application interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class ComplianceDocumentInterface extends PlivoResourceInterface { + constructor(client, data = {}) { + super(action, ComplianceDocument, idField, client); + extend(this, data); + this[clientKey] = client; + } + + /** + * get compliance document by given id + * @method + * @param {string} id - id of the document + * @promise {object} return {@link ComplianceDocument} object + * @fail {Error} return Error + */ + get(id) { + let client = this[clientKey]; + return new Promise((resolve, reject) => { + if (action !== '' && !id) { + reject(new Error(this[idKey] + ' must be set')); + } + client('GET', action + (id ? id + '/' : '')) + .then(response => { + let object = new ComplianceDocumentResponse(response.body, client); + Object.keys(object).forEach(key => object[key] === undefined && delete object[key]); + resolve(object); + }) + .catch(error => { + reject(error); + }); + }); + } + + /** + * list all documents + * @method + * @param {object} params - params containing options to list compliance documents by. + */ + list(params = {}) { + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('GET', action, params) + .then(response => { + resolve(new ListComplianceDocumentsResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } + + /** + * Create a complaince document + * @method + * @param {object} params + * @param {string} [params.complianceRequirementId] - compliance requirement ID. + * @param {string} [params.endUserId] - End user ID. + * @param {string} [params.alias] - Alias + * @param {string} [params.documentTypeId] - Document Type ID + * @param {string} [params.file] - File array of the files to be uploaded + * @fail {Error} return Error + */ + create(params = {}) { + let client = this[clientKey]; + let errors = validate([ + { field: 'endUserId', value: params.endUserId, validators: ['isRequired', 'isString'] } + ]); + + errors = validate([ + { field: 'documentTypeId', value: params.documentTypeId, validators: ['isRequired', 'isString'] } + ]); + + errors = validate([ + { field: 'alias', value: params.alias, validators: ['isRequired', 'isString'] } + ]); + + if (errors) { + return errors; + } + + return new Promise((resolve, reject) => { + params.multipart = true; + client('POST', action, params) + .then(response => { + let object = new CreateComplianceDocumentResponse(response.body, idField); + Object.keys(object).forEach(key => object[key] === undefined && delete object[key]); + resolve(object); + }) + .catch(error => { + reject(error); + }); + }) + } + + /** + * update Compliance Document + * @method + * @param {string} id - compliance document id of the document. + * @param {object} params - optional params array of updated values + * @promise {object} return {@link ComplianceDocument} object if success + * @fail {Error} return Error + */ + update(id, params) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); + + if (errors) { + return errors; + } + return new ComplianceDocument(this[clientKey], { + id: id + }).update(params, id); + } + + /** + * delete a Compliance Document + * @method + * @param {string} id - id to delete + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + delete(id) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); + + if (errors) { + return errors; + } + return new ComplianceDocument(this[clientKey], { + id: id + }).delete(); + } +} diff --git a/lib/resources/complianceRequirements.js b/lib/resources/complianceRequirements.js new file mode 100644 index 0000000..aa6a259 --- /dev/null +++ b/lib/resources/complianceRequirements.js @@ -0,0 +1,100 @@ +import { + PlivoResource, + PlivoResourceInterface +} from '../base'; +import { + extend, + validate +} from '../utils/common.js'; + +const clientKey = Symbol(); +const action = 'ComplianceRequirement/'; +const idField = 'ComplianceRequirementId'; + + +export class ComplianceRequirementResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.complianceRequirementId = params.complianceRequirementId; + this.countryIso2 = params.countryIso2; + this.numberType = params.numberType; + this.endUserType = params.endUserType; + this.acceptableDocumentTypes = params.acceptableDocumentTypes; + } +} + +export class ComplianceRequirement extends PlivoResource { + constructor(client, data = {}) { + super(action, ComplianceRequirement, idField, client); + if (idField in data) { + this.id = data[idField]; + } + this[clientKey] = client; + extend(this, data); + } +} + +/** + * Represents a Compliance Requirement + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class ComplianceRequirementInterface extends PlivoResourceInterface { + + constructor(client, data = {}) { + super(action, ComplianceRequirement, idField, client); + extend(this, data); + this[clientKey] = client; + } + + /** + * get compliance requirement by given id + * @method + * @param {string} id - id of the compliance requirement + * @promise {object} return {@link ComplianceRequirement} object + * @fail {Error} return Error + */ + get(id) { + let client = this[clientKey]; + + return new Promise((resolve, reject) => { + if (action !== '' && !id) { + reject(new Error(this[idKey] + ' must be set')); + } + client('GET', action + (id ? id + '/' : '')) + .then(response => { + resolve(new ComplianceRequirementResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); + }); + } + + /** + * list compliance requirements + * @method + * @param {object} params - params to list endusers + * @param {string} [params.countryIso2] - Document Type ID of the document id. + * @param {string} [params.numberType] - Document name of the document if present. + * @param {string} [params.phoneNumber] - Description of the document type. + * @param {string} [params.endUserType] - Information about the document type. + * A combination of countryIso2, numberType, endUserType OR + * phoneNumber, endUserType can be used to fetch compliance requirements. + */ + list(params = {}) { + let client = this[clientKey]; + + return new Promise((resolve, reject) => { + client('GET', action, params) + .then(response => { + resolve(new ComplianceRequirementResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); + }); + } +} \ No newline at end of file diff --git a/lib/resources/conferences.js b/lib/resources/conferences.js index 1073ba7..f5bfff7 100644 --- a/lib/resources/conferences.js +++ b/lib/resources/conferences.js @@ -1,5 +1,11 @@ -import {extend, validate} from '../utils/common.js'; -import {PlivoResource, PlivoResourceInterface} from '../base'; +import { + PlivoResource, + PlivoResourceInterface +} from '../base'; +import { + extend, + validate +} from '../utils/common.js'; const clientKey = Symbol(); const action = 'Conference/'; @@ -11,288 +17,434 @@ const idField = 'conferenceName'; * @param {function} client - make api call * @param {object} [data] - data of call */ + +export class MuteMemberResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.memberId = params.memberId; + this.message = params.message; + + } +} + +export class StartRecordingConferenceResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.message = params.message; + this.recordingId = params.recordingId; + this.url = params.url; + } +} + +export class RetrieveConferenceResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.conferenceMemberCount = params.conferenceMemberCount; + this.conferenceName = params.conferenceName; + this.conferenceRunTime = params.conferenceRunTime; + this.members = params.members; + } +} + +export class ListAllConferenceResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.conferences = params.conferences; + } +} +export class SpeakMemberResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.memberId = params.memberId; + this.message = params.message; + + } +} + +export class PlayAudioMemberResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.memberId = params.memberId; + this.message = params.message; + + } +} + +export class DeafMemberResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.memberId = params.memberId; + this.message = params.message; + + } +} + export class Conference extends PlivoResource { - constructor(client, data = {}) { - super(action, Conference, idField, client); + constructor(client, data = {}) { + super(action, Conference, idField, client); - if (idField in data) { - this.id = data[idField]; + if (idField in data) { + this.id = data[idField]; + } + + extend(this, data); + this[clientKey] = client; } - extend(this, data); - this[clientKey] = client; - } - -/** - * hangup conference - * @method - * @promise {Boolean} return true if call hung up - * @fail {Error} return Error - */ - hangup() { - let params = {} - params.isVoiceRequest = 'true' - return super.delete(params); - } - -/** - * hangup member from conference - * @method - * @param {string} memberId - id of member to be hangup - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - hangupMember(memberId) { - let errors = validate([ - {field: 'member_id', value: memberId, validators: ['isRequired']} - ]); - - if (errors) { - return errors; + /** + * hangup conference + * @method + * @promise {Boolean} return true if call hung up + * @fail {Error} return Error + */ + hangup() { + let params = {} + params.isVoiceRequest = 'true' + return super.delete(params); } - let params = {} - params.isVoiceRequest = 'true' - return super.executeAction(this.id + '/Member/' + memberId + '/', 'DELETE', params); - } -/** - * kick member from conference - * @method - * @param {string} memberId - id of member - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - kickMember(memberId) { - let errors = validate([ - {field: 'member_id', value: memberId, validators: ['isRequired']} - ]); + /** + * hangup member from conference + * @method + * @param {string} memberId - id of member to be hangup + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + hangupMember(memberId) { + let errors = validate([{ + field: 'member_id', + value: memberId, + validators: ['isRequired'] + }]); - if (errors) { - return errors; + if (errors) { + return errors; + } + let params = {} + params.isVoiceRequest = 'true' + return super.executeAction(this.id + '/Member/' + memberId + '/', 'DELETE', params); } - let params = {} - params.isVoiceRequest = 'true' - return super.executeAction(this.id + '/Member/' + memberId + '/Kick/', 'POST',params); - } -/** - * mute member from conference - * @method - * @param {string} memberId - id of member - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - muteMember(memberId) { - let errors = validate([ - {field: 'member_id', value: memberId, validators: ['isRequired']} - ]); + /** + * kick member from conference + * @method + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + kickMember(memberId) { + let errors = validate([{ + field: 'member_id', + value: memberId, + validators: ['isRequired'] + }]); - if (errors) { - return errors; + if (errors) { + return errors; + } + let params = {} + params.isVoiceRequest = 'true' + return super.executeAction(this.id + '/Member/' + memberId + '/Kick/', 'POST', params); } - let params = {} - params.isVoiceRequest = 'true' - return super.executeAction(this.id + '/Member/' + memberId + '/Mute/', 'POST',params); - } -/** - * unmute member from conference - * @method - * @param {string} memberId - id of member - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - unmuteMember(memberId) { - let errors = validate([ - {field: 'member_id', value: memberId, validators: ['isRequired']} - ]); + /** + * mute member from conference + * @method + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + muteMember(memberId) { + let errors = validate([{ + field: 'member_id', + value: memberId, + validators: ['isRequired'] + }]); - if (errors) { - return errors; + if (errors) { + return errors; + } + let params = {} + params.isVoiceRequest = 'true' + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('POST', action + this.id + '/Member/' + memberId + '/Mute/', params) + .then(response => { + resolve(new MuteMemberResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); } - let params = {} - params.isVoiceRequest = 'true' - return super.executeAction(this.id + '/Member/' + memberId + '/Mute/', 'DELETE', params); - } -/** - * deaf member from conference - * @method - * @param {string} memberId - id of member - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - deafMember(memberId) { - let errors = validate([ - {field: 'member_id', value: memberId, validators: ['isRequired']} - ]); + /** + * unmute member from conference + * @method + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + unmuteMember(memberId) { + let errors = validate([{ + field: 'member_id', + value: memberId, + validators: ['isRequired'] + }]); - if (errors) { - return errors; + if (errors) { + return errors; + } + let params = {} + params.isVoiceRequest = 'true' + return super.executeAction(this.id + '/Member/' + memberId + '/Mute/', 'DELETE', params); } - let params = {} - params.isVoiceRequest = 'true' - return super.executeAction(this.id + '/Member/' + memberId + '/Deaf/', 'POST', params); - } -/** - * undeaf member from conference - * @method - * @param {string} memberId - id of member - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - undeafMember(memberId) { - let errors = validate([ - {field: 'member_id', value: memberId, validators: ['isRequired']} - ]); + /** + * deaf member from conference + * @method + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + deafMember(memberId) { + let errors = validate([{ + field: 'member_id', + value: memberId, + validators: ['isRequired'] + }]); - if (errors) { - return errors; + if (errors) { + return errors; + } + let params = {} + params.isVoiceRequest = 'true' + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('POST', action + this.id + '/Member/' + memberId + '/Deaf/', params) + .then(response => { + resolve(new DeafMemberResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); } - let params = {} - params.isVoiceRequest = 'true' - return super.executeAction(this.id + '/Member/' + memberId + '/Deaf/', 'DELETE', params); - } -/** - * play audio to member - * @method - * @param {string} memberId - id of member - * @param {string} url - url for audio - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - playAudioToMember(memberId, url) { - let errors = validate([ - {field: 'member_id', value: memberId, validators: ['isRequired']}, - {field: 'url', value: url, validators: ['isRequired']} - ]); + /** + * undeaf member from conference + * @method + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + undeafMember(memberId) { + let errors = validate([{ + field: 'member_id', + value: memberId, + validators: ['isRequired'] + }]); - if (errors) { - return errors; + if (errors) { + return errors; + } + let params = {} + params.isVoiceRequest = 'true' + return super.executeAction(this.id + '/Member/' + memberId + '/Deaf/', 'DELETE', params); } - let params = {url: url}; - params.isVoiceRequest = 'true'; - return super.executeAction(this.id + '/Member/' + memberId + '/Play/', 'POST', params); - } -/** - * stop playing audio to member - * @method - * @param {string} memberId - id of member - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - stopPlayingAudioToMember(memberId) { - let errors = validate([ - {field: 'member_id', value: memberId, validators: ['isRequired']} - ]); + /** + * play audio to member + * @method + * @param {string} memberId - id of member + * @param {string} url - url for audio + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + playAudioToMember(memberId, url) { + let errors = validate([{ + field: 'member_id', + value: memberId, + validators: ['isRequired'] + }, + { + field: 'url', + value: url, + validators: ['isRequired'] + } + ]); - if (errors) { - return errors; + if (errors) { + return errors; + } + let params = { + url: url + }; + params.isVoiceRequest = 'true'; + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('POST', action + this.id + '/Member/' + memberId + '/Play/', params) + .then(response => { + resolve(new PlayAudioMemberResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); } - let params = {}; - params.isVoiceRequest = 'true'; - return super.executeAction(this.id + '/Member/' + memberId + '/Play/', 'DELETE', params); - } -/** - * speak text to member - * @method - * @param {string} memberId - id of member - * @param {string} text - text to be speak to member - * @param {object} optionalParams - optionalPrams to speak text - * @param {string} [optionalParams.voice] The voice to be used. Can be MAN or WOMAN. Defaults to WOMAN. - * @param {string} [optionalParams.language] The language to be used. Defaults to en-US. - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - speakTextToMember(memberId, text, optionalParams) { - let errors = validate([ - {field: 'member_id', value: memberId, validators: ['isRequired']}, - {field: 'text', value: text, validators: ['isRequired']} - ]); + /** + * stop playing audio to member + * @method + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + stopPlayingAudioToMember(memberId) { + let errors = validate([{ + field: 'member_id', + value: memberId, + validators: ['isRequired'] + }]); - if (errors) { - return errors; + if (errors) { + return errors; + } + let params = {}; + params.isVoiceRequest = 'true'; + return super.executeAction(this.id + '/Member/' + memberId + '/Play/', 'DELETE', params); } - let params = optionalParams || {}; - params.text = text; - params.isVoiceRequest = 'true'; - return super.executeAction(this.id + '/Member/' + memberId + '/Speak/', 'POST', params); - } -/** - * stop speaking text to member - * @method - * @param {string} memberId - id of member - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - stopSpeakingTextToMember(memberId) { - let errors = validate([ - {field: 'member_id', value: memberId, validators: ['isRequired']} - ]); + /** + * speak text to member + * @method + * @param {string} memberId - id of member + * @param {string} text - text to be speak to member + * @param {object} optionalParams - optionalPrams to speak text + * @param {string} [optionalParams.voice] The voice to be used. Can be MAN or WOMAN. Defaults to WOMAN. + * @param {string} [optionalParams.language] The language to be used. Defaults to en-US. + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + speakTextToMember(memberId, text, optionalParams) { + let errors = validate([{ + field: 'member_id', + value: memberId, + validators: ['isRequired'] + }, + { + field: 'text', + value: text, + validators: ['isRequired'] + } + ]); - if (errors) { - return errors; + if (errors) { + return errors; + } + let params = optionalParams || {}; + params.text = text; + params.isVoiceRequest = 'true'; + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('POST', action + this.id + '/Member/' + memberId + '/Speak/', params) + .then(response => { + resolve(new SpeakMemberResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); } - let params = {}; - params.isVoiceRequest = 'true'; - return super.executeAction(this.id + '/Member/' + memberId + '/Speak/', 'DELETE'); - } - /** - * Record conference - * @method - * @param {object} params - optional params to record conference - * @param {string} [params.fileFormat] The file format of the record can be of mp3 or wav format. Defaults to mp3 format. - * @param {string} [params.transcriptionType] The type of transcription required. The following values are allowed: - * - auto - This is the default value. Transcription is completely automated; turnaround time is about 5 minutes. - * - hybrid - Transcription is a combination of automated and human verification processes; turnaround time is about 10-15 minutes. - * @param {string} [params.transcriptionUrl] The URL where the transcription is available. - * @param {string} [params.transcriptionMethod] The method used to invoke the transcription_url. Defaults to POST. - * @param {string} [params.callbackUrl] The URL invoked by the API when the recording ends. - * @param {string} [params.callbackMethod] The method which is used to invoke the callback_url URL. Defaults to POST. - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - record(params) { - return this.startRecording(params); - } + /** + * stop speaking text to member + * @method + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + stopSpeakingTextToMember(memberId) { + let errors = validate([{ + field: 'member_id', + value: memberId, + validators: ['isRequired'] + }]); - /** - * Record conference - * @method - * @param {object} params - optional params to record conference - * @param {string} [params.fileFormat] The file format of the record can be of mp3 or wav format. Defaults to mp3 format. - * @param {string} [params.transcriptionType] The type of transcription required. The following values are allowed: - * - auto - This is the default value. Transcription is completely automated; turnaround time is about 5 minutes. - * - hybrid - Transcription is a combination of automated and human verification processes; turnaround time is about 10-15 minutes. - * @param {string} [params.transcriptionUrl] The URL where the transcription is available. - * @param {string} [params.transcriptionMethod] The method used to invoke the transcription_url. Defaults to POST. - * @param {string} [params.callbackUrl] The URL invoked by the API when the recording ends. - * @param {string} [params.callbackMethod] The method which is used to invoke the callback_url URL. Defaults to POST. - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - startRecording(params={}) { - params.isVoiceRequest = 'true'; - return super.executeAction(this.id + '/Record/', 'POST', params); - } + if (errors) { + return errors; + } + let params = {}; + params.isVoiceRequest = 'true'; + return super.executeAction(this.id + '/Member/' + memberId + '/Speak/', 'DELETE'); + } -/** - * stop recording conference - * @method - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - stopRecording() { - let params = {}; - params.isVoiceRequest = 'true'; - return super.executeAction(this.id + '/Record/', 'DELETE', params); - } + /** + * Record conference + * @method + * @param {object} params - optional params to record conference + * @param {string} [params.fileFormat] The file format of the record can be of mp3 or wav format. Defaults to mp3 format. + * @param {string} [params.transcriptionType] The type of transcription required. The following values are allowed: + * - auto - This is the default value. Transcription is completely automated; turnaround time is about 5 minutes. + * - hybrid - Transcription is a combination of automated and human verification processes; turnaround time is about 10-15 minutes. + * @param {string} [params.transcriptionUrl] The URL where the transcription is available. + * @param {string} [params.transcriptionMethod] The method used to invoke the transcription_url. Defaults to POST. + * @param {string} [params.callbackUrl] The URL invoked by the API when the recording ends. + * @param {string} [params.callbackMethod] The method which is used to invoke the callback_url URL. Defaults to POST. + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + record(params) { + return this.startRecording(params); + } + + /** + * Record conference + * @method + * @param {object} params - optional params to record conference + * @param {string} [params.fileFormat] The file format of the record can be of mp3 or wav format. Defaults to mp3 format. + * @param {string} [params.transcriptionType] The type of transcription required. The following values are allowed: + * - auto - This is the default value. Transcription is completely automated; turnaround time is about 5 minutes. + * - hybrid - Transcription is a combination of automated and human verification processes; turnaround time is about 10-15 minutes. + * @param {string} [params.transcriptionUrl] The URL where the transcription is available. + * @param {string} [params.transcriptionMethod] The method used to invoke the transcription_url. Defaults to POST. + * @param {string} [params.callbackUrl] The URL invoked by the API when the recording ends. + * @param {string} [params.callbackMethod] The method which is used to invoke the callback_url URL. Defaults to POST. + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + startRecording(params = {}) { + params.isVoiceRequest = 'true'; + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('POST', action + this.id + '/Record/', params) + .then(response => { + resolve(new StartRecordingConferenceResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } + + /** + * stop recording conference + * @method + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + stopRecording() { + let params = {}; + params.isVoiceRequest = 'true'; + return super.executeAction(this.id + '/Record/', 'DELETE', params); + } } /** @@ -303,387 +455,486 @@ export class Conference extends PlivoResource { */ export class ConferenceInterface extends PlivoResourceInterface { - constructor(client, data = {}) { - super(action, Conference, idField, client); - extend(this, data); + constructor(client, data = {}) { + super(action, Conference, idField, client); + extend(this, data); - this[clientKey] = client; - } - -/** - * get conference by id - * @method - * @param {string} id - id of conference - * @promise {@link Conference} return {@link Conference} object if success - * @fail {Error} return Error - */ - get(id) { - let errors = validate([ - {field: 'id', value: id, validators: ['isRequired']} - ]); - - if (errors) { - return errors; + this[clientKey] = client; } - let params = {}; - params.isVoiceRequest = 'true'; - return super.get(id, params); - } -/** - * get all conferences. returns name of all conferences - * @method - * @promise {@link [Conference]} returns list of {@link Conference} objects if success - * @fail {Error} return Error - */ - list() { - let client = this[clientKey]; - let params = {} - params.isVoiceRequest = 'true'; - return new Promise((resolve, reject) => { - client('GET', action, params) - .then(response => { - let conferences = []; - response.body.conferences.forEach(conference => { - conferences.push(new Conference(client, { - name: conference - })); - }); - resolve(response.body); - }) - .catch(error => { - reject(error); + /** + * get conference by id + * @method + * @param {string} id - id of conference + * @promise {@link Conference} return {@link Conference} object if success + * @fail {Error} return Error + */ + get(id) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); + + if (errors) { + return errors; + } + let params = {}; + params.isVoiceRequest = 'true'; + //return super.get(id, params); + let client = this[clientKey]; + return new Promise((resolve, reject) => { + if (action !== '' && !id) { + reject(new Error(this[idKey] + ' must be set')); + } + client('GET', action + (id ? id + '/' : ''), params) + .then(response => { + resolve(new RetrieveConferenceResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); }); - }); - } - -/** - * hangup conference - * @method - * @param {string} conferenceName - name of conference - * @promise {@link Conference} return {@link Conference} object if success - * @fail {Error} return Error - */ - hangup(conferenceName) { - let errors = validate([ - {field: 'conference_name', value: conferenceName, validators: ['isRequired']} - ]); - - if (errors) { - return errors; - } - let params = {}; - params.isVoiceRequest = 'true'; - return new Conference(this[clientKey], { - id: conferenceName - }).delete(params); - } - -/** - * hangup all - * @method - * @promise {@link PlivoGenericResponse} returns object of PlivoGenericResponse if success - * @fail {Error} return Error - */ - hangupAll() { - let params = {}; - params.isVoiceRequest = 'true'; - return new Conference(this[clientKey]) - .executeAction('', 'DELETE', params); - } - -/** - * hangup member from conference - * @method - * @param {string} id - id of conference - * @param {string} memberId - id of member to be hangup - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - hangupMember(id, memberId) { - let errors = validate([ - {field: 'id', value: id, validators: ['isRequired']}, - {field: 'memberId', value: memberId, validators: ['isRequired']} - ]); - - if (errors) { - return errors; - } - return new Conference(this[clientKey], { - id: id - }).hangupMember(memberId); - } - -/** - * kick member from conference - * @method - * @param {string} id - id of conference - * @param {string} memberId - id of member - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - kickMember(id, memberId) { - let errors = validate([ - {field: 'id', value: id, validators: ['isRequired']}, - {field: 'memberId', value: memberId, validators: ['isRequired']} - ]); - - if (errors) { - return errors; - } - return new Conference(this[clientKey], { - id: id - }).kickMember(memberId); - } - -/** - * mute member - * @method - * @param {string} id - id of conference - * @param {string} memberId - id of member - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - muteMember(id, memberId) { - let errors = validate([ - {field: 'id', value: id, validators: ['isRequired']}, - {field: 'memberId', value: memberId, validators: ['isRequired']} - ]); - - if (errors) { - return errors; - } - return new Conference(this[clientKey], { - id: id - }).muteMember(memberId); - } - -/** - * unmute member - * @method - * @param {string} id - id of conference - * @param {string} memberId - id of member - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - unmuteMember(id, memberId) { - let errors = validate([ - {field: 'id', value: id, validators: ['isRequired']}, - {field: 'memberId', value: memberId, validators: ['isRequired']} - ]); - - if (errors) { - return errors; - } - return new Conference(this[clientKey], { - id: id - }).unmuteMember(memberId); - } - -/** - * deaf member - * @method - * @param {string} id - id of conference - * @param {string} memberId - id of member - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - deafMember(id, memberId) { - let errors = validate([ - {field: 'id', value: id, validators: ['isRequired']}, - {field: 'memberId', value: memberId, validators: ['isRequired']} - ]); - - if (errors) { - return errors; - } - return new Conference(this[clientKey], { - id: id - }).deafMember(memberId); - } - -/** - * undeaf member - * @method - * @param {string} id - id of conference - * @param {string} memberId - id of member - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - undeafMember(id, memberId) { - let errors = validate([ - {field: 'id', value: id, validators: ['isRequired']}, - {field: 'memberId', value: memberId, validators: ['isRequired']} - ]); - - if (errors) { - return errors; - } - return new Conference(this[clientKey], { - id: id - }).undeafMember(memberId); - } -/** - * play audio to member - * @method - * @param {string} id - id of conference - * @param {string} memberId - id of member - * @param {string} url - urls for audio - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - - playAudioToMember(id, memberId, url) { - let errors = validate([ - {field: 'id', value: id, validators: ['isRequired']}, - {field: 'memberId', value: memberId, validators: ['isRequired']}, - {field: 'url', value: url, validators: ['isRequired']} - ]); - - if (errors) { - return errors; - } - return new Conference(this[clientKey], { - id: id - }).playAudioToMember(memberId, url); - } - -/** - * stop playing audio to member - * @method - * @param {string} id - id of conference - * @param {string} memberId - id of member - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - stopPlayingAudioToMember(id, memberId) { - let errors = validate([ - {field: 'id', value: id, validators: ['isRequired']}, - {field: 'memberId', value: memberId, validators: ['isRequired']} - ]); - - if (errors) { - return errors; - } - return new Conference(this[clientKey], { - id: id - }).stopPlayingAudioToMember(memberId); - } - -/** - * speak text to member - * @method - * @param {string} id - id of conference - * @param {string} memberId - id of member - * @param {string} text - text to speak - * @param {object} optionalParams - optional params - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - speakTextToMember(id, memberId, text, optionalParams) { - let errors = validate([ - {field: 'id', value: id, validators: ['isRequired']}, - {field: 'memberId', value: memberId, validators: ['isRequired']}, - {field: 'text', value: text, validators: ['isRequired']} - ]); - - if (errors) { - return errors; - } - return new Conference(this[clientKey], { - id: id - }).speakTextToMember(memberId, text, optionalParams); - } - -/** - * stop speaking text to member - * @method - * @param {string} id - id of conference - * @param {string} memberId - id of member - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - stopSpeakingTextToMember(id, memberId) { - let errors = validate([ - {field: 'id', value: id, validators: ['isRequired']}, - {field: 'memberId', value: memberId, validators: ['isRequired']} - ]); - - if (errors) { - return errors; - } - return new Conference(this[clientKey], { - id: id - }).stopSpeakingTextToMember(memberId); - } - -/** - * record conference - * @method - * @param {string} id - id of conference - * @param {object} params - optional params to record conference - * @param {string} [params.fileFormat] The file format of the record can be of mp3 or wav format. Defaults to mp3 format. - * @param {string} [params.transcriptionType] The type of transcription required. The following values are allowed: - * - auto - This is the default value. Transcription is completely automated; turnaround time is about 5 minutes. - * - hybrid - Transcription is a combination of automated and human verification processes; turnaround time is about 10-15 minutes. - * @param {string} [params.transcriptionUrl] The URL where the transcription is available. - * @param {string} [params.transcriptionMethod] The method used to invoke the transcription_url. Defaults to POST. - * @param {string} [params.callbackUrl] The URL invoked by the API when the recording ends. - * @param {string} [params.callbackMethod] The method which is used to invoke the callback_url URL. Defaults to POST. - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - record(id, params) { - return this.startRecording(id, params); - } - -/** - * record conference - * @method - * @param {string} id - id of conference - * @param {object} params - optional params to record conference - * @param {string} [params.fileFormat] The file format of the record can be of mp3 or wav format. Defaults to mp3 format. - * @param {string} [params.transcriptionType] The type of transcription required. The following values are allowed: - * - auto - This is the default value. Transcription is completely automated; turnaround time is about 5 minutes. - * - hybrid - Transcription is a combination of automated and human verification processes; turnaround time is about 10-15 minutes. - * @param {string} [params.transcriptionUrl] The URL where the transcription is available. - * @param {string} [params.transcriptionMethod] The method used to invoke the transcription_url. Defaults to POST. - * @param {string} [params.callbackUrl] The URL invoked by the API when the recording ends. - * @param {string} [params.callbackMethod] The method which is used to invoke the callback_url URL. Defaults to POST. - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - startRecording(id, params) { - let errors = validate([ - {field: 'id', value: id, validators: ['isRequired']} - ]); - - if (errors) { - return errors; } - return new Conference(this[clientKey], { - id: id - }).startRecording(params); - } - -/** - * stop recording - * @method - * @param {string} id - id of conference - * @promise {PlivoGenericResponse} return PlivoGenericResponse if success - * @fail {Error} return Error - */ - stopRecording(id) { - let errors = validate([ - {field: 'id', value: id, validators: ['isRequired']} - ]); - - if (errors) { - return errors; + /** + * get all conferences. returns name of all conferences + * @method + * @promise {@link [Conference]} returns list of {@link Conference} objects if success + * @fail {Error} return Error + */ + list() { + let client = this[clientKey]; + let params = {} + params.isVoiceRequest = 'true'; + return new Promise((resolve, reject) => { + client('GET', action, params) + .then(response => { + let conferences = []; + response.body.conferences.forEach(conference => { + conferences.push(new Conference(client, { + name: conference + })); + }); + resolve(new ListAllConferenceResponse(response.body)); + }) + .catch(error => { + reject(error); + }); + }); } - return new Conference(this[clientKey], { - id: id - }).stopRecording(); - } -} + + /** + * hangup conference + * @method + * @param {string} conferenceName - name of conference + * @promise {@link Conference} return {@link Conference} object if success + * @fail {Error} return Error + */ + hangup(conferenceName) { + let errors = validate([{ + field: 'conference_name', + value: conferenceName, + validators: ['isRequired'] + }]); + + if (errors) { + return errors; + } + let params = {}; + params.isVoiceRequest = 'true'; + return new Conference(this[clientKey], { + id: conferenceName + }).delete(params); + } + + /** + * hangup all + * @method + * @promise {@link PlivoGenericResponse} returns object of PlivoGenericResponse if success + * @fail {Error} return Error + */ + hangupAll() { + let params = {}; + params.isVoiceRequest = 'true'; + return new Conference(this[clientKey]) + .executeAction('', 'DELETE', params); + } + + /** + * hangup member from conference + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member to be hangup + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + hangupMember(id, memberId) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }, + { + field: 'memberId', + value: memberId, + validators: ['isRequired'] + } + ]); + + if (errors) { + return errors; + } + return new Conference(this[clientKey], { + id: id + }).hangupMember(memberId); + } + + /** + * kick member from conference + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + kickMember(id, memberId) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }, + { + field: 'memberId', + value: memberId, + validators: ['isRequired'] + } + ]); + + if (errors) { + return errors; + } + return new Conference(this[clientKey], { + id: id + }).kickMember(memberId); + } + + /** + * mute member + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + muteMember(id, memberId) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }, + { + field: 'memberId', + value: memberId, + validators: ['isRequired'] + } + ]); + + if (errors) { + return errors; + } + return new Conference(this[clientKey], { + id: id + }).muteMember(memberId); + } + + /** + * unmute member + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + unmuteMember(id, memberId) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }, + { + field: 'memberId', + value: memberId, + validators: ['isRequired'] + } + ]); + + if (errors) { + return errors; + } + return new Conference(this[clientKey], { + id: id + }).unmuteMember(memberId); + } + + /** + * deaf member + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + deafMember(id, memberId) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }, + { + field: 'memberId', + value: memberId, + validators: ['isRequired'] + } + ]); + + if (errors) { + return errors; + } + return new Conference(this[clientKey], { + id: id + }).deafMember(memberId); + } + + /** + * undeaf member + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + undeafMember(id, memberId) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }, + { + field: 'memberId', + value: memberId, + validators: ['isRequired'] + } + ]); + + if (errors) { + return errors; + } + return new Conference(this[clientKey], { + id: id + }).undeafMember(memberId); + } + /** + * play audio to member + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member + * @param {string} url - urls for audio + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + + playAudioToMember(id, memberId, url) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }, + { + field: 'memberId', + value: memberId, + validators: ['isRequired'] + }, + { + field: 'url', + value: url, + validators: ['isRequired'] + } + ]); + + if (errors) { + return errors; + } + return new Conference(this[clientKey], { + id: id + }).playAudioToMember(memberId, url); + } + + /** + * stop playing audio to member + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + stopPlayingAudioToMember(id, memberId) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }, + { + field: 'memberId', + value: memberId, + validators: ['isRequired'] + } + ]); + + if (errors) { + return errors; + } + return new Conference(this[clientKey], { + id: id + }).stopPlayingAudioToMember(memberId); + } + + /** + * speak text to member + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member + * @param {string} text - text to speak + * @param {object} optionalParams - optional params + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + speakTextToMember(id, memberId, text, optionalParams) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }, + { + field: 'memberId', + value: memberId, + validators: ['isRequired'] + }, + { + field: 'text', + value: text, + validators: ['isRequired'] + } + ]); + + if (errors) { + return errors; + } + return new Conference(this[clientKey], { + id: id + }).speakTextToMember(memberId, text, optionalParams); + } + + /** + * stop speaking text to member + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + stopSpeakingTextToMember(id, memberId) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }, + { + field: 'memberId', + value: memberId, + validators: ['isRequired'] + } + ]); + + if (errors) { + return errors; + } + return new Conference(this[clientKey], { + id: id + }).stopSpeakingTextToMember(memberId); + } + + /** + * record conference + * @method + * @param {string} id - id of conference + * @param {object} params - optional params to record conference + * @param {string} [params.fileFormat] The file format of the record can be of mp3 or wav format. Defaults to mp3 format. + * @param {string} [params.transcriptionType] The type of transcription required. The following values are allowed: + * - auto - This is the default value. Transcription is completely automated; turnaround time is about 5 minutes. + * - hybrid - Transcription is a combination of automated and human verification processes; turnaround time is about 10-15 minutes. + * @param {string} [params.transcriptionUrl] The URL where the transcription is available. + * @param {string} [params.transcriptionMethod] The method used to invoke the transcription_url. Defaults to POST. + * @param {string} [params.callbackUrl] The URL invoked by the API when the recording ends. + * @param {string} [params.callbackMethod] The method which is used to invoke the callback_url URL. Defaults to POST. + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + record(id, params) { + return this.startRecording(id, params); + } + + /** + * record conference + * @method + * @param {string} id - id of conference + * @param {object} params - optional params to record conference + * @param {string} [params.fileFormat] The file format of the record can be of mp3 or wav format. Defaults to mp3 format. + * @param {string} [params.transcriptionType] The type of transcription required. The following values are allowed: + * - auto - This is the default value. Transcription is completely automated; turnaround time is about 5 minutes. + * - hybrid - Transcription is a combination of automated and human verification processes; turnaround time is about 10-15 minutes. + * @param {string} [params.transcriptionUrl] The URL where the transcription is available. + * @param {string} [params.transcriptionMethod] The method used to invoke the transcription_url. Defaults to POST. + * @param {string} [params.callbackUrl] The URL invoked by the API when the recording ends. + * @param {string} [params.callbackMethod] The method which is used to invoke the callback_url URL. Defaults to POST. + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + startRecording(id, params) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); + + if (errors) { + return errors; + } + + return new Conference(this[clientKey], { + id: id + }).startRecording(params); + } + + /** + * stop recording + * @method + * @param {string} id - id of conference + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + stopRecording(id) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); + + if (errors) { + return errors; + } + return new Conference(this[clientKey], { + id: id + }).stopRecording(); + } +} \ No newline at end of file diff --git a/lib/resources/endUsers.js b/lib/resources/endUsers.js new file mode 100644 index 0000000..0bd77d8 --- /dev/null +++ b/lib/resources/endUsers.js @@ -0,0 +1,254 @@ +import { + PlivoResource, + PlivoResourceInterface +} from '../base'; +import { + extend, + validate +} from '../utils/common.js'; + +const clientKey = Symbol(); +const action = 'EndUser/'; +const idField = 'endUserId'; + +export class EndUsersResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.endUserId = params.endUserId; + this.endUserType = params.endUserType; + this.name = params.name; + this.lastName = params.lastName; + this.createdAt = params.createdAt; + } +} + +export class CreateEndUsersResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.endUserId = params.endUserId; + this.endUserType = params.endUserType; + this.name = params.name; + this.lastName = params.lastName; + this.message = params.message; + this.createdAt = params.createdAt; + } +} + +export class ListEndUsersResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.meta = params.meta; + this.objects = params.objects; + } +} + +export class UpdateEndUsersResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.message = params.message; + } +} + +export class EndUser extends PlivoResource { + constructor(client, data = {}) { + super(action, EndUser, idField, client); + if (idField in data) { + this.id = data[idField]; + } + this[clientKey] = client; + extend(this, data); + } + + /** + * update end user + * @method + * @param {object} params - to update end user + * @param {string} [params.name] - Name of the endUser if present. + * @param {string} [params.last_name] - Last name of the endUser if present. + * @param {string} [params.end_user_type] - Type of the end user. + * @fail {Error} return Error + */ + update(params, id) { + let client = this[clientKey]; + let that = this; + + return new Promise((resolve, reject) => { + client('POST', action + id + '/', params) + .then(response => { + extend(that, response.body); + extend(that, params); + resolve(new UpdateEndUsersResponse(that)); + }) + .catch(error => { + reject(error); + }); + }); + + } + + /** + * delete an EndUser + * @method + * @param {string} id - id to delete + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + delete() { + let client = this[clientKey]; + let id = this.id; + + return new Promise((resolve, reject) => { + client('DELETE', action + id + '/') + .then(() => { + resolve(true); + }) + .catch(error => { + reject(error); + }); + }); + } +} + +/** + * Represents a End Users interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class EndUserInterface extends PlivoResourceInterface { + + constructor(client, data = {}) { + super(action, EndUser, idField, client); + extend(this, data); + this[clientKey] = client; + } + + /** + * get an enduser by given id + * @method + * @param {string} id - id of the endUser + * @promise {object} return {@link EndUser} object + * @fail {Error} return Error + */ + get(id) { + let errors = validate([ + {field: 'id', value: id, validators: ['isRequired']} + ]); + + if (errors) { + return errors; + } + + let client = this[clientKey]; + + return new Promise((resolve, reject) => { + if (action !== '' && !id) { + reject(new Error(this[idKey] + ' must be set')); + } + client('GET', action + (id ? id + '/' : '')) + .then(response => { + resolve(new EndUsersResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); + }); + } + + /** + * list EndUsers + * @method + * @param {object} params - params to list endusers + * @param {string} [params.name] - Name of the endUser, if present. + * @param {string} [params.lastName] - Last name of the endUser, if present. + * @param {string} [params.endUserType] - Type of an end user. + * @param {integer} [params.offset] - No of value items by which results should be offset + * @param {integer} [params.limit] - No of value items by which results should be offset + */ + list(params = {}) { + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('GET', action, params) + .then(response => { + resolve(new ListEndUsersResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); + }); + } + + /** + * Create end user + * @method + * @param {object} params - to update end user + * @param {string} [params.name] - Name of the endUser if present. + * @param {string} [params.lastName] - Last name of the endUser if present. + * @param {string} [params.endUserType] - Type of the end user. + * @fail {Error} return Error + */ + create(params = {}) { + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('POST', action, params) + .then(response => { + resolve(new CreateEndUsersResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }) + } + + /** + * update end user + * @method + * @param {object} params - to update end user + * @param {string} [params.name] - Name of the endUser if present. + * @param {string} [params.lastName] - Last name of the endUser if present. + * @param {string} [params.endUserType] - Type of the end user. + * @fail {Error} return Error + */ + update(id, params) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); + + if (errors) { + return errors; + } + + return new EndUser(this[clientKey], { + id: id + }).update(params, id); + } + + /** + * delete EndUser + * @method + * @param {string} id - id to delete an enduser with + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + delete(id) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); + + if (errors) { + return errors; + } + + return new EndUser(this[clientKey], { + id: id + }).delete(); + } +} \ No newline at end of file diff --git a/lib/resources/endpoints.js b/lib/resources/endpoints.js index 13e371b..ed71eb8 100644 --- a/lib/resources/endpoints.js +++ b/lib/resources/endpoints.js @@ -1,168 +1,314 @@ -import {extend, validate} from '../utils/common.js'; -import {PlivoResource, PlivoResourceInterface} from '../base'; +import { + PlivoResource, + PlivoResourceInterface +} from '../base'; +import { + extend, + validate +} from '../utils/common.js'; const clientKey = Symbol(); const action = 'Endpoint/'; const idField = 'endpointId'; + +export class UpdateEndpointResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.message = params.message; + this.alias = params.alias; + + } +} +export class RetrieveEndpointResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.alias = params.alias; + this.application = params.application; + this.endpointId = params.endpointId; + this.password = params.password; + this.resourceUri = params.resourceUri; + this.sipRegistered = params.sipRegistered; + this.sipUri = params.sipUri; + this.subAccount = params.subAccount; + this.username = params.username; + } +} + +export class ListAllEndpointResponse { + constructor(params) { + params = params || {}; + this.alias = params.alias; + this.application = params.application; + this.endpointId = params.endpointId; + this.password = params.password; + this.resourceUri = params.resourceUri; + this.sipRegistered = params.sipRegistered; + this.sipUri = params.sipUri; + this.subAccount = params.subAccount; + this.username = params.username; + } +} + +export class CreateEndpointResponse { + constructor(params) { + params = params || {}; + this.alias = params.alias; + this.apiId = params.apiId; + this.endpointId = params.endpointId; + this.message = params.message; + this.username = params.username; + } +} + /** - * Represents a Endpoint - * @constructor - * @param {function} client - make api call - * @param {object} [data] - data of call - */ +* Represents a Endpoint +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ export class Endpoint extends PlivoResource { constructor(client, data = {}) { - super(action, Endpoint, idField, client); + super(action, Endpoint, idField, client); - if (idField in data) { - this.id = data[idField]; - } + if (idField in data) { + this.id = data[idField]; + } - extend(this, data); - this[clientKey] = client; + extend(this, data); + this[clientKey] = client; } -/** - * update Endpoint - * @method - * @param {object} params - * @param {string} [params.username] - username to update - * @param {string} [params.password] - password to update - * @param {string} [params.alias] - alias to update - * @param {string} [params.appId] - app id to update - * @promise {object} return {@link Endpoint} object if success - * @fail {Error} return Error - */ - update(params) { - params.isVoiceRequest = 'true'; - return super.update(params); + /** + * update Endpoint + * @method + * @param {object} params + * @param {string} [params.username] - username to update + * @param {string} [params.password] - password to update + * @param {string} [params.alias] - alias to update + * @param {string} [params.appId] - app id to update + * @promise {object} return {@link Endpoint} object if success + * @fail {Error} return Error + */ + update(params, id) { + params.isVoiceRequest = 'true'; + let client = this[clientKey]; + let that = this; + return new Promise((resolve, reject) => { + client('POST', action + id + '/', params) + .then(response => { + extend(that, response.body); + if (params.hasOwnProperty('isVoiceRequest')) { + delete params.isVoiceRequest; + } + extend(that, params); + resolve(new UpdateEndpointResponse(that)); + }) + .catch(error => { + reject(error); + }); + }); } -/** - * delete Endpoint - * @method - * @promise {boolean} return true if success - * @fail {Error} return Error - */ + /** + * delete Endpoint + * @method + * @promise {boolean} return true if success + * @fail {Error} return Error + */ delete() { - let params = {}; - params.isVoiceRequest = 'true'; - return super.delete(params); + let params = {}; + params.isVoiceRequest = 'true'; + + let client = this[clientKey]; + let id = this.id; + + return new Promise((resolve, reject) => { + client('DELETE', action + id + '/', params) + .then(() => { + resolve(true); + }) + .catch(error => { + reject(error); + }); + }); + } } /** - * Represents a Endpoint Interface - * @constructor - * @param {function} client - make api call - * @param {object} [data] - data of call - */ +* Represents a Endpoint Interface +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ export class EndpointInterface extends PlivoResourceInterface { constructor(client, data = {}) { - super(action, Endpoint, idField, client); - extend(this, data); + super(action, Endpoint, idField, client); + extend(this, data); - this[clientKey] = client; + this[clientKey] = client; } -/** - * Get Endpoint by given id - * @method - * @param {string} id - id of endpoint - * @promise {object} return {@link Endpoint} object if success - * @fail {Error} return Error - */ + /** + * Get Endpoint by given id + * @method + * @param {string} id - id of endpoint + * @promise {object} return {@link Endpoint} object if success + * @fail {Error} return Error + */ get(id) { - let params = {}; - params.isVoiceRequest = 'true'; - return super.get(id, params); + let params = {}; + params.isVoiceRequest = 'true'; + let client = this[clientKey]; + + return new Promise((resolve, reject) => { + if (action !== '' && !id) { + reject(new Error(this[idKey] + ' must be set')); + } + client('GET', action + (id ? id + '/' : ''), params) + .then(response => { + resolve(new RetrieveEndpointResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); + }); } list() { - let params = {}; - params.isVoiceRequest = 'true'; - return super.list(params); + let params = {}; + params.isVoiceRequest = 'true'; + + let client = this[clientKey]; + + return new Promise((resolve, reject) => { + client('GET', action, params) + .then(response => { + let objects = []; + Object.defineProperty(objects, 'meta', { + value: response.body.meta, + enumerable: true + }); + response.body.objects.forEach(item => { + objects.push(new ListAllEndpointResponse(item, client)); + }); + console.log(objects) + resolve(objects); + }) + .catch(error => { + reject(error); + }); + }); } -/** - * Create Endpoint - * @method - * @param {string} username - username to create - * @param {string} passwowrd - password to create - * @param {string} alias - alias to create - * @param {string} appId - app id to create - * @promise {object} return {@link PlivoGenericResponse} object if success - * @fail {Error} return Error - */ + /** + * Create Endpoint + * @method + * @param {string} username - username to create + * @param {string} passwowrd - password to create + * @param {string} alias - alias to create + * @param {string} appId - app id to create + * @promise {object} return {@link PlivoGenericResponse} object if success + * @fail {Error} return Error + */ create(username, password, alias, appId) { - let params = {}; + let params = {}; - let errors = validate([ - {field: 'username', value: username, validators: ['isRequired']}, - {field: 'password', value: password, validators: ['isRequired']}, - {field: 'alias', value: alias, validators: ['isRequired']} - ]); + let errors = validate([{ + field: 'username', + value: username, + validators: ['isRequired'] + }, + { + field: 'password', + value: password, + validators: ['isRequired'] + }, + { + field: 'alias', + value: alias, + validators: ['isRequired'] + } + ]); + + if (errors) { + return errors; + } + + params.username = username; + params.password = password; + params.alias = alias; + if (appId) { + params.app_id = appId; + } + params.isVoiceRequest = 'true'; + let client = this[clientKey]; + + return new Promise((resolve, reject) => { + client('POST', action, params) + .then(response => { + resolve(new CreateEndpointResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); - if (errors) { - return errors; - } - params.username = username; - params.password = password; - params.alias = alias; - if (appId) { - params.app_id = appId; - } - params.isVoiceRequest = 'true'; - return super.create(params); } -/** - * update Endpoint - * @method - * @param {string} id - id to update - * @param {object} params - * @param {string} [params.username] - username to update - * @param {string} [params.password] - password to update - * @param {string} [params.alias] - alias to update - * @param {string} [params.appId] - app id to update - * @promise {object} return {@link Endpoint} object if success - * @fail {Error} return Error - */ + /** + * update Endpoint + * @method + * @param {string} id - id to update + * @param {object} params + * @param {string} [params.username] - username to update + * @param {string} [params.password] - password to update + * @param {string} [params.alias] - alias to update + * @param {string} [params.appId] - app id to update + * @promise {object} return {@link Endpoint} object if success + * @fail {Error} return Error + */ update(id, params) { - let errors = validate([ - {field: 'id', value: id, validators: ['isRequired']} - ]); + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); - if (errors) { - return errors; - } - return new Endpoint(this[clientKey], { - id: id - }).update(params); + if (errors) { + return errors; + } + return new Endpoint(this[clientKey], { + id: id + }).update(params, id); } -/** - * delete Endpoint - * @method - * @param {string} id - id to delete - * @promise {boolean} return true if success - * @fail {Error} return Error - */ + /** + * delete Endpoint + * @method + * @param {string} id - id to delete + * @promise {boolean} return true if success + * @fail {Error} return Error + */ delete(id) { - let errors = validate([ - {field: 'id', value: id, validators: ['isRequired']} - ]); + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); - if (errors) { - return errors; - } - return new Endpoint(this[clientKey], { - id: id - }).delete(); + if (errors) { + return errors; + } + return new Endpoint(this[clientKey], { + id: id + }).delete(); } -} +} \ No newline at end of file diff --git a/lib/resources/lookup.js b/lib/resources/lookup.js index 8d0139f..080328d 100644 --- a/lib/resources/lookup.js +++ b/lib/resources/lookup.js @@ -1,20 +1,32 @@ -import { - extend, - validate -} from '../utils/common.js'; +import * as _ from "lodash"; import { PlivoResource, PlivoResourceInterface } from '../base'; - -import * as _ from "lodash"; +import { + extend, + validate +} from '../utils/common.js'; const clientKey = Symbol(); const action = 'Number/'; // unused as it is overridden, only for unit tests const idField = 'OVERRIDDEN'; const LOOKUP_API_BASE_URL = 'https://lookup.plivo.com/v1/Number' +export class LookupResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.phoneNumber = params.phoneNumber; + this.country = params.country; + this.format = params.format; + this.carrier = params.carrier; + this.resourceUri = params.resourceUri; + + } +} + export class Number extends PlivoResource { constructor(client, data = {}) { super(action, Number, idField, client); @@ -46,6 +58,15 @@ export class LookupInterface extends PlivoResourceInterface { overrideUrl: `${LOOKUP_API_BASE_URL}/${number}`, }; - return super.get(number, params); + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('GET', action + '/', params) + .then(response => { + resolve(new LookupResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); + }); } -} +} \ No newline at end of file diff --git a/lib/resources/media.js b/lib/resources/media.js index a628b92..ad027a7 100644 --- a/lib/resources/media.js +++ b/lib/resources/media.js @@ -1,18 +1,52 @@ -import { - extend, - validate -} from '../utils/common.js'; -import { - PlivoResource, - PlivoResourceInterface -} from '../base'; import * as _ from 'lodash'; + +import { + PlivoGenericResponse, + PlivoResource, + PlivoResourceInterface +} from '../base'; +import { + extend, + validate +} from '../utils/common.js'; + var fs = require('fs'); const clientKey = Symbol(); const action = 'Media/'; const idField = 'media_id'; +export class UploadMediaResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.objects = params.objects; + } +} + +export class RetrieveMediaResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.contentType = params.contentType; + this.fileName = params.fileName; + this.mediaId = params.mediaId; + this.mediaUrl = params.mediaUrl; + this.size = params.size; + this.uploadTime = params.uploadTime; + } +} + +export class ListMediaResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.meta = params.meta; + this.objects = params.objects; + + } +} + /** * Represents a Message * @constructor @@ -20,15 +54,15 @@ const idField = 'media_id'; * @param {object} [data] - data of call */ export class Media extends PlivoResource { - constructor(client, data = {}) { - super(action, Media, idField, client); + constructor(client, data = {}) { + super(action, Media, idField, client); - if (idField in data) { - this.id = data[idField]; + if (idField in data) { + this.id = data[idField]; + } + + extend(this, data); } - - extend(this, data); - } } /** * Represents a Media Interface @@ -38,61 +72,106 @@ export class Media extends PlivoResource { */ export class MediaInterface extends PlivoResourceInterface { - constructor(client, data = {}) { - super(action, Media, idField, client); - extend(this, data); - this[clientKey] = client; - } - - /** - * Upload Media - * @method - * @fail {Error} return Error - */ - upload(files) { - let errors = validate([{ - field: 'files', - value: files, - validators: ['isRequired'] - }]); - - if (errors) { - return errors; - } - let params = {} - params.file = files - return super.create(params); - } - - /** - * Get Media by given id - * @method - * @param {string} media_id - id of media - * @promise {object} return {@link Media} object if success - * @fail {Error} return Error - */ - get(media_id) { - let errors = validate([{ - field: 'media_id', - value: media_id, - validators: ['isRequired'] - }]); - - if (errors) { - return errors; + constructor(client, data = {}) { + super(action, Media, idField, client); + extend(this, data); + this[clientKey] = client; } - return super.get(media_id); - } + /** + * Upload Media + * @method + * @fail {Error} return Error + */ + upload(files) { + let errors = validate([{ + field: 'files', + value: files, + validators: ['isRequired'] + }]); - /** - * Get All Media Detail - * @method - * @param {object} params - params to get all media details. - * @promise {object[]} returns list of Media Object - * @fail {Error} returns Error - */ - list(params) { - return super.list(params); - } -} + if (errors) { + return errors; + } + let params = {} + params.file = files + + let client = this[clientKey]; + + return new Promise((resolve, reject) => { + client('POST', action, params) + .then(response => { + resolve(new UploadMediaResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + + } + + /** + * Get Media by given id + * @method + * @param {string} media_id - id of media + * @promise {object} return {@link Media} object if success + * @fail {Error} return Error + */ + get(media_id) { + let errors = validate([{ + field: 'media_id', + value: media_id, + validators: ['isRequired'] + }]); + + if (errors) { + return errors; + } + + let client = this[clientKey]; + + return new Promise((resolve, reject) => { + if (action !== '' && !media_id) { + reject(new Error(this[idKey] + ' must be set')); + } + client('GET', action + (media_id ? media_id + '/' : '')) + .then(response => { + resolve(new RetrieveMediaResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); + }); + + } + + /** + * Get All Media Detail + * @method + * @param {object} params - params to get all media details. + * @promise {object[]} returns list of Media Object + * @fail {Error} returns Error + */ + list(params) { + //return super.list(params); + + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('GET', action, params) + .then(response => { + let objects = []; + Object.defineProperty(objects, 'meta', { + value: response.body.meta, + enumerable: true + }); + response.body.objects.forEach(item => { + objects.push(new PlivoGenericResponse(item, client)); + }); + resolve(objects); + }) + .catch(error => { + reject(error); + }); + }); + } +} \ No newline at end of file diff --git a/lib/resources/messages.js b/lib/resources/messages.js index 92242e8..b0225fe 100644 --- a/lib/resources/messages.js +++ b/lib/resources/messages.js @@ -9,9 +9,85 @@ import { validate } from '../utils/common.js'; -const clientKey = Symbol(); const action = 'Message/'; const idField = 'messageUuid'; +let actionKey = Symbol('api action'); +let klassKey = Symbol('constructor'); +let idKey = Symbol('id filed'); +let clientKey = Symbol('make api call'); + +export class MessageResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.message = params.message; + this.messageUuid = params.messageUuid; + + } +} + +export class MessageGetResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.errorCode = params.errorCode; + this.fromNumber = params.fromNumber; + this.messageDirection = params.messageDirection; + this.messageState = params.messageState; + this.messageTime = params.messageTime; + this.messageType = params.messageType; + this.messageUuid = params.messageUuid; + this.resourceUri = params.resourceUri; + this.toNumber = params.toNumber; + this.totalAmount = params.totalAmount; + this.totalRate = params.totalRate; + this.units = params.units; + } +} + +export class MessageListResponse { + constructor(params) { + params = params || {}; + this.errorCode = params.errorCode; + this.fromNumber = params.fromNumber; + this.messageDirection = params.messageDirection; + this.messageState = params.messageState; + this.messageTime = params.messageTime; + this.messageType = params.messageType; + this.messageUuid = params.messageUuid; + this.resourceUri = params.resourceUri; + this.toNumber = params.toNumber; + this.totalAmount = params.totalAmount; + this.totalRate = params.totalRate; + this.units = params.units; + } +} + +export class MMSMediaResponse { + + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + let MMSMediaList = [] + params.objects.forEach(item => { + MMSMediaList.push(new MMSMedia(item)); + }); + this.objects = MMSMediaList; + } +} + +export class MMSMedia { + constructor(params) { + params = params || {}; + this.contentType = params.contentType; + this.fileName = params.fileName; + this.mediaId = params.mediaId; + this.mediaUrl = params.mediaUrl; + this.messageUuid = params.messageUuid; + this.size = params.size; + this.uploadTime = params.uploadTime; + } +} /** * Represents a Message @@ -22,7 +98,8 @@ const idField = 'messageUuid'; export class Message extends PlivoResource { constructor(client, data = {}) { super(action, Message, idField, client); - + this[actionKey] = action; + this[clientKey] = client; if (idField in data) { this.id = data[idField]; }; @@ -31,7 +108,18 @@ export class Message extends PlivoResource { } listMedia() { - return super.executeAction(this.id + '/Media/', 'Get', {}); + //return super.executeAction(this.id + '/Media/', 'Get', {}); + let client = this[clientKey]; + let idField = this[idKey]; + return new Promise((resolve, reject) => { + client('Get', this[actionKey] + this.id + '/Media/', {}) + .then(response => { + resolve(new MMSMediaResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); } } @@ -48,6 +136,10 @@ export class MessageInterface extends PlivoResourceInterface { super(action, Message, idField, client); extend(this, data); this[clientKey] = client; + this[actionKey] = action; + this[klassKey] = Message; + this[idKey] = idField; + } /** @@ -65,8 +157,9 @@ export class MessageInterface extends PlivoResourceInterface { * @promise {object} return {@link PlivoGenericMessage} object if success * @fail {Error} return Error */ - send(optionalParams) { - return this.create(optionalParams); + + send(src, dst, text, optionalParams) { + return this.create(src, dst, text, optionalParams); } /** @@ -164,7 +257,20 @@ export class MessageInterface extends PlivoResourceInterface { if (powerpackUUID) { params.powerpackUUID = powerpackUUID; } - return super.create(params); + + let client = this[clientKey]; + let idField = this[idKey]; + let action = this[actionKey] + (this.id ? this.id + '/' : ''); + + return new Promise((resolve, reject) => { + client('POST', action, params) + .then(response => { + resolve(new MessageResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }) } /** @@ -185,7 +291,43 @@ export class MessageInterface extends PlivoResourceInterface { return errors; } - return super.get(id); + let client = this[clientKey]; + let action = this[actionKey]; + + return new Promise((resolve, reject) => { + if (action !== '' && !id) { + reject(new Error(this[idKey] + ' must be set')); + } + client('GET', action + (id ? id + '/' : '')) + .then(response => { + resolve(new MessageGetResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); + }); + } + + list(params) { + let client = this[clientKey]; + let action = this[actionKey]; + return new Promise((resolve, reject) => { + client('GET', action, params) + .then(response => { + let objects = []; + Object.defineProperty(objects, 'meta', { + value: response.body.meta, + enumerable: true + }); + response.body.objects.forEach(item => { + objects.push(new MessageListResponse(item, client)); + }); + resolve(objects); + }) + .catch(error => { + reject(error); + }); + }); } listMedia(messageUUID) { @@ -193,5 +335,4 @@ export class MessageInterface extends PlivoResourceInterface { id: messageUUID }).listMedia(); } - -} +} \ No newline at end of file diff --git a/lib/resources/multiPartyCall.js b/lib/resources/multiPartyCall.js new file mode 100644 index 0000000..0ffe665 --- /dev/null +++ b/lib/resources/multiPartyCall.js @@ -0,0 +1,592 @@ +import {extend, validate} from '../utils/common.js'; +import {PlivoResource, PlivoResourceInterface, PlivoSecondaryResource} from '../base'; +import { + validSubAccount, + validUrl, + validParam, + validDateFormat, + validRange, + validMultipleDestinationNos, + isOneAmongStringUrl, multiValidParam +} from '../rest/utils.js' + +const clientKey = Symbol(); +const action = 'MultiPartyCall/'; +const idField = 'mpcUuid'; +const secondaryAction = 'Participant/'; +const secondaryIdField = 'participantUuid'; + +export class MPCError extends Error { } + +export class MultiPartyCall extends PlivoResource{ + constructor(client, data = {}) { + super(action, MultiPartyCall, idField, client); + + if (idField in data) { + this.id = data[idField]; + } + + extend(this, data); + this[clientKey] = client; + } + + get(params = {}){ + params.isVoiceRequest = 'true'; + return super.executeAction(this.id, 'GET', params); + } + + addParticipant(params){ + if((params.from && params.to) && (params.callUuid)){ + throw new MPCError('cannot specify callUuid when (from, to) is provided') + } + if((!params.from && !params.to) && !params.callUuid){ + throw new MPCError('specify either callUuid or (from, to)') + } + if((!params.callUuid) && (!params.from || !params.to)){ + throw new MPCError('specify (from, to) when not adding an existing callUuid to multi party participant') + } + + validParam('role', params.role.toLowerCase(), [String], true, ['agent', 'supervisor', 'customer']) + + if(params.from){ + validParam('from', params.from, [String], false) + } + + if(params.to){ + validParam('to', params.to, [String], false) + validMultipleDestinationNos('to', params.to, {role: params.role, delimiter: '<', agentLimit: 20}) + } + + if(params.callUuid){ + validParam('callUuid', params.callUuid, [String], false) + } + + if(params.callStatusCallbackUrl){ + validUrl('callStatusCallbackUrl', params.callStatusCallbackUrl, false) + } + + if(params.callStatusCallbackMethod){ + validParam('callStatusCallbackMethod', params.callStatusCallbackMethod.toUpperCase(), [String], false, ['GET', 'POST']) + } + else{ + params.callStatusCallbackMethod = 'POST' + } + + if(params.sipHeaders){ + validParam('sipHeaders', params.sipHeaders, [String], false) + } + + if(params.confirmKey){ + validParam('confirmKey', params.confirmKey, [String], false, ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '#', '*']) + } + + if(params.confirmKeySoundUrl){ + validUrl('confirmKeySoundUrl', params.confirmKeySoundUrl, false) + } + + if(params.confirmKeySoundMethod){ + validParam('confirmKeySoundMethod)', params.confirmKeySoundMethod.toUpperCase(), [String], false, ['GET', 'POST']) + } + else{ + params.confirmKeySoundMethod = 'GET' + } + + if(params.dialMusic){ + isOneAmongStringUrl('dialMusic', params.dialMusic, false, ['real', 'none']) + } + else { + params.dialMusic = 'Real' + } + + if(params.ringTimeout || params.ringTimeout === 0){ + validRange('ringTimeout', params.ringTimeout, false, 15, 120) + } + else { + params.ringTimeout = 45 + } + + if(params.maxDuration || params.maxDuration === 0){ + validRange('maxDuration', params.maxDuration, false, 300, 28800) + } + else { + params.maxDuration = 14400 + } + + if(params.maxParticipants || params.maxParticipants === 0){ + validRange('maxParticipants', params.maxParticipants, false, 2, 10) + } + else { + params.maxParticipants = 10 + } + + if(params.waitMusicUrl){ + validUrl('waitMusicUrl', params.waitMusicUrl, false) + } + + if(params.waitMusicMethod){ + validParam('waitMusicMethod', params.waitMusicMethod.toUpperCase(), [String], false, ['GET', 'POST']) + } + else { + params.waitMusicMethod = 'GET' + } + + if(params.agentHoldMusicUrl){ + validUrl('agentHoldMusicUrl', params.agentHoldMusicUrl, false) + } + + if(params.agentHoldMusicMethod){ + validParam('agentHoldMusicMethod', params.agentHoldMusicMethod.toUpperCase(), [String], false, ['GET', 'POST']) + } + else { + params.agentHoldMusicMethod = 'GET' + } + + if(params.customerHoldMusicUrl){ + validUrl('customerHoldMusicUrl', params.customerHoldMusicUrl, false) + } + + if(params.customerHoldMusicMethod){ + validParam('customerHoldMusicMethod', params.customerHoldMusicMethod.toUpperCase(), [String], false, ['GET', 'POST']) + } + else { + params.customerHoldMusicMethod = 'GET' + } + + if(params.recordingCallbackUrl){ + validUrl('recordingCallbackUrl', params.recordingCallbackUrl, false) + } + + if(params.recordingCallbackMethod){ + validParam('recordingCallbackMethod', params.recordingCallbackMethod.toUpperCase(), [String], false, ['GET', 'POST']) + } + else { + params.recordingCallbackMethod = 'GET' + } + + if(params.statusCallbackUrl){ + validUrl('statusCallbackUrl', params.statusCallbackUrl, false) + } + + if(params.statusCallbackMethod){ + validParam('statusCallbackMethod', params.statusCallbackMethod.toUpperCase(), [String], false, ['GET', 'POST']) + } + else { + params.statusCallbackMethod = 'GET' + } + + if(params.onExitActionUrl){ + validUrl('onExitActionUrl', params.onExitActionUrl, false) + } + + if(params.onExitActionMethod){ + validParam('statusCallbackMethod', params.statusCallbackMethod.toUpperCase(), [String], false, ['GET', 'POST']) + } + else { + params.onExitActionMethod = 'POST' + } + + if(params.record){ + validParam('record', params.record, [Boolean, String], false) + } + else { + params.record = 'false' + } + + if(params.recordFileFormat){ + validParam('recordFileFormat', params.recordFileFormat.toLowerCase(), [String], false, ['mp3', 'wav']) + } + else { + params.recordFileFormat = 'mp3' + } + + if(params.statusCallbackEvents){ + multiValidParam('statusCallbackEvents', params.statusCallbackEvents.toLowerCase(), [String], false, ['mpc-state-changes', 'participant-state-changes', 'participant-speak-events', 'participant-digit-input-events', 'add-participant-api-events'], true,',') + } + else { + params.statusCallbackEvents = 'mpc-state-changes,participant-state-changes' + } + + if(params.stayAlone){ + validParam('stayAlone', params.stayAlone, [Boolean, String], false) + } + else { + params.stayAlone = 'false' + } + + if(params.coachMode){ + validParam('coachMode', params.coachMode, [Boolean, String], false) + } + else { + params.coachMode = 'true' + } + + if(params.mute){ + validParam('mute', params.mute, [Boolean, String], false) + } + else { + params.mute = 'false' + } + + if(params.hold){ + validParam('hold', params.hold, [Boolean, String], false) + } + else { + params.hold = 'false' + } + + if(params.startMpcOnEnter){ + validParam('startMpcOnEnter', params.startMpcOnEnter, [Boolean, String], false) + } + else { + params.startMpcOnEnter = 'true' + } + + if(params.endMpcOnExit){ + validParam('endMpcOnExit', params.endMpcOnExit, [Boolean, String], false) + } + else { + params.endMpcOnExit = 'false' + } + + if(params.relayDTMFInputs){ + validParam('relayDTMFInputs', params.relayDTMFInputs, [Boolean, String], false) + } + else { + params.relayDTMFInputs = 'false' + } + + if(params.enterSound){ + isOneAmongStringUrl('enterSound', params.enterSound, false, ['beep:1', 'beep:2', 'none']) + } + else { + params.enterSound = 'beep:1' + } + + if(params.enterSoundMethod){ + validParam('enterSoundMethod', params.enterSoundMethod.toUpperCase(), [String], false, ['GET', 'POST']) + } + else { + params.enterSoundMethod = 'GET' + } + + if(params.exitSound){ + isOneAmongStringUrl('exitSound', params.exitSound, false, ['beep:1', 'beep:2', 'none']) + } + else { + params.exitSound = 'beep:2' + } + + if(params.exitSoundMethod){ + validParam('exitSoundMethod', params.exitSoundMethod.toUpperCase(), [String], false, ['GET', 'POST']) + } + else { + params.exitSoundMethod = 'GET' + } + params.isVoiceRequest = 'true'; + return super.executeAction(this.id + '/Participant/', 'POST', params) + } + + start(){ + return super.executeAction(this.id + '/', 'POST', {'status' : 'active', 'isVoiceRequest' : 'true'}) + } + + stop(){ + return super.delete({'isVoiceRequest' : 'true'}) + } + + startRecording(params = {}){ + if(params.fileFormat){ + validParam('fileFormat', params.fileFormat, [String], false, ['mp3', 'wav']) + } + else { + params.fileFormat = 'mp3' + } + + if(params.statusCallbackUrl){ + validUrl('statusCallbackUrl', params.statusCallbackUrl, false) + } + + if(params.statusCallbackMethod){ + validParam('statusCallbackMethod', params.statusCallbackMethod.toUpperCase(), [String], false, ['GET', 'POST']) + } + else { + params.statusCallbackMethod = 'POST' + } + params.isVoiceRequest = 'true'; + return super.executeAction(this.id + '/Record/', 'POST', params) + } + + stopRecording(){ + return super.executeAction(this.id + '/Record/', 'DELETE',{'isVoiceRequest' : 'true'}) + } + + pauseRecording(){ + return super.executeAction(this.id + '/Record/Pause/', 'POST',{'isVoiceRequest' : 'true'}) + } + + resumeRecording(){ + return super.executeAction(this.id + '/Record/Resume/', 'POST',{'isVoiceRequest' : 'true'}) + } + + listParticipants(params = {}){ + if(params.callUuid){ + validParam('callUuid', params.callUuid, [String], false) + } + params.isVoiceRequest = 'true'; + return super.executeAction(this.id + '/Participant/', 'GET', params) + } +} + +export class MultiPartyCallParticipant extends PlivoSecondaryResource{ + constructor(client, data = {}) { + super(action, MultiPartyCall, idField, secondaryAction, MultiPartyCallParticipant, secondaryIdField, client); + + if (idField in data) { + this.id = data[idField]; + } + + if(secondaryIdField in data){ + this.secondaryId = data[secondaryIdField]; + } + + extend(this, data); + this[clientKey] = client; + } + + updateParticipant(params = {}){ + if(params.coachMode){ + validParam('coachMode', params.coachMode, [Boolean, String], false) + } + + if(params.mute){ + validParam('mute', params.mute, [Boolean, String], false) + } + + if(params.hold){ + validParam('hold', params.hold, [Boolean, String], false) + } + params.isVoiceRequest = 'true'; + return super.executeAction(this.id, this.secondaryId, 'POST', params) + } + + kickParticipant(){ + return super.executeAction(this.id, this.secondaryId, 'DELETE',{'isVoiceRequest' : 'true'}) + } + + getParticipant(){ + return super.executeAction(this.id, this.secondaryId, 'GET',{'isVoiceRequest' : 'true'}) + } + +} + +export class MultiPartyCallInterface extends PlivoResourceInterface{ + constructor(client, data = {}) { + super(action, MultiPartyCall, idField, client); + extend(this, data); + + this[clientKey] = client; + } + + makeMpcId(uuid = null, friendlyName = null){ + if(!uuid && !friendlyName){ + throw new MPCError('Specify either multi party call friendly name or uuid') + } + if(uuid && friendlyName){ + throw new MPCError('Cannot specify both multi party call friendly name or uuid') + } + let identifier = '' + if(uuid){ + identifier = ['uuid_', uuid] + } + else{ + identifier = ['name_', friendlyName] + } + return identifier; + } + + list(params={}) { + if(params.subAccount){ + validSubAccount(params.subAccount); + } + if(params.friendlyName){ + validParam('friendlyName', params.friendlyName, [String], false) + } + if(params.status){ + validParam('status', params.status.toLowerCase(), [String], false, ['initialized', 'active', 'ended']) + } + if(params.terminationCauseCode){ + validParam('terminationCauseCode', params.terminationCauseCode, [Number, String], false) + } + if(params.end_time__gt){ + validDateFormat('end_time__gt', params.end_time__gt, false) + } + if(params.end_time__gte){ + validDateFormat('end_time__gte', params.end_time__gte, false) + } + if(params.end_time__lt){ + validDateFormat('end_time__lt', params.end_time__lt, false) + } + if(params.end_time__lte){ + validDateFormat('end_time__lte', params.end_time__lte, false) + } + if(params.creation_time__gt){ + validDateFormat('creation_time__gt', params.creation_time__gt, false) + } + if(params.creation_time__gte){ + validDateFormat('creation_time__gte', params.creation_time__gte, false) + } + if(params.creation_time__lt){ + validDateFormat('creation_time__lt', params.creation_time__lt, false) + } + if(params.creation_time__lte){ + validDateFormat('creation_time__lte', params.creation_time__lte, false) + } + if(params.limit){ + validRange('limit', params.limit, false, 1, 20) + } + if(params.offset){ + validRange('offset', params.offset, false, 0) + } + params.isVoiceRequest = 'true'; + return super.list(params); + } + + get(uuid = null, friendlyName = null){ + if(uuid){ + validParam('uuid', uuid, [String], false) + } + if(friendlyName){ + validParam('friendlyName', friendlyName, [String], false) + } + let mpcId = this.makeMpcId(uuid, friendlyName) + return new MultiPartyCall(this[clientKey], {id: mpcId[0] + mpcId[1]}).get(); + } + + addParticipant(role, params = {}){ + if(params.uuid){ + validParam('uuid', params.uuid, [String], false) + } + if(params.friendlyName){ + validParam('friendlyName', params.friendlyName, [String], false) + } + let mpcId = this.makeMpcId(params.uuid, params.friendlyName) + delete params.uuid + delete params.friendlyName + params.role = role + return new MultiPartyCall(this[clientKey], {id: mpcId[0] + mpcId[1]}).addParticipant(params) + } + + start(uuid = null, friendlyName = null){ + if(uuid){ + validParam('uuid', uuid, [String], false) + } + if(friendlyName){ + validParam('friendlyName', friendlyName, [String], false) + } + let mpcId = this.makeMpcId(uuid, friendlyName) + return new MultiPartyCall(this[clientKey], {id: mpcId[0] + mpcId[1]}).start() + } + + stop(uuid = null, friendlyName = null){ + if(uuid){ + validParam('uuid', uuid, [String], false) + } + if(friendlyName){ + validParam('friendlyName', friendlyName, [String], false) + } + let mpcId = this.makeMpcId(uuid, friendlyName) + return new MultiPartyCall(this[clientKey], {id: mpcId[0] + mpcId[1]}).stop() + } + + startRecording(uuid = null, friendlyName = null, params){ + if(uuid){ + validParam('uuid', uuid, [String], false) + } + if(friendlyName){ + validParam('friendlyName', friendlyName, [String], false) + } + let mpcId = this.makeMpcId(uuid, friendlyName) + return new MultiPartyCall(this[clientKey], {id: mpcId[0] + mpcId[1]}).startRecording(params) + } + + stopRecording(uuid = null, friendlyName = null){ + if(uuid){ + validParam('uuid', uuid, [String], false) + } + if(friendlyName){ + validParam('friendlyName', friendlyName, [String], false) + } + let mpcId = this.makeMpcId(uuid, friendlyName) + return new MultiPartyCall(this[clientKey], {id: mpcId[0] + mpcId[1]}).stopRecording() + } + + pauseRecording(uuid = null, friendlyName = null){ + if(uuid){ + validParam('uuid', uuid, [String], false) + } + if(friendlyName){ + validParam('friendlyName', friendlyName, [String], false) + } + let mpcId = this.makeMpcId(uuid, friendlyName) + return new MultiPartyCall(this[clientKey], {id: mpcId[0] + mpcId[1]}).pauseRecording() + } + + resumeRecording(uuid = null, friendlyName = null){ + if(uuid){ + validParam('uuid', uuid, [String], false) + } + if(friendlyName){ + validParam('friendlyName', friendlyName, [String], false) + } + let mpcId = this.makeMpcId(uuid, friendlyName) + return new MultiPartyCall(this[clientKey], {id: mpcId[0] + mpcId[1]}).resumeRecording() + } + + listParticipants(uuid = null, friendlyName = null, params){ + if(uuid){ + validParam('uuid', uuid, [String], false) + } + if(friendlyName){ + validParam('friendlyName', friendlyName, [String], false) + } + let mpcId = this.makeMpcId(uuid, friendlyName) + return new MultiPartyCall(this[clientKey], {id: mpcId[0] + mpcId[1]}).listParticipants(params) + } + + updateParticipant(participantId, uuid= null, friendlyName = null, params){ + validParam('participantId', participantId, [String, Number], true) + if(uuid){ + validParam('uuid', uuid, [String], false) + } + if(friendlyName){ + validParam('friendlyName', friendlyName, [String], false) + } + let mpcId = this.makeMpcId(uuid, friendlyName) + return new MultiPartyCallParticipant(this[clientKey], {id: mpcId[0] + mpcId[1], secondaryId: participantId}).updateParticipant(params) + } + + kickParticipant(participantId, uuid = null, friendlyName = null){ + validParam('participantId', participantId, [String, Number], true) + if(uuid){ + validParam('uuid', uuid, [String], false) + } + if(friendlyName){ + validParam('friendlyName', friendlyName, [String], false) + } + let mpcId = this.makeMpcId(uuid, friendlyName) + return new MultiPartyCallParticipant(this[clientKey], {id: mpcId[0] + mpcId[1], secondaryId: participantId}).kickParticipant() + } + + getParticipant(participantId, uuid = null, friendlyName = null){ + validParam('participantId', participantId, [String, Number], true) + if(uuid){ + validParam('uuid', uuid, [String], false) + } + if(friendlyName){ + validParam('friendlyName', friendlyName, [String], false) + } + let mpcId = this.makeMpcId(uuid, friendlyName) + return new MultiPartyCallParticipant(this[clientKey], {id: mpcId[0] + mpcId[1], secondaryId: participantId}).getParticipant() + } + +} diff --git a/lib/resources/numbers.js b/lib/resources/numbers.js index f927bf7..ccaec8b 100644 --- a/lib/resources/numbers.js +++ b/lib/resources/numbers.js @@ -1,10 +1,59 @@ -import {extend, validate} from '../utils/common.js'; -import {PlivoResource, PlivoResourceInterface} from '../base'; +import { + PlivoResource, + PlivoResourceInterface +} from '../base'; +import { + extend, + validate +} from '../utils/common.js'; const clientKey = Symbol(); const action = 'Number/'; const idField = 'number'; + +export class BuyNumberResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.numbers = params.numbers; + this.status = params.status; + + } +} + +export class SearchNumberResponse { + constructor(params) { + params = params || {}; + this.number = params.number; + this.prefix = params.prefix; + this.city = params.city; + this.country = params.country; + this.region = params.region; + this.rate_center = params.rate_center; + this.lata = params.lata; + this.type = params.type; + this.sub_type = params.sub_type; + this.setup_rate = params.setup_rate; + this.monthly_rental_rate = params.monthly_rental_rate; + this.sms_enabled = params.sms_enabled; + this.sms_rate = params.sms_rate; + this.voice_enabled = params.voice_enabled; + this.voice_rate = params.voice_rate; + this.restriction = params.restriction; + this.restriction_text = params.restriction_text; + this.resource_uri = params.resource_uri; + } +} + +export class UpdateNumberResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.message = params.message; + } +} + /** * Represents a PhoneNumber * @constructor @@ -12,29 +61,29 @@ const idField = 'number'; * @param {object} [data] - data of call */ export class PhoneNumber extends PlivoResource { - constructor(client, data = {}) { - super('PhoneNumber/', PhoneNumber, idField, client); + constructor(client, data = {}) { + super('PhoneNumber/', PhoneNumber, idField, client); - if (idField in data) { - this.id = data[idField]; + if (idField in data) { + this.id = data[idField]; + } + + extend(this, data); + this[clientKey] = client; } - extend(this, data); - this[clientKey] = client; - } - -/** - * Buy Phone Number - * @method - * @param {string} appId - app id - * @promise {@link PlivoGenericResponse} return PlivoGenericResponse Object if success - * @fail {Error} return Error - */ - buy(appId) { - return new PhoneNumberInterface(this[clientKey], { - id: this.id - }).buy(appId); - } + /** + * Buy Phone Number + * @method + * @param {string} appId - app id + * @promise {@link PlivoGenericResponse} return PlivoGenericResponse Object if success + * @fail {Error} return Error + */ + buy(appId) { + return new PhoneNumberInterface(this[clientKey], { + id: this.id + }).buy(appId); + } } /** @@ -45,27 +94,37 @@ export class PhoneNumber extends PlivoResource { * @param {string} [data.test] - test data */ export class PhoneNumberInterface extends PlivoResourceInterface { - constructor(client, data = {}) { - super('PhoneNumber/', PhoneNumber, idField, client); + constructor(client, data = {}) { + super('PhoneNumber/', PhoneNumber, idField, client); - extend(this, data); - this[clientKey] = client; - } - -/** - * Buy Phone Number - * @method - * @param {string} appId - app id - * @promise {@link PlivoGenericResponse} return PlivoGenericResponse Object if success - * @fail {Error} return Error - */ - buy(appId) { - let params = {}; - if (appId) { - params.app_id = appId; + extend(this, data); + this[clientKey] = client; + } + + /** + * Buy Phone Number + * @method + * @param {string} appId - app id + * @promise {@link PlivoGenericResponse} return PlivoGenericResponse Object if success + * @fail {Error} return Error + */ + buy(number, appId) { + let params = {}; + if (appId) { + params.app_id = appId; + } + let client = this[clientKey]; + + return new Promise((resolve, reject) => { + client('POST', 'PhoneNumber/' + number + '/', params) + .then(response => { + resolve(new BuyNumberResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); } - return super.create(params); - } } /** @@ -75,38 +134,68 @@ export class PhoneNumberInterface extends PlivoResourceInterface { * @param {object} [data] - data of call */ export class NumberResource extends PlivoResource { - constructor(client, data = {}) { - super(action, NumberResource, idField, client); + constructor(client, data = {}) { + super(action, NumberResource, idField, client); - if (idField in data) { - this.id = data[idField]; + if (idField in data) { + this.id = data[idField]; + } + extend(this, data); + this[clientKey] = client; } - extend(this, data); - } -/** - * Unrent Number - * @method - * @promise {boolean} return true if success - * @fail {Error} return Error - */ - unrent() { - return super.delete(); - } + /** + * Unrent Number + * @method + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + unrent(number) { + let client = this[clientKey]; + let action = 'Number/'; + return new Promise((resolve, reject) => { + client('DELETE', action + number + '/') + .then(() => { + resolve(true); + }) + .catch(error => { + reject(error); + }); + }); + } + + /** + * Update Number + * @method + * @param {object} params + * @param {string} [params.appId] - app id + * @param {string} [params.subAccount] - auth_id of subaccount + * @param {string} [params.alias] - textual name of number + * @promise {@link NumberResource} return NumberResource Object if success + * @fail {Error} return Error + */ + update(number, params) { + let client = this[clientKey]; + let action = 'Number/'; + let that = this; + + return new Promise((resolve, reject) => { + client('POST', action + number + '/', params) + .then(response => { + extend(that, response.body); + if (params.hasOwnProperty('isVoiceRequest')) { + delete params.isVoiceRequest; + } + extend(that, params); + resolve(new UpdateNumberResponse(that)); + }) + .catch(error => { + reject(error); + }); + }); + + } -/** - * Update Number - * @method - * @param {object} params - * @param {string} [params.appId] - app id - * @param {string} [params.subAccount] - auth_id of subaccount - * @param {string} [params.alias] - textual name of number - * @promise {@link NumberResource} return NumberResource Object if success - * @fail {Error} return Error - */ - update(params) { - return super.update(params); - } } /** @@ -117,125 +206,143 @@ export class NumberResource extends PlivoResource { */ export class NumberInterface extends PlivoResourceInterface { - constructor(client) { - super(action, NumberResource, idField, client); - this[clientKey] = client; - } - -/** - * Buy Phone Number - * @method - * @param {string} number - number to buy - * @param {string} appId - app id - * @promise {@link PlivoGenericResponse} return PlivoGenericResponse Object if success - * @fail {Error} return Error - */ - buy(number, appId) { - let errors = validate([ - {field: 'number', value: number, validators: ['isRequired']} - ]); - - if (errors) { - return errors; - } - return new PhoneNumber(this[clientKey], { - id: number - }).buy(appId); - } - -/** - * Add own number from carrier - * @method - * @param {string} numbers - A comma separated list of numbers that need to be added for the carrier. - * @param {string} carrier - The carrier_id of the IncomingCarrier that the number is associated with. - * @param {string} region - region that is associated with the Number - * @param {string} optionaParams - optional params - * @promise {@link PlivoGenericResponse} return PlivoGenericResponse Object if success - * @fail {Error} return Error - */ - addOwnNumber(numbers, carrier, region, optionalParams) { - let errors = validate([ - {field: 'numbers', value: numbers, validators: ['isRequired']}, - {field: 'carrier', value: carrier, validators: ['isRequired']}, - {field: 'region', value: region, validators: ['isRequired']} - ]); - - if (errors) { - return errors; - } - let params = optionalParams || {}; - - params.numbers = numbers; - params.carrier = carrier; - params.region = region; - - return super.create(params); - } - -/** - * Add own number from carrier - * @method - * @param {string} countryISO - The ISO code A2 of the country - * @param {string} optionaParams - optional params - * @promise {@link PhoneNumberInterface} return PhoneNumbers Object if success - * @fail {Error} return Error - */ - search(countryISO, optionalParams) { - let errors = validate([ - {field: 'country_iso', value: countryISO, validators: ['isRequired']} - ]); - - if (errors) { - return errors; + constructor(client) { + super(action, NumberResource, idField, client); + this[clientKey] = client; } - let params = optionalParams || {}; - params.country_iso = countryISO; - return new PhoneNumberInterface(this[clientKey]) - .list(params); - } + /** + * Buy Phone Number + * @method + * @param {string} number - number to buy + * @param {string} appId - app id + * @promise {@link PlivoGenericResponse} return PlivoGenericResponse Object if success + * @fail {Error} return Error + */ + buy(number, appId) { + let errors = validate([{ + field: 'number', + value: number, + validators: ['isRequired'] + }]); -/** - * Update Number - * @method - * @param {string} number - number to update - * @param {object} params - * @param {string} [params.appId] - app id - * @param {string} [params.subAccount] - auth_id of subaccount - * @param {string} [params.alias] - textual name of number - * @promise {@link NumberResource} return NumberResource Object if success - * @fail {Error} return Error - */ - update(number, params) { - let errors = validate([ - {field: 'number', value: number, validators: ['isRequired']} - ]); - - if (errors) { - return errors; + if (errors) { + return errors; + } + return new PhoneNumber(this[clientKey], { + id: number + }).buy(number, appId); } - return new NumberResource(this[clientKey], { - id: number - }).update(params); - } -/** - * Unrent Number - * @method - * @param {string} number - number to unrent - * @promise {boolean} return true if success - * @fail {Error} return Error - */ - unrent(number) { - let errors = validate([ - {field: 'number', value: number, validators: ['isRequired']} - ]); + /** + * Add own number from carrier + * @method + * @param {string} numbers - A comma separated list of numbers that need to be added for the carrier. + * @param {string} carrier - The carrier_id of the IncomingCarrier that the number is associated with. + * @param {string} region - region that is associated with the Number + * @param {string} optionaParams - optional params + * @promise {@link PlivoGenericResponse} return PlivoGenericResponse Object if success + * @fail {Error} return Error + */ + addOwnNumber(numbers, carrier, region, optionalParams) { + let errors = validate([{ + field: 'numbers', + value: numbers, + validators: ['isRequired'] + }, + { + field: 'carrier', + value: carrier, + validators: ['isRequired'] + }, + { + field: 'region', + value: region, + validators: ['isRequired'] + } + ]); - if (errors) { - return errors; + if (errors) { + return errors; + } + let params = optionalParams || {}; + + params.numbers = numbers; + params.carrier = carrier; + params.region = region; + + return super.create(params); + } + + /** + * Add own number from carrier + * @method + * @param {string} countryISO - The ISO code A2 of the country + * @param {string} optionaParams - optional params + * @promise {@link PhoneNumberInterface} return PhoneNumbers Object if success + * @fail {Error} return Error + */ + search(countryISO, optionalParams) { + let errors = validate([{ + field: 'country_iso', + value: countryISO, + validators: ['isRequired'] + }]); + + if (errors) { + return errors; + } + + let params = optionalParams || {}; + params.country_iso = countryISO; + return new PhoneNumberInterface(this[clientKey]).list(params); + } + + /** + * Update Number + * @method + * @param {string} number - number to update + * @param {object} params + * @param {string} [params.appId] - app id + * @param {string} [params.subAccount] - auth_id of subaccount + * @param {string} [params.alias] - textual name of number + * @promise {@link NumberResource} return NumberResource Object if success + * @fail {Error} return Error + */ + update(number, params) { + let errors = validate([{ + field: 'number', + value: number, + validators: ['isRequired'] + }]); + + if (errors) { + return errors; + } + return new NumberResource(this[clientKey], { + id: number + }).update(number, params); + } + + /** + * Unrent Number + * @method + * @param {string} number - number to unrent + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + unrent(number) { + let errors = validate([{ + field: 'number', + value: number, + validators: ['isRequired'] + }]); + + if (errors) { + return errors; + } + return new NumberResource(this[clientKey], { + id: number + }).unrent(number); } - return new NumberResource(this[clientKey], { - id: number - }).unrent(); - } } diff --git a/lib/resources/phlo.js b/lib/resources/phlo.js index e8000df..43d05a4 100644 --- a/lib/resources/phlo.js +++ b/lib/resources/phlo.js @@ -1,12 +1,44 @@ -import { extend, validate } from '../utils/common.js'; -import { PlivoResource, PlivoResourceInterface } from '../base'; -import { PhloMultiPartyCall, PhloMultiPartyCallInterface } from "../resources/phloMultipartyCall"; import * as _ from "lodash"; +import { + PhloMultiPartyCall, + PhloMultiPartyCallInterface +} from "../resources/phloMultipartyCall"; +import { + PlivoResource, + PlivoResourceInterface +} from '../base'; +import { + extend, + validate +} from '../utils/common.js'; + const clientKey = Symbol(); const action = 'phlo/'; const idField = 'phloUuid'; + +export class RunPHLOResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.phloId = params.phloId; + this.message = params.message; + + } +} + +export class RetrievePHLOResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.phloId = params.phloId; + this.name = params.name; + this.createdOn = params.createdOn; + + } +} + /** * Represents a Phlo * @constructor @@ -14,39 +46,58 @@ const idField = 'phloUuid'; * @param {object} [data] - data of phlo */ export class Phlo extends PlivoResource { - constructor(client, data = {}) { - super(action, Phlo, idField, client); - extend(this, data); + constructor(client, data = {}) { + super(action, Phlo, idField, client); + extend(this, data); + this.client = client; - this.client = client; + // Define multiparty call getters + let item = this; + this.multiPartyCall = function(nodeId) { + let dd = new PhloMultiPartyCall(client, { + phloId: item.phloId, + nodeId: nodeId + }); + return dd; + }; - // Define multiparty call getters - let item = this; - this.multiPartyCall = function (nodeId) { - let dd = new PhloMultiPartyCall(client, { phloId: item.phloId, nodeId: nodeId }); - return dd; - }; + this.multiPartyCall.get = function(nodeId) { + let dd = new PhloMultiPartyCallInterface(client, { + phloId: item.phloId, + nodeId: nodeId + }); + return dd.get(item.phloId, nodeId); + } + + this[clientKey] = client; - this.multiPartyCall.get = function (nodeId) { - let dd = new PhloMultiPartyCallInterface(client, { phloId: item.phloId, nodeId: nodeId }); - return dd.get(item.phloId, nodeId); } - } + /** + * run phlo + * @method + * @promise {Boolean} return true if phlo is complete + * @fail {Error} return Error + */ + run(params) { - /** - * run phlo - * @method - * @promise {Boolean} return true if phlo is complete - * @fail {Error} return Error - */ - run(params) { + //Url for phlo running + // https://phlorunner.plivo.com/v1/account/{AUTH_ID}/phlo/{PHLO_ID} + let action = 'account/' + this.authId + '/phlo/' + this.phloId; + let client = this[clientKey]; + action = action == null ? this[actionKey] : action; - //Url for phlo running - // https://phlorunner.plivo.com/v1/account/{AUTH_ID}/phlo/{PHLO_ID} - let action = 'account/' + this.authId + '/phlo/' + this.phloId; - return super.executeAction(action, 'POST', params, ''); - } + return new Promise((resolve, reject) => { + client('POST', action, params) + .then(response => { + resolve(new RunPHLOResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + + } } @@ -58,37 +109,52 @@ export class Phlo extends PlivoResource { */ export class PhloInterface extends PlivoResourceInterface { - constructor(client, data = {}) { - super(action, Phlo, idField, client); - extend(this, data); - } - - /** - * Get A Phlo Detail - * @method - * @param {string} id - phlo uuid to get information of. - * @promise {object} returns Phlo Object - * @fail {Error} returns Error - */ - get(id) { - - //Validate id first - let errors = validate([{ - field: 'id', - value: id, - validators: ['isRequired'] - }]); - - if (errors) { - return errors; + constructor(client, data = {}) { + super(action, Phlo, idField, client); + extend(this, data); + this[clientKey] = client; } - let params = { - phlo_id: id - }; + /** + * Get A Phlo Detail + * @method + * @param {string} id - phlo uuid to get information of. + * @promise {object} returns Phlo Object + * @fail {Error} returns Error + */ + get(id) { - // Url pattern for getting phlo resource by id - // https://phlorunner.plivo.com/v1/phlo/{phlo_id} - return super.get(id, params); - } -} + //Validate id first + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); + + if (errors) { + return errors; + } + + let params = { + phlo_id: id + }; + + // Url pattern for getting phlo resource by id + // https://phlorunner.plivo.com/v1/phlo/{phlo_id} + let client = this[clientKey]; + + return new Promise((resolve, reject) => { + if (action !== '' && !id) { + reject(new Error(this[idKey] + ' must be set')); + } + + client('GET', action + (id ? id + '/' : ''), params) + .then(response => { + resolve(new RetrievePHLOResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); + }); + } +} \ No newline at end of file diff --git a/lib/resources/phloMultiPartyCallMember.js b/lib/resources/phloMultiPartyCallMember.js index b1c469e..58b9399 100644 --- a/lib/resources/phloMultiPartyCallMember.js +++ b/lib/resources/phloMultiPartyCallMember.js @@ -1,5 +1,11 @@ -import { extend, validate } from '../utils/common.js'; -import { PlivoResource, PlivoResourceInterface } from '../base'; +import { + PlivoResource, + PlivoResourceInterface +} from '../base'; +import { + extend, + validate +} from '../utils/common.js'; const clientKey = Symbol(); const action = 'Phlo/'; @@ -11,6 +17,14 @@ const idField = 'phloUuid'; * @param {function} client - make api call * @param {object} [data] - data of phlo */ + +export class UpdateMemberResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.error = params.error; + } +} export class PhloMultiPartyCallMember extends PlivoResource { constructor(client, data = {}) { @@ -51,7 +65,16 @@ export class PhloMultiPartyCallMember extends PlivoResource { // https://phlorunner.plivo.com/v1/phlo/{PHLO_ID}/multi_party_call/{NODE_ID}/members/{MemberAddress} let task = this.action + this.memberAddress; - return super.executeAction(task, 'POST', params, ''); + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('POST', task, params) + .then(response => { + resolve(new UpdateMemberResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); } } @@ -79,7 +102,11 @@ export class PhloMultiPartyCallMemberInterface extends PlivoResourceInterface { return errors; } - return new PhloMultiPartyCallMember(this.client, { phloId: phloId, nodeId: nodeId, memberAddress: memberAddress }); + return new PhloMultiPartyCallMember(this.client, { + phloId: phloId, + nodeId: nodeId, + memberAddress: memberAddress + }); } -} +} \ No newline at end of file diff --git a/lib/resources/phloMultipartyCall.js b/lib/resources/phloMultipartyCall.js index 9e6ac68..c8dd65b 100644 --- a/lib/resources/phloMultipartyCall.js +++ b/lib/resources/phloMultipartyCall.js @@ -1,10 +1,40 @@ -import { extend, validate } from '../utils/common.js'; -import { PlivoResource, PlivoResourceInterface } from '../base'; -import { PhloMultiPartyCallMemberInterface, PhloMultiPartyCallMember } from './phloMultiPartyCallMember'; +import { + PhloMultiPartyCallMember, + PhloMultiPartyCallMemberInterface +} from './phloMultiPartyCallMember'; +import { + PlivoResource, + PlivoResourceInterface +} from '../base'; +import { + extend, + validate +} from '../utils/common.js'; const clientKey = Symbol(); const idField = 'nodeId'; + +export class UpdateMultipartyCallResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.error = params.error; + } +} + +export class RetrieveMultipartyCallResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.nodeId = params.nodeId; + this.phloId = params.phloId; + this.name = params.name; + this.nodeType = params.nodeType; + this.createdOn = params.createdOn; + } +} + export class PhloMultiPartyCall extends PlivoResource { constructor(client, data = {}) { let action = 'phlo/' + data.phloId + '/multi_party_call/'; @@ -12,16 +42,25 @@ export class PhloMultiPartyCall extends PlivoResource { extend(this, data); this.action = action; this.client = client; + this[clientKey] = client; // Define member getters let item = this; - this.member = function (memberAddress) { - let dd = new PhloMultiPartyCallMember(client, { phloId: item.phloId, nodeId: item.nodeId, memberAddress: memberAddress }); + this.member = function(memberAddress) { + let dd = new PhloMultiPartyCallMember(client, { + phloId: item.phloId, + nodeId: item.nodeId, + memberAddress: memberAddress + }); return dd; }; - this.member.get = function (memberAddress) { - let dd = new PhloMultiPartyCallMemberInterface(client, { phloId: item.phloId, nodeId: item.nodeId, memberAddress: memberAddress }); + this.member.get = function(memberAddress) { + let dd = new PhloMultiPartyCallMemberInterface(client, { + phloId: item.phloId, + nodeId: item.nodeId, + memberAddress: memberAddress + }); return dd.get(item.phloId, item.nodeId, memberAddress); } @@ -53,7 +92,6 @@ export class PhloMultiPartyCall extends PlivoResource { action: action }; - // Url pattern for mp call update // https://phlorunnner.plivo.com/v1/phlo/{phlo_id}/{node_type}/{node_id} let task = this.action + this.nodeId; @@ -65,8 +103,16 @@ export class PhloMultiPartyCall extends PlivoResource { params.trigger_source = triggerSource; } - return super.executeAction(task, 'POST', params, ''); - + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('POST', task, params) + .then(response => { + resolve(new UpdateMultipartyCallResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); } } @@ -78,15 +124,16 @@ export class PhloMultiPartyCallInterface extends PlivoResourceInterface { let action = 'phlo/' + data.phloId + '/multi_party_call/'; super(action, PhloMultiPartyCall, idField, client); extend(this, data); + this[clientKey] = client; } /** - * Get A Phlo Detail - * @method - * @param {string} id - phlo uuid to get information of. - * @promise {object} returns Phlo Object - * @fail {Error} returns Error - */ + * Get A Phlo Detail + * @method + * @param {string} id - phlo uuid to get information of. + * @promise {object} returns Phlo Object + * @fail {Error} returns Error + */ get(phloId, id) { //Validate id first @@ -109,8 +156,18 @@ export class PhloMultiPartyCallInterface extends PlivoResourceInterface { // Url pattern for getting phlo resource by id // https://phlorunner.plivo.com/v1/phlo/{phlo_id} - // console.log('get multi party call with ', id, params); - return super.get(id, params); - + let client = this[clientKey]; + return new Promise((resolve, reject) => { + if (action !== '' && !id) { + reject(new Error(this[idKey] + ' must be set')); + } + client('GET', action + (id ? id + '/' : ''), params) + .then(response => { + resolve(new RetrieveMultipartyCallResponse(client, response.body)); + }) + .catch(error => { + reject(error); + }); + }); } -} +} \ No newline at end of file diff --git a/lib/resources/powerpacks.js b/lib/resources/powerpacks.js index 3596492..c6352ac 100644 --- a/lib/resources/powerpacks.js +++ b/lib/resources/powerpacks.js @@ -1,12 +1,165 @@ -import { extend, validate } from '../utils/common.js'; -import { PlivoResource, PlivoResourceInterface } from '../base'; import * as _ from 'lodash'; +import { + PlivoResource, + PlivoResourceInterface +} from '../base'; +import { + extend, + validate +} from '../utils/common.js'; + const action = 'Powerpack/'; const idField = 'uuid'; const numberpoolIdField = 'numberPool'; const clientKey = Symbol(); + +export class ListAllNumbersResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.meta = params.meta; + this.objects = params.objects; + } +} + +export class CreatePowerpackResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.applicationId = params.applicationId; + this.applicationType = params.applicationType; + this.createdOn = params.createdOn; + this.localConnect = params.localConnect; + this.name = params.name; + this.numberPool = params.numberPool; + this.numberPriority = params.numberPriority; + this.stickySender = params.stickySender; + this.uuid = params.uuid; + } +} + +export class UpdatePowerpackResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.applicationId = params.applicationId; + this.applicationType = params.applicationType; + this.createdOn = params.createdOn; + this.localConnect = params.localConnect; + this.name = params.name; + this.numberPool = params.numberPool; + this.stickySender = params.stickySender; + this.uuid = params.uuid; + } +} + +export class ListShortCodeResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.meta = params.meta; + this.objects = params.objects; + } +} +export class ListTollFreeResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.meta = params.meta; + this.objects = params.objects; + } +} + +export class AddNumberResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.accountPhoneNumberResource = params.accountPhoneNumberResource; + this.addedOn = params.addedOn; + this.countryIso2 = params.countryIso2; + this.number = params.number; + this.numberPoolUuid = params.numberPoolUuid; + this.type = params.type; + this.service = params.service; + } +} + +export class RemoveNumberResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.response = params.response; + } +} + +export class RemoveTollFreeNumberResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.response = params.response; + } +} + +export class RemoveShortCodeResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.response = params.response; + } +} +export class AddTollFreeNumberresponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.accountPhoneNumberResource = params.accountPhoneNumberResource; + this.addedOn = params.addedOn; + this.countryIso2 = params.countryIso2; + this.number = params.number; + this.numberPoolUuid = params.numberPoolUuid; + this.type = params.type; + this.service = params.service; + } +} + +export class RetrieveNumberResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.accountPhoneNumberResource = params.accountPhoneNumberResource; + this.addedOn = params.addedOn; + this.countryIso2 = params.countryIso2; + this.number = params.number; + this.numberPoolUuid = params.numberPoolUuid; + this.type = params.type; + } +} + + +export class RetrieveTollFreeResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.accountPhoneNumberResource = params.accountPhoneNumberResource; + this.addedOn = params.addedOn; + this.countryIso2 = params.countryIso2; + this.number = params.number; + this.numberPoolUuid = params.numberPoolUuid; + this.type = params.type; + } +} +export class RetrieveShortCodeResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.addedOn = params.addedOn; + this.countryIso2 = params.countryIso2; + this.shortCode = params.shortCode; + this.numberPoolUuid = params.numberPoolUuid; + } +} + /** * Represents a Powerpack * @constructor @@ -14,180 +167,286 @@ const clientKey = Symbol(); * @param {object} [data] - data of call */ export class Powerpack extends PlivoResource { - constructor(client, data = {}) { - super(action, Powerpack, idField, client); + constructor(client, data = {}) { + super(action, Powerpack, idField, client); - if (idField in data) { - this.uuid = data[idField]; - } - if (numberpoolIdField in data) { - this.number_pool_id = data[numberpoolIdField].split('/')[5]; - } - this.number_pool = new NumberPool(client, { - number_pool_id: this.number_pool_id - }); - extend(this, data); - } + if (idField in data) { + this.uuid = data[idField]; + } + if (numberpoolIdField in data) { + this.number_pool_id = data[numberpoolIdField].split('/')[5]; + } + this.number_pool = new NumberPool(client, { + number_pool_id: this.number_pool_id + }); + extend(this, data); + this[clientKey] = client; + } - list_numbers(params) { - let query = this.search_query(params); - var queryparams = {}; - queryparams['search'] = 'hack'; - let path = 'NumberPool/' + this.number_pool_id + '/Number/?' + query; - return super.customexecuteAction(path.toString().trim(), 'GET', queryparams); - } + list_numbers(params) { + let query = this.search_query(params); + var queryparams = {}; + queryparams['search'] = 'hack'; + let path = 'NumberPool/' + this.number_pool_id + '/Number/?' + query; + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('GET', path.toString().trim(), queryparams) + .then(response => { + resolve(new ListAllNumbersResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } - search_query(params) { - if (params === undefined) { - params = {}; - } - var query = ''; - if (params.type != undefined) { - query = 'type=' + params.type; - } - if (params.starts_with != undefined) { - if (query == '') { - query = 'starts_with=' + params.starts_with; - } else { - query += '&starts_with=' + params.starts_with; - } - } - // return params; - if (params.country_iso2 != undefined) { - if (query == '') { - query = 'country_iso2=' + params.country_iso2; - } else { - query += '&country_iso2=' + params.country_iso2; - } - } - if (params.limit != undefined) { - if (query == '') { - query = 'limit=' + params.limit; - } else { - query += '&limit=' + params.limit; - } - } - if (params.offset != undefined) { - if (query == '') { - query = 'offset=' + params.offset; - } else { - query += '&offset=' + params.offset; - } - } + search_query(params) { + if (params === undefined) { + params = {}; + } + var query = ''; + if (params.type != undefined) { + query = 'type=' + params.type; + } + if (params.starts_with != undefined) { + if (query == '') { + query = 'starts_with=' + params.starts_with; + } else { + query += '&starts_with=' + params.starts_with; + } + } + // return params; + if (params.country_iso2 != undefined) { + if (query == '') { + query = 'country_iso2=' + params.country_iso2; + } else { + query += '&country_iso2=' + params.country_iso2; + } + } + if (params.limit != undefined) { + if (query == '') { + query = 'limit=' + params.limit; + } else { + query += '&limit=' + params.limit; + } + } + if (params.offset != undefined) { + if (query == '') { + query = 'offset=' + params.offset; + } else { + query += '&offset=' + params.offset; + } + } - if (params.service != undefined) { - if (query == '') { - query = 'service=' + params.service; - } else { - query += '&service=' + params.service; - } - } + if (params.service != undefined) { + if (query == '') { + query = 'service=' + params.service; + } else { + query += '&service=' + params.service; + } + } - query = query + '&'; + query = query + '&'; - return query; - } + return query; + } - count_numbers(params) { - let query = this.search_query(params); - var queryparams = {}; - queryparams['search'] = 'hack'; - let path = 'NumberPool/' + this.number_pool_id + '/Number/?' + query; - return super.getMetaResponse(path.toString().trim(), 'GET', queryparams); - } + count_numbers(params) { + let query = this.search_query(params); + var queryparams = {}; + queryparams['search'] = 'hack'; + let path = 'NumberPool/' + this.number_pool_id + '/Number/?' + query; + return super.getMetaResponse(path.toString().trim(), 'GET', queryparams); + } - find_number(number) { - let path = 'NumberPool/' + this.number_pool_id + '/Number/' + number + '/'; - return super.customexecuteAction(path.toString().trim(), 'GET'); - } - add_number(number, service = '') { - var params = {}; - params['rent'] = 'false'; - if (service != '') { - params['service'] = service - } - let path = 'NumberPool/' + this.number_pool_id + '/Number/' + number + '/'; - return super.customexecuteAction(path.toString().trim(), 'POST', params); - } - add_tollfree(tollfree, service = '') { - var params = {}; - params['rent'] = 'false'; - if (service != '') { - params['service'] = service - } - let path = 'NumberPool/' + this.number_pool_id + '/Tollfree/' + tollfree + '/'; - return super.customexecuteAction(path.toString().trim(), 'POST', params); - } - remove_number(number, unrent = false) { - var params = {}; - params['unrent'] = unrent.toString(); - let path = 'NumberPool/' + this.number_pool_id + '/Number/' + number + '/'; - return super.customexecuteAction(path.toString().trim(), 'DELETE', params); - } - remove_tollfree(tollfree, unrent = false) { - var params = {}; - params['unrent'] = unrent.toString(); - let path = 'NumberPool/' + this.number_pool_id + '/Tollfree/' + tollfree + '/'; - return super.customexecuteAction(path.toString().trim(), 'DELETE', params); - } - remove_shortcode(shortcode) { - let path = 'NumberPool/' + this.number_pool_id + '/Shortcode/' + shortcode + '/'; - return super.customexecuteAction(path.toString().trim(), 'DELETE'); - } - list_shortcodes(params) { - if (params === undefined) { - params = {}; - } - let path = 'NumberPool/' + this.number_pool_id + '/Shortcode/'; - return super.customexecuteAction(path.toString().trim(), 'GET', params); - } - list_tollfree(params) { - if (params === undefined) { - params = {}; - } - let path = 'NumberPool/' + this.number_pool_id + '/Tollfree/'; - return super.customexecuteAction(path.toString().trim(), 'GET', params); - } - find_shortcode(shortcode, service = '') { - let path = 'NumberPool/' + this.number_pool_id + '/Shortcode/' + shortcode + '/'; - if (service != '') { - path = path + '&service=' + service - } - return super.customexecuteAction(path.toString().trim(), 'GET'); - } - find_tollfree(tollfree, service = '') { - let path = 'NumberPool/' + this.number_pool_id + '/Tollfree/' + tollfree + '/'; - if (service != '') { - path = path + '&service=' + service - } - return super.customexecuteAction(path.toString().trim(), 'GET'); - } - buy_add_number(params) { - var number = params.number; - var rentparam = {}; - rentparam['rent'] = 'true'; - if (params.number == undefined) { - try { - if (params.country_iso2 != undefined) { - params['country_iso'] = params.country_iso2; - } - if (params.service != undefined) { - params['service'] = params.service; - } - var test = super.customexecuteGetNumberAction('PhoneNumber/', 'GET', params); - return test.then((val) => { - let path = 'NumberPool/' + this.number_pool_id + '/Number/' + val + '/'; - return super.customexecuteAction(path.toString().trim(), 'POST', rentparam); - }); - } catch (err) { - return err.message; - } - } - let path = 'NumberPool/' + this.number_pool_id + '/Number/' + number + '/'; - return super.customexecuteAction(path.toString().trim(), 'POST', rentparam); - } + find_number(number) { + let path = 'NumberPool/' + this.number_pool_id + '/Number/' + number + '/'; + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('GET', path.toString().trim()) + .then(response => { + resolve(new RetrieveNumberResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } + add_number(number, service = '') { + var params = {}; + params['rent'] = 'false'; + if (service != '') { + params['service'] = service + } + let client = this[clientKey]; + let path = 'NumberPool/' + this.number_pool_id + '/Number/' + number + '/'; + return new Promise((resolve, reject) => { + client('POST', path.toString().trim(), params) + .then(response => { + resolve(new AddNumberResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } - /** + add_tollfree(tollfree, service = '') { + var params = {}; + params['rent'] = 'false'; + if (service != '') { + params['service'] = service + } + let path = 'NumberPool/' + this.number_pool_id + '/Tollfree/' + tollfree + '/'; + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('POST', path.toString().trim(), params) + .then(response => { + resolve(new AddTollFreeNumberresponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } + + remove_number(number, unrent = false) { + var params = {}; + params['unrent'] = unrent.toString(); + let path = 'NumberPool/' + this.number_pool_id + '/Number/' + number + '/'; + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('DELETE', path.toString().trim(), params) + .then(response => { + resolve(new RemoveNumberResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } + remove_tollfree(tollfree, unrent = false) { + var params = {}; + params['unrent'] = unrent.toString(); + let path = 'NumberPool/' + this.number_pool_id + '/Tollfree/' + tollfree + '/'; + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('DELETE', path.toString().trim(), params) + .then(response => { + resolve(new RemoveTollFreeNumberResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } + remove_shortcode(shortcode) { + let path = 'NumberPool/' + this.number_pool_id + '/Shortcode/' + shortcode + '/'; + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('DELETE', path.toString().trim()) + .then(response => { + resolve(new RemoveShortCodeResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } + + list_shortcodes(params) { + if (params === undefined) { + params = {}; + } + let path = 'NumberPool/' + this.number_pool_id + '/Shortcode/'; + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('GET', path.toString().trim(), params) + .then(response => { + resolve(new ListShortCodeResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } + list_tollfree(params) { + if (params === undefined) { + params = {}; + } + let path = 'NumberPool/' + this.number_pool_id + '/Tollfree/'; + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('GET', path.toString().trim(), params) + .then(response => { + resolve(new ListTollFreeResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } + + find_shortcode(shortcode, service = '') { + let path = 'NumberPool/' + this.number_pool_id + '/Shortcode/' + shortcode + '/'; + if (service != '') { + path = path + '&service=' + service + } + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('GET', path.toString().trim()) + .then(response => { + resolve(new RetrieveShortCodeResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } + + find_tollfree(tollfree, service = '') { + let path = 'NumberPool/' + this.number_pool_id + '/Tollfree/' + tollfree + '/'; + if (service != '') { + path = path + '&service=' + service + } + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('GET', path.toString().trim()) + .then(response => { + resolve(new RetrieveTollFreeResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } + + buy_add_number(params) { + var number = params.number; + var rentparam = {}; + rentparam['rent'] = 'true'; + if (params.number == undefined) { + try { + if (params.country_iso2 != undefined) { + params['country_iso'] = params.country_iso2; + } + if (params.service != undefined) { + params['service'] = params.service; + } + var test = super.customexecuteGetNumberAction('PhoneNumber/', 'GET', params); + return test.then((val) => { + let path = 'NumberPool/' + this.number_pool_id + '/Number/' + val + '/'; + return super.customexecuteAction(path.toString().trim(), 'POST', rentparam); + }); + } catch (err) { + return err.message; + } + } + let path = 'NumberPool/' + this.number_pool_id + '/Number/' + number + '/'; + return super.customexecuteAction(path.toString().trim(), 'POST', rentparam); + } + + /** * update powerpack * @method * @param {object} params - to update Powerpack @@ -201,210 +460,220 @@ export class Powerpack extends PlivoResource { * @promise {object} return {@link Powerpack} object * @fail {Error} return Error */ - update(params) { - let path = 'Powerpack/' + this.uuid + '/'; - return super.customexecuteAction(path.toString().trim(), 'POST', params); - } + update(params) { + let path = 'Powerpack/' + this.uuid + '/'; + //return super.customexecuteAction(path.toString().trim(), 'POST', params); + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('GET', path.toString().trim(), params) + .then(response => { + resolve(new UpdatePowerpackResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } - /** - * delete Powerpack - * @method - * @promise {object} return true on success - * @fail {Error} return Error - */ - delete(unrent_numbers = false) { - let params = {}; - if (typeof unrent_numbers === 'boolean') { - params.unrent_numbers = unrent_numbers.toString(); - } - let path = 'Powerpack/' + this.uuid + '/'; - return super.customexecuteAction(path.toString().trim(), 'DELETE', params); - } + /** + * delete Powerpack + * @method + * @promise {object} return true on success + * @fail {Error} return Error + */ + delete(unrent_numbers = false) { + let params = {}; + if (typeof unrent_numbers === 'boolean') { + params.unrent_numbers = unrent_numbers.toString(); + } + let path = 'Powerpack/' + this.uuid + '/'; + return super.customexecuteAction(path.toString().trim(), 'DELETE', params); + } } const numberPoolField = 'number_pool_id'; export class NumberPool extends PlivoResource { - constructor(client, data = {}) { - super(action, NumberPool, numberPoolField, client); - this.numbers = new Numbers(client, { - number_pool_id: data.number_pool_id - }); - this.shortcodes = new Shortcode(client, { - number_pool_id: data.number_pool_id - }); - this.tollfree = new Tollfree(client, { - number_pool_id: data.number_pool_id - }); + constructor(client, data = {}) { + super(action, NumberPool, numberPoolField, client); + this.numbers = new Numbers(client, { + number_pool_id: data.number_pool_id + }); + this.shortcodes = new Shortcode(client, { + number_pool_id: data.number_pool_id + }); + this.tollfree = new Tollfree(client, { + number_pool_id: data.number_pool_id + }); - extend(this, data); - } + extend(this, data); + } } export class Numbers extends PlivoResource { - constructor(client, data = {}) { - super(action, Numbers, numberPoolField, client); - extend(this, data); - } - buy_add_number(params) { - var number = params.number; - var rentparam = {}; - rentparam['rent'] = 'true'; - if (params.number == undefined) { - try { - if (params.country_iso2 != undefined) { - params['country_iso'] = params.country_iso2; - } - if (params.service != undefined) { - params['service'] = params.service; - } - var test = super.customexecuteGetNumberAction('PhoneNumber/', 'GET', params); - return test.then((val) => { - let path = 'NumberPool/' + this.number_pool_id + '/Number/' + val + '/'; - return super.customexecuteAction(path.toString().trim(), 'POST', rentparam); - }); - } catch (err) { - return err.message; - } - } - let path = 'NumberPool/' + this.number_pool_id + '/Number/' + number + '/'; - return super.customexecuteAction(path.toString().trim(), 'POST', rentparam); - } + constructor(client, data = {}) { + super(action, Numbers, numberPoolField, client); + extend(this, data); + } + buy_add_number(params) { + var number = params.number; + var rentparam = {}; + rentparam['rent'] = 'true'; + if (params.number == undefined) { + try { + if (params.country_iso2 != undefined) { + params['country_iso'] = params.country_iso2; + } + if (params.service != undefined) { + params['service'] = params.service; + } + var test = super.customexecuteGetNumberAction('PhoneNumber/', 'GET', params); + return test.then((val) => { + let path = 'NumberPool/' + this.number_pool_id + '/Number/' + val + '/'; + return super.customexecuteAction(path.toString().trim(), 'POST', rentparam); + }); + } catch (err) { + return err.message; + } + } + let path = 'NumberPool/' + this.number_pool_id + '/Number/' + number + '/'; + return super.customexecuteAction(path.toString().trim(), 'POST', rentparam); + } - list(params) { - let query = this.search_query(params); - var queryparams = {}; - queryparams['search'] = 'hack'; - let path = 'NumberPool/' + this.number_pool_id + '/Number//?' + query; - return super.customexecuteAction(path.toString().trim(), 'GET', queryparams); - } - count(params) { - let query = this.search_query(params); - var queryparams = {}; - queryparams['search'] = 'hack'; - let path = 'NumberPool/' + this.number_pool_id + '/Number//?' + query; - return super.getMetaResponse(path.toString().trim(), 'GET', queryparams); - } + list(params) { + let query = this.search_query(params); + var queryparams = {}; + queryparams['search'] = 'hack'; + let path = 'NumberPool/' + this.number_pool_id + '/Number//?' + query; + return super.customexecuteAction(path.toString().trim(), 'GET', queryparams); + } + count(params) { + let query = this.search_query(params); + var queryparams = {}; + queryparams['search'] = 'hack'; + let path = 'NumberPool/' + this.number_pool_id + '/Number//?' + query; + return super.getMetaResponse(path.toString().trim(), 'GET', queryparams); + } - search_query(params) { - if (params === undefined) { - params = {}; - } - var query = ''; - if (params.type != undefined) { - query = 'type=' + params.type; - } - if (params.starts_with != undefined) { - if (query == '') { - query = 'starts_with=' + params.starts_with; - } else { - query += '&starts_with=' + params.starts_with; - } - } - // return params; - if (params.country_iso2 != undefined) { - if (query == '') { - query = 'country_iso2=' + params.country_iso2; - } else { - query += '&country_iso2=' + params.country_iso2; - } - } - if (params.limit != undefined) { - if (query == '') { - query = 'limit=' + params.limit; - } else { - query += '&limit=' + params.limit; - } - } - if (params.offset != undefined) { - if (query == '') { - query = 'offset=' + params.offset; - } else { - query += '&offset=' + params.offset; - } - } - if (params.service != undefined) { - if (query == '') { - query = 'service=' + params.service; - } else { - query += '&service=' + params.service; - } - } + search_query(params) { + if (params === undefined) { + params = {}; + } + var query = ''; + if (params.type != undefined) { + query = 'type=' + params.type; + } + if (params.starts_with != undefined) { + if (query == '') { + query = 'starts_with=' + params.starts_with; + } else { + query += '&starts_with=' + params.starts_with; + } + } + // return params; + if (params.country_iso2 != undefined) { + if (query == '') { + query = 'country_iso2=' + params.country_iso2; + } else { + query += '&country_iso2=' + params.country_iso2; + } + } + if (params.limit != undefined) { + if (query == '') { + query = 'limit=' + params.limit; + } else { + query += '&limit=' + params.limit; + } + } + if (params.offset != undefined) { + if (query == '') { + query = 'offset=' + params.offset; + } else { + query += '&offset=' + params.offset; + } + } + if (params.service != undefined) { + if (query == '') { + query = 'service=' + params.service; + } else { + query += '&service=' + params.service; + } + } - query = query + '&'; + query = query + '&'; - return query; - } + return query; + } - find(number) { - let path = 'NumberPool/' + this.number_pool_id + '/Number/' + number + '/'; - return super.customexecuteAction(path.toString().trim(), 'GET'); - } - add(number, service='') { - var params = {}; - params['rent'] = 'false'; - if (service != '') { - params['service'] = service - } - let path = 'NumberPool/' + this.number_pool_id + '/Number/' + number + '/'; - return super.customexecuteAction(path.toString().trim(), 'POST', params); - } - remove(number, unrent = false) { - var params = {}; - params['unrent'] = unrent.toString(); - let path = 'NumberPool/' + this.number_pool_id + '/Number/' + number + '/'; - return super.customexecuteAction(path.toString().trim(), 'DELETE', params); - } + find(number) { + let path = 'NumberPool/' + this.number_pool_id + '/Number/' + number + '/'; + return super.customexecuteAction(path.toString().trim(), 'GET'); + } + add(number, service = '') { + var params = {}; + params['rent'] = 'false'; + if (service != '') { + params['service'] = service + } + let path = 'NumberPool/' + this.number_pool_id + '/Number/' + number + '/'; + return super.customexecuteAction(path.toString().trim(), 'POST', params); + } + remove(number, unrent = false) { + var params = {}; + params['unrent'] = unrent.toString(); + let path = 'NumberPool/' + this.number_pool_id + '/Number/' + number + '/'; + return super.customexecuteAction(path.toString().trim(), 'DELETE', params); + } } export class Shortcode extends PlivoResource { - constructor(client, data = {}) { - super(action, Shortcode, numberPoolField, client); - extend(this, data); - this.number_pool_id = data.number_pool_id; - } - list(params) { - if (params === undefined) { - params = {}; - } - let path = 'NumberPool/' + this.number_pool_id + '/Shortcode/'; - return super.customexecuteAction(path.toString().trim(), 'GET', params); - } - find(shortcode) { - let path = 'NumberPool/' + this.number_pool_id + '/Shortcode/' + shortcode + '/'; - return super.customexecuteAction(path.toString().trim(), 'GET'); - } - remove(shortcode) { - let path = 'NumberPool/' + this.number_pool_id + '/Shortcode/' + shortcode + '/'; - return super.customexecuteAction(path.toString().trim(), 'DELETE'); - } + constructor(client, data = {}) { + super(action, Shortcode, numberPoolField, client); + extend(this, data); + this.number_pool_id = data.number_pool_id; + } + list(params) { + if (params === undefined) { + params = {}; + } + let path = 'NumberPool/' + this.number_pool_id + '/Shortcode/'; + return super.customexecuteAction(path.toString().trim(), 'GET', params); + } + find(shortcode) { + let path = 'NumberPool/' + this.number_pool_id + '/Shortcode/' + shortcode + '/'; + return super.customexecuteAction(path.toString().trim(), 'GET'); + } + remove(shortcode) { + let path = 'NumberPool/' + this.number_pool_id + '/Shortcode/' + shortcode + '/'; + return super.customexecuteAction(path.toString().trim(), 'DELETE'); + } } export class Tollfree extends PlivoResource { - constructor(client, data = {}) { - super(action, Tollfree, numberPoolField, client); - extend(this, data); - this.number_pool_id = data.number_pool_id; - } - add(tollfree) { - var params = {}; - params['rent'] = 'false'; - let path = 'NumberPool/' + this.number_pool_id + '/Tollfree/' + tollfree + '/'; - return super.customexecuteAction(path.toString().trim(), 'POST', params); - } - remove(tollfree, unrent = false) { - var params = {}; - params['unrent'] = unrent.toString(); - let path = 'NumberPool/' + this.number_pool_id + '/Tollfree/' + tollfree + '/'; - return super.customexecuteAction(path.toString().trim(), 'DELETE', params); - } - list(params) { - if (params === undefined) { - params = {}; - } - let path = 'NumberPool/' + this.number_pool_id + '/Tollfree/'; - return super.customexecuteAction(path.toString().trim(), 'GET', params); - } - find(tollfree) { - let path = 'NumberPool/' + this.number_pool_id + '/Tollfree/' + tollfree + '/'; - return super.customexecuteAction(path.toString().trim(), 'GET'); - } + constructor(client, data = {}) { + super(action, Tollfree, numberPoolField, client); + extend(this, data); + this.number_pool_id = data.number_pool_id; + } + add(tollfree) { + var params = {}; + params['rent'] = 'false'; + let path = 'NumberPool/' + this.number_pool_id + '/Tollfree/' + tollfree + '/'; + return super.customexecuteAction(path.toString().trim(), 'POST', params); + } + remove(tollfree, unrent = false) { + var params = {}; + params['unrent'] = unrent.toString(); + let path = 'NumberPool/' + this.number_pool_id + '/Tollfree/' + tollfree + '/'; + return super.customexecuteAction(path.toString().trim(), 'DELETE', params); + } + list(params) { + if (params === undefined) { + params = {}; + } + let path = 'NumberPool/' + this.number_pool_id + '/Tollfree/'; + return super.customexecuteAction(path.toString().trim(), 'GET', params); + } + find(tollfree) { + let path = 'NumberPool/' + this.number_pool_id + '/Tollfree/' + tollfree + '/'; + return super.customexecuteAction(path.toString().trim(), 'GET'); + } } /** * Represents a Powerpack interface @@ -413,92 +682,96 @@ export class Tollfree extends PlivoResource { * @param {object} [data] - data of call */ export class PowerpackInterface extends PlivoResourceInterface { - constructor(client, data = {}) { - super(action, Powerpack, idField, client); - extend(this, data); - } + constructor(client, data = {}) { + super(action, Powerpack, idField, client); + extend(this, data); + this[clientKey] = client; + } - /** - * get Powerpack by given id - * @method - * @param {string} uuid - id of Powerpack - * @promise {object} return {@link Powerpack} object - * @fail {Error} return Error - */ - get(uuid) { - return super.get(uuid); - } + /** + * get Powerpack by given id + * @method + * @param {string} uuid - id of Powerpack + * @promise {object} return {@link Powerpack} object + * @fail {Error} return Error + */ + get(uuid) { + return super.get(uuid); + } + /** + * create Powerpack + * @method + * @param {string} name - name of Powerpack + * @param {object} params - params to create Powerpack + * @param {string} [params.sticky_sender] - + * @param {string} [params.local_connect] + * @param {string} [params.application_type] + * @param {string} [params.application_id] + * @promise {object} return {@link PlivoGenericResponse} object + * @fail {Error} return Error + */ + create(name, params = {}) { + let errors = validate([{ + field: 'name', + value: name, + validators: ['isRequired', 'isString'] + }]); - /** - * create Powerpack - * @method - * @param {string} name - name of Powerpack - * @param {object} params - params to create Powerpack - * @param {string} [params.sticky_sender] - - * @param {string} [params.local_connect] - * @param {string} [params.application_type] - * @param {string} [params.application_id] - * @param {list} [params.number_priority] - * @promise {object} return {@link PlivoGenericResponse} object - * @fail {Error} return Error - */ - create(name, params = {}) { - let errors = validate([ - { - field: 'name', - value: name, - validators: [ 'isRequired', 'isString' ] - } - ]); + if (errors) { + return errors; + } - if (errors) { - return errors; - } + params.name = name; - params.name = name; + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('POST', action, params) + .then(response => { + resolve(new CreatePowerpackResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); - return super.create(params); - } + } - /** - * update Powerpack - * @method - * @param {string} uuid - id of Powerpack - * @param {object} params - to update Powerpack - * @param {string} [params.name] - * @param {string} [params.sticky_sender] - * @param {string} [params.local_connect] - * @param {string} [params.application_type] - * @param {string} [params.application_id] - * @param {list} [params.number_priority] - * @promise {object} return {@link Powerpack} object - * @fail {Error} return Error - */ - update(uuid, params) { - let errors = validate([ - { - field: 'uuid', - value: uuid, - validators: [ 'isRequired' ] - } - ]); + /** + * update Powerpack + * @method + * @param {string} uuid - id of Powerpack + * @param {object} params - to update Powerpack + * @param {string} [params.name] + * @param {string} [params.sticky_sender] + * @param {string} [params.local_connect] + * @param {string} [params.application_type] + * @param {string} [params.application_id] + * @promise {object} return {@link Powerpack} object + * @fail {Error} return Error + */ + update(uuid, params) { + let errors = validate([{ + field: 'uuid', + value: uuid, + validators: ['isRequired'] + }]); - if (errors) { - return errors; - } - return new Powerpack(this[clientKey], { - uuid: uuid - }).update(params); - } + if (errors) { + return errors; + } + return new Powerpack(this[clientKey], { + uuid: uuid + }).update(params); + } - /** - * Get All Call Detail - * @method - * @param {object} params - params to get all call details. - * @promise {object[]} returns list of Call Object - * @fail {Error} returns Error - */ - list(params) { - return super.list(params); - } -} + /** + * Get All Call Detail + * @method + * @param {object} params - params to get all call details. + * @promise {object[]} returns list of Call Object + * @fail {Error} returns Error + */ + list(params) { + return super.list(params); + } +} \ No newline at end of file diff --git a/lib/resources/pricings.js b/lib/resources/pricings.js index 8bf13bc..3874e82 100644 --- a/lib/resources/pricings.js +++ b/lib/resources/pricings.js @@ -1,66 +1,102 @@ -import {extend, validate} from '../utils/common.js'; -import {PlivoResource, PlivoResourceInterface} from '../base'; +import { + PlivoResource, + PlivoResourceInterface +} from '../base'; +import { + extend, + validate +} from '../utils/common.js'; const clientKey = Symbol(); const action = 'Pricing/'; const idField = 'countryIso'; /** - * Represents a Pricing - * @constructor - * @param {function} client - make api call - * @param {object} [data] - data of call - */ +* Represents a Pricing +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ + +export class PricingResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.country = params.country; + this.countryCode = params.countryCode; + this.countryIso = params.countryIso; + this.message = params.message; + this.mms = params.mms; + this.phoneNumbers = params.phoneNumbers; + this.voice = params.voice; + + } +} export class Pricing extends PlivoResource { constructor(client, data = {}) { - super(action, Pricing, idField, client); - extend(this, data); + super(action, Pricing, idField, client); + extend(this, data); + this[clientKey] = client } -/** - * Get pricings by country - * @method - * @promise {object} return {@link PlivoGenericResponse} object - * @fail {Error} return Error - */ + + /** + * Get pricings by country + * @method + * @promise {object} return {@link PlivoGenericResponse} object + * @fail {Error} return Error + */ get() { - let params = { - country_iso: this.id - }; - return super.executeAction('', 'GET', params); + let params = { + country_iso: this.id + }; + let client = this[clientKey]; + + return new Promise((resolve, reject) => { + client('GET', action, params) + .then(response => { + resolve(new PricingResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); + } } /** - * Represents a Pricing Interface - * @constructor - * @param {function} client - make api call - * @param {object} [data] - data of call - */ +* Represents a Pricing Interface +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ export class PricingInterface extends PlivoResourceInterface { constructor(client, data = {}) { - super(action, Pricing, idField, client); - extend(this, data); + super(action, Pricing, idField, client); + extend(this, data); - this[clientKey] = client; + this[clientKey] = client; } -/** - * Get pricings by country - * @method - * @param {string} countryISO - country iso to get pricings - * @promise {object} return {@link PlivoGenericResponse} object - * @fail {Error} return Error - */ + /** + * Get pricings by country + * @method + * @param {string} countryISO - country iso to get pricings + * @promise {object} return {@link PlivoGenericResponse} object + * @fail {Error} return Error + */ get(countryISO) { - let errors = validate([ - {field: 'country_iso', value: countryISO, validators: ['isRequired']} - ]); + let errors = validate([{ + field: 'country_iso', + value: countryISO, + validators: ['isRequired'] + }]); - if (errors) { - return errors; - } - return new Pricing(this[clientKey], { - id: countryISO - }).get(); + if (errors) { + return errors; + } + return new Pricing(this[clientKey], { + id: countryISO + }).get(); } -} +} \ No newline at end of file diff --git a/lib/resources/recordings.js b/lib/resources/recordings.js index d5299b4..f9294fe 100644 --- a/lib/resources/recordings.js +++ b/lib/resources/recordings.js @@ -1,73 +1,143 @@ -import {extend, validate} from '../utils/common.js'; -import {PlivoResource, PlivoResourceInterface} from '../base'; +import { + PlivoResource, + PlivoResourceInterface +} from '../base'; +import { + extend, + validate +} from '../utils/common.js'; const clientKey = Symbol(); const action = 'Recording/'; const idField = 'recordingId'; + +export class RetrieveRecordingResponse { + constructor(params) { + params = params || {}; + this.addTime = params.addTime; + this.apiId = params.apiId; + this.callUuid = params.callUuid; + this.conferenceName = params.conferenceName; + this.recordingDurationMs = params.recordingDurationMs; + this.recordingEndMs = params.recordingEndMs; + this.recordingFormat = params.recordingFormat; + this.recordingId = params.recordingId; + this.recordingStartMs = params.recordingStartMs; + this.recordingType = params.recordingType; + this.recordingUrl = params.recordingUrl; + this.resourceUri = params.resourceUri; + } +} + +export class ListRecordingResponse { + constructor(params) { + params = params || {}; + this.addTime = params.addTime; + this.apiId = params.apiId; + this.callUuid = params.callUuid; + this.conferenceName = params.conferenceName; + this.recordingDurationMs = params.recordingDurationMs; + this.recordingEndMs = params.recordingEndMs; + this.recordingFormat = params.recordingFormat; + this.recordingId = params.recordingId; + this.recordingStartMs = params.recordingStartMs; + this.recordingType = params.recordingType; + this.recordingUrl = params.recordingUrl; + this.resourceUri = params.resourceUri; + } +} + /** - * Represents a Recording - * @constructor - * @param {function} client - make api call - * @param {object} [data] - data of call - */ +* Represents a Recording +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ export class Recording extends PlivoResource { constructor(client, data = {}) { - super(action, Recording, idField, client); - if (idField in data) { - this.id = data[idField]; - } - extend(this, data); + super(action, Recording, idField, client); + this[clientKey] = client + + if (idField in data) { + this.id = data[idField]; + } + extend(this, data); } -/** - * Delete recording - * @method - * @promise {boolean} return true if success - * @fail {Error} return Error - */ - delete() { - let params = {}; - params.isVoiceRequest = 'true'; - return super.delete(params); + /** + * Delete recording + * @method + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + delete(id) { + let params = {}; + params.isVoiceRequest = 'true'; + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('DELETE', action + id + '/', params) + .then(() => { + resolve(true); + }) + .catch(error => { + reject(error); + }); + }); } } /** - * Represents a Recording Interface - * @constructor - * @param {function} client - make api call - * @param {object} [data] - data of call - */ +* Represents a Recording Interface +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ export class RecordingInterface extends PlivoResourceInterface { constructor(client, data = {}) { - super(action, Recording, idField, client); - extend(this, data); + super(action, Recording, idField, client); + extend(this, data); - this[clientKey] = client; + this[clientKey] = client; } -/** - * Get recording by id - * @method - * @param {string} id - id to get recording information - * @promise {object} return {@link Pricing} object - * @fail {Error} return Error - */ + /** + * Get recording by id + * @method + * @param {string} id - id to get recording information + * @promise {object} return {@link Pricing} object + * @fail {Error} return Error + */ get(id) { - let errors = validate([ - {field: 'id', value: id, validators: ['isRequired']} - ]); + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); - if (errors) { - return errors; - } - let params = {}; - params.isVoiceRequest = 'true'; - return super.get(id, params); + if (errors) { + return errors; + } + let params = {}; + params.isVoiceRequest = 'true'; + + let client = this[clientKey]; + + return new Promise((resolve, reject) => { + if (action !== '' && !id) { + reject(new Error(this[idKey] + ' must be set')); + } + client('GET', action + (id ? id + '/' : ''), params) + .then(response => { + resolve(new RetrieveRecordingResponse(response.body, client)); + }) + .catch(error => { + reject(error); + }); + }); } /** @@ -80,28 +150,47 @@ export class RecordingInterface extends PlivoResourceInterface { * @param {string} [params.limit] - Display no of results per page * @param {string} [params.offset] - No of value items by which results should be offset */ - list(params= {}) { - params.isVoiceRequest = 'true'; - return super.list(params); + list(params = {}) { + params.isVoiceRequest = 'true'; + let client = this[clientKey]; + return new Promise((resolve, reject) => { + client('GET', action, params) + .then(response => { + let objects = []; + Object.defineProperty(objects, 'meta', { + value: response.body.meta, + enumerable: true + }); + response.body.objects.forEach(item => { + objects.push(new ListRecordingResponse(item, client)); + }); + resolve(objects); + }) + .catch(error => { + reject(error); + }); + }); } -/** - * Delete recording by id - * @method - * @param {string} id - id to delete recording - * @promise {boolean} return true if success - * @fail {Error} return Error - */ + /** + * Delete recording by id + * @method + * @param {string} id - id to delete recording + * @promise {boolean} return true if success + * @fail {Error} return Error + */ delete(id) { - let errors = validate([ - {field: 'id', value: id, validators: ['isRequired']} - ]); + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); - if (errors) { - return errors; - } - return new Recording(this[clientKey], { - id: id - }).delete(); + if (errors) { + return errors; + } + return new Recording(this[clientKey], { + id: id + }).delete(id); } } diff --git a/lib/rest/axios.js b/lib/rest/axios.js new file mode 100644 index 0000000..d323f07 --- /dev/null +++ b/lib/rest/axios.js @@ -0,0 +1,215 @@ +import axios from 'axios'; +import queryString from 'querystring'; +import * as Exceptions from '../utils/exceptions'; +import * as _ from "lodash"; + +export function Axios(config) { + let auth = 'Basic ' + new Buffer(config.authId + ':' + config.authToken) + .toString('base64'); + + let headers = { + Authorization: auth, + 'User-Agent': config.userAgent, + 'Content-Type': 'application/json' + }; + + const retryWrapper = (axios, options) => { + const max_time = options.retryTime; + let counter = 0; + axios.interceptors.response.use(null, (error) => { + const config = error.config; + if (counter < max_time && error.response.status >= 500) { + counter++; + config.url = options.urls[counter] + options.authId + '/' + options.action; + return new Promise((resolve) => { + resolve(axios(config)); + }) + } + return Promise.reject(error) + }) + } + + return (method, action, params) => { + let configuration = config; + // Add support fot multipart requests. + if (typeof (params) != 'undefined' && params.multipart == true) { + return new Promise((resolve, reject) => { + delete params.multipart; + + var FormData = require('form-data'); + var multipartParams = new FormData(); + + for(const key in params) { + if (key != 'file') { + multipartParams.append(key, params[key]); + } else { + multipartParams.append(key, require('fs').createReadStream(params[key])); + } + } + + let headers = multipartParams.getHeaders(); + + var config = { + method: method, + url: configuration.url + '/' + action, + headers: { + 'Authorization': 'Basic ' + new Buffer(configuration.authId + ':' + configuration.authToken).toString('base64'), + 'User-Agent': configuration.userAgent, + 'content-type': headers['content-type'] + }, + data : multipartParams + }; + + axios(config).then(response => { + const exceptionClass = { + 400: Exceptions.InvalidRequestError, + 401: Exceptions.AuthenticationError, + 404: Exceptions.ResourceNotFoundError, + 405: Exceptions.InvalidRequestError, + 500: Exceptions.ServerError, + } [response.status] || Error; + + if (!_.inRange(response.status, 200, 300)) { + let body = response.data; + if (typeof body === 'object') { + reject(new exceptionClass(JSON.stringify(body))); + } + else { + reject(new exceptionClass(body)); + } + } + resolve({ + response: response, + body: response.data + }); + }) + .catch(function (error) { + reject(error.stack+ "\r\n" + JSON.stringify(error.response.data)); + }); + }) + } + + if (typeof (params) != 'undefined' && typeof (params.file) != 'undefined') { + let files = []; + if (Array.isArray(params.file)) { + for (let index = 0; index < params.file.length; index++) { + files[index] = require('fs').createReadStream(params.file[index]); + } + } else { + files[0] = require('fs').createReadStream(params.file); + } + params.file = files; + } + + let options = { + url: config.url + '/' + action, + method: method, + data: params || '', + headers: headers, + json: true + }; + let apiVoiceUris = ['https://voice.plivo.com/v1/Account/','https://voice-usw1.plivo.com/v1/Account/','https://voice-use1.plivo.com/v1/Account/']; + let isVoiceReq = false; + if (params) { + if (params.hasOwnProperty('is_call_insights_request')) { + options.url = params.call_insights_base_url + params.call_insights_request_path; + delete params.is_call_insights_request; + delete params.call_insights_base_url; + delete params.call_insights_request_path; + delete options.data; + options.json = params; + } + else if (params.hasOwnProperty('is_voice_request')){ + options.url = apiVoiceUris[0] + config.authId + '/' + action; + delete params.is_voice_request; + isVoiceReq = true; + } else if (params.hasOwnProperty('override_url')) { + // currently used by Lookup API but is generic enough to be used + // by any product in future. + options.url = params.override_url; + delete params.override_url; + } + } + + if (method === 'GET' && options.data !== '') { + let query = '?' + queryString.stringify(params); + options.url += query; + } + + if (typeof config.proxy !== 'undefined') { + options.proxy = config.proxy; + } + + if (typeof config.timeout !== 'undefined') { + options.timeout = config.timeout; + } + + return new Promise((resolve, reject) => { + if (isVoiceReq) { + retryWrapper(axios, {retryTime: 2, urls: apiVoiceUris, authId: config.authId, action: action}); + options.url = apiVoiceUris[0] + config.authId + '/' + action; + axios(options).then(response => { + const exceptionClass = { + 400: Exceptions.InvalidRequestError, + 401: Exceptions.AuthenticationError, + 404: Exceptions.ResourceNotFoundError, + 405: Exceptions.InvalidRequestError, + 500: Exceptions.ServerError, + } [response.status] || Error; + + if (!_.inRange(response.status, 200, 300)) { + let body = response.data; + if (typeof body === 'object') { + reject(new exceptionClass(JSON.stringify(body))); + } + else { + reject(new exceptionClass(body)); + } + } + resolve({ + response: response, + body: response.data + }); + }) + .catch(function (error) { + reject(error.stack+ "\r\n" + JSON.stringify(error.response.data)); + }) + } + else { + axios(options).then(response => { + const exceptionClass = { + 400: Exceptions.InvalidRequestError, + 401: Exceptions.AuthenticationError, + 404: Exceptions.ResourceNotFoundError, + 405: Exceptions.InvalidRequestError, + 500: Exceptions.ServerError, + } [response.status] || Error; + + if (!_.inRange(response.status, 200, 300)) { + let body = response.data; + if (typeof body === 'object') { + reject(new exceptionClass(JSON.stringify(body))); + } + else { + reject(new exceptionClass(body)); + } + } + else { + let body = response.data; + let isObj = typeof _body === 'object' && _body !== null && !(_body instanceof Array) && !(_body instanceof Date) + if (isObj) { + _body['statusCode'] = response.status; + } + resolve({ + response: response, + body: body + }); + } + }) + .catch(function (error) { + reject(error.stack + '\n' + JSON.stringify(error.response.data)); + }) + } + }); + }; +} diff --git a/lib/rest/client-test.js b/lib/rest/client-test.js index b8bd8cc..848c901 100644 --- a/lib/rest/client-test.js +++ b/lib/rest/client-test.js @@ -48,6 +48,7 @@ import { import { MediaInterface } from '../resources/media.js'; +import {MultiPartyCallInterface} from "../resources/multiPartyCall"; export class Client { constructor(authId, authToken, proxy) { @@ -90,6 +91,12 @@ export class Client { this.pricings = new PricingInterface(client); this.recordings = new RecordingInterface(client); this.media = new MediaInterface(client); + this.endUsers = new EndUserInterface(client); + this.complianceDocumentTypes = new ComplianceDocumentTypeInterface(client); + this.complianceDocuments = new ComplianceDocumentInterface(client); + this.complianceRequirements = new ComplianceRequirementInterface(client); + this.complianceApplications = new ComplianceApplicationInterface(client); + this.multiPartyCalls = new MultiPartyCallInterface(client); } } diff --git a/lib/rest/client.js b/lib/rest/client.js index fb5874e..492c32d 100644 --- a/lib/rest/client.js +++ b/lib/rest/client.js @@ -1,4 +1,4 @@ -import { Request } from "./request.js"; +import { Axios } from "./axios.js"; import { camelCaseRequestWrapper } from "./utils"; import { name, version } from "../../package.json"; import { Phlo, PhloInterface } from "../resources/phlo"; @@ -20,6 +20,12 @@ import { validateV3Signature } from "../utils/v3Security"; import { stringify } from "./../utils/jsonStrinfigier"; import { CallFeedbackInterface } from "../resources/callFeedback"; import { MediaInterface } from "../resources/media.js"; +import { EndUserInterface } from "../resources/endUsers"; +import { ComplianceDocumentTypeInterface } from "../resources/complianceDocumentTypes"; +import { ComplianceDocumentInterface} from "../resources/complianceDocuments"; +import { ComplianceRequirementInterface } from "../resources/complianceRequirements"; +import { ComplianceApplicationInterface } from "../resources/complianceApplications"; +import {MultiPartyCallInterface} from "../resources/multiPartyCall"; exports.Response = function() { return new Response(); @@ -66,8 +72,7 @@ export class Client { }, options ); - - let client = camelCaseRequestWrapper(Request(options)); + let client = camelCaseRequestWrapper(Axios(options)); this.calls = new CallInterface(client); this.accounts = new AccountInterface(client); @@ -83,6 +88,12 @@ export class Client { this.recordings = new RecordingInterface(client); this.callFeedback = new CallFeedbackInterface(client); this.media = new MediaInterface(client); + this.endUsers = new EndUserInterface(client); + this.complianceDocumentTypes = new ComplianceDocumentTypeInterface(client); + this.complianceDocuments = new ComplianceDocumentInterface(client); + this.complianceRequirements = new ComplianceRequirementInterface(client); + this.complianceApplications = new ComplianceApplicationInterface(client); + this.multiPartyCalls = new MultiPartyCallInterface(client); } toJSON() { @@ -125,7 +136,7 @@ export class PhloClient { options ); - let client = camelCaseRequestWrapper(Request(options)); + let client = camelCaseRequestWrapper(Axios(options)); this.phlo = function(phloId) { let dd = new Phlo(client, { phloId: phloId, authId: authId }); diff --git a/lib/rest/request-test.js b/lib/rest/request-test.js index be2e21d..9f60e97 100644 --- a/lib/rest/request-test.js +++ b/lib/rest/request-test.js @@ -583,6 +583,306 @@ export function Request(config) { }); } + // ============= MultiPartyCalls =============== + else if (method === 'GET' && action === 'MultiPartyCall/'){ + resolve({ + response: {}, + body: { + "api_id": "d53ab14c-eddb-11ea-b02e-0242ac110003", + "meta": { + "count": 6, + "limit": 20, + "next": null, + "offset": 0, + "previous": null + }, + "objects": [ + { + "billed_amount": "0.00500", + "billed_duration": 60, + "creation_time": "2020-08-31 15:12:03+00:00", + "duration": 3, + "end_time": "2020-08-31 15:12:06+00:00", + "friendly_name": "TestMPC", + "mpc_uuid": "ca8e8a44-48e1-445d-afd5-1fcccdbccd9d", + "participants": "/v1/Account/MAMDJMMTEZOWY0ZMQWM2/MultiPartyCall/uuid_ca8e8a44-48e1-445d-afd5-1fcccdbccd9d/Participant/", + "recording": null, + "resource_uri": "/v1/Account/MAMDJMMTEZOWY0ZMQWM2/MultiPartyCall/uuid_ca8e8a44-48e1-445d-afd5-1fcccdbccd9d/", + "start_time": null, + "status": "Ended", + "stay_alone": false, + "sub_account": null, + "termination_cause": "No Active Participants", + "termination_cause_code": 1000 + }, + { + "billed_amount": "0.00500", + "billed_duration": 60, + "creation_time": "2020-08-31 14:32:40+00:00", + "duration": 5, + "end_time": "2020-08-31 14:32:45+00:00", + "friendly_name": "TestMPC", + "mpc_uuid": "9b531a1f-1692-4802-a7d6-3ef25bcfe3fc", + "participants": "/v1/Account/MAMDJMMTEZOWY0ZMQWM2/MultiPartyCall/uuid_9b531a1f-1692-4802-a7d6-3ef25bcfe3fc/Participant/", + "recording": null, + "resource_uri": "/v1/Account/MAMDJMMTEZOWY0ZMQWM2/MultiPartyCall/uuid_9b531a1f-1692-4802-a7d6-3ef25bcfe3fc/", + "start_time": null, + "status": "Ended", + "stay_alone": false, + "sub_account": null, + "termination_cause": "No Active Participants", + "termination_cause_code": 1000 + }, + { + "billed_amount": "0.01000", + "billed_duration": 120, + "creation_time": "2020-08-31 14:32:11+00:00", + "duration": 11, + "end_time": "2020-08-31 14:32:22+00:00", + "friendly_name": "TestMPC", + "mpc_uuid": "6f84d47c-ee82-4172-a155-c6e22f87d874", + "participants": "/v1/Account/MAMDJMMTEZOWY0ZMQWM2/MultiPartyCall/uuid_6f84d47c-ee82-4172-a155-c6e22f87d874/Participant/", + "recording": null, + "resource_uri": "/v1/Account/MAMDJMMTEZOWY0ZMQWM2/MultiPartyCall/uuid_6f84d47c-ee82-4172-a155-c6e22f87d874/", + "start_time": null, + "status": "Ended", + "stay_alone": false, + "sub_account": null, + "termination_cause": "Stay Alone Not Permitted", + "termination_cause_code": 1010 + }, + { + "billed_amount": "0.00500", + "billed_duration": 60, + "creation_time": "2020-08-31 14:31:20+00:00", + "duration": 3, + "end_time": "2020-08-31 14:31:23+00:00", + "friendly_name": "TestMPC", + "mpc_uuid": "0746f6c6-7447-4e0a-9013-186e4220aaf4", + "participants": "/v1/Account/MAMDJMMTEZOWY0ZMQWM2/MultiPartyCall/uuid_0746f6c6-7447-4e0a-9013-186e4220aaf4/Participant/", + "recording": null, + "resource_uri": "/v1/Account/MAMDJMMTEZOWY0ZMQWM2/MultiPartyCall/uuid_0746f6c6-7447-4e0a-9013-186e4220aaf4/", + "start_time": "2020-08-31 14:31:20+00:00", + "status": "Ended", + "stay_alone": false, + "sub_account": null, + "termination_cause": "No Active Participants", + "termination_cause_code": 1000 + }, + { + "billed_amount": "0.00500", + "billed_duration": 60, + "creation_time": "2020-08-31 06:42:50+00:00", + "duration": 36, + "end_time": "2020-08-31 06:43:26+00:00", + "friendly_name": "TestMPC", + "mpc_uuid": "b89150fd-0387-4bf8-bde7-a4fed39601ce", + "participants": "/v1/Account/MAMDJMMTEZOWY0ZMQWM2/MultiPartyCall/uuid_b89150fd-0387-4bf8-bde7-a4fed39601ce/Participant/", + "recording": null, + "resource_uri": "/v1/Account/MAMDJMMTEZOWY0ZMQWM2/MultiPartyCall/uuid_b89150fd-0387-4bf8-bde7-a4fed39601ce/", + "start_time": "2020-08-31 06:42:50+00:00", + "status": "Ended", + "stay_alone": false, + "sub_account": null, + "termination_cause": "No Active Participants", + "termination_cause_code": 1000 + }, + { + "billed_amount": "0.00500", + "billed_duration": 60, + "creation_time": "2020-08-28 17:30:10+00:00", + "duration": 2, + "end_time": "2020-08-28 17:30:12+00:00", + "friendly_name": "tank", + "mpc_uuid": "2999c70d-b635-420f-b6f2-2fd4421f0381", + "participants": "/v1/Account/MAMDJMMTEZOWY0ZMQWM2/MultiPartyCall/uuid_2999c70d-b635-420f-b6f2-2fd4421f0381/Participant/", + "recording": null, + "resource_uri": "/v1/Account/MAMDJMMTEZOWY0ZMQWM2/MultiPartyCall/uuid_2999c70d-b635-420f-b6f2-2fd4421f0381/", + "start_time": "2020-08-28 17:30:10+00:00", + "status": "Ended", + "stay_alone": true, + "sub_account": null, + "termination_cause": "No Active Participants", + "termination_cause_code": 1000 + } + ] + } + }); + } + + else if (method === 'GET' && action === 'MultiPartyCall/uuid_ca8e8a44-48e1-445d-afd5-1fcccdbccd9d'){ + resolve({ + response: {}, + body: { + "api_id": "8970c2b3-edfb-11ea-b02e-0242ac110003", + "billed_amount": "0.00500", + "billed_duration": 60, + "creation_time": "2020-08-31 15:12:03+00:00", + "duration": 3, + "end_time": "2020-08-31 15:12:06+00:00", + "friendly_name": "TestMPC", + "mpc_uuid": "ca8e8a44-48e1-445d-afd5-1fcccdbccd9d", + "participants": "/v1/Account/MAMDJMMTEZOWY0ZMQWM2/MultiPartyCall/uuid_ca8e8a44-48e1-445d-afd5-1fcccdbccd9d/Participant/", + "recording": null, + "resource_uri": "/v1/Account/MAMDJMMTEZOWY0ZMQWM2/MultiPartyCall/uuid_ca8e8a44-48e1-445d-afd5-1fcccdbccd9d/", + "start_time": null, + "status": "Ended", + "stay_alone": false, + "sub_account": null, + "termination_cause": "No Active Participants", + "termination_cause_code": 1000 + } + }); + } + + else if (method === 'POST' && action === 'MultiPartyCall/name_Voice/Participant/' && params.role === 'Agent' && params.from === '+919090909090' && params.to === '+918309866821'){ + resolve({ + response: {}, + body: { + "api_id": "1cebd713-ee00-11ea-b02e-0242ac110003", + "calls": [ + { + "to": "sip:koushikqa119062465586783372208@phone-qa.voice.plivodev.com", + "from": "918888888888", + "call_uuid": "c0267574-5c12-4861-8990-da9404c8cdf6" + } + ], + "message": "add participant action initiated", + "request_uuid": "c0267574-5c12-4861-8990-da9404c8cdf6" + } + }); + } + + else if (method === 'POST' && action === 'MultiPartyCall/name_Voice/' && params.status === 'active'){ + resolve({ + response: {}, + body: {} + }); + } + + else if (method === 'DELETE' && action === 'MultiPartyCall/name_Voice/'){ + resolve({ + response: {}, + body: {} + }); + } + + else if (method === 'POST' && action === 'MultiPartyCall/name_TestMPC/Record/'){ + resolve({ + response: {}, + body: { + "api_id" : "e9b9b0cf-ee0a-11ea-b02e-0242ac110003", + "message" : "MPC: TestMPC record started", + "recording_id" : "e9bd7634-ee0a-11ea-9ddf-06feebbe3347", + "recording_url" : "https://media-qa.voice.plivodev.com/v1/Account/MAMDJMMTEZOWY0ZMQWM2/Recording/e9bd7634-ee0a-11ea-9ddf-06feebbe3347.mp3" + } + }); + } + + else if (method === 'DELETE' && action === 'MultiPartyCall/name_TestMPC/Record/'){ + resolve({ + response: {}, + body: { + } + }); + } + + else if (method === 'POST' && action === 'MultiPartyCall/name_TestMPC/Record/Pause/'){ + resolve({ + response: {}, + body: { + } + }); + } + + else if (method === 'POST' && action === 'MultiPartyCall/name_TestMPC/Record/Resume/'){ + resolve({ + response: {}, + body: { + } + }); + } + + else if (method === 'GET' && action === 'MultiPartyCall/uuid_12345678-90123456/Participant/'){ + resolve({ + response: {}, + body: { + "api_id": "d53e6c49-ee0e-11ea-b02e-0242ac110003", + "meta": { + "count": 1, + "limit": 20, + "next": null, + "offset": 0, + "previous": null + }, + "objects": [ + { + "billed_amount": null, + "billed_duration": null, + "call_uuid": "426c1fb3-8f47-46e5-a916-51faa85ca90e", + "coach_mode": false, + "duration": null, + "end_mpc_on_exit": false, + "exit_cause": null, + "exit_time": null, + "hold": false, + "join_time": "2020-09-03 17:24:12+00:00", + "member_id": "2132", + "mpc_uuid": "7503f05f-2d6e-4ab3-b9e6-3b0d81ae9087", + "mute": false, + "resource_uri": "/v1/Account/MAMDJMMTEZOWY0ZMQWM2/MultiPartyCall/uuid_7503f05f-2d6e-4ab3-b9e6-3b0d81ae9087/Participant/2132/", + "role": "agent", + "start_mpc_on_enter": true + } + ] + } + }); + } + + else if (method === 'POST' && action === 'MultiPartyCall/uuid_12345678-90123456/Participant/10/'){ + resolve({ + response: {}, + body: { + "api_id" : "be5a333a-ee0f-11ea-b02e-0242ac110003", + "hold" : "MPC: TestMPC hold/unhold member(s) succeded", + "mute" : "MPC: TestMPC mute/unmute member(s) succeded" + } + }); + } + + else if (method === 'DELETE' && action === 'MultiPartyCall/uuid_12345678-90123456/Participant/10/'){ + resolve({ + response: {}, + body: { + } + }); + } + + else if (method === 'GET' && action === 'MultiPartyCall/uuid_7503f05f-2d6e-4ab3-b9e6-3b0d81ae9087/Participant/2132/'){ + resolve({ + response: {}, + body: { + "api_id": "7ca274bb-ee11-11ea-b02e-0242ac110003", + "billed_amount": null, + "billed_duration": null, + "call_uuid": "426c1fb3-8f47-46e5-a916-51faa85ca90e", + "coach_mode": false, + "duration": null, + "end_mpc_on_exit": false, + "exit_cause": null, + "exit_time": null, + "hold": false, + "join_time": "2020-09-03 17:24:12+00:00", + "member_id": "2132", + "mpc_uuid": "7503f05f-2d6e-4ab3-b9e6-3b0d81ae9087", + "mute": false, + "resource_uri": "/v1/Account/MAMDJMMTEZOWY0ZMQWM2/MultiPartyCall/uuid_7503f05f-2d6e-4ab3-b9e6-3b0d81ae9087/Participant/2132/", + "role": "agent", + "start_mpc_on_enter": true + } + }); + } + // ============= Numbers =================== else if (method == 'GET' && action == 'Number/+919999999990/') { resolve({ diff --git a/lib/rest/utils.js b/lib/rest/utils.js index 1ece32a..300fe5b 100644 --- a/lib/rest/utils.js +++ b/lib/rest/utils.js @@ -5,6 +5,8 @@ import _mapValues from 'lodash/mapValues'; import _map from 'lodash/map'; import { parseString } from 'xml2js'; +export class InvalidRequestError extends Error {} + function recursivelyRenameObject(object, renameFunc) { if (!(object instanceof Object)) { return object; @@ -47,7 +49,8 @@ export function camelCaseRequestWrapper(requestFunc) { .replace('_greater_or_equal', '__gte') .replace('_less_or_equal', '__lte') .replace('_equal', '') - .replace('_equals', ''); + .replace('_equals', '') + .replace('country_iso_2', 'country_iso2'); }); return requestFunc(method, action, params).then(res => { @@ -78,3 +81,203 @@ export function validateSpeakAttributes(content, voice) { } } +export function validSubAccount(accountId){ + if(accountId.constructor !== String){ + throw new InvalidRequestError('Subaccount Id must be a string'); + } + + if(accountId.length !== 20){ + throw new InvalidRequestError('Subaccount Id should be of length 20'); + } + + if(accountId.substring(0,2) !== 'SA'){ + throw new InvalidRequestError("Subaccount Id should start with 'SA'"); + } + + return true; +} + +export function validMultipleDestinationNos(paramName, paramValue, options = {}){ + if(paramValue.split(options.delimiter).length > 1 && options.role.toLowerCase()!=='agent'){ + throw new InvalidRequestError('Multiple ' + paramName + ' values given for role ' + options.role) + } + else if (paramValue.split(options.delimiter).length >= options.agentLimit){ + throw new InvalidRequestError('No of ' + paramName + ' values provided should be lesser than ' + options.agentLimit) + } + else { + return true + } +} + +export function validParam(paramName, paramValue, expectedTypes = null, mandatory = false, expectedValues = null){ + if(mandatory && !paramValue){ + throw new InvalidRequestError(paramName + " is a required parameter"); + } + + if (!paramValue){ + return true; + } + + if(!expectedValues){ + return expectedType(paramName, expectedTypes, paramValue); + } + + if(expectedValue(paramName, expectedValues, paramValue)){ + return true; + } +} + +export function expectedType(paramName, expectedTypes, paramValue){ + if(!expectedTypes){ + return true; + } + + if(expectedTypes.indexOf(paramValue.constructor)===-1){ + throw new InvalidRequestError(paramName + ": Expected one of " + expectedTypes + " but received " + paramValue.constructor + " instead") + } + return true; +} + +export function expectedValue(paramName, expectedValues, paramValue){ + if(!expectedValues){ + return true; + } + + if(expectedValues.constructor === Array){ + if(expectedValues.indexOf(paramValue) === -1){ + throw new InvalidRequestError(paramName + ': Expected one of ' + expectedValues + ' but received ' + paramValue + ' instead'); + } + return true; + } + else{ + if(expectedValues !== paramValue){ + throw new InvalidRequestError(paramName + ': Expected ' + expectedValues + ' but received ' + paramValue + ' instead') + } + return true; + } +} + +export function multiValidParam(paramName, paramValue, expectedTypes = null, mandatory = false, expectedValues = null, makeLowerCase = false, seperator = ','){ + if(mandatory && !paramValue){ + throw new InvalidRequestError(paramName + 'is a required parameter'); + } + + if(!paramValue){ + return true; + } + + if(makeLowerCase){ + paramValue = paramValue.toLowerCase(); + } + else{ + paramValue = paramValue.toUpperCase(); + } + let values = paramValue.split(seperator) + if(expectedValues) { + for (let i = 0; i < values.length; i++) { + expectedValue(paramName, expectedValues, values[i].trim()); + } + } + return true; +} + +export function validUrl(paramName, paramValue, mandatory = false){ + if(mandatory && !paramValue){ + throw new InvalidRequestError(paramName + 'is a required parameter'); + } + + if(!paramValue){ + return true; + } + + let response = paramValue.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g); + if(response == null){ + throw new InvalidRequestError("Invalid URL : Doesn't satisfy the URL format") + } + else { + return true; + } +} + +export function isOneAmongStringUrl(paramName, paramValue, mandatory = false, expectedValues = null){ + if(mandatory && !paramValue){ + throw new InvalidRequestError(paramName + 'is a required parameter'); + } + + if(!paramValue){ + return true; + } + + if(!(expectedValues.indexOf(paramValue.toLowerCase()) === -1) || !(expectedValues.indexOf(paramValue.toUpperCase()) === -1)){ + return true; + } + else if (validUrl(paramName, paramValue)){ + return true; + } + else { + throw new InvalidRequestError(paramName + ' neither a valid URL nor in the expected values') + } +} + +export function validDateFormat(paramName, paramValue, mandatory = false){ + if(mandatory && !paramValue){ + throw new InvalidRequestError(paramName + " is a required parameter") + } + + if(!paramValue){ + return true; + } + + let response = paramValue.match(/^\d{4}\-\d{2}\-\d{2} \d{2}:\d{2}(:\d{2}(\.\d{1,6})?)?$/); + if(response == null){ + throw new InvalidRequestError("Invalid Date : Doesn't satisfy the date format") + } + else { + return true; + } +} + +export function validRange(paramName, paramValue, mandatory = false, lowerBound = null, upperBound = null){ + if(mandatory && !paramValue){ + throw new InvalidRequestError(paramName + " is a required parameter") + } + + if(!paramValue && paramValue !== 0){ + return true; + } + + if(!expectedType(paramName, [Number], paramValue)){ + throw new InvalidRequestError(paramName + ": Expected an Integer but received " + paramValue.constructor + " instead") + } + + if(lowerBound && upperBound){ + if(paramValue < lowerBound || paramValue > upperBound) { + throw new InvalidRequestError(paramName + " ranges between " + lowerBound + " and " + upperBound) + } + + if(paramValue >= lowerBound && paramValue <= upperBound){ + return true; + } + } + else if(lowerBound){ + if(paramValue < lowerBound){ + throw new InvalidRequestError(paramName + " should be greater than " + lowerBound) + } + + if(paramValue >= lowerBound){ + return true; + } + } + else if(upperBound){ + if(paramValue > upperBound){ + throw new InvalidRequestError(paramName + " should be lesser than " + upperBound) + } + + if(paramValue <= upperBound){ + return true; + } + } + else{ + throw new InvalidRequestError("Any one or both of lower and upper bound should be provided") + } +} diff --git a/lib/utils/jwt.js b/lib/utils/jwt.js index 1dd6070..5ce78d6 100644 --- a/lib/utils/jwt.js +++ b/lib/utils/jwt.js @@ -38,8 +38,8 @@ export function AccessToken(authId, authToken, username, validityOptions = {}, u this.uid = uid || this.username + "-" + (new Date()).getTime(); } -AccessToken.prototype = { - addVoiceGrants: function(incoming = false, outgoing = false) { + +AccessToken.prototype.addVoiceGrants= function(incoming = false, outgoing = false) { this.grants = { voice: { incoming_allow: incoming, @@ -47,7 +47,8 @@ AccessToken.prototype = { } }; - }, + } + AccessToken.prototype = { toJwt: function() { let payload = { jti: this.uid, diff --git a/lib/utils/plivoxml.js b/lib/utils/plivoxml.js index 79ec786..f6a30b3 100644 --- a/lib/utils/plivoxml.js +++ b/lib/utils/plivoxml.js @@ -14,7 +14,7 @@ export class PlivoXMLError extends Error { } export function Response() { this.element = 'Response'; this.nestables = ['Speak', 'Play', 'GetDigits', 'GetInput', 'Record', 'Dial', 'Message', - 'Redirect', 'Wait', 'Hangup', 'PreAnswer', 'Conference', 'DTMF']; + 'Redirect', 'Wait', 'Hangup', 'PreAnswer', 'Conference', 'DTMF', 'MultiPartyCall']; this.valid_attributes = []; this.elem = xmlBuilder.begin().ele(this.element); } @@ -439,6 +439,234 @@ Response.prototype = { return this.add(new DTMF(Response), body, attributes); }, + /** + * Add a MultiPartyCall element + * @method + * @param {string} body + * @param {object} attributes + * @param {string} [attributes.role] + * @param {number} [attributes.maxDuration] + * @param {number} [attributes.maxParticipants] + * @param {string} [attributes.waitMusicMethod] + * @param {string} [attributes.agentHoldMusicMethod] + * @param {string} [attributes.customerHoldMusicMethod] + * @param {boolean} [attributes.record] + * @param {string} [attributes.recordFileFormat] + * @param {string} [attributes.recordingCallbackMethod] + * @param {string} [attributes.statusCallbackEvents] + * @param {string} [attributes.statusCallbackMethod] + * @param {boolean} [attributes.stayAlone] + * @param {boolean} [attributes.coachMode] + * @param {boolean} [attributes.mute] + * @param {boolean} [attributes.hold] + * @param {boolean} [attributes.startMpcOnEnter] + * @param {boolean} [attributes.endMpcOnExit] + * @param {string} [attributes.enterSound] + * @param {string} [attributes.enterSoundMethod] + * @param {string} [attributes.exitSound] + * @param {string} [attributes.exitSoundMethod] + * @param {string} [attributes.onExitActionMethod] + * @param {boolean} [attributes.relayDTMFInputs] + * @param {string} [attributes.waitMusicUrl] + * @param {string} [attributes.agentHoldMusicUrl] + * @param {string} [attributes.customerHoldMusicUrl] + * @param {string} [attributes.recordingCallbackUrl] + * @param {string} [attributes.statusCallbackUrl] + * @param {string} [attributes.customerHoldMusicUrl] + */ + addMultiPartyCall: function (body, attributes){ + const VALID_ROLE_VALUES = ['agent', 'supervisor', 'customer'] + const VALID_METHOD_VALUES = ['GET', 'POST'] + const VALID_BOOL_VALUES = [true, false] + const VALID_RECORD_FILE_FORMAT_VALUES = ['mp3', 'wav'] + + if(attributes.role && VALID_ROLE_VALUES.indexOf(attributes.role.toLowerCase())===-1){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.role + ' for role') + } + else if (!attributes.role){ + throw new PlivoXMLError('role not mentioned : possible values - Agent / Supervisor / Customer') + } + + if(attributes.maxDuration && (attributes.maxDuration<300 || attributes.maxDuration>28800)){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.maxDuration + ' for maxDuration') + } + else if(!attributes.maxDuration){ + attributes.maxDuration = 14400 + } + + if(attributes.maxParticipants && (attributes.maxParticipants<2 || attributes.maxParticipants>10)){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.maxParticipants + ' for maxParticipants') + } + else if(!attributes.maxParticipants){ + attributes.maxParticipants = 10 + } + + if(attributes.waitMusicMethod && VALID_METHOD_VALUES.indexOf(attributes.waitMusicMethod.toUpperCase())===-1){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.waitMusicMethod + ' for waitMusicMethod') + } + else if (!attributes.waitMusicMethod){ + attributes.waitMusicMethod = 'GET' + } + + if(attributes.agentHoldMusicMethod && VALID_METHOD_VALUES.indexOf(attributes.agentHoldMusicMethod.toUpperCase())===-1){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.agentHoldMusicMethod + ' for agentHoldMusicMethod') + } + else if (!attributes.agentHoldMusicMethod){ + attributes.agentHoldMusicMethod = 'GET' + } + + if(attributes.customerHoldMusicMethod && VALID_METHOD_VALUES.indexOf(attributes.customerHoldMusicMethod.toUpperCase())===-1){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.customerHoldMusicMethod + ' for customerHoldMusicMethod') + } + else if (!attributes.customerHoldMusicMethod){ + attributes.customerHoldMusicMethod = 'GET' + } + + if(attributes.record && VALID_BOOL_VALUES.indexOf(attributes.record)===-1){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.record + ' for record') + } + else if (!attributes.record){ + attributes.record = false + } + + if(attributes.recordFileFormat && VALID_RECORD_FILE_FORMAT_VALUES.indexOf(attributes.recordFileFormat.toLowerCase())===-1){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.recordFileFormat + ' for recordFileFormat') + } + else if (!attributes.recordFileFormat){ + attributes.recordFileFormat = 'mp3' + } + + if(attributes.recordingCallbackMethod && VALID_METHOD_VALUES.indexOf(attributes.recordingCallbackMethod.toUpperCase())===-1){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.recordingCallbackMethod + ' for recordingCallbackMethod') + } + else if (!attributes.recordingCallbackMethod){ + attributes.recordingCallbackMethod = 'GET' + } + + if(attributes.statusCallbackEvents && !plivoUtils.multiValidParam('statusCallbackEvents', attributes.statusCallbackEvents, String, false, ['mpc-state-changes', 'participant-state-changes', 'participant-speak-events', 'participant-digit-input-events', 'add-participant-api-events'], true, ',')){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.statusCallbackEvents + ' for statusCallbackEvents') + } + else if(!attributes.statusCallbackEvents){ + attributes.statusCallbackEvents = 'mpc-state-changes,participant-state-changes' + } + + if(attributes.statusCallbackMethod && VALID_METHOD_VALUES.indexOf(attributes.statusCallbackMethod.toUpperCase())===-1){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.statusCallbackMethod + ' for statusCallbackMethod') + } + else if (!attributes.statusCallbackMethod){ + attributes.statusCallbackMethod = 'POST' + } + + if(attributes.stayAlone && VALID_BOOL_VALUES.indexOf(attributes.stayAlone)===-1){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.stayAlone + ' for stayAlone') + } + else if (!attributes.stayAlone){ + attributes.stayAlone = false + } + + if(attributes.coachMode && VALID_BOOL_VALUES.indexOf(attributes.coachMode)===-1){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.coachMode + ' for coachMode') + } + else if (!attributes.coachMode){ + attributes.coachMode = true + } + + if(attributes.mute && VALID_BOOL_VALUES.indexOf(attributes.mute)===-1){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.mute + ' for mute') + } + else if (!attributes.mute){ + attributes.mute = false + } + + if(attributes.hold && VALID_BOOL_VALUES.indexOf(attributes.hold)===-1){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.hold + ' for hold') + } + else if (!attributes.hold){ + attributes.hold = false + } + + if(attributes.startMpcOnEnter && VALID_BOOL_VALUES.indexOf(attributes.startMpcOnEnter)===-1){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.startMpcOnEnter + ' for startMpcOnEnter') + } + else if (!attributes.startMpcOnEnter){ + attributes.startMpcOnEnter = true + } + + if(attributes.endMpcOnExit && VALID_BOOL_VALUES.indexOf(attributes.endMpcOnExit)===-1){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.endMpcOnExit + ' for endMpcOnExit') + } + else if (!attributes.endMpcOnExit){ + attributes.endMpcOnExit = false + } + + if(attributes.enterSound && !plivoUtils.isOneAmongStringUrl('enterSound', attributes.enterSound, false, ['beep:1', 'beep:2', 'none'])){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.enterSound + ' for enterSound') + } + else if(!attributes.enterSound){ + attributes.enterSound = 'beep:1' + } + + if(attributes.enterSoundMethod && VALID_METHOD_VALUES.indexOf(attributes.enterSoundMethod.toUpperCase())===-1){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.enterSoundMethod + ' for enterSoundMethod') + } + else if (!attributes.enterSoundMethod){ + attributes.enterSoundMethod = 'GET' + } + + if(attributes.exitSound && !plivoUtils.isOneAmongStringUrl('exitSound', attributes.exitSound, false, ['beep:1', 'beep:2', 'none'])){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.exitSound + ' for exitSound') + } + else if(!attributes.exitSound){ + attributes.exitSound = 'beep:2' + } + + if(attributes.exitSoundMethod && VALID_METHOD_VALUES.indexOf(attributes.exitSoundMethod.toUpperCase())===-1){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.exitSoundMethod + ' for exitSoundMethod') + } + else if (!attributes.exitSoundMethod){ + attributes.exitSoundMethod = 'GET' + } + + if(attributes.onExitActionMethod && VALID_METHOD_VALUES.indexOf(attributes.onExitActionMethod.toUpperCase())===-1){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.onExitActionMethod + ' for onExitActionMethod') + } + else if (!attributes.onExitActionMethod){ + attributes.onExitActionMethod = 'POST' + } + + if(attributes.relayDTMFInputs && VALID_BOOL_VALUES.indexOf(attributes.relayDTMFInputs)===-1){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.relayDTMFInputs + ' for relayDTMFInputs') + } + else if (!attributes.relayDTMFInputs){ + attributes.relayDTMFInputs = false + } + + if(attributes.waitMusicUrl && !plivoUtils.validUrl('waitMusicUrl', attributes.waitMusicUrl, false)){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.waitMusicUrl + ' for waitMusicUrl') + } + + if(attributes.agentHoldMusicUrl && !plivoUtils.validUrl('agentHoldMusicUrl', attributes.agentHoldMusicUrl, false)){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.agentHoldMusicUrl + ' for agentHoldMusicUrl') + } + + if(attributes.customerHoldMusicUrl && !plivoUtils.validUrl('customerHoldMusicUrl', attributes.customerHoldMusicUrl, false)){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.customerHoldMusicUrl + ' for customerHoldMusicUrl') + } + + if(attributes.recordingCallbackUrl && !plivoUtils.validUrl('recordingCallbackUrl', attributes.recordingCallbackUrl, false)){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.recordingCallbackUrl + ' for recordingCallbackUrl') + } + + if(attributes.statusCallbackUrl && !plivoUtils.validUrl('statusCallbackUrl', attributes.statusCallbackUrl, false)){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.statusCallbackUrl + ' for statusCallbackUrl') + } + + if(attributes.customerHoldMusicUrl && !plivoUtils.validUrl('customerHoldMusicUrl', attributes.customerHoldMusicUrl, false)){ + throw new PlivoXMLError('Invalid attribute value ' + attributes.customerHoldMusicUrl + ' for customerHoldMusicUrl') + } + return this.add(new MultiPartyCall(Response), body, attributes); + }, + toXML: function () { return this.elem.toString(); }, @@ -520,7 +748,7 @@ function GetInput(Response) { this.element = 'GetInput'; this.valid_attributes = ['action', 'method', 'inputType', 'executionTimeout', 'digitEndTimeout', 'speechEndTimeout', 'finishOnKey', 'numDigits', - 'speechModel', 'hints','language', 'interimSpeechResultsCallback', + 'speechModel', 'hints','language', 'interimSpeechResultsCallback', 'interimSpeechResultsCallbackMethod', 'log', 'redirect', 'profanityFilter']; this.nestables = ['Speak', 'Play', 'Wait']; } @@ -741,3 +969,21 @@ function DTMF(Response) { } util.inherits(DTMF, Response); + +/** + * MultiPartyCall element + * @constructor + */ +function MultiPartyCall(Response){ + this.element = 'MultiPartyCall'; + this.nestables = []; + this.valid_attributes = ['role', 'maxDuration', 'maxParticipants', 'waitMusicUrl', + 'waitMusicMethod', 'agentHoldMusicUrl', 'agentHoldMusicMethod', + 'customerHoldMusicUrl', 'customerHoldMusicMethod', 'record', + 'recordFileFormat', 'recordingCallbackUrl', 'recordingCallbackMethod', + 'statusCallbackEvents', 'statusCallbackUrl', 'statusCallbackMethod', + 'stayAlone', 'coachMode', 'mute', 'hold', 'startMpcOnEnter', 'endMpcOnExit', + 'enterSound', 'enterSoundMethod', 'exitSound', 'exitSoundMethod', + 'onExitActionUrl', 'onExitActionMethod', 'relayDTMFInputs']; +} +util.inherits(MultiPartyCall, Response); diff --git a/lib/utils/security.js b/lib/utils/security.js index 3990ecf..5b3dc56 100644 --- a/lib/utils/security.js +++ b/lib/utils/security.js @@ -2,21 +2,23 @@ const utf8 = require('utf8'); const buildUrl = require('build-url'); const base64 = require('base-64'); -import * as parser from 'uri-parser'; -import crypto from 'crypto'; -import _ from 'lodash'; -export function computeOldSignature(authId: string, uri: string, params: {[string]: string}): string { +import * as parser from 'uri-parser'; + +import _ from 'lodash'; +import crypto from 'crypto'; + +export function computeOldSignature(authId, uri, params){ const joinedParams = uri + _.join(_.map(_.sortBy(_.toPairs(params)), item => item[0] + item[1]), ''); // console.log(joinedParams); return crypto.createHmac('sha1', authId).update(joinedParams).digest('base64'); } -export function verifyOldSignature(authId: string, uri: string, params: {[string]: string}, signature: string): boolean { +export function verifyOldSignature(authId, uri, params, signature) { return computeOldSignature(authId, uri, params) === signature; } -export function validateSignature(uri: string, nonce: string, signature: string, auth_token: string) { +export function validateSignature(uri, nonce, signature, auth_token) { nonce = utf8.encode(nonce); signature = utf8.encode(signature); auth_token = utf8.encode(auth_token); diff --git a/lib/utils/v3Security.js b/lib/utils/v3Security.js index af9c97b..464a936 100644 --- a/lib/utils/v3Security.js +++ b/lib/utils/v3Security.js @@ -3,9 +3,11 @@ const utf8 = require('utf8'); const buildUrl = require('build-url'); const base64 = require('base-64'); const qs = require('querystring'); + import * as parser from 'uri-parser'; -import crypto from 'crypto'; + import _ from 'lodash'; +import crypto from 'crypto'; function get_map_from_query(params1, params2) { let params = {}; @@ -85,9 +87,9 @@ function get_signature_v3(auth_token, base_url, nonce) { return base64.encode(hmacBytes); } -export function validateV3Signature(method: string, uri: string, - nonce: string, auth_token: string, - v3_signature: string, params={}) { +export function validateV3Signature(method, uri, + nonce, auth_token, + v3_signature, params={}) { auth_token = utf8.encode(auth_token); nonce = utf8.encode(nonce); v3_signature = utf8.encode(v3_signature); diff --git a/package.json b/package.json index 539fd0c..7df55cd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "plivo", - "version": "4.12.0", + "version": "4.16.0", "description": "A Node.js SDK to make voice calls and send SMS using Plivo and to generate Plivo XML", "homepage": "https://github.com/plivo/plivo-node", "files": [ @@ -40,6 +40,7 @@ "gulp-mocha": "^3.0.1", "gulp-plumber": "^1.0.0", "isparta": "^4.0.0", + "merge-stream": "^2.0.0", "sinon": "^2.1.0" }, "eslintConfig": { @@ -57,12 +58,14 @@ "test": "gulp" }, "dependencies": { + "@types/node": "^14.14.14", + "axios": "^0.19.2", "base-64": "^0.1.0", "build-url": "^1.0.10", + "form-data": "^4.0.0", "jsonwebtoken": "^8.5.1", "lodash": "^4.17.4", "querystring": "^0.2.0", - "request": "^2.81.0", "uri-parser": "^1.0.0", "utf8": "^2.1.2", "xml2js": "^0.4.19", diff --git a/test/calls.js b/test/calls.js index f60efee..4e623a6 100644 --- a/test/calls.js +++ b/test/calls.js @@ -68,6 +68,7 @@ describe('calls', function () { client.calls.get(1) .then(function(call){ return call.transfer() + done() }) .then(function(call) { assert.equal(call.id, 5) diff --git a/test/multiPartyCalls.js b/test/multiPartyCalls.js new file mode 100644 index 0000000..c5887bc --- /dev/null +++ b/test/multiPartyCalls.js @@ -0,0 +1,95 @@ +import assert from 'assert'; +import sinon from 'sinon'; +import {Client} from '../lib/rest/client-test'; +import {PlivoGenericResponse} from '../lib/base.js'; +import {MultiPartyCall} from "../lib/resources/multiPartyCall"; + +let client = new Client('sampleid', 'sammpletoken', 'sampleproxy'); + +describe('multiPartyCalls', function (){ + it('should list all MultiPartyCalls', function (){ + return client.multiPartyCalls.list().then(function (response){ + for(let i=0; i< response.length;i++) { + assert(response[i] instanceof MultiPartyCall) + } + }) + }); + + it('should get details of a MultiPartyCall', function (){ + return client.multiPartyCalls.get('ca8e8a44-48e1-445d-afd5-1fcccdbccd9d').then(function (response){ + assert(response instanceof PlivoGenericResponse) + assert.equal(response.id, 'ca8e8a44-48e1-445d-afd5-1fcccdbccd9d') + assert.equal(response.resourceUri, '/v1/Account/MAMDJMMTEZOWY0ZMQWM2/MultiPartyCall/uuid_ca8e8a44-48e1-445d-afd5-1fcccdbccd9d/') + }) + }); + + it('should add a Participant', function (){ + return client.multiPartyCalls.addParticipant('Agent', {'friendlyName' : 'Voice', 'from' : '+919090909090', 'to' : '+918309866821'}).then(function (response){ + assert(response instanceof PlivoGenericResponse) + assert.equal(response.message, 'add participant action initiated') + }) + }); + + it('should start an MPC', function (){ + return client.multiPartyCalls.start(null, 'Voice').then(function (response){ + assert(response instanceof PlivoGenericResponse) + }) + }); + + it('should end an MPC', function (){ + return client.multiPartyCalls.stop(null, 'Voice').then(function (response){ + assert(response, true) + }) + }); + + it('should start MPC Recording', function (){ + return client.multiPartyCalls.startRecording(null, 'TestMPC').then(function (response){ + assert(response.message, "MPC: TestMPC record started") + }) + }); + + it('should stop MPC Recording', function (){ + return client.multiPartyCalls.stopRecording(null, 'TestMPC').then(function (response){ + assert(response instanceof PlivoGenericResponse) + }) + }); + + it('should pause MPC Recording', function (){ + return client.multiPartyCalls.pauseRecording(null, 'TestMPC').then(function (response){ + assert(response instanceof PlivoGenericResponse) + }) + }); + + it('should resume MPC Recording', function (){ + return client.multiPartyCalls.resumeRecording(null, 'TestMPC').then(function (response){ + assert(response instanceof PlivoGenericResponse) + }) + }); + + it('should list MPC Participants', function (){ + return client.multiPartyCalls.listParticipants('12345678-90123456', null).then(function (response){ + assert(response instanceof PlivoGenericResponse) + }) + }); + + it('should update MPC Participant', function (){ + return client.multiPartyCalls.updateParticipant(10, '12345678-90123456', null).then(function (response){ + assert(response instanceof PlivoGenericResponse) + assert.equal(response.hold, 'MPC: TestMPC hold/unhold member(s) succeded') + assert.equal(response.mute, 'MPC: TestMPC mute/unmute member(s) succeded') + }) + }); + + it('should kick MPC Participant', function (){ + return client.multiPartyCalls.kickParticipant(10, '12345678-90123456', null).then(function (response){ + assert(response instanceof PlivoGenericResponse) + }) + }); + + it('should get MPC Participant', function (){ + return client.multiPartyCalls.getParticipant(2132, '7503f05f-2d6e-4ab3-b9e6-3b0d81ae9087', null).then(function (response){ + assert(response instanceof PlivoGenericResponse) + assert.equal(response.resourceUri, '/v1/Account/MAMDJMMTEZOWY0ZMQWM2/MultiPartyCall/uuid_7503f05f-2d6e-4ab3-b9e6-3b0d81ae9087/Participant/2132/') + }) + }); +}) diff --git a/test/xml.js b/test/xml.js index efb2b60..b2ce224 100644 --- a/test/xml.js +++ b/test/xml.js @@ -29,4 +29,15 @@ describe('PlivoXML', function () { done("Failed to test Plivo Xml due to unknown error"); }); }); + + it('tests MultiPartyCall', function (done){ + const mpcResponse = new Response(); + mpcResponse.addMultiPartyCall('Nairobi',{ + role: 'Agent', + maxDuration: 1000, + statusCallbackEvents: 'participant-speak-events, participant-digit-input-events, add-participant-api-events, participant-state-changes, mpc-state-changes' + }); + assert.equal('Nairobi',mpcResponse.toXML()); + done(); + }) }); diff --git a/types/base.d.ts b/types/base.d.ts new file mode 100644 index 0000000..b53c07b --- /dev/null +++ b/types/base.d.ts @@ -0,0 +1,19 @@ +export class PlivoGenericResponse { + constructor(params: object, idString: string); + id: string; +} +export class PlivoResource { + constructor(action: string, Klass: Symbol, idField: string, request: any); + update(params: object, id: string): Promise; + delete(params: object): Promise; + executeAction(task: string, method: string, params: {}, action: string): Promise; + customexecuteAction(url: string, method?: string, params?: {}): Promise; + customexecuteGetNumberAction(url: string, method?: string, params?: {}): any; + getMetaResponse(url: string, method?: string, params?: {}): Promise; +} +export class PlivoResourceInterface { + constructor(action: string, Klass: Symbol, idField: string, request: any); + get(id: string, params?: {}): Promise; + list(params: object): Promise; + create(params: object): Promise; +} diff --git a/types/resources/accounts.d.ts b/types/resources/accounts.d.ts new file mode 100644 index 0000000..796696a --- /dev/null +++ b/types/resources/accounts.d.ts @@ -0,0 +1,172 @@ +/** + * Represents a SubAccount + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class GetAccountDetails { + constructor(params: object); + accountType: string; + address: string; + apiId: string; + autoRecharge: string; + billingMode: string; + cashCredits: string; + city: string; + name: string; + resourceUri: string; + state: string; + timezone: string; +} +export class CreateSubAccountResponse { + constructor(params: object); + apiId: string; + authId: string; + authToken: string; + message: string; +} +export class UpdateSubAccountDetails { + constructor(params: object); + apiId: string; + message: string; +} +export class UpdateAccountDetailsResponse { + constructor(params: object); + apiId: string; + message: string; +} +export class GetSubAccountDetails { + constructor(params: object); + account: string; + apiId: string; + authId: string; + authToken: string; + created: string; + enabled: string; + modified: string; + name: string; + resourceUri: string; +} +export class Subaccount extends PlivoResource { + constructor(client: Function, data?: {}); + id: string; + /** + * update subaccount + * @method + * @param {string} name - name of subaccount + * @param {boolean} enabled - make account enable or disable + * @promise {Subaccount} return object of subaccount + * @fail {Error} return Error + */ + update(name: string, enabled: boolean): Promise; + /** + * delete subaccount + * @method + * @param {boolean} cascade - delete associated applications, phonenumbers & endpoints + * @promise {boolean} return true if subaccount deleted + * @fail {Error} return Error + */ + delete(cascade: boolean): Promise; + [clientKey]: symbol; +} +/** + * Represents a Subaccount Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class SubaccountInterface extends PlivoResourceInterface { + constructor(client: Function, data?: {}); + /** + * get subaccount by id + * @method + * @param {string} id - id of subaccount + * @promise {Subaccount} return object of subaccount + * @fail {Error} return Error + */ + get(id: string): Promise; + /** + * create subaccount + * @method + * @param {string} name - name of subaccount + * @param {boolean} enabled - enable or disable subaccount + * @promise {PlivoGenericResponse} return object of PlivoGenericObject + * @fail {Error} return Error + */ + create(name: string, enabled: boolean): Promise; + /** + * update subaccount + * @method + * @param {id} id - id of subaccount + * @param {string} name - name of subaccount + * @param {boolean} enabled - make account enable or disable + * @promise {Subaccount} return object of subaccount + * @fail {Error} return Error + */ + update(id: string, name: string, enabled: boolean): Promise; + /** + * delete subaccount + * @method + * @param {id} id - id of subaccount + * @param {boolean} cascade - delete associated applications, phonenumbers & endpoints + * @promise {boolean} return true if subaccount deleted + * @fail {Error} return Error + */ + delete(id: string, cascade: boolean): Promise; + [clientKey]: symbol; +} +/** + * Represents a Account + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class Account extends PlivoResource { + constructor(client: Function, data?: {}); + id: string; + /** + * get account detail + * @method + * @promise {PlivoGenericResponse} return PlivoGenericResponse object + * @fail {Error} return Error + */ + get(): Promise; + update(params: object): Promise; + [clientKey]: symbol; +} +/** + * Represents a Account Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class AccountInterface extends PlivoResourceInterface { + constructor(client: Function, data?: {}); + /** + * get account detail + * @method + * @promise {PlivoGenericResponse} return PlivoGenericResponse object + * @fail {Error} return Error + */ + get(): Promise; + /** + * update account detail + * @method + * @param {object} params - parameters + * @param {string} [params.name] - name of account + * @param {string} [params.city] - city of account + * @param {string} [params.address] - address of account + * @promise {Account} return Account object + * @fail {Error} return Error + */ + update(params: { + name: string; + city: string; + address: string; + }): Promise; + [clientKey]: symbol; +} +import { PlivoResource } from "../base"; +declare const clientKey: unique symbol; +import { PlivoResourceInterface } from "../base"; +export {}; diff --git a/types/resources/applications.d.ts b/types/resources/applications.d.ts new file mode 100644 index 0000000..4c2b0b1 --- /dev/null +++ b/types/resources/applications.d.ts @@ -0,0 +1,163 @@ +/** +* Represents a Application +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ +export class UpdateApplicationResponse { + constructor(params: object); + apiId: string; + message: string; +} +export class CreateApplicationResponse { + constructor(params: object); + apiId: string; + appId: string; + message: string; +} +export class RetrieveApplicationResponse { + constructor(params: object); + answerMethod: string; + answerUrl: string; + apiId: string; + appId: string; + appName: string; + applicationType: string; + defaultApp: string; + defaultEndpointApp: string; + enabled: string; + fallbackAnswerUrl: string; + fallbackMethod: string; + hangupMethod: string; + logIncomingMessage: string; + messageMethod: string; + resourceUri: string; + sipUri: string; + subAccount: string; +} +export class ListAllApplicationResponse { + constructor(params: object); + answerMethod: string; + answerUrl: string; + appId: string; + appName: string; + applicationType: string; + defaultApp: string; + defaultEndpointApp: string; + enabled: string; + fallbackAnswerUrl: string; + fallbackMethod: string; + hangupMethod: string; + logIncomingMessage: string; + messageMethod: string; + resourceUri: string; + sipUri: string; + subAccount: string; +} +export class Application extends PlivoResource { + constructor(client: Function, data?: {}); + id: string; + [clientKey]: symbol; +} +/** +* Represents a Application interface +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ +export class ApplicationInterface extends PlivoResourceInterface { + constructor(client: Function, data?: {}); + /** + * get application by given id + * @method + * @param {string} id - id of application + * @promise {object} return {@link Application} object + * @fail {Error} return Error + */ + get(id: string): Promise; + /** + * list applications + * @method + * @param {object} params - params to list applications + * @param {string} [params.subaccount] - ID of the subaccount if present + * @param {integer} [params.limit] - To display no of results per page + * @param {integer} [params.offset] - No of value items by which results should be offset + */ + list(params?: {}): Promise; + /** + * create Application + * @method + * @param {string} appName - name of application + * @param {object} params - params to create application + * @param {string} [params.answerUrl] - answer url + * @param {string} [params.appName] The name of your application + * @param {string} [params.answerUrl] The URL invoked by Plivo when a call executes this application. + * @param {string} [params.answerMethod] The method used to call the answer_url. Defaults to POST. + * @param {string} [params.hangupUrl] The URL that is notified by Plivo when the call hangs up. + * @param {string} [params.hangupMethod] The method used to call the hangup_url. Defaults to POST + * @param {string} [params.fallbackAnswerUrl] Invoked by Plivo only if answer_url is unavailable or the XML response is invalid. Should contain a XML response. + * @param {string} [params.fallbackMethod] The method used to call the fallback_answer_url. Defaults to POST. + * @param {string} [params.messageUrl] The URL that is notified by Plivo when an inbound message is received. Defaults not set. + * @param {string} [params.messageMethod] The method used to call the message_url. Defaults to POST. + * @param {boolean} [params.defaultNumberApp] If set to true, associates all newly created Plivo numbers that have not specified an app_id, to this application. + * @param {boolean} [params.defaultEndpointApp] If set to true, associates all newly created Plivo endpoints that have not specified an app_id, to this application. + * @param {string} [params.subaccount] Id of the subaccount, in case only subaccount applications are needed. + * @param {boolean} [params.logIncomingMessages] flag to control incoming message logs. + * @promise {object} return {@link PlivoGenericResponse} object + * @fail {Error} return Error + */ + create(appName: string, params?: {}): Promise; + /** + * update Application + * @method + * @param {string} id - id of application + * @param {object} params - to update application + * @param {string} [params.answerUrl] The URL invoked by Plivo when a call executes this application. + * @param {string} [params.answerMethod] The method used to call the answer_url. Defaults to POST. + * @param {string} [params.hangupUrl] The URL that is notified by Plivo when the call hangs up. + * @param {string} [params.hangupMethod] The method used to call the hangup_url. Defaults to POST + * @param {string} [params.fallbackAnswerUrl] Invoked by Plivo only if answer_url is unavailable or the XML response is invalid. Should contain a XML response. + * @param {string} [params.fallbackMethod] The method used to call the fallback_answer_url. Defaults to POST. + * @param {string} [params.messageUrl] The URL that is notified by Plivo when an inbound message is received. Defaults not set. + * @param {string} [params.messageMethod] The method used to call the message_url. Defaults to POST. + * @param {boolean} [params.defaultNumberApp] If set to true, associates all newly created Plivo numbers that have not specified an app_id, to this application. + * @param {boolean} [params.defaultEndpointApp] If set to true, associates all newly created Plivo endpoints that have not specified an app_id, to this application. + * @param {string} [params.subaccount] Id of the subaccount, in case only subaccount applications are needed. + * @param {boolean} [params.logIncomingMessages] flag to control incoming message logs. + * @promise {object} return {@link Application} object + * @fail {Error} return Error + */ + update(id: string, params: { + answerUrl: string; + answerMethod: string; + hangupUrl: string; + hangupMethod: string; + fallbackAnswerUrl: string; + fallbackMethod: string; + messageUrl: string; + messageMethod: string; + defaultNumberApp: boolean; + defaultEndpointApp: boolean; + subaccount: string; + logIncomingMessages: boolean; + }): Promise; + /** + * delete Application + * @method + * @param {string} id - id of application + * @param {object} params - params to delete application + * @param {boolean} [params.cascade] - delete associated endpoints + * @param {string} [params.newEndpointApplication] - link associated endpoints with app + * @promise {object} return true on success + * @fail {Error} return Error + */ + delete(id: string, params?: { + cascade: boolean; + newEndpointApplication: string; + }): Promise; + [clientKey]: symbol; +} +import { PlivoResource } from "../base"; +declare const clientKey: unique symbol; +import { PlivoResourceInterface } from "../base"; +export {}; diff --git a/types/resources/call.d.ts b/types/resources/call.d.ts new file mode 100644 index 0000000..a565095 --- /dev/null +++ b/types/resources/call.d.ts @@ -0,0 +1,446 @@ +export class CallTransferResponse { + constructor(params: object); + apiId: string; + callUuids: object; + message: string; +} +export class ListAllQueuedCalls { + constructor(params: object); + apiId: string; + calls: object; +} +export class ListAllLiveCallResponse { + constructor(params: object); + apiId: string; + callUuid: object; +} +export class CreateCallResponse { + constructor(params: object); + apiId: string; + message: string; + requestUuid: string; +} +export class GetQueuedCallResponse { + constructor(params: object); + apiId: string; + direction: string; + from: string; + callStatus: string; + to: string; + callerName: string; + callUuid: string; + requestUuid: string; +} +export class GetLiveCallResponse { + constructor(params: object); + apiId: string; + callStatus: string; + callUuid: string; + callerName: string; + direction: string; + from: string; + requestUuid: string; + sessionStart: string; + to: string; +} +export class RetrieveCallResponse { + constructor(params: object); + apiId: string; + answerTime: string; + billDuration: string; + billedDuration: string; + callDirection: string; + callDuration: string; + callState: string; + callUuid: string; + conferenceUuid: string; + endTime: string; + fromNumber: string; + hangupCauseCode: string; + hangupCauseName: string; + hangupSource: string; + initiationTime: string; + parentCallUuid: string; + resourceUri: string; + toNumber: string; + totalAmount: string; + totalRate: string; +} +export class ListAllCallsResponse { + constructor(params: object); + apiId: string; + answerTime: string; + billDuration: string; + billedDuration: string; + callDirection: string; + callDuration: string; + callState: string; + callUuid: string; + conferenceUuid: string; + endTime: string; + fromNumber: string; + hangupCauseCode: string; + hangupCauseName: string; + hangupSource: string; + initiationTime: string; + parentCallUuid: string; + resourceUri: string; + toNumber: string; + totalAmount: string; + totalRate: string; +} +export class StartPlayingMusicResponse { + constructor(params: object); + apiId: string; + message: string; +} +export class StartSpeakingTextResponse { + constructor(params: object); + apiId: string; + message: string; +} +export class SendDigitsResponse { + constructor(params: object); + apiId: string; + message: string; +} +export class RecordCallResponse { + constructor(params: object); + apiId: string; + message: string; + recordingId: string; + url: string; +} +/** + * Represents a Call + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class Call extends PlivoResource { + constructor(client: Function, data ? : {}); + id: string; + /** + * hangup call + * @method + * @promise {Boolean} return true if call hung up + * @fail {Error} return Error + */ + hangup(): Promise < any > ; + /** + * transfer call + * @method + * @param {object} params - optional params to transfer a call + * @param {string} [params.legs] aleg, bleg or both Defaults to aleg. aleg will transfer call_uuid ; bleg will transfer the bridged leg (if found) of call_uuid ; both will transfer call_uuid and bridged leg of call_uuid + * @param {string} [params.alegUrl] URL to transfer for aleg, if legs is aleg or both, then aleg_url has to be specified. + * @param {string} [params.alegMethod] HTTP method to invoke aleg_url. Defaults to POST. + * @param {string} [params.blegUrl] URL to transfer for bridged leg, if legs is bleg or both, then bleg_url has to be specified. + * @param {string} [params.blegMethod] HTTP method to invoke bleg_url. Defaults to POST. + * @promise {object} return call object + * @fail {Error} return Error + */ + transfer(params: { + legs: string; + alegUrl: string; + alegMethod: string; + blegUrl: string; + blegMethod: string; + }, callUUid: string): Promise < CallTransferResponse > ; + /** + * record call + * @method + * @param {object} params - to record call + * @promise {object} return PlivoGenericResponse Object + * @fail {Error} return Error + */ + record(params: object): Promise < any > ; + /** + * record call + * @method + * @param {object} params - to record call + * @promise {object} return PlivoGenericResponse Object + * @fail {Error} return Error + */ + startRecording(params: object): Promise < RecordCallResponse > ; + /** + * stop recording call + * @method + * @param {object} params - to stop recording call + * @promise {object} return PlivoGenericResponse Object + * @fail {Error} return Error + */ + stopRecording(params: object): Promise < any > ; + /** + * play music for call + * @method + * @param {string} url - url which contains audio to play for call + * @param {object} optionalParams - to stop recording call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + playMusic(url: string, optionalParams: object): Promise < any > ; + /** + * play music for call + * @method + * @param {string} url - url which contains audio to play for call + * @param {object} optionalParams - to stop recording call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + startPlayingMusic(urls: any, optionalParams: object): Promise < StartPlayingMusicResponse > ; + /** + * stop playing music for call + * @method + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + stopPlayingMusic(): Promise < any > ; + /** + * speak text for call + * @method + * @param {string} text - text to speak for call + * @param {object} optionalParams - to speak for call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + speakText(text: string, optionalParams: object): Promise < any > ; + /** + * speak text for call + * @method + * @param {string} text - text to speak for call + * @param {object} optionalParams - to speak for call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + startSpeakingText(text: string, optionalParams: object): Promise < StartSpeakingTextResponse > ; + /** + * stop speaking text for call + * @method + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + stopSpeakingText(): Promise < any > ; + /** + * Send digits on a call + * @method + * @param {number} digits - digits to be send + * @param {object} optionalParams - to send digits for call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + sendDigits(digits: number, optionalParams: object): Promise < SendDigitsResponse > ; + /** + * Hangup a Call Request + * @method + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + cancel(): Promise < any > ; + [clientKey]: symbol; +} +/** + * Represents a Call Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class CallInterface extends PlivoResourceInterface { + constructor(client: Function, data ? : {}); + /** + * Get A Call Detail + * @method + * @param {string} id - call uuid to get information of. + * @promise {object} returns Call Object + * @fail {Error} returns Error + */ + get(id: string): Promise < RetrieveCallResponse > ; + /** + * Get All Call Detail + * @method + * @param {object} params - params to get all call details. + * @promise {object[]} returns list of Call Object + * @fail {Error} returns Error + */ + list(params: object): Promise < ListAllCallsResponse > ; + /** + * Create a call + * @method + * @param {string} from - The phone number to be used as the caller id (with the country code).For e.g, a USA caller id number could be, 15677654321, with '1' for the country code. + * @param {string} to - The regular number(s) or sip endpoint(s) to call. Regular number must be prefixed with country code but without the + sign). For e.g, to dial a number in the USA, the number could be, 15677654321, with '1' for the country code. Multiple numbers can be sent by using a delimiter. For e.g. 15677654321<12077657621<12047657621. Sip endpoints must be prefixed with sip: E.g., sip:john1234@phone.plivo.com. To make bulk calls, the delimiter < is used. For example, 15677654321<15673464321 0(in seconds). + * @param {number} [params.hangupOnRing] Schedules the call for hangup at a specified time after the call starts ringing. Value should be an integer >= 0 (in seconds). + * @param {string} [params.machineDetection] Used to detect if the call has been answered by a machine. The valid values are true and hangup. + * @param {number} [params.machineDetectionTime] Time allotted to analyze if the call has been answered by a machine. It should be an integer >= 2000 and <= 10000 and the unit is ms. The default value is 5000 ms. + * @param {string} [params.machineDetectionUrl] A URL where machine detection parameters will be sent by Plivo. This parameter should be used to make machine detection asynchronous + * @param {string} [params.machineDetectionMethod] The HTTP method which will be used by Plivo to request the machine_detection_url. Defaults to POST. + * @param {string} [params.sipHeaders] List of SIP headers in the form of 'key=value' pairs, separated by commas. + * @param {number} [params.ringTimeout] Determines the time in seconds the call should ring. If the call is not answered within the ring_timeout value or the default value of 120s, it is canceled. + * @param {string} [params.parentCallUuid] The call_uuid of the first leg in an ongoing conference call. It is recommended to use this parameter in scenarios where a member who is already present in the conference intends to add new members by initiating outbound API calls. + * @param {boolean} [params.errorIfParentNotFound] if set to true and the parent_call_uuid cannot be found, the API request would return an error. If set to false, the outbound call API request will be executed even if the parent_call_uuid is not found. Defaults to false. + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + create(from: string, to: string, answerUrl: string, params ? : {}): Promise < CreateCallResponse > ; + /** + * Hangup A Specific Call + * @method + * @param {string} callUUID - call uuid to hangup call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + hangup(callUUID: string): Promise < any > ; + /** + * Transfer a Call + * @method + * @param {string} callUUID - call uuid to transfer call + * @param {object} params - optional params to transfer a call + * @param {string} [params.legs] aleg, bleg or both Defaults to aleg. aleg will transfer call_uuid ; bleg will transfer the bridged leg (if found) of call_uuid ; both will transfer call_uuid and bridged leg of call_uuid + * @param {string} [params.alegUrl] URL to transfer for aleg, if legs is aleg or both, then aleg_url has to be specified. + * @param {string} [params.alegMethod] HTTP method to invoke aleg_url. Defaults to POST. + * @param {string} [params.blegUrl] URL to transfer for bridged leg, if legs is bleg or both, then bleg_url has to be specified. + * @param {string} [params.blegMethod] HTTP method to invoke bleg_url. Defaults to POST. + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + transfer(callUUID: string, params: { + legs: string; + alegUrl: string; + alegMethod: string; + blegUrl: string; + blegMethod: string; + }): Promise < any > ; + /** + * Record a Call + * @method + * @param {string} callUUID - call uuid to record call + * @param {object} optionalParams - optional params to record a call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + record(callUUID: string, optionalParams: object): Promise < any > ; + /** + * Stop Recording a Call + * @method + * @param {string} callUUID - call uuid to stop recording a call + * @param {object} optionalParams - optional params to stop recording a call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + stopRecording(callUUID: string, optionalParams: object): Promise < any > ; + /** + * Play a music file + * @method + * @param {string} callUUID - call uuid to play music file + * @param {string} url - A single URL or a list of comma separated URLs linking to an mp3 or wav file. + * @param {object} optionalParams - optional params to play music file. + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + playMusic(callUUID: string, urls: any, optionalParams: object): Promise < any > ; + /** + * Stop Playing a music file + * @method + * @param {string} callUUID - call uuid to stop plaing music file + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + stopPlayingMusic(callUUID: string): Promise < any > ; + /** + * Speak text during a call + * @method + * @param {string} callUUID - call uuid to speak text during a call + * @param {string} text - text to be played. + * @param {object} optionalParams - optional params to speak text during a call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + speakText(callUUID: string, text: string, optionalParams: object): Promise < any > ; + /** + * Stop Speaking text during a call + * @method + * @param {string} callUUID - call uuid to stop speaking text during a call + * @param {object} optionalParams - optional params to stop speaking text during a call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + stopSpeakingText(callUUID: string): Promise < any > ; + /** + * Send digits on a call + * @method + * @param {string} callUUID - call uuid to send digits on a call + * @param {number} digits - digits to be send + * @param {object} optionalParams - optional params to send digits + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + sendDigits(callUUID: string, digits: number, optionalParams: object): Promise < any > ; + /** + * Hangup a call request + * @method + * @param {string} callUUID - call uuid to send digits on a call + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + cancel(id: string): Promise < any > ; + listLiveCalls(params: object): Promise < any > ; + getLiveCall(id: string): Promise < any > ; + listQueuedCalls(): Promise < any > ; + getQueuedCall(id: string): Promise < any > ; + [clientKey]: symbol; + [liveCallInterfaceKey]: LiveCallInterface; + [queuedCallInterfaceKey]: QueuedCallInterface; +} +export class LiveCallResource extends PlivoResource { + constructor(client: Function, data ? : {}); + id: string; + [clientKey]: symbol; +} +export class QueuedCallResource extends PlivoResource { + constructor(client: Function, data ? : {}); + id: string; + [clientKey]: symbol; +} +import { + PlivoResource +} from "../base"; +declare const clientKey: unique symbol; +import { + PlivoResourceInterface +} from "../base"; +declare const liveCallInterfaceKey: unique symbol; +/** + * Represents a LiveCall interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +declare class LiveCallInterface extends PlivoResourceInterface { + constructor(client: Function, data ? : {}); + [clientKey]: symbol; +} +declare const queuedCallInterfaceKey: unique symbol; +/** + * Represents a QueuedCall interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ + +declare class QueuedCallInterface extends PlivoResourceInterface { + constructor(client: Function, data ? : {}); + get(id: string): Promise < GetQueuedCallResponse > ; + list(): Promise < ListAllQueuedCalls > ; + [clientKey]: symbol; +} +export {}; \ No newline at end of file diff --git a/types/resources/callFeedback.d.ts b/types/resources/callFeedback.d.ts new file mode 100644 index 0000000..a662df3 --- /dev/null +++ b/types/resources/callFeedback.d.ts @@ -0,0 +1,26 @@ +export class CallFeedbackResponse { + constructor(params: object); + apiId: string; + message: string; + status: string; +} +export class CallFeedback extends PlivoResource { + constructor(client: Function, data?: {}); + id: string; + [clientKey]: symbol; +} +/** + * Represents a CallFeedback Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class CallFeedbackInterface extends PlivoResourceInterface { + constructor(client: Function, data?: {}); + create(callUUID: string, rating: string, issues?: never[], notes?: string): Promise; + [clientKey]: symbol; +} +import { PlivoResource } from "../base"; +declare const clientKey: unique symbol; +import { PlivoResourceInterface } from "../base"; +export {}; diff --git a/types/resources/complianceApplications.d.ts b/types/resources/complianceApplications.d.ts new file mode 100644 index 0000000..37b3a7d --- /dev/null +++ b/types/resources/complianceApplications.d.ts @@ -0,0 +1,146 @@ +export class ComplianceApplicationResponse { + constructor(params: object); + apiId: string; + complianceApplicationId: string; + endUserID: string; + endUserType: string; + alias: string; + status: string; + countryIso2: string; + numberType: string; + complianceRequirementId: string; + documents: Array; + createdAt: string; +} + +export class CreateComplianceApplicationResponse { + constructor(params: object); + apiId: string; + complianceApplicationId: string; + endUserID: string; + endUserType: string; + alias: string; + status: string; + countryIso2: string; + numberType: string; + complianceRequirementId: string; + documents: Array; + createdAt: string; + message: string; +} + +export class UpdateComplianceApplicationResponse { + constructor(params: object); + apiId: string; + message: string; +} + +export class ListComplianceApplicationResponse { + constructor(params: object); + apiId: string; + meta: Object; + objects: Array; +} + +/** +* Represents a ComplianceApplication +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ +export class ComplianceApplication extends PlivoResource { + constructor(client: Function, data?: {}); + id: string; + + /** + * update ComplianceApplication + * @method + * @param {string} id - id to update + * @param {object} params + * @param {string} [params.documentIds] - Document IDs + * @promise {object} return {@link ComplianceApplication} object if success + * @fail {Error} return Error + */ + update(params: object, id: string): Promise; + + /** + * delete an Compliance application + * @method + * @param {string} id - id to delete + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + delete(): Promise; + [clientKey]: symbol; +} + +/** +* Represents a ComplianceApplication Interface +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ +export class ComplianceApplicationInterface extends PlivoResourceInterface { + constructor(client: Function, data?: {}); + /** + * get application by given id + * @method + * @param {string} id - id of application + * @promise {object} return {@link EndUser} object + * @fail {Error} return Error + */ + get(id: string): Promise; + + /** + * list all applications + * @method + * @param {object} params - params to list endusers + * @param {string} [params.status] - Status of the application + * @param {string} [params.endUserId] - End user ID related to application + * @param {string} [params.numberType] -Number Type related to application + * @param {integer} [params.offset] - No of value items by which results should be offset + * @param {integer} [params.limit] - No of value items by which results should be offset + */ + list(params: object): Promise; + + /** + * Create a complaince application + * @method + * @param {object} params + * @param {string} [params.complianceRequirementId] - compliance requirement ID. + * @param {string} [params.endUserId] - End user ID. + * @param {string} [params.alias] - Alias + * @param {string} [params.documentIds] - Document IDs + * @param {string} [params.endUserType] - End user type + * @param {string} [params.countryIso2] - CountryISo2 + * @param {string} [params.numberType] - Number Type + * @fail {Error} return Error + */ + create(params: object): Promise; + + /** + * update ComplianceApplication + * @method + * @param {string} id - id to update + * @param {object} params + * @param {string} [params.documentIds] - Document IDs + * @promise {object} return {@link ComplianceApplication} object if success + * @fail {Error} return Error + */ + update(id: string, params: object): Promise; + + /** + * delete a ComplianceApplication + * @method + * @param {string} id - id to delete + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + delete(id: string): any; + [clientKey]: symbol; +} + +import { PlivoResource } from "../base"; +declare const clientKey: unique symbol; +import { PlivoResourceInterface } from "../base"; +export {}; diff --git a/types/resources/complianceDocumentTypes.d.ts b/types/resources/complianceDocumentTypes.d.ts new file mode 100644 index 0000000..2f30b50 --- /dev/null +++ b/types/resources/complianceDocumentTypes.d.ts @@ -0,0 +1,65 @@ +export class ComplianceDocumentTypeResponse { + constructor(params: object); + apiId: string; + documentTypeID: string; + documentName: string; + description: string; + information: object; + proofRequired: string; + createdAt: string; +} + +export class ListComplianceDocumentTypeResponse { + constructor(params: object); + apiId: string; + objects: Array; + meta: Object; +} + +/** +* Represents a Compliance Document Type. +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ +export class ComplianceDocumentType extends PlivoResource { + constructor(client: Function, data?: {}); + [clientKey]: symbol; +} + +/** +* Represents a ComplianceDocumentTypeInterface Interface +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ +export class ComplianceDocumentTypeInterface extends PlivoResourceInterface { + constructor(client: Function, data?: {}); + + /** + * get compliance document types by id + * @method + * @param {string} id - id of the compliane document type. + * @promise {object} return {@link ComplianceDocumentType} object + * @fail {Error} return Error + */ + get(id: string): Promise; + + + /** + * list compliance document types + * @method + * @param {object} params - params to list endusers + * @param {string} [params.documentTypeID] - Document Type ID of the document id. + * @param {string} [params.documentName] - Document name of the document if present. + * @param {string} [params.description] - Description of the document type. + * @param {string} [params.information] - Information about the document type. + * @param {string} [params.proofRequired] - Proofs required for the document. + */ + list(params: object): Promise; +} + +import { PlivoResource } from "../base"; +declare const clientKey: unique symbol; +import { PlivoResourceInterface } from "../base"; +export {}; diff --git a/types/resources/complianceDocuments.d.ts b/types/resources/complianceDocuments.d.ts new file mode 100644 index 0000000..cb2b8ee --- /dev/null +++ b/types/resources/complianceDocuments.d.ts @@ -0,0 +1,134 @@ +export class ComplianceDocumentResponse { + constructor(params: object); + apiId: string; + documentTypeId: string; + complianceDocumentId: string; + documentId: string; + alias: string; + metaInformation: string; + file: string; + fileName: string; + createdAt: string; +} + +export class CreateComplianceDocumentResponse { + constructor(params: object); + apiId: string; + documentTypeId: string; + complianceDocumentId: string; + documentId: string; + endUserId: string; + alias: string; + message: string; + metaInformation: string; + fileName: string; + createdAt: string; +} + +export class ListComplianceDocumentResponse { + constructor(params: object); + apiId: string; + meta: Object; + objects: Array; +} + +export class UpdateComplianceDocumentResponse { + constructor(params: object); + apiId: string; + message: string; +} +/** +* Represents a Compliance Document +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ +export class ComplianceDocument extends PlivoResource { + constructor(client: Function, data?: {}); + id: string; + + /** + * update Compliance Document + * @method + * @param {string} id - compliance document id of the document. + * @param {object} params - optional params array of updated values + * @promise {object} return {@link ComplianceDocument} object if success + * @fail {Error} return Error + */ + update(params: object, id: string): Promise; + + /** + * delete an Compliance Document + * @method + * @param {string} id - id to delete + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + delete(): Promise; + [clientKey]: symbol; +} + +/** +* Represents a ComplianceDocument Interface +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ +export class ComplianceDocumentInterface extends PlivoResourceInterface { + constructor(client: Function, data?: {}); + + /** + * get compliance document by given id + * @method + * @param {string} id - id of the document + * @promise {object} return {@link ComplianceDocument} object + * @fail {Error} return Error + */ + get(id: string): Promise; + + + /** + * list all documents + * @method + * @param {object} params - params containing options to list compliance documents by. + */ + list(params: object): Promise; + + /** + * Create a complaince document + * @method + * @param {object} params + * @param {string} [params.complianceRequirementId] - compliance requirement ID. + * @param {string} [params.endUserId] - End user ID. + * @param {string} [params.alias] - Alias + * @param {string} [params.documentTypeId] - Document Type ID + * @param {string} [params.file] - File array of the files to be uploaded + * @fail {Error} return Error + */ + create(params: object): Promise; + + /** + * update Compliance Document + * @method + * @param {string} id - compliance document id of the document. + * @param {object} params - optional params array of updated values + * @promise {object} return {@link ComplianceDocument} object if success + * @fail {Error} return Error + */ + update(id: string, params: object): Promise; + + /** + * delete a Compliance Document + * @method + * @param {string} id - id to delete + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + delete(id: string): any; + [clientKey]: symbol; +} + +import { PlivoResource } from "../base"; +declare const clientKey: unique symbol; +import { PlivoResourceInterface } from "../base"; +export {}; diff --git a/types/resources/complianceRequirements.d.ts b/types/resources/complianceRequirements.d.ts new file mode 100644 index 0000000..c60b44f --- /dev/null +++ b/types/resources/complianceRequirements.d.ts @@ -0,0 +1,58 @@ +export class ComplianceRequirementResponse { + constructor(params: object); + apiId: string; + ComplianceRequirementId: string; + countryIso2: string; + numberType: string; + endUserType: object; + acceptableDocumentTypes: string; +} + +/** +* Represents a Compliance Requirement +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ +export class ComplianceRequirement extends PlivoResource { + constructor(client: Function, data?: {}); + [clientKey]: symbol; +} + +/** + * Represents a Compliance Requirement + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class ComplianceRequirementInterface extends PlivoResourceInterface { + constructor(client: Function, data?: {}); + + /** + * get compliance requirement by given id + * @method + * @param {string} id - id of the compliance requirement + * @promise {object} return {@link ComplianceRequirement} object + * @fail {Error} return Error + */ + get(id: string): Promise; + + + /** + * list compliance requirements + * @method + * @param {object} params - params to list endusers + * @param {string} [params.countryIso2] - Document Type ID of the document id. + * @param {string} [params.numberType] - Document name of the document if present. + * @param {string} [params.phoneNumber] - Description of the document type. + * @param {string} [params.endUserType] - Information about the document type. + * A combination of country_iso2, number_type, end_user_type OR + * phone_number, end_user_type can be used to fetch compliance requirements. + */ + list(params: object): Promise; +} + +import { PlivoResource } from "../base"; +declare const clientKey: unique symbol; +import { PlivoResourceInterface } from "../base"; +export {}; diff --git a/types/resources/conferences.d.ts b/types/resources/conferences.d.ts new file mode 100644 index 0000000..c80e695 --- /dev/null +++ b/types/resources/conferences.d.ts @@ -0,0 +1,397 @@ +/** +* Represents a Conference +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ +export class MuteMemberResponse { + constructor(params: object); + apiId: string; + memberId: string; + message: string; +} +export class StartRecordingConferenceResponse { + constructor(params: object); + apiId: string; + message: string; + recordingId: string; + url: string; +} +export class RetrieveConferenceResponse { + constructor(params: object); + apiId: string; + conferenceMemberCount: string; + conferenceName: string; + conferenceRunTime: string; + members: string; +} +export class ListAllConferenceResponse { + constructor(params: object); + apiId: string; + conferences: string; +} +export class SpeakMemberResponse { + constructor(params: object); + apiId: string; + memberId: string; + message: string; +} +export class PlayAudioMemberResponse { + constructor(params: object); + apiId: string; + memberId: string; + message: string; +} +export class DeafMemberResponse { + constructor(params: string); + apiId: string; + memberId: string; + message: string; +} +export class Conference extends PlivoResource { + constructor(client: Function, data?: {}); + id: string; + /** + * hangup conference + * @method + * @promise {Boolean} return true if call hung up + * @fail {Error} return Error + */ + hangup(): Promise; + /** + * hangup member from conference + * @method + * @param {string} memberId - id of member to be hangup + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + hangupMember(memberId: string): Promise; + /** + * kick member from conference + * @method + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + kickMember(memberId: string): Promise; + /** + * mute member from conference + * @method + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + muteMember(memberId: string): Promise; + /** + * unmute member from conference + * @method + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + unmuteMember(memberId: string): Promise; + /** + * deaf member from conference + * @method + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + deafMember(memberId: string): Promise; + /** + * undeaf member from conference + * @method + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + undeafMember(memberId: string): Promise; + /** + * play audio to member + * @method + * @param {string} memberId - id of member + * @param {string} url - url for audio + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + playAudioToMember(memberId: string, url: string): Promise; + /** + * stop playing audio to member + * @method + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + stopPlayingAudioToMember(memberId: string): Promise; + /** + * speak text to member + * @method + * @param {string} memberId - id of member + * @param {string} text - text to be speak to member + * @param {object} optionalParams - optionalPrams to speak text + * @param {string} [optionalParams.voice] The voice to be used. Can be MAN or WOMAN. Defaults to WOMAN. + * @param {string} [optionalParams.language] The language to be used. Defaults to en-US. + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + speakTextToMember(memberId: string, text: string, optionalParams: { + voice: string; + language: string; + }): Promise; + /** + * stop speaking text to member + * @method + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + stopSpeakingTextToMember(memberId: string): Promise; + /** + * Record conference + * @method + * @param {object} params - optional params to record conference + * @param {string} [params.fileFormat] The file format of the record can be of mp3 or wav format. Defaults to mp3 format. + * @param {string} [params.transcriptionType] The type of transcription required. The following values are allowed: + * - auto - This is the default value. Transcription is completely automated; turnaround time is about 5 minutes. + * - hybrid - Transcription is a combination of automated and human verification processes; turnaround time is about 10-15 minutes. + * @param {string} [params.transcriptionUrl] The URL where the transcription is available. + * @param {string} [params.transcriptionMethod] The method used to invoke the transcription_url. Defaults to POST. + * @param {string} [params.callbackUrl] The URL invoked by the API when the recording ends. + * @param {string} [params.callbackMethod] The method which is used to invoke the callback_url URL. Defaults to POST. + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + record(params: { + fileFormat: string; + transcriptionType: string; + transcriptionUrl: string; + transcriptionMethod: string; + callbackUrl: string; + callbackMethod: string; + }): Promise; + /** + * Record conference + * @method + * @param {object} params - optional params to record conference + * @param {string} [params.fileFormat] The file format of the record can be of mp3 or wav format. Defaults to mp3 format. + * @param {string} [params.transcriptionType] The type of transcription required. The following values are allowed: + * - auto - This is the default value. Transcription is completely automated; turnaround time is about 5 minutes. + * - hybrid - Transcription is a combination of automated and human verification processes; turnaround time is about 10-15 minutes. + * @param {string} [params.transcriptionUrl] The URL where the transcription is available. + * @param {string} [params.transcriptionMethod] The method used to invoke the transcription_url. Defaults to POST. + * @param {string} [params.callbackUrl] The URL invoked by the API when the recording ends. + * @param {string} [params.callbackMethod] The method which is used to invoke the callback_url URL. Defaults to POST. + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + startRecording(params?: { + fileFormat: string; + transcriptionType: string; + transcriptionUrl: string; + transcriptionMethod: string; + callbackUrl: string; + callbackMethod: string; + }): Promise; + /** + * stop recording conference + * @method + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + stopRecording(): Promise; + [clientKey]: symbol; +} +/** +* Represents a Conference Interface +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ +export class ConferenceInterface extends PlivoResourceInterface { + constructor(client: Function, data?: {}); + + /** + * get conference by id + * @method + * @param {string} id - id of conference + * @promise {@link Conference} return {@link Conference} object if success + * @fail {Error} return Error + */ + get(id: string): Promise; + /** + * get all conferences. returns name of all conferences + * @method + * @promise {@link [Conference]} returns list of {@link Conference} objects if success + * @fail {Error} return Error + */ + list(): Promise; + /** + * hangup conference + * @method + * @param {string} conferenceName - name of conference + * @promise {@link Conference} return {@link Conference} object if success + * @fail {Error} return Error + */ + hangup(conferenceName: string): Promise; + /** + * hangup all + * @method + * @promise {@link PlivoGenericResponse} returns object of PlivoGenericResponse if success + * @fail {Error} return Error + */ + hangupAll(): Promise; + /** + * hangup member from conference + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member to be hangup + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + hangupMember(id: string, memberId: string): Promise; + /** + * kick member from conference + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + kickMember(id: string, memberId: string): Promise; + /** + * mute member + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + muteMember(id: string, memberId: string): Promise; + /** + * unmute member + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + unmuteMember(id: string, memberId: string): Promise; + /** + * deaf member + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + deafMember(id: string, memberId: string): Promise; + /** + * undeaf member + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + undeafMember(id: string, memberId: string): Promise; + /** + * play audio to member + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member + * @param {string} url - urls for audio + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + playAudioToMember(id: string, memberId: string, url: string): Promise; + /** + * stop playing audio to member + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + stopPlayingAudioToMember(id: string, memberId: string): Promise; + /** + * speak text to member + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member + * @param {string} text - text to speak + * @param {object} optionalParams - optional params + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + speakTextToMember(id: string, memberId: string, text: string, optionalParams: object): Promise; + /** + * stop speaking text to member + * @method + * @param {string} id - id of conference + * @param {string} memberId - id of member + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + stopSpeakingTextToMember(id: string, memberId: string): Promise; + /** + * record conference + * @method + * @param {string} id - id of conference + * @param {object} params - optional params to record conference + * @param {string} [params.fileFormat] The file format of the record can be of mp3 or wav format. Defaults to mp3 format. + * @param {string} [params.transcriptionType] The type of transcription required. The following values are allowed: + * - auto - This is the default value. Transcription is completely automated; turnaround time is about 5 minutes. + * - hybrid - Transcription is a combination of automated and human verification processes; turnaround time is about 10-15 minutes. + * @param {string} [params.transcriptionUrl] The URL where the transcription is available. + * @param {string} [params.transcriptionMethod] The method used to invoke the transcription_url. Defaults to POST. + * @param {string} [params.callbackUrl] The URL invoked by the API when the recording ends. + * @param {string} [params.callbackMethod] The method which is used to invoke the callback_url URL. Defaults to POST. + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + record(id: string, params: { + fileFormat: string; + transcriptionType: string; + transcriptionUrl: string; + transcriptionMethod: string; + callbackUrl: string; + callbackMethod: string; + }): Promise; + /** + * record conference + * @method + * @param {string} id - id of conference + * @param {object} params - optional params to record conference + * @param {string} [params.fileFormat] The file format of the record can be of mp3 or wav format. Defaults to mp3 format. + * @param {string} [params.transcriptionType] The type of transcription required. The following values are allowed: + * - auto - This is the default value. Transcription is completely automated; turnaround time is about 5 minutes. + * - hybrid - Transcription is a combination of automated and human verification processes; turnaround time is about 10-15 minutes. + * @param {string} [params.transcriptionUrl] The URL where the transcription is available. + * @param {string} [params.transcriptionMethod] The method used to invoke the transcription_url. Defaults to POST. + * @param {string} [params.callbackUrl] The URL invoked by the API when the recording ends. + * @param {string} [params.callbackMethod] The method which is used to invoke the callback_url URL. Defaults to POST. + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + startRecording(id: string, params: { + fileFormat: string; + transcriptionType: string; + transcriptionUrl: string; + transcriptionMethod: string; + callbackUrl: string; + callbackMethod: string; + }): Promise; + /** + * stop recording + * @method + * @param {string} id - id of conference + * @promise {PlivoGenericResponse} return PlivoGenericResponse if success + * @fail {Error} return Error + */ + stopRecording(id: string): Promise; + [clientKey]: symbol; +} +import { PlivoResource } from "../base"; +declare const clientKey: unique symbol; +import { PlivoResourceInterface } from "../base"; +export {}; diff --git a/types/resources/endUsers.d.ts b/types/resources/endUsers.d.ts new file mode 100644 index 0000000..fbdca55 --- /dev/null +++ b/types/resources/endUsers.d.ts @@ -0,0 +1,131 @@ +export class EndUsersResponse { + constructor(params: object); + apiId: string; + endUserId: string; + endUserType: string; + name: string; + lastName: string; + createdAt: string; +} + +export class CreateEndUsersResponse { + constructor(params: object); + apiId: string; + endUserId: string; + endUserType: string; + name: string; + lastName: string; + createdAt: string; + message: string; +} + +export class UpdateEndUsersResponse { + constructor(params: object); + apiId: string; + message: string; +} + +export class ListEndUsersResponse { + constructor(params: object); + apiId: string; + meta: Object; + objects: Array; +} + +/** +* Represents an EndUser +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ +export class EndUser extends PlivoResource { + constructor(client: Function, data?: {}); + id: string; + /** + * update end user + * @method + * @param {object} params - to update end user + * @param {string} [params.name] - Name of the endUser if present. + * @param {string} [params.last_name] - Last name of the endUser if present. + * @param {string} [params.end_user_type] - Type of the end user. + * @fail {Error} return Error + */ + + update(params: object, id: string): Promise; + /** + * delete EndUser + * @method + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + delete(): Promise; + [clientKey]: symbol; +} + +/** +* Represents a EndUser Interface +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ +export class EndUserInterface extends PlivoResourceInterface { + constructor(client: Function, data?: {}); + /** + * get EndUser by given id + * @method + * @param {string} id - id of the end user. + * @promise {object} return {@link EndUser} object + * @fail {Error} return Error + */ + get(id: string): Promise; + + + /** + * list endUsers + * @method + * @param {object} params - params to list endusers + * @param {string} [params.name] - Name of the endUser if present. + * @param {string} [params.last_name] - Last name of the endUser if present. + * @param {string} [params.end_user_type] - Type of the end user. + * @param {integer} [params.offset] - No of value items by which results should be offset + * @param {integer} [params.limit] - No of value items by which results should be offset + */ + list(params: object): Promise; + + /** + * Create end user + * @method + * @param {object} params - to update end user + * @param {string} [params.name] - Name of the endUser if present. + * @param {string} [params.last_name] - Last name of the endUser if present. + * @param {string} [params.end_user_type] - Type of the end user. + * @fail {Error} return Error + */ + create(params: object): Promise; + + /** + * update end user + * @method + * @param {object} params - to update end user + * @param {string} [params.name] - Name of the endUser if present. + * @param {string} [params.last_name] - Last name of the endUser if present. + * @param {string} [params.end_user_type] - Type of the end user. + * @fail {Error} return Error + */ + update(id: string, params: object): Promise; + + /** + * delete an EndUser + * @method + * @param {string} id - id to delete + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + delete(id: string): any; + [clientKey]: symbol; +} + +import { PlivoResource } from "../base"; +declare const clientKey: unique symbol; +import { PlivoResourceInterface } from "../base"; +export {}; diff --git a/types/resources/endpoints.d.ts b/types/resources/endpoints.d.ts new file mode 100644 index 0000000..09ba026 --- /dev/null +++ b/types/resources/endpoints.d.ts @@ -0,0 +1,125 @@ +export class UpdateEndpointResponse { + constructor(params: object); + apiId: string; + message: string; + alias: string; +} +export class RetrieveEndpointResponse { + constructor(params: object); + apiId: string; + alias: string; + application: string; + endpointId: string; + password: string; + resourceUri: string; + sipRegistered: string; + sipUri: string; + subAccount: string; + username: string; +} +export class ListAllEndpointResponse { + constructor(params: object); + apiId: string; + alias: string; + application: string; + endpointId: string; + password: string; + resourceUri: string; + sipRegistered: string; + sipUri: string; + subAccount: string; + username: string; +} +export class CreateEndpointResponse { + constructor(params: object); + alias: string; + apiId: string; + endpointId: string; + message: string; + username: string; +} +/** +* Represents a Endpoint +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ +export class Endpoint extends PlivoResource { + constructor(client: Function, data?: {}); + id: string; + /** + * update Endpoint + * @method + * @param {object} params + * @param {string} [params.username] - username to update + * @param {string} [params.password] - password to update + * @param {string} [params.alias] - alias to update + * @param {string} [params.appId] - app id to update + * @promise {object} return {@link Endpoint} object if success + * @fail {Error} return Error + */ + update(params: object, id: string): Promise; + /** + * delete Endpoint + * @method + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + delete(): Promise; + [clientKey]: symbol; +} +/** +* Represents a Endpoint Interface +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ +export class EndpointInterface extends PlivoResourceInterface { + constructor(client: Function, data?: {}); + /** + * Get Endpoint by given id + * @method + * @param {string} id - id of endpoint + * @promise {object} return {@link Endpoint} object if success + * @fail {Error} return Error + */ + get(id: string): Promise; + list(): Promise; + /** + * Create Endpoint + * @method + * @param {string} username - username to create + * @param {string} passwowrd - password to create + * @param {string} alias - alias to create + * @param {string} appId - app id to create + * @promise {object} return {@link PlivoGenericResponse} object if success + * @fail {Error} return Error + */ + create(username: string, password: string, alias: string, appId: string): Promise; + /** + * update Endpoint + * @method + * @param {string} id - id to update + * @param {object} params + * @param {string} [params.username] - username to update + * @param {string} [params.password] - password to update + * @param {string} [params.alias] - alias to update + * @param {string} [params.appId] - app id to update + * @promise {object} return {@link Endpoint} object if success + * @fail {Error} return Error + */ + update(id: string, params: object): Promise; + /** + * delete Endpoint + * @method + * @param {string} id - id to delete + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + delete(id: string): any; + [clientKey]: symbol; +} +import { PlivoResource } from "../base"; +declare const clientKey: unique symbol; +import { PlivoResourceInterface } from "../base"; +export {}; diff --git a/types/resources/lookup.d.ts b/types/resources/lookup.d.ts new file mode 100644 index 0000000..9d4fbcd --- /dev/null +++ b/types/resources/lookup.d.ts @@ -0,0 +1,22 @@ +export class LookupResponse { + constructor(params: object); + apiId: string; + phoneNumber: string; + country: object; + format: object; + carrier: object; + resourceUri: string; +} +export class Number extends PlivoResource { + constructor(client: Function, data?: {}); + [clientKey]: symbol; +} +export class LookupInterface extends PlivoResourceInterface { + constructor(client: Function, data?: {}); + get(number: string, type?: string): Promise; + [clientKey]: symbol; +} +import { PlivoResource } from "../base"; +declare const clientKey: unique symbol; +import { PlivoResourceInterface } from "../base"; +export {}; diff --git a/types/resources/media.d.ts b/types/resources/media.d.ts new file mode 100644 index 0000000..fe251e5 --- /dev/null +++ b/types/resources/media.d.ts @@ -0,0 +1,71 @@ +export class UploadMediaResponse { + constructor(params: object); + apiId: string; + objects: object; +} +export class RetrieveMediaResponse { + constructor(params: object); + apiId: string; + contentType: string; + fileName: string; + mediaId: string; + mediaUrl: string; + size: string; + uploadTime: string; +} +export class ListMediaResponse { + constructor(params: object); + apiId: string; + meta: string; + objects: string; +} +/** + * Represents a Message + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class Media extends PlivoResource { + constructor(client: Function, data ? : {}); + id: string; +} +/** + * Represents a Media Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class MediaInterface extends PlivoResourceInterface { + constructor(client: Function, data ? : {}); + /** + * Upload Media + * @method + * @fail {Error} return Error + */ + upload(files: Array): Promise; + /** + * Get Media by given id + * @method + * @param {string} media_id - id of media + * @promise {object} return {@link Media} object if success + * @fail {Error} return Error + */ + get(media_id: string): Promise; + /** + * Get All Media Detail + * @method + * @param {object} params - params to get all media details. + * @promise {object[]} returns list of Media Object + * @fail {Error} returns Error + */ + list(params: object): Promise; + [clientKey]: symbol; +} +import { + PlivoResource +} from "../base"; +import { + PlivoResourceInterface +} from "../base"; +declare const clientKey: unique symbol; +export {}; \ No newline at end of file diff --git a/types/resources/messages.d.ts b/types/resources/messages.d.ts new file mode 100644 index 0000000..6d6b37d --- /dev/null +++ b/types/resources/messages.d.ts @@ -0,0 +1,122 @@ +export class MessageResponse { + constructor(params: object); + apiId: string; + message: string; + messageUuid: string; +} +export class MessageGetResponse { + constructor(params: object); + apiId: string; + errorCode: string; + fromNumber: string; + messageDirection: string; + messageState: string; + messageTime: string; + messageType: string; + messageUuid: string; + resourceUri: string; + toNumber: string; + totalAmount: string; + totalRate: string; + units: string; +} +export class MessageListResponse { + constructor(params: object); + errorCode: string; + fromNumber: string; + messageDirection: string; + messageState: string; + messageTime: string; + messageType: string; + messageUuid: string; + resourceUri: string; + toNumber: string; + totalAmount: string; + totalRate: string; + units: string; +} +export class MMSMediaResponse { + constructor(params: object); + apiid: string; + objects: MMSMedia[]; +} +export class MMSMedia { + constructor(params: object); + contentType: string; + fileName: string; + mediaId: string; + mediaUrl: string; + messageUuid: string; + size: string; + uploadTime: string; +} +/** + * Represents a Message + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class Message extends PlivoResource { + constructor(client: Function, data ? : {}); + id: string; + listMedia(): Promise < any > ; +} +/** + * Represents a Message Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class MessageInterface extends PlivoResourceInterface { + constructor(client: Function, data?: {}); + /** + * Send Message + * @method + * @param {string} src - source number + * @param {string} dst - destination number + * @param {string} text - text to send + * @param {object} optionalParams - Optional Params to send message + * @param {string} [optionalParams.type] - The type of message. Should be `sms` or `mms`. Defaults to `sms`. + * @param {string} [optionalParams.url] The URL to which with the status of the message is sent. + * @param {string} [optionalParams.method] The method used to call the url. Defaults to POST. + * @param {list} [optionalParams.media_urls] For sending mms, specify the media urls in list of string + * @param {boolean} [optionalParams.log] If set to false, the content of this message will not be logged on the Plivo infrastructure and the dst value will be masked (e.g., 141XXXXX528). Default is set to true. + * @promise {object} return {@link PlivoGenericMessage} object if success + * @fail {Error} return Error + */ + send(src: string, dst: string, text: string, optionalParams?: { + type: string; + url: string; + method: string; + media_urls: Array; + log: boolean; + }): Promise < MessageResponse > ; + /** + * Create Message + * @method + * @param {string} src - source number + * @param {string} dst - destination number + * @param {string} text - text to send + * @param {object} optionalParams - Optional Params to send message + * @param {string} [optionalParams.type] - The type of message. Should be `sms` or `mms`. Defaults to `sms`. + * @param {string} [optionalParams.url] The URL to which with the status of the message is sent. + * @param {string} [optionalParams.method] The method used to call the url. Defaults to POST. + * @param {boolean} [optionalParams.log] If set to false, the content of this message will not be logged on the Plivo infrastructure and the dst value will be masked (e.g., 141XXXXX528). Default is set to true. + * @param {Array} [optionalParams.media_urls] For sending mms, specify the media urls in list of string + * @promise {object} return {@link MessageResponse} object if success + * @fail {Error} return Error + */ + create(src: any, dst: any, text: string, optionalParams?: object, powerpackUUID?: string ): Promise < MessageResponse >; + + get(id: string): Promise; + + list(params: object): Promise < MessageListResponse> ; + + listMedia(messageUUID: string): Promise ; +} +import { + PlivoResource +} from "../base"; +import { + PlivoResourceInterface +} from "../base"; \ No newline at end of file diff --git a/types/resources/numbers.d.ts b/types/resources/numbers.d.ts new file mode 100644 index 0000000..19cceca --- /dev/null +++ b/types/resources/numbers.d.ts @@ -0,0 +1,161 @@ +export class BuyNumberResponse { + constructor(params: object); + apiId: string; + numbers: object; + status: string; +} +export class UpdateNumberResponse { + constructor(params: object); + apiId: string; + message: string; +} + +export class SearchNumberResponse { + constructor(params: object); + number: string; + prefix: string; + city: string; + country: string; + region: string; + rate_center: string; + lata: number; + type: string; + sub_type: string; + setup_rate: string; + monthly_rental_rate: string; + sms_enabled: boolean; + sms_rate: string; + voice_enabled: boolean; + voice_rate: string; + restriction: string; + restriction_text: string; + resource_uri: string; +} + +/** + * Represents a PhoneNumber + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class PhoneNumber extends PlivoResource { + constructor(client: Function, data ? : {}); + id: string; + /** + * Buy Phone Number + * @method + * @param {string} appId - app id + * @promise {@link PlivoGenericResponse} return PlivoGenericResponse Object if success + * @fail {Error} return Error + */ + buy(appId: string): Promise < any > ; + [clientKey]: symbol; +} +/** + * Represents a PhoneNumbers Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + * @param {string} [data.test] - test data + */ +export class PhoneNumberInterface extends PlivoResourceInterface { + constructor(client: Function, data ? : {}); + /** + * Buy Phone Number + * @method + * @param {string} appId - app id + * @promise {@link PlivoGenericResponse} return PlivoGenericResponse Object if success + * @fail {Error} return Error + */ + buy(number: string, appId: string): Promise < any > ; + [clientKey]: symbol; +} +/** + * Represents a Number + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class NumberResource extends PlivoResource { + constructor(client: Function, data ? : {}); + id: string; + /** + * Unrent Number + * @method + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + unrent(number: string): Promise < any > ; + [clientKey]: symbol; +} +/** + * Represents a Numbers + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class NumberInterface extends PlivoResourceInterface { + constructor(client: Function); + /** + * Buy Phone Number + * @method + * @param {string} number - number to buy + * @param {string} appId - app id + * @promise {@link PlivoGenericResponse} return PlivoGenericResponse Object if success + * @fail {Error} return Error + */ + buy(number: string, appId: string): Promise < BuyNumberResponse > ; + /** + * Add own number from carrier + * @method + * @param {string} numbers - A comma separated list of numbers that need to be added for the carrier. + * @param {string} carrier - The carrier_id of the IncomingCarrier that the number is associated with. + * @param {string} region - region that is associated with the Number + * @param {string} optionaParams - optional params + * @promise {@link PlivoGenericResponse} return PlivoGenericResponse Object if success + * @fail {Error} return Error + */ + addOwnNumber(numbers: string, carrier: string, region: string, optionalParams: object): Promise < UpdateNumberResponse > ; + /** + * Add own number from carrier + * @method + * @param {string} countryISO - The ISO code A2 of the country + * @param {string} optionaParams - optional params + * @promise {@link PhoneNumberInterface} return PhoneNumbers Object if success + * @fail {Error} return Error + */ + search(countryISO: string, optionalParams: object): Promise < SearchNumberResponse > ; + /** + * Update Number + * @method + * @param {string} number - number to update + * @param {object} params + * @param {string} [params.appId] - app id + * @param {string} [params.subAccount] - auth_id of subaccount + * @param {string} [params.alias] - textual name of number + * @promise {@link NumberResource} return NumberResource Object if success + * @fail {Error} return Error + */ + update(number: string, params: { + appId: string; + subAccount: string; + alias: string; + }): Promise < UpdateNumberResponse > ; + /** + * Unrent Number + * @method + * @param {string} number - number to unrent + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + unrent(number: string): Promise < any > ; + [clientKey]: symbol; +} +import { + PlivoResource +} from "../base"; +declare const clientKey: unique symbol; +import { + PlivoResourceInterface +} from "../base"; +export {}; \ No newline at end of file diff --git a/types/resources/phlo.d.ts b/types/resources/phlo.d.ts new file mode 100644 index 0000000..8bc5c26 --- /dev/null +++ b/types/resources/phlo.d.ts @@ -0,0 +1,54 @@ +export class RunPHLOResponse { + constructor(params: object); + apiid: string; + phloid: string; + message: string; +} +export class RetrievePHLOResponse { + constructor(params: object); + apiid: string; + phloid: string; + name: string; + createdOn: string; +} +/** + * Represents a Phlo + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of phlo + */ +export class Phlo extends PlivoResource { + constructor(client: Function, data ? : {}); + client: Function; + multiPartyCall: (nodeid: string) => PhloMultiPartyCall; + /** + * run phlo + * @method + * @promise {Boolean} return true if phlo is complete + * @fail {Error} return Error + */ + run(params: object): Promise < RunPHLOResponse > ; + [clientKey]: symbol; +} +/** + * Represents a Phlo Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class PhloInterface extends PlivoResourceInterface { + constructor(client: Function, data?: {}); + get(id: string): Promise; + [clientKey]: symbol; +} +import { + PlivoResource +} from "../base"; +import { + PhloMultiPartyCall +} from "./phloMultipartyCall"; +declare const clientKey: unique symbol; +import { + PlivoResourceInterface +} from "../base"; +export {}; \ No newline at end of file diff --git a/types/resources/phloMultiPartyCallMember.d.ts b/types/resources/phloMultiPartyCallMember.d.ts new file mode 100644 index 0000000..73a7ded --- /dev/null +++ b/types/resources/phloMultiPartyCallMember.d.ts @@ -0,0 +1,34 @@ +/** + * Represents a Multiparty Call Member + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of phlo + */ +export class UpdateMemberResponse { + constructor(params: object); + apiId: string; + error: string; +} +export class PhloMultiPartyCallMember extends PlivoResource { + constructor(client: Function, data ? : {}); + action: string; + client: Function; + resumeCall(): Promise < any > ; + voicemailDrop(): Promise < any > ; + hangup(): Promise < any > ; + hold(): Promise < any > ; + unhold(): Promise; + update(action: object): Promise; +} +export class PhloMultiPartyCallMemberInterface extends PlivoResourceInterface { + constructor(client: Function, data ? : {}); + action: string; + client: Function; + get(phloId: string, nodeId: string, memberAddress: string): any; +} +import { + PlivoResource +} from "../base"; +import { + PlivoResourceInterface +} from "../base"; \ No newline at end of file diff --git a/types/resources/phloMultipartyCall.d.ts b/types/resources/phloMultipartyCall.d.ts new file mode 100644 index 0000000..b19dcea --- /dev/null +++ b/types/resources/phloMultipartyCall.d.ts @@ -0,0 +1,42 @@ +export class UpdateMultipartyCallResponse { + constructor(params: object); + apiId: string; + error: string; +} +export class RetrieveMultipartyCallResponse { + constructor(params: object); + apiId: string; + nodeId: string; + phloId: string; + name: string; + nodeType: string; + createdOn: string; +} +export class PhloMultiPartyCall extends PlivoResource { + constructor(client: Function, data ? : {}); + action: string; + client: Function; + member: (memberAddress: string) => PhloMultiPartyCallMember; + call(triggerSource: string, to: string, role: string): Promise < any > ; + warmTransfer(triggerSource: string, to: string, role: string): Promise < UpdateMultipartyCallResponse > ; + coldTransfer(triggerSource: string, to: string, role: string): Promise < UpdateMultipartyCallResponse > ; + abortTransfer(memberAddress: string): Promise; + update(action: string, triggerSource: string, to: string, role: string): Promise; + [clientKey]: symbol; +} +export class PhloMultiPartyCallInterface extends PlivoResourceInterface { + constructor(client: Function, data?: {}); + get(phloId: string, id: string): Promise; + [clientKey]: symbol; +} +import { + PlivoResource +} from "../base"; +import { + PhloMultiPartyCallMember +} from "./phloMultiPartyCallMember"; +declare const clientKey: unique symbol; +import { + PlivoResourceInterface +} from "../base"; +export {}; \ No newline at end of file diff --git a/types/resources/powerpacks.d.ts b/types/resources/powerpacks.d.ts new file mode 100644 index 0000000..1892aa3 --- /dev/null +++ b/types/resources/powerpacks.d.ts @@ -0,0 +1,225 @@ +export class ListAllNumbersResponse { + constructor(params: object); + apiId: string; + meta: object; + objects: object; +} +export class CreatePowerpackResponse { + constructor(params: object); + apiId: string; + applicationId: string; + applicationType: string; + createdOn: string; + localConnect: string; + name: string; + numberPool: string; + numberPriority: string; + stickySender: string; + uuid: string; +} +export class UpdatePowerpackResponse { + constructor(params: object); + apiId: string; + applicationId: string; + applicationType: string; + createdOn: string; + localConnect: string; + name: string; + numberPool: string; + stickySender: string; + uuid: string; +} +export class ListShortCodeResponse { + constructor(params: object); + apiId: string; + meta: object; + objects: object; +} +export class ListTollFreeResponse { + constructor(params: object); + apiId: string; + meta: object; + objects: object; +} +export class AddNumberResponse { + constructor(params: object); + apiId: string; + accountPhoneNumberResource: string; + addedOn: string; + countryIso2: string; + number: string; + numberPoolUuid: string; + type: string; + service: string; +} +export class RemoveNumberResponse { + constructor(params: object); + apiId: string; + response: string; +} +export class RemoveTollFreeNumberResponse { + constructor(params: object); + apiid: string; + response: string; +} +export class RemoveShortCodeResponse { + constructor(params: object); + apiid: string; + response: string; +} +export class AddTollFreeNumberresponse { + constructor(params: object); + apiId: string; + accountPhoneNumberResource: string; + addedOn: string; + countryIso2: string; + number: string; + numberPoolUuid: string; + type: string; + service: string; +} +export class RetrieveNumberResponse { + constructor(params: object); + apiId: string; + accountPhoneNumberResource: string; + addedOn: string; + countryIso2: string; + number: string; + numberPoolUuid: string; + type: string; +} +export class RetrieveTollFreeResponse { + constructor(params: object); + apiId: string; + accountPhoneNumberResource: string; + addedOn: string; + countryIso2: string; + number: string; + numberPoolUuid: string; + type: string; +} +export class RetrieveShortCodeResponse { + constructor(params: object); + apiId: string; + addedOn: string; + countryIso2: string; + shortCode: string; + numberPoolUuid: string; +} +/** + * Represents a Powerpack + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class Powerpack extends PlivoResource { + constructor(client: Function, data ? : {}); + uuid: string; + number_pool_id: string; + number_pool: NumberPool; + list_numbers(params: object): Promise < ListAllNumbersResponse > ; + search_query(params: object): string; + count_numbers(params: object): Promise < any > ; + find_number(number: string): Promise < RetrieveNumberResponse > ; + add_number(number: string, service ? : string): Promise < AddNumberResponse > ; + add_tollfree(tollfree: string, service ? : string): Promise < AddTollFreeNumberresponse > ; + remove_number(number: string, unrent ? : boolean): Promise < RemoveNumberResponse > ; + remove_tollfree(tollfree: string, unrent ? : boolean): Promise < RemoveTollFreeNumberResponse > ; + remove_shortcode(shortcode: string): Promise < RemoveShortCodeResponse > ; + list_shortcodes(params: object): Promise < ListShortCodeResponse > ; + list_tollfree(params: object): Promise < ListTollFreeResponse > ; + find_shortcode(shortcode: object, service ? : string): Promise < RetrieveShortCodeResponse > ; + find_tollfree(tollfree: string, service ? : string): Promise < RetrieveTollFreeResponse > ; + buy_add_number(params: object): Promise ; + [clientKey]: symbol; +} +export class NumberPool extends PlivoResource { + constructor(client: Function, data ? : {}); + numbers: Numbers; + shortcodes: Shortcode; + tollfree: Tollfree; +} +export class Numbers extends PlivoResource { + constructor(client: Function, data ? : {}); + buy_add_number(params: object): any; + list(params: object): Promise < any > ; + count(params: object): Promise < any > ; + search_query(params: object): string; + find(number: object): Promise < any > ; + add(number: string, service ? : string): Promise < any > ; + remove(number: string, unrent ? : boolean): Promise < any > ; +} +export class Shortcode extends PlivoResource { + constructor(client: Function, data ? : {}); + number_pool_id: string; + list(params: object): Promise < any > ; + find(shortcode: object): Promise < any > ; + remove(shortcode: object): Promise < any > ; +} +export class Tollfree extends PlivoResource { + constructor(client: Function, data ? : {}); + number_pool_id: string; + add(tollfree: string): Promise < any > ; + remove(tollfree: string, unrent ? : boolean): Promise < any > ; + list(params: object): Promise < any > ; + find(tollfree: object): Promise < any > ; +} +/** + * Represents a Powerpack interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class PowerpackInterface extends PlivoResourceInterface { + constructor(client: Function, data ? : {}); + /** + * get Powerpack by given id + * @method + * @param {string} uuid - id of Powerpack + * @promise {object} return {@link Powerpack} object + * @fail {Error} return Error + */ + get(uuid: string): any; + /** + * create Powerpack + * @method + * @param {string} name - name of Powerpack + * @param {object} params - params to create Powerpack + * @param {string} [params.sticky_sender] - + * @param {string} [params.local_connect] + * @param {string} [params.application_type] + * @param {string} [params.application_id] + * @promise {object} return {@link PlivoGenericResponse} object + * @fail {Error} return Error + */ + create(name: string, params?: {}): Promise; + /** + * update Powerpack + * @method + * @param {string} uuid - id of Powerpack + * @param {object} params - to update Powerpack + * @param {string} [params.name] + * @param {string} [params.sticky_sender] + * @param {string} [params.local_connect] + * @param {string} [params.application_type] + * @param {string} [params.application_id] + * @promise {object} return {@link Powerpack} object + * @fail {Error} return Error + */ + update(uuid: string, params: { + name: string; + sticky_sender: string; + local_connect: string; + application_type: string; + application_id: string; + }): Promise < UpdatePowerpackResponse > ; + [clientKey]: symbol; +} +import { + PlivoResource +} from "../base"; +declare const clientKey: unique symbol; +import { + PlivoResourceInterface +} from "../base"; +export {}; \ No newline at end of file diff --git a/types/resources/pricings.d.ts b/types/resources/pricings.d.ts new file mode 100644 index 0000000..cbda073 --- /dev/null +++ b/types/resources/pricings.d.ts @@ -0,0 +1,42 @@ +/** +* Represents a Pricing +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ +export class PricingResponse { + constructor(params: object); + apiId: string; + country: string; + countryCode: string; + countryIso: string; + message: object; + mms: object; + phoneNumbers: object; + voice: object; +} +export class Pricing extends PlivoResource { + constructor(client: Function, data?: {}); + /** + * Get pricings by country + * @method + * @promise {object} return {@link PlivoGenericResponse} object + * @fail {Error} return Error + */ + get(): Promise; + [clientKey]: symbol; +} +/** +* Represents a Pricing Interface +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ +export class PricingInterface extends PlivoResourceInterface { + constructor(client: Function, data?: {}); + [clientKey]: symbol; +} +import { PlivoResource } from "../base"; +declare const clientKey: unique symbol; +import { PlivoResourceInterface } from "../base"; +export {}; diff --git a/types/resources/recordings.d.ts b/types/resources/recordings.d.ts new file mode 100644 index 0000000..2cc6f4b --- /dev/null +++ b/types/resources/recordings.d.ts @@ -0,0 +1,86 @@ +export class RetrieveRecordingResponse { + constructor(params: object); + addTime: string; + apiId: string; + callUuid: string; + conferenceName: string; + recordingDurationMs: string; + recordingEndMs: string; + recordingFormat: string; + recordingId: string; + recordingStartMs: string; + recordingType: string; + recordingUrl: string; + resourceUri: string; +} +export class ListRecordingResponse { + constructor(params: object); + addTime: string; + apiId: string; + callUuid: string; + conferenceName: string; + recordingDurationMs: string; + recordingEndMs: string; + recordingFormat: string; + recordingId: string; + recordingStartMs: string; + recordingType: string; + recordingUrl: string; + resourceUri: string; +} +/** + * Represents a Recording + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class Recording extends PlivoResource { + constructor(client: Function, data ? : {}); + id: string; + [clientKey]: symbol; +} +/** + * Represents a Recording Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class RecordingInterface extends PlivoResourceInterface { + constructor(client: Function, data ? : {}); + /** + * Delete recording by id + * @method + * @param {string} id - id to delete recording + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + delete(id: string): Promise < any > ; + [clientKey]: symbol; + /** + * Get recording by id + * @method + * @param {string} id - id to get recording information + * @promise {object} return {@link Pricing} object + * @fail {Error} return Error + */ + get(id: string): Promise; + /** + * list recordings + * @method + * @param {object} params - params to list recordings + * @param {string} [params.subaccount] - ID of the subaccount if present + * @param {string} [params.callUuid] - Call UUID of the call to filter recordings associated with it + * @param {string} [params.addTime] - Filter based on the timings they were added + * @param {string} [params.limit] - Display no of results per page + * @param {string} [params.offset] - No of value items by which results should be offset + */ + list(params?: {}): Promise; +} +import { + PlivoResource +} from "../base"; +declare const clientKey: unique symbol; +import { + PlivoResourceInterface +} from "../base"; +export {}; \ No newline at end of file diff --git a/types/rest/client-test.d.ts b/types/rest/client-test.d.ts new file mode 100644 index 0000000..6e73f73 --- /dev/null +++ b/types/rest/client-test.d.ts @@ -0,0 +1,39 @@ +export class Client { + constructor(authid: string, authToken: string, proxy: string); + calls: CallInterface; + accounts: AccountInterface; + subAccounts: SubaccountInterface; + applications: ApplicationInterface; + conferences: ConferenceInterface; + endpoints: EndpointInterface; + messages: MessageInterface; + lookup: LookupInterface; + powerpacks: PowerpackInterface; + numbers: NumberInterface; + pricings: PricingInterface; + recordings: RecordingInterface; + media: MediaInterface; +} +/** + * Plivo API client which can be used to access the Plivo APIs. + * To set a proxy or timeout, pass in options.proxy (url) or options.timeout (number in ms) + * You can also pass in additional parameters accepted by the node requests module. + */ +export class PhloClient { + constructor(authid: string, authToken: string, options: string); + phlo: (phloid: string) => Phlo; +} +import { CallInterface } from "../resources/call.js"; +import { AccountInterface } from "../resources/accounts.js"; +import { SubaccountInterface } from "../resources/accounts.js"; +import { ApplicationInterface } from "../resources/applications.js"; +import { ConferenceInterface } from "../resources/conferences.js"; +import { EndpointInterface } from "../resources/endpoints.js"; +import { MessageInterface } from "../resources/messages.js"; +import { LookupInterface } from "../resources/lookup.js"; +import { PowerpackInterface } from "../resources/powerpacks.js"; +import { NumberInterface } from "../resources/numbers.js"; +import { PricingInterface } from "../resources/pricings.js"; +import { RecordingInterface } from "../resources/recordings.js"; +import { MediaInterface } from "../resources/media.js"; +import { Phlo } from "../resources/phlo.js"; diff --git a/types/rest/client.d.ts b/types/rest/client.d.ts new file mode 100644 index 0000000..641839b --- /dev/null +++ b/types/rest/client.d.ts @@ -0,0 +1,56 @@ +export function Response(): any; +export function validateV3Signature(method: string, uri: string, nonce: string, auth_token: string, v3_signature: string, params?: {}): Boolean; +export function validateSignature(uri: string, nonce: string, signature: string, auth_token: string): Boolean; +/** + * Plivo API client which can be used to access the Plivo APIs. + * To set a proxy or timeout, pass in options.proxy (url) or options.timeout (number in ms) + * You can also pass in additional parameters accepted by the node requests module. + */ +export class Client { + constructor(authId?: string, authToken?: string, options?: string); + calls: CallInterface; + accounts: AccountInterface; + subaccounts: SubaccountInterface; + subAccounts: SubaccountInterface; + applications: ApplicationInterface; + conferences: ConferenceInterface; + endpoints: EndpointInterface; + messages: MessageInterface; + lookup: LookupInterface; + powerpacks: PowerpackInterface; + numbers: NumberInterface; + pricings: PricingInterface; + recordings: RecordingInterface; + callFeedback: CallFeedbackInterface; + media: MediaInterface; + endUsers: EndUserInterface; + complianceDocumentTypes: ComplianceDocumentTypeInterface; + complianceDocuments: ComplianceDocumentInterface; + complianceRequirements: ComplianceRequirementInterface; + complianceApplications: ComplianceApplicationInterface; + toJSON(...args: any[]): any; +} +/** + * Plivo API client which can be used to access the Plivo APIs. + * To set a proxy or timeout, pass in options.proxy (url) or options.timeout (number in ms) + * You can also pass in additional parameters accepted by the node requests module. + */ +export class PhloClient { + constructor(authId: any, authToken: any, options: any); + phlo: (phloId: any) => Phlo; +} +import { CallInterface } from "../resources/call.js"; +import { AccountInterface } from "../resources/accounts.js"; +import { SubaccountInterface } from "../resources/accounts.js"; +import { ApplicationInterface } from "../resources/applications.js"; +import { ConferenceInterface } from "../resources/conferences.js"; +import { EndpointInterface } from "../resources/endpoints.js"; +import { MessageInterface } from "../resources/messages.js"; +import { LookupInterface } from "../resources/lookup.js"; +import { PowerpackInterface } from "../resources/powerpacks.js"; +import { NumberInterface } from "../resources/numbers.js"; +import { PricingInterface } from "../resources/pricings.js"; +import { RecordingInterface } from "../resources/recordings.js"; +import { CallFeedbackInterface } from "../resources/callFeedback.js"; +import { MediaInterface } from "../resources/media.js"; +import { Phlo } from "../resources/phlo.js"; \ No newline at end of file diff --git a/types/rest/request-test.d.ts b/types/rest/request-test.d.ts new file mode 100644 index 0000000..1f56632 --- /dev/null +++ b/types/rest/request-test.d.ts @@ -0,0 +1 @@ +export function Request(config: any): (method: string, action: string, params: object) => Promise; diff --git a/types/rest/request.d.ts b/types/rest/request.d.ts new file mode 100644 index 0000000..1f56632 --- /dev/null +++ b/types/rest/request.d.ts @@ -0,0 +1 @@ +export function Request(config: any): (method: string, action: string, params: object) => Promise; diff --git a/types/rest/utils.d.ts b/types/rest/utils.d.ts new file mode 100644 index 0000000..13c7262 --- /dev/null +++ b/types/rest/utils.d.ts @@ -0,0 +1,8 @@ +export function camelCaseRequestWrapper(requestFunc: any): (method: string, action: string, params: object) => any; +export function validateSpeakAttributes(content: any, voice: any): { + success: boolean; + msg?: undefined; +} | { + success: boolean; + msg: string; +}; diff --git a/types/utils/common.d.ts b/types/utils/common.d.ts new file mode 100644 index 0000000..8677f23 --- /dev/null +++ b/types/utils/common.d.ts @@ -0,0 +1,2 @@ +export function extend(instance: any, data: any): void; +export function validate(data?: any[]): false | Promise; diff --git a/types/utils/exceptions.d.ts b/types/utils/exceptions.d.ts new file mode 100644 index 0000000..f0e32c2 --- /dev/null +++ b/types/utils/exceptions.d.ts @@ -0,0 +1,21 @@ +export class PlivoRestError extends Error { + constructor(message?: string); +} +export class ResourceNotFoundError extends PlivoRestError { + constructor(message?: string); +} +export class ServerError extends PlivoRestError { + constructor(message?: string); +} +export class InvalidRequestError extends PlivoRestError { + constructor(message?: string); +} +export class PlivoXMLError extends PlivoRestError { + constructor(message?: string); +} +export class PlivoXMLValidationError extends PlivoRestError { + constructor(message?: string); +} +export class AuthenticationError extends PlivoRestError { + constructor(message?: string); +} diff --git a/types/utils/jsonStrinfigier.d.ts b/types/utils/jsonStrinfigier.d.ts new file mode 100644 index 0000000..c1de530 --- /dev/null +++ b/types/utils/jsonStrinfigier.d.ts @@ -0,0 +1,7 @@ +export default Flatted; +export function parse(text: any, reviver: any): any; +export function stringify(value: any, replacer: any, space: any): string; +declare namespace Flatted { + function parse(text: any, reviver: any): any; + function stringify(value: any, replacer: any, space: any): string; +} diff --git a/types/utils/jwt.d.ts b/types/utils/jwt.d.ts new file mode 100644 index 0000000..03d4ad2 --- /dev/null +++ b/types/utils/jwt.d.ts @@ -0,0 +1,21 @@ +export function AccessToken(authid: string, authToken: string, username: string, validityOptions?: {}, uid?: any): void; +export class AccessToken { + constructor(authId: string, authToken: string, username: string, validityOptions?: {}, uid?: any); + authId: string; + key: string; + username: string; + validFrom: string; + lifetime: string; + uid: string; +} +export function addVoiceGrants(incoming?: boolean, outgoing?: boolean): void; +export class addVoiceGrants { + constructor(incoming?: boolean, outgoing?: boolean); + grants: { + voice: { + incoming_allow: boolean; + outgoing_allow: boolean; + }; + }; +} +export function toJwt(): any; diff --git a/types/utils/plivoxml.d.ts b/types/utils/plivoxml.d.ts new file mode 100644 index 0000000..3b304ce --- /dev/null +++ b/types/utils/plivoxml.d.ts @@ -0,0 +1,179 @@ +/** + * Response element + * @constructor + */ +export function Response(): void; +export class Response { + element: string; + nestables: string[]; + valid_attributes: any[]; + elem: object; + add: (new_element: object, body: string, attributes: object) => object; + addConference: (body: string, attributes: { + muted?: boolean; + enterSound?: string; + exitSound?: string; + startConferenceOnEnter?: boolean; + endConferenceOnExit?: boolean; + stayAlone?: boolean; + waitSound?: string; + maxMembers?: number; + record?: boolean; + recordFileFormat?: string; + timeLimit?: number; + hangupOnStar?: boolean; + action?: string; + method?: string; + callbackUrl?: string; + callbackMethod?: string; + digitsMatch?: string; + floorEvent?: boolean; + redirect?: boolean; + relayDTMF?: boolean; + }) => object; + addNumber: (body: string, attributes: { + sendDigits?: string; + sendOnPreanswer?: boolean; + }) => object; + addUser: (body: string, attributes: { + sendDigits?: string; + sendOnPreanswer?: boolean; + sipHeaders?: string; + }) => object; + addDial: (attributes: { + action?: string; + method?: string; + hangupOnStar?: boolean; + timeLimit?: number; + timeout?: number; + callerID?: string; + callerName?: string; + confirmSound?: string; + confirmKey?: string; + dialMusic?: string; + callbackUrl?: string; + callbackMethod?: string; + redirect?: boolean; + digitsMatch?: string; + digitsMatchBLeg?: string; + sipHeaders?: string; + }) => object; + addGetDigits: (attributes: { + action?: string; + method?: string; + timeout?: number; + digitTimeout?: number; + finishOnKey?: string; + numDigits?: number; + retries?: number; + redirect?: boolean; + playBeep?: boolean; + validDigits?: string; + invalidDigitsSound?: string; + log?: boolean; + }) => object; + addGetInput: (attributes: { + action?: string; + method?: string; + inputType?: string; + executionTimeout?: number; + digitEndTimeout?: number; + speechEndTimeout?: number; + finishOnKey?: string; + numDigits?: number; + speechModel?: string; + hints?: string; + language?: string; + interimSpeechResultsCallback?: string; + interimSpeechResultsCallbackMethod?: string; + log?: boolean; + redirect?: boolean; + profanityFilter?: string; + }) => object; + addHangup: (attributes: { + reason?: string; + schedule?: number; + }) => object; + addMessage: (body: string, attributes: { + src?: string; + dst?: string; + type?: string; + callbackUrl?: string; + callbackMethod?: string; + }) => object; + addPlay: (body: string, attributes: { + loop?: number; + }) => object; + addPreAnswer: () => any; + addRecord: (attributes: { + action?: string; + method?: string; + fileFormat?: string; + redirect?: boolean; + timeout?: number; + maxLength?: number; + playBeep?: boolean; + finishOnKey?: string; + recordSession?: boolean; + startOnDialAnswer?: boolean; + transcriptionType?: string; + transcriptionUrl?: string; + transcriptionMethod?: string; + callbackUrl?: string; + callbackMethod?: string; + }) => object; + addRedirect: (body: string, attributes: { + method?: string; + }) => object; + addSpeak: (body: string, attributes: { + voice?: string; + language?: string; + loop?: number; + }) => object; + addBreak: (attributes: { + strength?: string; + time?: string; + }) => object; + addEmphasis: (body: string, attributes: { + level?: string; + }) => object; + addLang: (body: string, attributes: { + xml?: string; + }) => object; + addP: (body: string) => any; + addPhoneme: (body: string, attributes: { + alphabet?: string; + ph?: string; + }) => object; + addProsody: (body: string, attributes: { + pitch?: string; + rate?: string; + volume?: string; + }) => object; + addS: (body: string) => any; + addSayAs: (body: string, attributes: { + interpret?: string; + format?: string; + }) => object; + addSub: (body: string, attributes: { + alias?: string; + }) => object; + addW: (body: string, attributes: { + role?: string; + }) => object; + addText: (body: string) => object; + addWait: (attributes: { + length?: number; + silence?: boolean; + minSilence?: number; + beep?: boolean; + }) => object; + addDTMF: (body: string, attributes: { + async?: boolean; + }) => object; + toXML: () => string; + toJSON: string; +} +export class PlivoXMLError extends Error { + constructor(message?: string); +} diff --git a/types/utils/security.d.ts b/types/utils/security.d.ts new file mode 100644 index 0000000..95c38e6 --- /dev/null +++ b/types/utils/security.d.ts @@ -0,0 +1,3 @@ +export function computeOldSignature(authid: string, uri: string, params: object): boolean; +export function verifyOldSignature(authid: string, uri: string, params: object, signature: string): boolean; +export function validateSignature(uri: string, nonce: string, signature: string, auth_token: string): boolean; diff --git a/types/utils/v3Security.d.ts b/types/utils/v3Security.d.ts new file mode 100644 index 0000000..cecdaeb --- /dev/null +++ b/types/utils/v3Security.d.ts @@ -0,0 +1 @@ +export function validateV3Signature(method:string, uri: string, nonce: string, auth_token: string, v3_signature: string, params?: {}): boolean; diff --git a/types/version.d.ts b/types/version.d.ts new file mode 100644 index 0000000..e69de29