From 49a217f635f061555788d65491225e29ac101df0 Mon Sep 17 00:00:00 2001 From: huzaif Date: Sun, 16 Aug 2020 19:14:58 +0530 Subject: [PATCH 01/75] add message typescript support --- gulpfile.js | 9 +- package.json | 1 + types/base.d.ts | 19 + types/resources/accounts.d.ts | 86 +++++ types/resources/applications.d.ts | 72 ++++ types/resources/call.d.ts | 280 +++++++++++++++ types/resources/callFeedback.d.ts | 19 + types/resources/conferences.d.ts | 337 ++++++++++++++++++ types/resources/endpoints.d.ts | 51 +++ types/resources/media.d.ts | 30 ++ types/resources/messages.d.ts | 61 ++++ types/resources/numbers.d.ts | 122 +++++++ types/resources/phlo.d.ts | 30 ++ types/resources/phloMultiPartyCallMember.d.ts | 23 ++ types/resources/phloMultipartyCall.d.ts | 16 + types/resources/powerpacks.d.ts | 88 +++++ types/resources/pricings.d.ts | 30 ++ types/resources/recordings.d.ts | 32 ++ types/rest/client-test.d.ts | 37 ++ types/rest/client.d.ts | 46 +++ types/rest/request-test.d.ts | 1 + types/rest/request.d.ts | 1 + types/rest/utils.d.ts | 8 + types/utils/common.d.ts | 2 + types/utils/exceptions.d.ts | 21 ++ types/utils/jsonStrinfigier.d.ts | 7 + types/utils/security.d.ts | 7 + types/utils/v3Security.d.ts | 1 + types/version.d.ts | 0 29 files changed, 1435 insertions(+), 2 deletions(-) create mode 100644 types/base.d.ts create mode 100644 types/resources/accounts.d.ts create mode 100644 types/resources/applications.d.ts create mode 100644 types/resources/call.d.ts create mode 100644 types/resources/callFeedback.d.ts create mode 100644 types/resources/conferences.d.ts create mode 100644 types/resources/endpoints.d.ts create mode 100644 types/resources/media.d.ts create mode 100644 types/resources/messages.d.ts create mode 100644 types/resources/numbers.d.ts create mode 100644 types/resources/phlo.d.ts create mode 100644 types/resources/phloMultiPartyCallMember.d.ts create mode 100644 types/resources/phloMultipartyCall.d.ts create mode 100644 types/resources/powerpacks.d.ts create mode 100644 types/resources/pricings.d.ts create mode 100644 types/resources/recordings.d.ts create mode 100644 types/rest/client-test.d.ts create mode 100644 types/rest/client.d.ts create mode 100644 types/rest/request-test.d.ts create mode 100644 types/rest/request.d.ts create mode 100644 types/rest/utils.d.ts create mode 100644 types/utils/common.d.ts create mode 100644 types/utils/exceptions.d.ts create mode 100644 types/utils/jsonStrinfigier.d.ts create mode 100644 types/utils/security.d.ts create mode 100644 types/utils/v3Security.d.ts create mode 100644 types/version.d.ts 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/package.json b/package.json index c435957..d5e417c 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/types/base.d.ts b/types/base.d.ts new file mode 100644 index 0000000..1beb4c8 --- /dev/null +++ b/types/base.d.ts @@ -0,0 +1,19 @@ +export class PlivoGenericResponse { + constructor(params: any, idString: any); + id: any; +} +export class PlivoResource { + constructor(action: any, klass: any, idField: any, request: any); + update(params: any, id: any): Promise; + delete(params: any): Promise; + executeAction(task: string, method: string, params: {}, action: any): Promise; + customexecuteAction(url: any, method?: string, params?: {}): Promise; + customexecuteGetNumberAction(url: any, method?: string, params?: {}): any; + getMetaResponse(url: any, method?: string, params?: {}): Promise; +} +export class PlivoResourceInterface { + constructor(action: any, klass: any, idField: any, request: any); + get(id: any, params?: {}): Promise; + list(params: any): Promise; + create(params: any): Promise; +} diff --git a/types/resources/accounts.d.ts b/types/resources/accounts.d.ts new file mode 100644 index 0000000..f109892 --- /dev/null +++ b/types/resources/accounts.d.ts @@ -0,0 +1,86 @@ +/** + * Represents a SubAccount + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class Subaccount extends PlivoResource { + constructor(client: any, data?: {}); + id: any; +} +/** + * Represents a Subaccount Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class SubaccountInterface extends PlivoResourceInterface { + constructor(client: any, data?: {}); + /** + * 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: any, 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: any, cascade: boolean): Promise; + [clientKey]: any; +} +/** + * Represents a Account + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class Account extends PlivoResource { + constructor(client: any, data?: {}); + id: any; + /** + * get account detail + * @method + * @promise {PlivoGenericResponse} return PlivoGenericResponse object + * @fail {Error} return Error + */ + get(): Promise; + [clientKey]: any; +} +/** + * Represents a Account Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class AccountInterface extends PlivoResourceInterface { + constructor(client: any, data?: {}); + /** + * 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]: any; +} +import { PlivoResource } from "../base.js"; +import { PlivoResourceInterface } from "../base.js"; +declare const clientKey: unique symbol; +export {}; diff --git a/types/resources/applications.d.ts b/types/resources/applications.d.ts new file mode 100644 index 0000000..5afe15c --- /dev/null +++ b/types/resources/applications.d.ts @@ -0,0 +1,72 @@ +/** + * Represents a Application + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class Application extends PlivoResource { + constructor(client: any, data?: {}); + id: any; +} +/** + * Represents a Application interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class ApplicationInterface extends PlivoResourceInterface { + constructor(client: any, data?: {}); + /** + * 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]: any; +} +import { PlivoResource } from "../base.js"; +import { PlivoResourceInterface } from "../base.js"; +declare const clientKey: unique symbol; +export {}; diff --git a/types/resources/call.d.ts b/types/resources/call.d.ts new file mode 100644 index 0000000..e7efab2 --- /dev/null +++ b/types/resources/call.d.ts @@ -0,0 +1,280 @@ +/** + * Represents a Call + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class Call extends PlivoResource { + constructor(client: any, data?: {}); + id: any; + /** + * hangup call + * @method + * @promise {Boolean} return true if call hung up + * @fail {Error} return Error + */ + hangup(): Promise; + /** + * 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; + }): Promise; + /** + * record call + * @method + * @param {object} params - to record call + * @promise {object} return PlivoGenericResponse Object + * @fail {Error} return Error + */ + record(params: object): Promise; + /** + * record call + * @method + * @param {object} params - to record call + * @promise {object} return PlivoGenericResponse Object + * @fail {Error} return Error + */ + startRecording(params: object): Promise; + /** + * stop recording call + * @method + * @param {object} params - to stop recording call + * @promise {object} return PlivoGenericResponse Object + * @fail {Error} return Error + */ + stopRecording(params: object): Promise; + /** + * 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; + /** + * 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; + /** + * stop playing music for call + * @method + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + stopPlayingMusic(): Promise; + /** + * 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; + /** + * 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; + /** + * stop speaking text for call + * @method + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + stopSpeakingText(): Promise; + /** + * 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; + /** + * Hangup a Call Request + * @method + * @promise {object} returns PlivoGenericResponse Object + * @fail {Error} returns Error + */ + cancel(): Promise; + [clientKey]: any; +} +/** + * Represents a Call Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class CallInterface extends PlivoResourceInterface { + constructor(client: any, data?: {}); + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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; + /** + * 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: any): Promise; + listLiveCalls(params: any): Promise; + getLiveCall(id: any): Promise; + listQueuedCalls(): Promise; + getQueuedCall(id: any): Promise; + [clientKey]: any; + [liveCallInterfaceKey]: LiveCallInterface; + [queuedCallInterfaceKey]: QueuedCallInterface; +} +export class LiveCallResource extends PlivoResource { + constructor(client: any, data?: {}); + id: any; + [clientKey]: any; +} +export class QueuedCallResource extends PlivoResource { + constructor(client: any, data?: {}); + id: any; + [clientKey]: any; +} +import { PlivoResource } from "../base.js"; +declare const clientKey: unique symbol; +import { PlivoResourceInterface } from "../base.js"; +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: any, data?: {}); + [clientKey]: any; +} +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: any, data?: {}); + [clientKey]: any; +} +export {}; diff --git a/types/resources/callFeedback.d.ts b/types/resources/callFeedback.d.ts new file mode 100644 index 0000000..a11b890 --- /dev/null +++ b/types/resources/callFeedback.d.ts @@ -0,0 +1,19 @@ +export class CallFeedback extends PlivoResource { + constructor(client: any, data?: {}); + id: any; + [clientKey]: any; +} +/** + * Represents a CallFeedback Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class CallFeedbackInterface extends PlivoResourceInterface { + constructor(client: any, data?: {}); + [clientKey]: any; +} +import { PlivoResource } from "../base.js"; +declare const clientKey: unique symbol; +import { PlivoResourceInterface } from "../base.js"; +export {}; diff --git a/types/resources/conferences.d.ts b/types/resources/conferences.d.ts new file mode 100644 index 0000000..afcdde0 --- /dev/null +++ b/types/resources/conferences.d.ts @@ -0,0 +1,337 @@ +/** + * Represents a Conference + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class Conference extends PlivoResource { + constructor(client: any, data?: {}); + id: any; + /** + * 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]: any; +} +/** + * Represents a Conference Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class ConferenceInterface extends PlivoResourceInterface { + constructor(client: any, data?: {}); + /** + * 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]: any; +} +import { PlivoResource } from "../base.js"; +declare const clientKey: unique symbol; +import { PlivoResourceInterface } from "../base.js"; +export {}; diff --git a/types/resources/endpoints.d.ts b/types/resources/endpoints.d.ts new file mode 100644 index 0000000..e1850ef --- /dev/null +++ b/types/resources/endpoints.d.ts @@ -0,0 +1,51 @@ +/** + * Represents a Endpoint + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class Endpoint extends PlivoResource { + constructor(client: any, data?: {}); + id: any; + [clientKey]: any; +} +/** + * Represents a Endpoint Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class EndpointInterface extends PlivoResourceInterface { + constructor(client: any, data?: {}); + /** + * 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: { + username: string; + password: string; + alias: string; + appId: string; + }): Promise; + /** + * delete Endpoint + * @method + * @param {string} id - id to delete + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + delete(id: string): Promise; + [clientKey]: any; +} +import { PlivoResource } from "../base.js"; +declare const clientKey: unique symbol; +import { PlivoResourceInterface } from "../base.js"; +export {}; diff --git a/types/resources/media.d.ts b/types/resources/media.d.ts new file mode 100644 index 0000000..52e514a --- /dev/null +++ b/types/resources/media.d.ts @@ -0,0 +1,30 @@ +/** + * Represents a Message + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class Media extends PlivoResource { + constructor(client: any, data?: {}); + id: any; +} +/** + * Represents a Media Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class MediaInterface extends PlivoResourceInterface { + constructor(client: any, data?: {}); + /** + * Upload Media + * @method + * @fail {Error} return Error + */ + upload(files: any): Promise; + [clientKey]: any; +} +import { PlivoResource } from "../base.js"; +import { PlivoResourceInterface } from "../base.js"; +declare const clientKey: unique symbol; +export {}; diff --git a/types/resources/messages.d.ts b/types/resources/messages.d.ts new file mode 100644 index 0000000..4411a4a --- /dev/null +++ b/types/resources/messages.d.ts @@ -0,0 +1,61 @@ +import { PlivoResource, PlivoResourceInterface } from '../base'; +/** + * Represents a Message + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export declare class Message extends PlivoResource { + constructor(client: any, data?: {}); + listMedia(): any; +} +/** + * Represents a Message Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export declare class MessageInterface extends PlivoResourceInterface { + constructor(client: any, 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: any, dst: any, text: any, optionalParams: any): any; + /** + * 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 PlivoGenericMessage} object if success + * @fail {Error} return Error + */ + create(src: any, dst: any, text: any, optionalParams?: any, powerpackUUID: any): any; + /** + * Get Message by given id + * @method + * @param {string} id - id of message + * @promise {object} return {@link Message} object if success + * @fail {Error} return Error + */ + get(id: any): any; + listMedia(messageUUID: any): any; +} \ 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..a59ff0c --- /dev/null +++ b/types/resources/numbers.d.ts @@ -0,0 +1,122 @@ +/** + * Represents a PhoneNumber + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class PhoneNumber extends PlivoResource { + constructor(client: any, data?: {}); + id: any; + /** + * 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; + [clientKey]: any; +} +/** + * 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: any, data?: {}); + /** + * 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; + [clientKey]: any; +} +/** + * Represents a Number + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class NumberResource extends PlivoResource { + constructor(client: any, data?: {}); + id: any; + /** + * Unrent Number + * @method + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + unrent(): Promise; +} +/** + * Represents a Numbers + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class NumberInterface extends PlivoResourceInterface { + constructor(client: any); + /** + * 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; + /** + * 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: any): Promise; + /** + * 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: any): Promise; + /** + * 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; + /** + * Unrent Number + * @method + * @param {string} number - number to unrent + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + unrent(number: string): Promise; + [clientKey]: any; +} +import { PlivoResource } from "../base.js"; +declare const clientKey: unique symbol; +import { PlivoResourceInterface } from "../base.js"; +export {}; diff --git a/types/resources/phlo.d.ts b/types/resources/phlo.d.ts new file mode 100644 index 0000000..9a3875a --- /dev/null +++ b/types/resources/phlo.d.ts @@ -0,0 +1,30 @@ +/** + * Represents a Phlo + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of phlo + */ +export class Phlo extends PlivoResource { + constructor(client: any, data?: {}); + client: any; + multiPartyCall: (nodeId: any) => PhloMultiPartyCall; + /** + * run phlo + * @method + * @promise {Boolean} return true if phlo is complete + * @fail {Error} return Error + */ + run(params: any): Promise; +} +/** + * Represents a Phlo Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class PhloInterface extends PlivoResourceInterface { + constructor(client: any, data?: {}); +} +import { PlivoResource } from "../base.js"; +import { PhloMultiPartyCall } from "./phloMultipartyCall.js"; +import { PlivoResourceInterface } from "../base.js"; diff --git a/types/resources/phloMultiPartyCallMember.d.ts b/types/resources/phloMultiPartyCallMember.d.ts new file mode 100644 index 0000000..14af70c --- /dev/null +++ b/types/resources/phloMultiPartyCallMember.d.ts @@ -0,0 +1,23 @@ +/** + * Represents a Multiparty Call Member + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of phlo + */ +export class PhloMultiPartyCallMember extends PlivoResource { + constructor(client: any, data?: {}); + action: string; + client: any; + resumeCall(): Promise; + voicemailDrop(): Promise; + hangup(): Promise; + hold(): Promise; + unhold(): Promise; +} +export class PhloMultiPartyCallMemberInterface extends PlivoResourceInterface { + constructor(client: any, data?: {}); + action: string; + client: any; +} +import { PlivoResource } from "../base.js"; +import { PlivoResourceInterface } from "../base.js"; diff --git a/types/resources/phloMultipartyCall.d.ts b/types/resources/phloMultipartyCall.d.ts new file mode 100644 index 0000000..1177f39 --- /dev/null +++ b/types/resources/phloMultipartyCall.d.ts @@ -0,0 +1,16 @@ +export class PhloMultiPartyCall extends PlivoResource { + constructor(client: any, data?: {}); + action: string; + client: any; + member: (memberAddress: any) => PhloMultiPartyCallMember; + call(triggerSource: any, to: any, role: any): Promise; + warmTransfer(triggerSource: any, to: any, role: any): Promise; + coldTransfer(triggerSource: any, to: any, role: any): Promise; + abortTransfer(memberAddress: any): Promise; +} +export class PhloMultiPartyCallInterface extends PlivoResourceInterface { + constructor(client: any, data?: {}); +} +import { PlivoResource } from "../base.js"; +import { PhloMultiPartyCallMember } from "./phloMultiPartyCallMember.js"; +import { PlivoResourceInterface } from "../base.js"; diff --git a/types/resources/powerpacks.d.ts b/types/resources/powerpacks.d.ts new file mode 100644 index 0000000..c5aeb70 --- /dev/null +++ b/types/resources/powerpacks.d.ts @@ -0,0 +1,88 @@ +/** + * Represents a Powerpack + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class Powerpack extends PlivoResource { + constructor(client: any, data?: {}); + uuid: any; + number_pool_id: any; + number_pool: NumberPool; + list_numbers(params: any): Promise; + search_query(params: any): string; + count_numbers(params: any): Promise; + find_number(number: any): Promise; + add_number(number: any): Promise; + add_tollfree(tollfree: any): Promise; + remove_number(number: any, unrent?: boolean): Promise; + remove_tollfree(tollfree: any, unrent?: boolean): Promise; + remove_shortcode(shortcode: any): Promise; + list_shortcodes(params: any): Promise; + list_tollfree(params: any): Promise; + find_shortcode(shortcode: any): Promise; + find_tollfree(tollfree: any): Promise; + buy_add_number(params: any): any; +} +export class NumberPool extends PlivoResource { + constructor(client: any, data?: {}); + numbers: Numbers; + shortcodes: Shortcode; + tollfree: Tollfree; +} +export class Numbers extends PlivoResource { + constructor(client: any, data?: {}); + buy_add_number(params: any): any; + list(params: any): Promise; + count(params: any): Promise; + search_query(params: any): string; + find(number: any): Promise; + add(number: any): Promise; + remove(number: any, unrent?: boolean): Promise; +} +export class Shortcode extends PlivoResource { + constructor(client: any, data?: {}); + number_pool_id: any; + list(params: any): Promise; + find(shortcode: any): Promise; + remove(shortcode: any): Promise; +} +export class Tollfree extends PlivoResource { + constructor(client: any, data?: {}); + number_pool_id: any; + add(tollfree: any): Promise; + remove(tollfree: any, unrent?: boolean): Promise; + list(params: any): Promise; + find(tollfree: any): Promise; +} +/** + * Represents a Powerpack interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class PowerpackInterface extends PlivoResourceInterface { + constructor(client: any, data?: {}); + /** + * 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; +} +import { PlivoResource } from "../base.js"; +import { PlivoResourceInterface } from "../base.js"; diff --git a/types/resources/pricings.d.ts b/types/resources/pricings.d.ts new file mode 100644 index 0000000..2c66c24 --- /dev/null +++ b/types/resources/pricings.d.ts @@ -0,0 +1,30 @@ +/** + * Represents a Pricing + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class Pricing extends PlivoResource { + constructor(client: any, data?: {}); + /** + * Get pricings by country + * @method + * @promise {object} return {@link PlivoGenericResponse} object + * @fail {Error} return Error + */ + get(): Promise; +} +/** + * Represents a Pricing Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class PricingInterface extends PlivoResourceInterface { + constructor(client: any, data?: {}); + [clientKey]: any; +} +import { PlivoResource } from "../base.js"; +import { PlivoResourceInterface } from "../base.js"; +declare const clientKey: unique symbol; +export {}; diff --git a/types/resources/recordings.d.ts b/types/resources/recordings.d.ts new file mode 100644 index 0000000..60e3a25 --- /dev/null +++ b/types/resources/recordings.d.ts @@ -0,0 +1,32 @@ +/** + * Represents a Recording + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class Recording extends PlivoResource { + constructor(client: any, data?: {}); + id: any; +} +/** + * Represents a Recording Interface + * @constructor + * @param {function} client - make api call + * @param {object} [data] - data of call + */ +export class RecordingInterface extends PlivoResourceInterface { + constructor(client: any, 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; + [clientKey]: any; +} +import { PlivoResource } from "../base.js"; +import { PlivoResourceInterface } from "../base.js"; +declare const clientKey: unique symbol; +export {}; diff --git a/types/rest/client-test.d.ts b/types/rest/client-test.d.ts new file mode 100644 index 0000000..9fe8a7d --- /dev/null +++ b/types/rest/client-test.d.ts @@ -0,0 +1,37 @@ +export class Client { + constructor(authId: any, authToken: any, proxy: any); + calls: CallInterface; + accounts: AccountInterface; + subAccounts: SubaccountInterface; + applications: ApplicationInterface; + conferences: ConferenceInterface; + endpoints: EndpointInterface; + messages: MessageInterface; + 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: 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 { 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..d52bce4 --- /dev/null +++ b/types/rest/client.d.ts @@ -0,0 +1,46 @@ +/** + * 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: any, authToken: any, options?: any); + calls: CallInterface; + accounts: AccountInterface; + subaccounts: SubaccountInterface; + subAccounts: SubaccountInterface; + applications: ApplicationInterface; + conferences: ConferenceInterface; + endpoints: EndpointInterface; + messages: MessageInterface; + powerpacks: PowerpackInterface; + numbers: NumberInterface; + pricings: PricingInterface; + recordings: RecordingInterface; + callFeedback: CallFeedbackInterface; + media: MediaInterface; + 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 { 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"; diff --git a/types/rest/request-test.d.ts b/types/rest/request-test.d.ts new file mode 100644 index 0000000..6093327 --- /dev/null +++ b/types/rest/request-test.d.ts @@ -0,0 +1 @@ +export function Request(config: any): (method: any, action: any, params: any) => Promise; diff --git a/types/rest/request.d.ts b/types/rest/request.d.ts new file mode 100644 index 0000000..6093327 --- /dev/null +++ b/types/rest/request.d.ts @@ -0,0 +1 @@ +export function Request(config: any): (method: any, action: any, params: any) => Promise; diff --git a/types/rest/utils.d.ts b/types/rest/utils.d.ts new file mode 100644 index 0000000..bd0a981 --- /dev/null +++ b/types/rest/utils.d.ts @@ -0,0 +1,8 @@ +export function camelCaseRequestWrapper(requestFunc: any): (method: any, action: any, params: any) => 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..d985f4b --- /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 { + export function parse(text: any, reviver: any): any; + export function stringify(value: any, replacer: any, space: any): string; +} diff --git a/types/utils/security.d.ts b/types/utils/security.d.ts new file mode 100644 index 0000000..52e3081 --- /dev/null +++ b/types/utils/security.d.ts @@ -0,0 +1,7 @@ +export function computeOldSignature(authId: string, uri: string, params: { + [string]: string; +}): string; +export function verifyOldSignature(authId: string, uri: string, params: { + [string]: string; +}, 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..d1ab388 --- /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 From 8f161d1bcbd4ddc99c1fe482e723575bcf71fc9f Mon Sep 17 00:00:00 2001 From: huzaif Date: Mon, 16 Nov 2020 21:33:46 +0530 Subject: [PATCH 02/75] Added MessageInterface and fixed Types for Send message --- lib/resources/messages.js | 52 ++++++++++++++++---- lib/utils/security.js | 14 +++--- lib/utils/v3Security.js | 10 ++-- types/resources/messages.d.ts | 89 +++++++++++++++++------------------ 4 files changed, 100 insertions(+), 65 deletions(-) diff --git a/lib/resources/messages.js b/lib/resources/messages.js index d6736a0..a05d788 100644 --- a/lib/resources/messages.js +++ b/lib/resources/messages.js @@ -1,17 +1,32 @@ +import * as _ from "lodash"; + +import { + PlivoGenericResponse, + PlivoResource, + PlivoResourceInterface +} from '../base'; import { extend, validate } from '../utils/common.js'; -import { - PlivoResource, - PlivoResourceInterface -} from '../base'; -import * as _ from "lodash"; -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; + + } +} /** * Represents a Message * @constructor @@ -47,6 +62,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; + } /** @@ -69,7 +88,7 @@ export class MessageInterface extends PlivoResourceInterface { } /** - * Send Message + * Create Message * @method * @param {string} src - source number * @param {string} dst - destination number @@ -80,10 +99,10 @@ export class MessageInterface extends PlivoResourceInterface { * @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 PlivoGenericMessage} object if success + * @promise {object} return {@link MessageResponse} object if success * @fail {Error} return Error */ - create(src, dst, text, optionalParams, powerpackUUID) { + createtest(src, dst, text, optionalParams, powerpackUUID) { let errors = validate([{ field: 'dst', value: dst, @@ -117,7 +136,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); + }); + }) } /** 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/types/resources/messages.d.ts b/types/resources/messages.d.ts index 4411a4a..e421fc3 100644 --- a/types/resources/messages.d.ts +++ b/types/resources/messages.d.ts @@ -1,4 +1,12 @@ import { PlivoResource, PlivoResourceInterface } from '../base'; +export declare class MessageResponse { + constructor(params: object); + apiId: string + message: string + messageUuid: object +} + + /** * Represents a Message * @constructor @@ -6,8 +14,8 @@ import { PlivoResource, PlivoResourceInterface } from '../base'; * @param {object} [data] - data of call */ export declare class Message extends PlivoResource { - constructor(client: any, data?: {}); - listMedia(): any; + constructor(client: any, data?: {}); + listMedia(): any; } /** * Represents a Message Interface @@ -16,46 +24,37 @@ export declare class Message extends PlivoResource { * @param {object} [data] - data of call */ export declare class MessageInterface extends PlivoResourceInterface { - constructor(client: any, 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: any, dst: any, text: any, optionalParams: any): any; - /** - * 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 PlivoGenericMessage} object if success - * @fail {Error} return Error - */ - create(src: any, dst: any, text: any, optionalParams?: any, powerpackUUID: any): any; - /** - * Get Message by given id - * @method - * @param {string} id - id of message - * @promise {object} return {@link Message} object if success - * @fail {Error} return Error - */ - get(id: any): any; - listMedia(messageUUID: any): any; -} \ No newline at end of file + constructor(client: any, 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: any, dst: string, text: string, optionalParams: object): Promise; + /** + * 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 + */ + createtest(src: any, dst: string, text: string, optionalParams: object, powerpackUUID: any): Promise; +} From 6884ba55f9de5e2017e8ec66244c82f05dc11be5 Mon Sep 17 00:00:00 2001 From: huzaif Date: Thu, 24 Dec 2020 17:27:11 +0530 Subject: [PATCH 03/75] updated node response and added types --- lib/base.js | 283 ++-- lib/resources/accounts.js | 179 +- lib/resources/applications.js | 471 ++++-- lib/resources/call.js | 1496 +++++++++------- lib/resources/callFeedback.js | 66 +- lib/resources/conferences.js | 1503 ++++++++++------- lib/resources/endpoints.js | 390 +++-- lib/resources/lookup.js | 37 +- lib/resources/media.js | 219 ++- lib/resources/messages.js | 375 ++-- lib/resources/numbers.js | 451 +++-- lib/resources/phlo.js | 186 +- lib/resources/phloMultiPartyCallMember.js | 37 +- lib/resources/phloMultipartyCall.js | 97 +- lib/resources/powerpacks.js | 1142 ++++++++----- lib/resources/pricings.js | 124 +- lib/resources/recordings.js | 219 ++- lib/utils/jwt.js | 7 +- lib/utils/plivoxml.js | 1 + package.json | 1 + types/resources/accounts.d.ts | 90 +- types/resources/applications.d.ts | 115 +- types/resources/call.d.ts | 648 ++++--- types/resources/callFeedback.d.ts | 11 +- types/resources/conferences.d.ts | 94 +- types/resources/endpoints.d.ts | 112 +- types/resources/lookup.d.ts | 22 + types/resources/media.d.ts | 59 +- types/resources/messages.d.ts | 152 +- types/resources/numbers.d.ts | 192 ++- types/resources/phlo.d.ts | 50 +- types/resources/phloMultiPartyCallMember.d.ts | 33 +- types/resources/phloMultipartyCall.d.ts | 46 +- types/resources/powerpacks.d.ts | 263 ++- types/resources/pricings.d.ts | 38 +- types/resources/recordings.d.ts | 76 +- types/rest/client-test.d.ts | 2 + types/rest/client.d.ts | 2 + types/utils/jsonStrinfigier.d.ts | 4 +- types/utils/jwt.d.ts | 21 + types/utils/security.d.ts | 10 +- types/utils/v3Security.d.ts | 2 +- 42 files changed, 6071 insertions(+), 3255 deletions(-) create mode 100644 types/resources/lookup.d.ts create mode 100644 types/utils/jwt.d.ts diff --git a/lib/base.js b/lib/base.js index 98d0f49..8049673 100644 --- a/lib/base.js +++ b/lib/base.js @@ -1,4 +1,6 @@ -import { extend } from './utils/common.js'; +import { + extend +} from './utils/common.js'; let actionKey = Symbol('api action'); let klassKey = Symbol('constructor'); @@ -7,182 +9,187 @@ let clientKey = Symbol('make api call'); 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; + 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; + 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); - }); - }); + 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; + 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); - }); - }); + 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]; + 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); - }); - }); + 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); - }); - }); + 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; + 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); - }); - }); + 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 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); + }); + }); } -} +} \ No newline at end of file diff --git a/lib/resources/accounts.js b/lib/resources/accounts.js index c40b9e7..da8a22c 100644 --- a/lib/resources/accounts.js +++ b/lib/resources/accounts.js @@ -1,8 +1,10 @@ -import {extend, validate} from '../utils/common.js'; import {PlivoResource, PlivoResourceInterface} from '../base'; +import {extend, validate} from '../utils/common.js'; + +import { PlivoGenericResponse } from '../../dist/base'; const clientKey = Symbol(); -const action = ''; +const action = 'Subaccount/'; const idField = 'authId'; /** @@ -11,10 +13,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 +116,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 +141,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 +193,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 +233,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 +313,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 +331,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 +372,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..d8895dd 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,144 @@ 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]; + return new Promise((resolve, reject) => { + client('DELETE', action + id + '/', params) + .then(() => { + resolve(true); + }) + .catch(error => { + reject(error); + }); + }); + } +} + /** * Represents a Application interface * @constructor @@ -73,126 +163,165 @@ 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]; + 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; + 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); + } +} \ No newline at end of file diff --git a/lib/resources/call.js b/lib/resources/call.js index 655c0ac..2b25bfe 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,268 @@ 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) { + 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 +444,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 +887,72 @@ 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, params) + .then(response => { + let calls = []; + response.body.calls.forEach(callUuid => { + calls.push(new LiveCallResource(client, { + callUuid: callUuid + })); + }); + resolve(new ListAllLiveCallResponse(calls[0])); + }) + .catch(error => { + reject(error); + }); + }); + } } @@ -636,49 +963,72 @@ 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(new ListAllQueuedCalls(calls[0])); + }) + .catch(error => { + reject(error); + }); + }); + } +} \ No newline at end of file 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/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/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 a05d788..58799b7 100644 --- a/lib/resources/messages.js +++ b/lib/resources/messages.js @@ -1,16 +1,15 @@ import * as _ from "lodash"; import { - PlivoGenericResponse, - PlivoResource, - PlivoResourceInterface + PlivoGenericResponse, + PlivoResource, + PlivoResourceInterface } from '../base'; import { - extend, - validate + extend, + validate } from '../utils/common.js'; - const action = 'Message/'; const idField = 'messageUuid'; let actionKey = Symbol('api action'); @@ -19,14 +18,78 @@ 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; + 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 * @constructor @@ -34,19 +97,31 @@ export class MessageResponse { * @param {object} [data] - data of call */ export class Message extends PlivoResource { - constructor(client, data = {}) { - super(action, Message, idField, client); + constructor(client, data = {}) { + super(action, Message, idField, client); + this[actionKey] = action; + this[clientKey] = client; + if (idField in data) { + this.id = data[idField]; + }; - if (idField in data) { - this.id = data[idField]; - }; + extend(this, data); + } - extend(this, data); - } - - listMedia() { - return super.executeAction(this.id + '/Media/', 'Get', {}); - } + listMedia() { + //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); + }); + }); + } } /** @@ -58,125 +133,161 @@ export class Message extends PlivoResource { export class MessageInterface extends PlivoResourceInterface { - constructor(client, data = {}) { - super(action, Message, idField, client); - extend(this, data); - this[clientKey] = client; - this[actionKey] = action; - this[klassKey] = Message; - this[idKey] = idField; + constructor(client, data = {}) { + super(action, Message, idField, client); + extend(this, data); + this[clientKey] = client; + this[actionKey] = action; + this[klassKey] = Message; + this[idKey] = idField; - } - - /** - * 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, dst, text, optionalParams) { - return this.create(src, dst, text, optionalParams); - } - - /** - * 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 - */ - createtest(src, dst, text, optionalParams, powerpackUUID) { - let errors = validate([{ - field: 'dst', - value: dst, - validators: ['isRequired'] - }]); - - if (errors) { - return errors; } - if (!src && !powerpackUUID) { - let errorText = 'Neither of src or powerpack uuid present, either one is required' - return new Promise(function (resolve, reject) { - reject(new Error(errorText)); - }); + /** + * 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, dst, text, optionalParams) { + return this.create(src, dst, text, optionalParams); } - if (src && powerpackUUID) { - let errorText = 'Either of src or powerpack uuid, both of them are present' - return new Promise(function (resolve, reject) { - reject(new Error(errorText)); - }) - } + /** + * 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, dst, text, optionalParams, powerpackUUID) { + let errors = validate([{ + field: 'dst', + value: dst, + validators: ['isRequired'] + }]); - let params = optionalParams || {}; - if (src) { - params.src = src; - } - params.dst = _.isArray(dst) ? _.join(dst, '<') : dst; - params.text = text; - if (powerpackUUID) { - params.powerpackUUID = powerpackUUID; - } + if (errors) { + return errors; + } - let client = this[clientKey]; - let idField = this[idKey]; - let action = this[actionKey] + (this.id ? this.id + '/' : ''); + if (!src && !powerpackUUID) { + let errorText = 'Neither of src or powerpack uuid present, either one is required' + return new Promise(function(resolve, reject) { + reject(new Error(errorText)); + }); + } - return new Promise((resolve, reject) => { - client('POST', action, params) - .then(response => { - resolve(new MessageResponse(response.body, idField)); + if (src && powerpackUUID) { + let errorText = 'Either of src or powerpack uuid, both of them are present' + return new Promise(function(resolve, reject) { + reject(new Error(errorText)); + }) + } + + let params = optionalParams || {}; + if (src) { + params.src = src; + } + params.dst = _.isArray(dst) ? _.join(dst, '<') : dst; + params.text = text; + if (powerpackUUID) { + params.powerpackUUID = powerpackUUID; + } + + 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); + }); }) - .catch(error => { - reject(error); - }); - }) - } - - /** - * Get Message by given id - * @method - * @param {string} id - id of message - * @promise {object} return {@link Message} object if success - * @fail {Error} return Error - */ - get(id) { - let errors = validate([{ - field: 'id', - value: id, - validators: ['isRequired'] - }]); - - if (errors) { - return errors; } - return super.get(id); - } + /** + * Get Message by given id + * @method + * @param {string} id - id of message + * @promise {object} return {@link Message} object if success + * @fail {Error} return Error + */ + get(id) { + let errors = validate([{ + field: 'id', + value: id, + validators: ['isRequired'] + }]); - listMedia(messageUUID) { - return new Message(this[clientKey], { - id: messageUUID - }).listMedia(); - } + if (errors) { + return errors; + } -} + 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) { + return new Message(this[clientKey], { + id: messageUUID + }).listMedia(); + } + +} \ No newline at end of file diff --git a/lib/resources/numbers.js b/lib/resources/numbers.js index f927bf7..14c8152 100644 --- a/lib/resources/numbers.js +++ b/lib/resources/numbers.js @@ -1,10 +1,35 @@ -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 UpdateNumberResponse { + constructor(params) { + params = params || {}; + this.apiId = params.apiId; + this.message = params.message; + } +} + /** * Represents a PhoneNumber * @constructor @@ -12,29 +37,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 +70,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', action + number + '/', params) + .then(response => { + resolve(new BuyNumberResponse(response.body, idField)); + }) + .catch(error => { + reject(error); + }); + }); } - return super.create(params); - } } /** @@ -75,38 +110,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 +182,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); } - return new NumberResource(this[clientKey], { - id: number - }).unrent(); - } -} + + /** + * 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(countryISO, 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); + } +} \ No newline at end of file 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 f10c34e..0941181 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 @@ -200,210 +459,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 @@ -412,90 +681,97 @@ 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] + * @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; - return super.create(params); - } + 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); + }); + }); - /** - * 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); - } + /** + * 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'] + }]); - /** - * 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); - } -} + 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); + } +} \ 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..81dc158 100644 --- a/lib/resources/recordings.js +++ b/lib/resources/recordings.js @@ -1,73 +1,141 @@ -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 client = this[clientKey]; + return new Promise((resolve, reject) => { + client('DELETE', action + id + '/') + .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 +148,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); } -} +} \ No newline at end of file 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..002d668 100644 --- a/lib/utils/plivoxml.js +++ b/lib/utils/plivoxml.js @@ -2,6 +2,7 @@ var qs = require('querystring'); var xmlBuilder = require('xmlbuilder'); var util = require('util'); var plivoUtils = require('./../rest/utils'); + import * as Exceptions from './exceptions'; var jsonStringifier = require('./jsonStrinfigier'); diff --git a/package.json b/package.json index 0a3bee6..a3ef871 100644 --- a/package.json +++ b/package.json @@ -58,6 +58,7 @@ "test": "gulp" }, "dependencies": { + "@types/node": "^14.14.14", "base-64": "^0.1.0", "build-url": "^1.0.10", "jsonwebtoken": "^8.5.1", diff --git a/types/resources/accounts.d.ts b/types/resources/accounts.d.ts index f109892..a907f4e 100644 --- a/types/resources/accounts.d.ts +++ b/types/resources/accounts.d.ts @@ -4,9 +4,70 @@ * @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: stringy; + 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: any, data?: {}); id: any; + /** + * 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: any): Promise; + [clientKey]: any; } /** * Represents a Subaccount Interface @@ -16,6 +77,23 @@ export class Subaccount extends PlivoResource { */ export class SubaccountInterface extends PlivoResourceInterface { constructor(client: any, 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 @@ -53,6 +131,7 @@ export class Account extends PlivoResource { * @fail {Error} return Error */ get(): Promise; + update(params: any): Promise; [clientKey]: any; } /** @@ -63,6 +142,13 @@ export class Account extends PlivoResource { */ export class AccountInterface extends PlivoResourceInterface { constructor(client: any, data?: {}); + /** + * get account detail + * @method + * @promise {PlivoGenericResponse} return PlivoGenericResponse object + * @fail {Error} return Error + */ + get(): Promise; /** * update account detail * @method @@ -80,7 +166,7 @@ export class AccountInterface extends PlivoResourceInterface { }): Promise; [clientKey]: any; } -import { PlivoResource } from "../base.js"; -import { PlivoResourceInterface } from "../base.js"; +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 index 5afe15c..26245a8 100644 --- a/types/resources/applications.d.ts +++ b/types/resources/applications.d.ts @@ -1,21 +1,112 @@ /** - * Represents a Application - * @constructor - * @param {function} client - make api call - * @param {object} [data] - data of call - */ +* 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: any, data?: {}); id: any; + [clientKey]: any; } /** - * Represents a Application interface - * @constructor - * @param {function} client - make api call - * @param {object} [data] - data of call - */ +* Represents a Application interface +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ export class ApplicationInterface extends PlivoResourceInterface { constructor(client: any, 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 @@ -66,7 +157,7 @@ export class ApplicationInterface extends PlivoResourceInterface { }): Promise; [clientKey]: any; } -import { PlivoResource } from "../base.js"; -import { PlivoResourceInterface } from "../base.js"; +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 index e7efab2..2a9d67d 100644 --- a/types/resources/call.d.ts +++ b/types/resources/call.d.ts @@ -1,3 +1,116 @@ +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: any); + 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 @@ -5,125 +118,125 @@ * @param {object} [data] - data of call */ export class Call extends PlivoResource { - constructor(client: any, data?: {}); - id: any; - /** - * hangup call - * @method - * @promise {Boolean} return true if call hung up - * @fail {Error} return Error - */ - hangup(): Promise; - /** - * 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; - }): Promise; - /** - * record call - * @method - * @param {object} params - to record call - * @promise {object} return PlivoGenericResponse Object - * @fail {Error} return Error - */ - record(params: object): Promise; - /** - * record call - * @method - * @param {object} params - to record call - * @promise {object} return PlivoGenericResponse Object - * @fail {Error} return Error - */ - startRecording(params: object): Promise; - /** - * stop recording call - * @method - * @param {object} params - to stop recording call - * @promise {object} return PlivoGenericResponse Object - * @fail {Error} return Error - */ - stopRecording(params: object): Promise; - /** - * 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; - /** - * 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; - /** - * stop playing music for call - * @method - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - stopPlayingMusic(): Promise; - /** - * 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; - /** - * 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; - /** - * stop speaking text for call - * @method - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - stopSpeakingText(): Promise; - /** - * 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; - /** - * Hangup a Call Request - * @method - * @promise {object} returns PlivoGenericResponse Object - * @fail {Error} returns Error - */ - cancel(): Promise; - [clientKey]: any; + constructor(client: any, data ? : {}); + id: any; + /** + * 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: any): 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]: any; } /** * Represents a Call Interface @@ -132,129 +245,179 @@ export class Call extends PlivoResource { * @param {object} [data] - data of call */ export class CallInterface extends PlivoResourceInterface { - constructor(client: any, data?: {}); - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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; - /** - * 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: any): Promise; - listLiveCalls(params: any): Promise; - getLiveCall(id: any): Promise; - listQueuedCalls(): Promise; - getQueuedCall(id: any): Promise; - [clientKey]: any; - [liveCallInterfaceKey]: LiveCallInterface; - [queuedCallInterfaceKey]: QueuedCallInterface; + constructor(client: any, 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: any): Promise < any > ; + listLiveCalls(params: any): Promise < any > ; + getLiveCall(id: any): Promise < any > ; + listQueuedCalls(): Promise < any > ; + getQueuedCall(id: any): Promise < any > ; + [clientKey]: any; + [liveCallInterfaceKey]: LiveCallInterface; + [queuedCallInterfaceKey]: QueuedCallInterface; } export class LiveCallResource extends PlivoResource { - constructor(client: any, data?: {}); - id: any; - [clientKey]: any; + constructor(client: any, data ? : {}); + id: any; + [clientKey]: any; } export class QueuedCallResource extends PlivoResource { - constructor(client: any, data?: {}); - id: any; - [clientKey]: any; + constructor(client: any, data ? : {}); + id: any; + [clientKey]: any; } -import { PlivoResource } from "../base.js"; +import { + PlivoResource +} from "../base"; declare const clientKey: unique symbol; -import { PlivoResourceInterface } from "../base.js"; +import { + PlivoResourceInterface +} from "../base"; declare const liveCallInterfaceKey: unique symbol; /** * Represents a LiveCall interface @@ -263,8 +426,8 @@ declare const liveCallInterfaceKey: unique symbol; * @param {object} [data] - data of call */ declare class LiveCallInterface extends PlivoResourceInterface { - constructor(client: any, data?: {}); - [clientKey]: any; + constructor(client: any, data ? : {}); + [clientKey]: any; } declare const queuedCallInterfaceKey: unique symbol; /** @@ -273,8 +436,11 @@ declare const queuedCallInterfaceKey: unique symbol; * @param {function} client - make api call * @param {object} [data] - data of call */ + declare class QueuedCallInterface extends PlivoResourceInterface { - constructor(client: any, data?: {}); - [clientKey]: any; + constructor(client: any, data ? : {}); + get(id: any): Promise < GetQueuedCallResponse > ; + list(): Promise < ListAllQueuedCalls > ; + [clientKey]: any; } -export {}; +export {}; \ No newline at end of file diff --git a/types/resources/callFeedback.d.ts b/types/resources/callFeedback.d.ts index a11b890..e2635d7 100644 --- a/types/resources/callFeedback.d.ts +++ b/types/resources/callFeedback.d.ts @@ -1,3 +1,9 @@ +export class CallFeedbackResponse { + constructor(params: object); + apiId: string; + message: string; + status: string; +} export class CallFeedback extends PlivoResource { constructor(client: any, data?: {}); id: any; @@ -11,9 +17,10 @@ export class CallFeedback extends PlivoResource { */ export class CallFeedbackInterface extends PlivoResourceInterface { constructor(client: any, data?: {}); + create(callUUID: string, rating: string, issues?: never[], notes?: string): Promise; [clientKey]: any; } -import { PlivoResource } from "../base.js"; +import { PlivoResource } from "../base"; declare const clientKey: unique symbol; -import { PlivoResourceInterface } from "../base.js"; +import { PlivoResourceInterface } from "../base"; export {}; diff --git a/types/resources/conferences.d.ts b/types/resources/conferences.d.ts index afcdde0..1eb9f1d 100644 --- a/types/resources/conferences.d.ts +++ b/types/resources/conferences.d.ts @@ -1,9 +1,53 @@ /** - * Represents a Conference - * @constructor - * @param {function} client - make api call - * @param {object} [data] - data of call - */ +* 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: any, data?: {}); id: any; @@ -37,7 +81,7 @@ export class Conference extends PlivoResource { * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ - muteMember(memberId: string): Promise; + muteMember(memberId: string): Promise; /** * unmute member from conference * @method @@ -53,7 +97,7 @@ export class Conference extends PlivoResource { * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ - deafMember(memberId: string): Promise; + deafMember(memberId: string): Promise; /** * undeaf member from conference * @method @@ -70,7 +114,7 @@ export class Conference extends PlivoResource { * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ - playAudioToMember(memberId: string, url: string): Promise; + playAudioToMember(memberId: string, url: string): Promise; /** * stop playing audio to member * @method @@ -93,7 +137,7 @@ export class Conference extends PlivoResource { speakTextToMember(memberId: string, text: string, optionalParams: { voice: string; language: string; - }): Promise; + }): Promise; /** * stop speaking text to member * @method @@ -147,7 +191,7 @@ export class Conference extends PlivoResource { transcriptionMethod: string; callbackUrl: string; callbackMethod: string; - }): Promise; + }): Promise; /** * stop recording conference * @method @@ -158,13 +202,29 @@ export class Conference extends PlivoResource { [clientKey]: any; } /** - * Represents a Conference Interface - * @constructor - * @param {function} client - make api call - * @param {object} [data] - data of call - */ +* Represents a Conference Interface +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ export class ConferenceInterface extends PlivoResourceInterface { constructor(client: any, 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 @@ -331,7 +391,7 @@ export class ConferenceInterface extends PlivoResourceInterface { stopRecording(id: string): Promise; [clientKey]: any; } -import { PlivoResource } from "../base.js"; +import { PlivoResource } from "../base"; declare const clientKey: unique symbol; -import { PlivoResourceInterface } from "../base.js"; +import { PlivoResourceInterface } from "../base"; export {}; diff --git a/types/resources/endpoints.d.ts b/types/resources/endpoints.d.ts index e1850ef..d40fd8c 100644 --- a/types/resources/endpoints.d.ts +++ b/types/resources/endpoints.d.ts @@ -1,22 +1,101 @@ +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: any); + 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 - */ +* Represents a Endpoint +* @constructor +* @param {function} client - make api call +* @param {object} [data] - data of call +*/ export class Endpoint extends PlivoResource { constructor(client: any, data?: {}); id: any; + /** + * 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]: any; } /** - * 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: any, 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 @@ -29,12 +108,7 @@ export class EndpointInterface extends PlivoResourceInterface { * @promise {object} return {@link Endpoint} object if success * @fail {Error} return Error */ - update(id: string, params: { - username: string; - password: string; - alias: string; - appId: string; - }): Promise; + update(id: string, params: object): any; /** * delete Endpoint * @method @@ -42,10 +116,10 @@ export class EndpointInterface extends PlivoResourceInterface { * @promise {boolean} return true if success * @fail {Error} return Error */ - delete(id: string): Promise; + delete(id: any): any; [clientKey]: any; } -import { PlivoResource } from "../base.js"; +import { PlivoResource } from "../base"; declare const clientKey: unique symbol; -import { PlivoResourceInterface } from "../base.js"; +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..04c6610 --- /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: any, data?: {}); + [clientKey]: any; +} +export class LookupInterface extends PlivoResourceInterface { + constructor(client: any, data?: {}); + get(number: string, type?: string): Promise; + [clientKey]: any; +} +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 index 52e514a..da86885 100644 --- a/types/resources/media.d.ts +++ b/types/resources/media.d.ts @@ -1,3 +1,24 @@ +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 @@ -5,8 +26,8 @@ * @param {object} [data] - data of call */ export class Media extends PlivoResource { - constructor(client: any, data?: {}); - id: any; + constructor(client: any, data ? : {}); + id: any; } /** * Represents a Media Interface @@ -15,16 +36,36 @@ export class Media extends PlivoResource { * @param {object} [data] - data of call */ export class MediaInterface extends PlivoResourceInterface { - constructor(client: any, data?: {}); + constructor(client: any, data ? : {}); + /** + * Upload Media + * @method + * @fail {Error} return Error + */ + upload(files: any): Promise; /** - * Upload Media + * 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 */ - upload(files: any): Promise; - [clientKey]: any; + 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]: any; } -import { PlivoResource } from "../base.js"; -import { PlivoResourceInterface } from "../base.js"; +import { + PlivoResource +} from "../base"; +import { + PlivoResourceInterface +} from "../base"; declare const clientKey: unique symbol; -export {}; +export {}; \ No newline at end of file diff --git a/types/resources/messages.d.ts b/types/resources/messages.d.ts index e421fc3..235a835 100644 --- a/types/resources/messages.d.ts +++ b/types/resources/messages.d.ts @@ -1,21 +1,65 @@ -import { PlivoResource, PlivoResourceInterface } from '../base'; -export declare class MessageResponse { - constructor(params: object); - apiId: string - message: string - messageUuid: object +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: any; + 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 declare class Message extends PlivoResource { - constructor(client: any, data?: {}); - listMedia(): any; +export class Message extends PlivoResource { + constructor(client: any, data ? : {}); + id: any; + listMedia(): Promise < any > ; } /** * Represents a Message Interface @@ -23,38 +67,56 @@ export declare class Message extends PlivoResource { * @param {function} client - make api call * @param {object} [data] - data of call */ -export declare class MessageInterface extends PlivoResourceInterface { - constructor(client: any, 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: any, dst: string, text: string, optionalParams: object): Promise; - /** - * 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 - */ - createtest(src: any, dst: string, text: string, optionalParams: object, powerpackUUID: any): Promise; +export class MessageInterface extends PlivoResourceInterface { + constructor(client: any, 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: any; + 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 index a59ff0c..25fc5d6 100644 --- a/types/resources/numbers.d.ts +++ b/types/resources/numbers.d.ts @@ -1,3 +1,14 @@ +export class BuyNumberResponse { + constructor(params: object); + apiId: string; + numbers: object; + status: string; +} +export class UpdateNumberResponse { + constructor(params: object); + apiId: string; + message: string; +} /** * Represents a PhoneNumber * @constructor @@ -5,17 +16,17 @@ * @param {object} [data] - data of call */ export class PhoneNumber extends PlivoResource { - constructor(client: any, data?: {}); - id: any; - /** - * 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; - [clientKey]: any; + constructor(client: any, data ? : {}); + id: any; + /** + * 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]: any; } /** * Represents a PhoneNumbers Interface @@ -25,16 +36,16 @@ export class PhoneNumber extends PlivoResource { * @param {string} [data.test] - test data */ export class PhoneNumberInterface extends PlivoResourceInterface { - constructor(client: any, data?: {}); - /** - * 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; - [clientKey]: any; + constructor(client: any, 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 < BuyNumberResponse > ; + [clientKey]: any; } /** * Represents a Number @@ -43,15 +54,16 @@ export class PhoneNumberInterface extends PlivoResourceInterface { * @param {object} [data] - data of call */ export class NumberResource extends PlivoResource { - constructor(client: any, data?: {}); - id: any; - /** - * Unrent Number - * @method - * @promise {boolean} return true if success - * @fail {Error} return Error - */ - unrent(): Promise; + constructor(client: any, data ? : {}); + id: any; + /** + * Unrent Number + * @method + * @promise {boolean} return true if success + * @fail {Error} return Error + */ + unrent(number: string): Promise < any > ; + [clientKey]: any; } /** * Represents a Numbers @@ -60,63 +72,67 @@ export class NumberResource extends PlivoResource { * @param {object} [data] - data of call */ export class NumberInterface extends PlivoResourceInterface { - constructor(client: any); - /** - * 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; - /** - * 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: any): Promise; - /** - * 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: any): Promise; - /** - * 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; - /** - * Unrent Number - * @method - * @param {string} number - number to unrent - * @promise {boolean} return true if success - * @fail {Error} return Error - */ - unrent(number: string): Promise; - [clientKey]: any; + constructor(client: any); + /** + * 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 < any > ; + /** + * 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: any): Promise < any > ; + /** + * 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: any): Promise < any > ; + /** + * 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 < any > ; + /** + * 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]: any; } -import { PlivoResource } from "../base.js"; +import { + PlivoResource +} from "../base"; declare const clientKey: unique symbol; -import { PlivoResourceInterface } from "../base.js"; -export {}; +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 index 9a3875a..c7b449b 100644 --- a/types/resources/phlo.d.ts +++ b/types/resources/phlo.d.ts @@ -1,3 +1,16 @@ +export class RunPHLOResponse { + constructor(params: any); + apiId: any; + phloId: any; + message: any; +} +export class RetrievePHLOResponse { + constructor(params: any); + apiId: any; + phloId: any; + name: any; + createdOn: any; +} /** * Represents a Phlo * @constructor @@ -5,16 +18,17 @@ * @param {object} [data] - data of phlo */ export class Phlo extends PlivoResource { - constructor(client: any, data?: {}); - client: any; - multiPartyCall: (nodeId: any) => PhloMultiPartyCall; - /** - * run phlo - * @method - * @promise {Boolean} return true if phlo is complete - * @fail {Error} return Error - */ - run(params: any): Promise; + constructor(client: any, data ? : {}); + client: any; + multiPartyCall: (nodeId: any) => PhloMultiPartyCall; + /** + * run phlo + * @method + * @promise {Boolean} return true if phlo is complete + * @fail {Error} return Error + */ + run(params: object): Promise < RunPHLOResponse > ; + [clientKey]: any; } /** * Represents a Phlo Interface @@ -24,7 +38,17 @@ export class Phlo extends PlivoResource { */ export class PhloInterface extends PlivoResourceInterface { constructor(client: any, data?: {}); + get(id: string): Promise; + [clientKey]: any; } -import { PlivoResource } from "../base.js"; -import { PhloMultiPartyCall } from "./phloMultipartyCall.js"; -import { PlivoResourceInterface } from "../base.js"; +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 index 14af70c..de765d9 100644 --- a/types/resources/phloMultiPartyCallMember.d.ts +++ b/types/resources/phloMultiPartyCallMember.d.ts @@ -4,20 +4,31 @@ * @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: any, data?: {}); - action: string; - client: any; - resumeCall(): Promise; - voicemailDrop(): Promise; - hangup(): Promise; - hold(): Promise; + constructor(client: any, data ? : {}); + action: string; + client: any; + 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: any, data?: {}); - action: string; + constructor(client: any, data ? : {}); + action: string; client: any; + get(phloId: string, nodeId: string, memberAddress: string): any; } -import { PlivoResource } from "../base.js"; -import { PlivoResourceInterface } from "../base.js"; +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 index 1177f39..c5dabc9 100644 --- a/types/resources/phloMultipartyCall.d.ts +++ b/types/resources/phloMultipartyCall.d.ts @@ -1,16 +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: any, data?: {}); - action: string; - client: any; - member: (memberAddress: any) => PhloMultiPartyCallMember; - call(triggerSource: any, to: any, role: any): Promise; - warmTransfer(triggerSource: any, to: any, role: any): Promise; - coldTransfer(triggerSource: any, to: any, role: any): Promise; + constructor(client: any, data ? : {}); + action: string; + client: any; + member: (memberAddress: any) => PhloMultiPartyCallMember; + call(triggerSource: any, to: any, role: any): Promise < any > ; + warmTransfer(triggerSource: any, to: any, role: any): Promise < UpdateMultipartyCallResponse > ; + coldTransfer(triggerSource: any, to: any, role: any): Promise < UpdateMultipartyCallResponse > ; abortTransfer(memberAddress: any): Promise; + update(action: any, triggerSource: any, to: any, role: any): Promise; + [clientKey]: any; } export class PhloMultiPartyCallInterface extends PlivoResourceInterface { constructor(client: any, data?: {}); + get(phloId: string, id: string): Promise; + [clientKey]: any; } -import { PlivoResource } from "../base.js"; -import { PhloMultiPartyCallMember } from "./phloMultiPartyCallMember.js"; -import { PlivoResourceInterface } from "../base.js"; +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 index c5aeb70..4fabcab 100644 --- a/types/resources/powerpacks.d.ts +++ b/types/resources/powerpacks.d.ts @@ -1,3 +1,111 @@ +export class ListAllNumbersResponse { + constructor(params: object); + apiId: string; + meta: object; + objects: object; +} +export class CreatePowerpackResponse { + constructor(params: any); + 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: any; + response: string; +} +export class RemoveShortCodeResponse { + constructor(params: any); + apiId: any; + 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 @@ -5,55 +113,56 @@ * @param {object} [data] - data of call */ export class Powerpack extends PlivoResource { - constructor(client: any, data?: {}); - uuid: any; - number_pool_id: any; - number_pool: NumberPool; - list_numbers(params: any): Promise; - search_query(params: any): string; - count_numbers(params: any): Promise; - find_number(number: any): Promise; - add_number(number: any): Promise; - add_tollfree(tollfree: any): Promise; - remove_number(number: any, unrent?: boolean): Promise; - remove_tollfree(tollfree: any, unrent?: boolean): Promise; - remove_shortcode(shortcode: any): Promise; - list_shortcodes(params: any): Promise; - list_tollfree(params: any): Promise; - find_shortcode(shortcode: any): Promise; - find_tollfree(tollfree: any): Promise; - buy_add_number(params: any): any; + constructor(client: any, data ? : {}); + uuid: any; + number_pool_id: any; + 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): any; + [clientKey]: any; } export class NumberPool extends PlivoResource { - constructor(client: any, data?: {}); - numbers: Numbers; - shortcodes: Shortcode; - tollfree: Tollfree; + constructor(client: any, data ? : {}); + numbers: Numbers; + shortcodes: Shortcode; + tollfree: Tollfree; } export class Numbers extends PlivoResource { - constructor(client: any, data?: {}); - buy_add_number(params: any): any; - list(params: any): Promise; - count(params: any): Promise; - search_query(params: any): string; - find(number: any): Promise; - add(number: any): Promise; - remove(number: any, unrent?: boolean): Promise; + constructor(client: any, 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: any, data?: {}); - number_pool_id: any; - list(params: any): Promise; - find(shortcode: any): Promise; - remove(shortcode: any): Promise; + constructor(client: any, data ? : {}); + number_pool_id: any; + list(params: object): Promise < any > ; + find(shortcode: object): Promise < any > ; + remove(shortcode: object): Promise < any > ; } export class Tollfree extends PlivoResource { - constructor(client: any, data?: {}); - number_pool_id: any; - add(tollfree: any): Promise; - remove(tollfree: any, unrent?: boolean): Promise; - list(params: any): Promise; - find(tollfree: any): Promise; + constructor(client: any, data ? : {}); + number_pool_id: any; + 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 @@ -62,27 +171,55 @@ export class Tollfree extends PlivoResource { * @param {object} [data] - data of call */ export class PowerpackInterface extends PlivoResourceInterface { - constructor(client: any, data?: {}); + constructor(client: any, data ? : {}); /** - * 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; + * 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]: any; } -import { PlivoResource } from "../base.js"; -import { PlivoResourceInterface } from "../base.js"; +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 index 2c66c24..dfcf9d3 100644 --- a/types/resources/pricings.d.ts +++ b/types/resources/pricings.d.ts @@ -1,9 +1,20 @@ /** - * 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: any); + apiId: string; + country: string; + countryCode: string; + countryIso: string; + message: object; + mms: object; + phoneNumbers: object; + voice: object; +} export class Pricing extends PlivoResource { constructor(client: any, data?: {}); /** @@ -12,19 +23,20 @@ export class Pricing extends PlivoResource { * @promise {object} return {@link PlivoGenericResponse} object * @fail {Error} return Error */ - get(): Promise; + get(): Promise; + [clientKey]: any; } /** - * 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: any, data?: {}); [clientKey]: any; } -import { PlivoResource } from "../base.js"; -import { PlivoResourceInterface } from "../base.js"; +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 index 60e3a25..fa51f2a 100644 --- a/types/resources/recordings.d.ts +++ b/types/resources/recordings.d.ts @@ -1,3 +1,33 @@ +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 @@ -5,8 +35,9 @@ * @param {object} [data] - data of call */ export class Recording extends PlivoResource { - constructor(client: any, data?: {}); - id: any; + constructor(client: any, data ? : {}); + id: any; + [clientKey]: any; } /** * Represents a Recording Interface @@ -15,18 +46,41 @@ export class Recording extends PlivoResource { * @param {object} [data] - data of call */ export class RecordingInterface extends PlivoResourceInterface { - constructor(client: any, data?: {}); + constructor(client: any, 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]: any; /** - * Delete recording by id + * Get recording by id * @method - * @param {string} id - id to delete recording - * @promise {boolean} return true if success + * @param {string} id - id to get recording information + * @promise {object} return {@link Pricing} object * @fail {Error} return Error */ - delete(id: string): Promise; - [clientKey]: any; + 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.js"; -import { PlivoResourceInterface } from "../base.js"; +import { + PlivoResource +} from "../base"; declare const clientKey: unique symbol; -export {}; +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 index 9fe8a7d..bbf1693 100644 --- a/types/rest/client-test.d.ts +++ b/types/rest/client-test.d.ts @@ -7,6 +7,7 @@ export class Client { conferences: ConferenceInterface; endpoints: EndpointInterface; messages: MessageInterface; + lookup: LookupInterface; powerpacks: PowerpackInterface; numbers: NumberInterface; pricings: PricingInterface; @@ -29,6 +30,7 @@ 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"; diff --git a/types/rest/client.d.ts b/types/rest/client.d.ts index d52bce4..8723574 100644 --- a/types/rest/client.d.ts +++ b/types/rest/client.d.ts @@ -13,6 +13,7 @@ export class Client { conferences: ConferenceInterface; endpoints: EndpointInterface; messages: MessageInterface; + lookup: LookupInterface; powerpacks: PowerpackInterface; numbers: NumberInterface; pricings: PricingInterface; @@ -37,6 +38,7 @@ 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"; diff --git a/types/utils/jsonStrinfigier.d.ts b/types/utils/jsonStrinfigier.d.ts index d985f4b..c1de530 100644 --- a/types/utils/jsonStrinfigier.d.ts +++ b/types/utils/jsonStrinfigier.d.ts @@ -2,6 +2,6 @@ export default Flatted; export function parse(text: any, reviver: any): any; export function stringify(value: any, replacer: any, space: any): string; declare namespace Flatted { - export function parse(text: any, reviver: any): any; - export function stringify(value: any, replacer: any, space: any): string; + 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..ad12cfd --- /dev/null +++ b/types/utils/jwt.d.ts @@ -0,0 +1,21 @@ +export function AccessToken(authId: any, authToken: any, username: any, 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/security.d.ts b/types/utils/security.d.ts index 52e3081..fd33bb2 100644 --- a/types/utils/security.d.ts +++ b/types/utils/security.d.ts @@ -1,7 +1,3 @@ -export function computeOldSignature(authId: string, uri: string, params: { - [string]: string; -}): string; -export function verifyOldSignature(authId: string, uri: string, params: { - [string]: string; -}, signature: string): boolean; -export function validateSignature(uri: string, nonce: string, signature: string, auth_token: string): boolean; +export function computeOldSignature(authId: any, uri: any, params: any): any; +export function verifyOldSignature(authId: any, uri: any, params: any, signature: any): boolean; +export function validateSignature(uri: any, nonce: any, signature: any, auth_token: any): boolean; diff --git a/types/utils/v3Security.d.ts b/types/utils/v3Security.d.ts index d1ab388..79b13cb 100644 --- a/types/utils/v3Security.d.ts +++ b/types/utils/v3Security.d.ts @@ -1 +1 @@ -export function validateV3Signature(method: string, uri: string, nonce: string, auth_token: string, v3_signature: string, params?: {}): boolean; +export function validateV3Signature(method: any, uri: any, nonce: any, auth_token: any, v3_signature: any, params?: {}): boolean; From b5fd78f526e4d778173d55d89fe66626577d34d7 Mon Sep 17 00:00:00 2001 From: huzaif Date: Tue, 5 Jan 2021 22:46:55 +0530 Subject: [PATCH 04/75] updated types --- lib/resources/accounts.js | 2 -- types/base.d.ts | 6 ++-- types/resources/accounts.d.ts | 18 ++++++------ types/resources/applications.d.ts | 6 ++-- types/resources/call.d.ts | 28 +++++++++---------- types/resources/callFeedback.d.ts | 6 ++-- types/resources/conferences.d.ts | 6 ++-- types/resources/endpoints.d.ts | 8 +++--- types/resources/lookup.d.ts | 4 +-- types/resources/media.d.ts | 6 ++-- types/resources/messages.d.ts | 8 +++--- types/resources/numbers.d.ts | 12 ++++---- types/resources/phlo.d.ts | 16 +++++------ types/resources/phloMultiPartyCallMember.d.ts | 8 +++--- types/resources/phloMultipartyCall.d.ts | 6 ++-- types/resources/powerpacks.d.ts | 24 ++++++++-------- types/resources/pricings.d.ts | 4 +-- types/resources/recordings.d.ts | 6 ++-- types/rest/client-test.d.ts | 6 ++-- types/rest/client.d.ts | 6 ++-- types/utils/jwt.d.ts | 2 +- types/utils/security.d.ts | 6 ++-- 22 files changed, 96 insertions(+), 98 deletions(-) diff --git a/lib/resources/accounts.js b/lib/resources/accounts.js index da8a22c..6446c8b 100644 --- a/lib/resources/accounts.js +++ b/lib/resources/accounts.js @@ -1,8 +1,6 @@ import {PlivoResource, PlivoResourceInterface} from '../base'; import {extend, validate} from '../utils/common.js'; -import { PlivoGenericResponse } from '../../dist/base'; - const clientKey = Symbol(); const action = 'Subaccount/'; const idField = 'authId'; diff --git a/types/base.d.ts b/types/base.d.ts index 1beb4c8..6f598a8 100644 --- a/types/base.d.ts +++ b/types/base.d.ts @@ -1,10 +1,10 @@ export class PlivoGenericResponse { constructor(params: any, idString: any); - id: any; + id: string; } export class PlivoResource { constructor(action: any, klass: any, idField: any, request: any); - update(params: any, id: any): Promise; + update(params: any, id: string): Promise; delete(params: any): Promise; executeAction(task: string, method: string, params: {}, action: any): Promise; customexecuteAction(url: any, method?: string, params?: {}): Promise; @@ -13,7 +13,7 @@ export class PlivoResource { } export class PlivoResourceInterface { constructor(action: any, klass: any, idField: any, request: any); - get(id: any, params?: {}): Promise; + get(id: string, params?: {}): Promise; list(params: any): Promise; create(params: any): Promise; } diff --git a/types/resources/accounts.d.ts b/types/resources/accounts.d.ts index a907f4e..a1a69bb 100644 --- a/types/resources/accounts.d.ts +++ b/types/resources/accounts.d.ts @@ -27,7 +27,7 @@ export class CreateSubAccountResponse { } export class UpdateSubAccountDetails { constructor(params: object); - apiId: stringy; + apiId: string; message: string; } export class UpdateAccountDetailsResponse { @@ -48,8 +48,8 @@ export class GetSubAccountDetails { resourceUri: string; } export class Subaccount extends PlivoResource { - constructor(client: any, data?: {}); - id: any; + constructor(client: function, data?: {}); + id: string; /** * update subaccount * @method @@ -76,7 +76,7 @@ export class Subaccount extends PlivoResource { * @param {object} [data] - data of call */ export class SubaccountInterface extends PlivoResourceInterface { - constructor(client: any, data?: {}); + constructor(client: function, data?: {}); /** * get subaccount by id * @method @@ -103,7 +103,7 @@ export class SubaccountInterface extends PlivoResourceInterface { * @promise {Subaccount} return object of subaccount * @fail {Error} return Error */ - update(id: any, name: string, enabled: boolean): Promise; + update(id: string, name: string, enabled: boolean): Promise; /** * delete subaccount * @method @@ -112,7 +112,7 @@ export class SubaccountInterface extends PlivoResourceInterface { * @promise {boolean} return true if subaccount deleted * @fail {Error} return Error */ - delete(id: any, cascade: boolean): Promise; + delete(id: string, cascade: boolean): Promise; [clientKey]: any; } /** @@ -122,8 +122,8 @@ export class SubaccountInterface extends PlivoResourceInterface { * @param {object} [data] - data of call */ export class Account extends PlivoResource { - constructor(client: any, data?: {}); - id: any; + constructor(client: function, data?: {}); + id: string; /** * get account detail * @method @@ -141,7 +141,7 @@ export class Account extends PlivoResource { * @param {object} [data] - data of call */ export class AccountInterface extends PlivoResourceInterface { - constructor(client: any, data?: {}); + constructor(client: function, data?: {}); /** * get account detail * @method diff --git a/types/resources/applications.d.ts b/types/resources/applications.d.ts index 26245a8..053951f 100644 --- a/types/resources/applications.d.ts +++ b/types/resources/applications.d.ts @@ -55,8 +55,8 @@ export class ListAllApplicationResponse { subAccount: string; } export class Application extends PlivoResource { - constructor(client: any, data?: {}); - id: any; + constructor(client: function, data?: {}); + id: string; [clientKey]: any; } /** @@ -66,7 +66,7 @@ export class Application extends PlivoResource { * @param {object} [data] - data of call */ export class ApplicationInterface extends PlivoResourceInterface { - constructor(client: any, data?: {}); + constructor(client: function, data?: {}); /** * get application by given id * @method diff --git a/types/resources/call.d.ts b/types/resources/call.d.ts index 2a9d67d..24995fa 100644 --- a/types/resources/call.d.ts +++ b/types/resources/call.d.ts @@ -118,8 +118,8 @@ export class RecordCallResponse { * @param {object} [data] - data of call */ export class Call extends PlivoResource { - constructor(client: any, data ? : {}); - id: any; + constructor(client: function, data ? : {}); + id: string; /** * hangup call * @method @@ -145,7 +145,7 @@ export class Call extends PlivoResource { alegMethod: string; blegUrl: string; blegMethod: string; - }, callUUID: any): Promise < CallTransferResponse > ; + }, callUUid: string): Promise < CallTransferResponse > ; /** * record call * @method @@ -245,7 +245,7 @@ export class Call extends PlivoResource { * @param {object} [data] - data of call */ export class CallInterface extends PlivoResourceInterface { - constructor(client: any, data ? : {}); + constructor(client: function, data ? : {}); /** * Get A Call Detail * @method @@ -392,23 +392,23 @@ export class CallInterface extends PlivoResourceInterface { * @promise {object} returns PlivoGenericResponse Object * @fail {Error} returns Error */ - cancel(id: any): Promise < any > ; + cancel(id: string): Promise < any > ; listLiveCalls(params: any): Promise < any > ; - getLiveCall(id: any): Promise < any > ; + getLiveCall(id: string): Promise < any > ; listQueuedCalls(): Promise < any > ; - getQueuedCall(id: any): Promise < any > ; + getQueuedCall(id: string): Promise < any > ; [clientKey]: any; [liveCallInterfaceKey]: LiveCallInterface; [queuedCallInterfaceKey]: QueuedCallInterface; } export class LiveCallResource extends PlivoResource { - constructor(client: any, data ? : {}); - id: any; + constructor(client: function, data ? : {}); + id: string; [clientKey]: any; } export class QueuedCallResource extends PlivoResource { - constructor(client: any, data ? : {}); - id: any; + constructor(client: function, data ? : {}); + id: string; [clientKey]: any; } import { @@ -426,7 +426,7 @@ declare const liveCallInterfaceKey: unique symbol; * @param {object} [data] - data of call */ declare class LiveCallInterface extends PlivoResourceInterface { - constructor(client: any, data ? : {}); + constructor(client: function, data ? : {}); [clientKey]: any; } declare const queuedCallInterfaceKey: unique symbol; @@ -438,8 +438,8 @@ declare const queuedCallInterfaceKey: unique symbol; */ declare class QueuedCallInterface extends PlivoResourceInterface { - constructor(client: any, data ? : {}); - get(id: any): Promise < GetQueuedCallResponse > ; + constructor(client: function, data ? : {}); + get(id: string): Promise < GetQueuedCallResponse > ; list(): Promise < ListAllQueuedCalls > ; [clientKey]: any; } diff --git a/types/resources/callFeedback.d.ts b/types/resources/callFeedback.d.ts index e2635d7..2b8df48 100644 --- a/types/resources/callFeedback.d.ts +++ b/types/resources/callFeedback.d.ts @@ -5,8 +5,8 @@ export class CallFeedbackResponse { status: string; } export class CallFeedback extends PlivoResource { - constructor(client: any, data?: {}); - id: any; + constructor(client: function, data?: {}); + id: string; [clientKey]: any; } /** @@ -16,7 +16,7 @@ export class CallFeedback extends PlivoResource { * @param {object} [data] - data of call */ export class CallFeedbackInterface extends PlivoResourceInterface { - constructor(client: any, data?: {}); + constructor(client: function, data?: {}); create(callUUID: string, rating: string, issues?: never[], notes?: string): Promise; [clientKey]: any; } diff --git a/types/resources/conferences.d.ts b/types/resources/conferences.d.ts index 1eb9f1d..739355a 100644 --- a/types/resources/conferences.d.ts +++ b/types/resources/conferences.d.ts @@ -49,8 +49,8 @@ export class DeafMemberResponse { message: string; } export class Conference extends PlivoResource { - constructor(client: any, data?: {}); - id: any; + constructor(client: function, data?: {}); + id: string; /** * hangup conference * @method @@ -208,7 +208,7 @@ export class Conference extends PlivoResource { * @param {object} [data] - data of call */ export class ConferenceInterface extends PlivoResourceInterface { - constructor(client: any, data?: {}); + constructor(client: function, data?: {}); /** * get conference by id diff --git a/types/resources/endpoints.d.ts b/types/resources/endpoints.d.ts index d40fd8c..bf8f063 100644 --- a/types/resources/endpoints.d.ts +++ b/types/resources/endpoints.d.ts @@ -45,8 +45,8 @@ export class CreateEndpointResponse { * @param {object} [data] - data of call */ export class Endpoint extends PlivoResource { - constructor(client: any, data?: {}); - id: any; + constructor(client: function, data?: {}); + id: string; /** * update Endpoint * @method @@ -75,7 +75,7 @@ export class Endpoint extends PlivoResource { * @param {object} [data] - data of call */ export class EndpointInterface extends PlivoResourceInterface { - constructor(client: any, data?: {}); + constructor(client: function, data?: {}); /** * Get Endpoint by given id * @method @@ -116,7 +116,7 @@ export class EndpointInterface extends PlivoResourceInterface { * @promise {boolean} return true if success * @fail {Error} return Error */ - delete(id: any): any; + delete(id: string): any; [clientKey]: any; } import { PlivoResource } from "../base"; diff --git a/types/resources/lookup.d.ts b/types/resources/lookup.d.ts index 04c6610..14c5831 100644 --- a/types/resources/lookup.d.ts +++ b/types/resources/lookup.d.ts @@ -8,11 +8,11 @@ export class LookupResponse { resourceUri: string; } export class Number extends PlivoResource { - constructor(client: any, data?: {}); + constructor(client: function, data?: {}); [clientKey]: any; } export class LookupInterface extends PlivoResourceInterface { - constructor(client: any, data?: {}); + constructor(client: function, data?: {}); get(number: string, type?: string): Promise; [clientKey]: any; } diff --git a/types/resources/media.d.ts b/types/resources/media.d.ts index da86885..a451af1 100644 --- a/types/resources/media.d.ts +++ b/types/resources/media.d.ts @@ -26,8 +26,8 @@ export class ListMediaResponse { * @param {object} [data] - data of call */ export class Media extends PlivoResource { - constructor(client: any, data ? : {}); - id: any; + constructor(client: function, data ? : {}); + id: string; } /** * Represents a Media Interface @@ -36,7 +36,7 @@ export class Media extends PlivoResource { * @param {object} [data] - data of call */ export class MediaInterface extends PlivoResourceInterface { - constructor(client: any, data ? : {}); + constructor(client: function, data ? : {}); /** * Upload Media * @method diff --git a/types/resources/messages.d.ts b/types/resources/messages.d.ts index 235a835..891058f 100644 --- a/types/resources/messages.d.ts +++ b/types/resources/messages.d.ts @@ -37,7 +37,7 @@ export class MessageListResponse { } export class MMSMediaResponse { constructor(params: object); - apiId: any; + apiid: string; objects: MMSMedia[]; } export class MMSMedia { @@ -57,8 +57,8 @@ export class MMSMedia { * @param {object} [data] - data of call */ export class Message extends PlivoResource { - constructor(client: any, data ? : {}); - id: any; + constructor(client: function, data ? : {}); + id: string; listMedia(): Promise < any > ; } /** @@ -68,7 +68,7 @@ export class Message extends PlivoResource { * @param {object} [data] - data of call */ export class MessageInterface extends PlivoResourceInterface { - constructor(client: any, data ? : {}); + constructor(client: function, data?: {}); /** * Send Message * @method diff --git a/types/resources/numbers.d.ts b/types/resources/numbers.d.ts index 25fc5d6..c320cb8 100644 --- a/types/resources/numbers.d.ts +++ b/types/resources/numbers.d.ts @@ -16,8 +16,8 @@ export class UpdateNumberResponse { * @param {object} [data] - data of call */ export class PhoneNumber extends PlivoResource { - constructor(client: any, data ? : {}); - id: any; + constructor(client: function, data ? : {}); + id: string; /** * Buy Phone Number * @method @@ -36,7 +36,7 @@ export class PhoneNumber extends PlivoResource { * @param {string} [data.test] - test data */ export class PhoneNumberInterface extends PlivoResourceInterface { - constructor(client: any, data ? : {}); + constructor(client: function, data ? : {}); /** * Buy Phone Number * @method @@ -54,8 +54,8 @@ export class PhoneNumberInterface extends PlivoResourceInterface { * @param {object} [data] - data of call */ export class NumberResource extends PlivoResource { - constructor(client: any, data ? : {}); - id: any; + constructor(client: function, data ? : {}); + id: string; /** * Unrent Number * @method @@ -72,7 +72,7 @@ export class NumberResource extends PlivoResource { * @param {object} [data] - data of call */ export class NumberInterface extends PlivoResourceInterface { - constructor(client: any); + constructor(client: function); /** * Buy Phone Number * @method diff --git a/types/resources/phlo.d.ts b/types/resources/phlo.d.ts index c7b449b..3ddb7bc 100644 --- a/types/resources/phlo.d.ts +++ b/types/resources/phlo.d.ts @@ -1,13 +1,13 @@ export class RunPHLOResponse { constructor(params: any); - apiId: any; - phloId: any; + apiid: string; + phloid: string; message: any; } export class RetrievePHLOResponse { constructor(params: any); - apiId: any; - phloId: any; + apiid: string; + phloid: string; name: any; createdOn: any; } @@ -18,9 +18,9 @@ export class RetrievePHLOResponse { * @param {object} [data] - data of phlo */ export class Phlo extends PlivoResource { - constructor(client: any, data ? : {}); - client: any; - multiPartyCall: (nodeId: any) => PhloMultiPartyCall; + constructor(client: function, data ? : {}); + client: function; + multiPartyCall: (nodeid: string) => PhloMultiPartyCall; /** * run phlo * @method @@ -37,7 +37,7 @@ export class Phlo extends PlivoResource { * @param {object} [data] - data of call */ export class PhloInterface extends PlivoResourceInterface { - constructor(client: any, data?: {}); + constructor(client: function, data?: {}); get(id: string): Promise; [clientKey]: any; } diff --git a/types/resources/phloMultiPartyCallMember.d.ts b/types/resources/phloMultiPartyCallMember.d.ts index de765d9..43fe788 100644 --- a/types/resources/phloMultiPartyCallMember.d.ts +++ b/types/resources/phloMultiPartyCallMember.d.ts @@ -10,9 +10,9 @@ export class UpdateMemberResponse { error: string; } export class PhloMultiPartyCallMember extends PlivoResource { - constructor(client: any, data ? : {}); + constructor(client: function, data ? : {}); action: string; - client: any; + client: function; resumeCall(): Promise < any > ; voicemailDrop(): Promise < any > ; hangup(): Promise < any > ; @@ -21,9 +21,9 @@ export class PhloMultiPartyCallMember extends PlivoResource { update(action: object): Promise; } export class PhloMultiPartyCallMemberInterface extends PlivoResourceInterface { - constructor(client: any, data ? : {}); + constructor(client: function, data ? : {}); action: string; - client: any; + client: function; get(phloId: string, nodeId: string, memberAddress: string): any; } import { diff --git a/types/resources/phloMultipartyCall.d.ts b/types/resources/phloMultipartyCall.d.ts index c5dabc9..b3915fc 100644 --- a/types/resources/phloMultipartyCall.d.ts +++ b/types/resources/phloMultipartyCall.d.ts @@ -13,9 +13,9 @@ export class RetrieveMultipartyCallResponse { createdOn: string; } export class PhloMultiPartyCall extends PlivoResource { - constructor(client: any, data ? : {}); + constructor(client: function, data ? : {}); action: string; - client: any; + client: function; member: (memberAddress: any) => PhloMultiPartyCallMember; call(triggerSource: any, to: any, role: any): Promise < any > ; warmTransfer(triggerSource: any, to: any, role: any): Promise < UpdateMultipartyCallResponse > ; @@ -25,7 +25,7 @@ export class PhloMultiPartyCall extends PlivoResource { [clientKey]: any; } export class PhloMultiPartyCallInterface extends PlivoResourceInterface { - constructor(client: any, data?: {}); + constructor(client: function, data?: {}); get(phloId: string, id: string): Promise; [clientKey]: any; } diff --git a/types/resources/powerpacks.d.ts b/types/resources/powerpacks.d.ts index 4fabcab..90520fb 100644 --- a/types/resources/powerpacks.d.ts +++ b/types/resources/powerpacks.d.ts @@ -59,12 +59,12 @@ export class RemoveNumberResponse { } export class RemoveTollFreeNumberResponse { constructor(params: object); - apiId: any; + apiid: string; response: string; } export class RemoveShortCodeResponse { constructor(params: any); - apiId: any; + apiid: string; response: string; } export class AddTollFreeNumberresponse { @@ -113,9 +113,9 @@ export class RetrieveShortCodeResponse { * @param {object} [data] - data of call */ export class Powerpack extends PlivoResource { - constructor(client: any, data ? : {}); - uuid: any; - number_pool_id: any; + constructor(client: function, data ? : {}); + uuid: string; + number_pool_id: string; number_pool: NumberPool; list_numbers(params: object): Promise < ListAllNumbersResponse > ; search_query(params: object): string; @@ -134,13 +134,13 @@ export class Powerpack extends PlivoResource { [clientKey]: any; } export class NumberPool extends PlivoResource { - constructor(client: any, data ? : {}); + constructor(client: function, data ? : {}); numbers: Numbers; shortcodes: Shortcode; tollfree: Tollfree; } export class Numbers extends PlivoResource { - constructor(client: any, data ? : {}); + constructor(client: function, data ? : {}); buy_add_number(params: object): any; list(params: object): Promise < any > ; count(params: object): Promise < any > ; @@ -150,15 +150,15 @@ export class Numbers extends PlivoResource { remove(number: string, unrent ? : boolean): Promise < any > ; } export class Shortcode extends PlivoResource { - constructor(client: any, data ? : {}); - number_pool_id: any; + 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: any, data ? : {}); - number_pool_id: any; + 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 > ; @@ -171,7 +171,7 @@ export class Tollfree extends PlivoResource { * @param {object} [data] - data of call */ export class PowerpackInterface extends PlivoResourceInterface { - constructor(client: any, data ? : {}); + constructor(client: function, data ? : {}); /** * get Powerpack by given id * @method diff --git a/types/resources/pricings.d.ts b/types/resources/pricings.d.ts index dfcf9d3..5e5683b 100644 --- a/types/resources/pricings.d.ts +++ b/types/resources/pricings.d.ts @@ -16,7 +16,7 @@ export class PricingResponse { voice: object; } export class Pricing extends PlivoResource { - constructor(client: any, data?: {}); + constructor(client: function, data?: {}); /** * Get pricings by country * @method @@ -33,7 +33,7 @@ export class Pricing extends PlivoResource { * @param {object} [data] - data of call */ export class PricingInterface extends PlivoResourceInterface { - constructor(client: any, data?: {}); + constructor(client: function, data?: {}); [clientKey]: any; } import { PlivoResource } from "../base"; diff --git a/types/resources/recordings.d.ts b/types/resources/recordings.d.ts index fa51f2a..b47f077 100644 --- a/types/resources/recordings.d.ts +++ b/types/resources/recordings.d.ts @@ -35,8 +35,8 @@ export class ListRecordingResponse { * @param {object} [data] - data of call */ export class Recording extends PlivoResource { - constructor(client: any, data ? : {}); - id: any; + constructor(client: function, data ? : {}); + id: string; [clientKey]: any; } /** @@ -46,7 +46,7 @@ export class Recording extends PlivoResource { * @param {object} [data] - data of call */ export class RecordingInterface extends PlivoResourceInterface { - constructor(client: any, data ? : {}); + constructor(client: function, data ? : {}); /** * Delete recording by id * @method diff --git a/types/rest/client-test.d.ts b/types/rest/client-test.d.ts index bbf1693..15f2b17 100644 --- a/types/rest/client-test.d.ts +++ b/types/rest/client-test.d.ts @@ -1,5 +1,5 @@ export class Client { - constructor(authId: any, authToken: any, proxy: any); + constructor(authid: string, authToken: any, proxy: any); calls: CallInterface; accounts: AccountInterface; subAccounts: SubaccountInterface; @@ -20,8 +20,8 @@ export class Client { * 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; + constructor(authid: string, authToken: any, options: any); + phlo: (phloid: string) => Phlo; } import { CallInterface } from "../resources/call.js"; import { AccountInterface } from "../resources/accounts.js"; diff --git a/types/rest/client.d.ts b/types/rest/client.d.ts index 8723574..59c30c2 100644 --- a/types/rest/client.d.ts +++ b/types/rest/client.d.ts @@ -4,7 +4,7 @@ * You can also pass in additional parameters accepted by the node requests module. */ export class Client { - constructor(authId: any, authToken: any, options?: any); + constructor(authid: string, authToken: any, options?: any); calls: CallInterface; accounts: AccountInterface; subaccounts: SubaccountInterface; @@ -28,8 +28,8 @@ export class Client { * 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; + constructor(authid: string, authToken: any, options: any); + phlo: (phloid: string) => Phlo; } import { CallInterface } from "../resources/call.js"; import { AccountInterface } from "../resources/accounts.js"; diff --git a/types/utils/jwt.d.ts b/types/utils/jwt.d.ts index ad12cfd..5f54522 100644 --- a/types/utils/jwt.d.ts +++ b/types/utils/jwt.d.ts @@ -1,4 +1,4 @@ -export function AccessToken(authId: any, authToken: any, username: any, validityOptions?: {}, uid?: any): void; +export function AccessToken(authid: string, authToken: any, username: any, validityOptions?: {}, uid?: any): void; export class AccessToken { constructor(authId: string, authToken: string, username: string, validityOptions?: {}, uid?: any); authId: string; diff --git a/types/utils/security.d.ts b/types/utils/security.d.ts index fd33bb2..2755e7c 100644 --- a/types/utils/security.d.ts +++ b/types/utils/security.d.ts @@ -1,3 +1,3 @@ -export function computeOldSignature(authId: any, uri: any, params: any): any; -export function verifyOldSignature(authId: any, uri: any, params: any, signature: any): boolean; -export function validateSignature(uri: any, nonce: any, signature: any, auth_token: any): boolean; +export function computeOldSignature(authid: string, uri: any, params: any): any; +export function verifyOldSignature(authid: string, uri: any, params: any, signature: any): boolean; +export function validateSignature(uri: string, nonce: string, signature: string, auth_token: string): boolean; From c6f1d00b63058ca848927af8ca382a7b39e74e99 Mon Sep 17 00:00:00 2001 From: huzaif Date: Tue, 5 Jan 2021 23:16:29 +0530 Subject: [PATCH 05/75] updated types --- lib/resources/messages.js | 2 ++ types/base.d.ts | 10 +++++----- types/resources/accounts.d.ts | 12 ++++++------ types/resources/applications.d.ts | 4 ++-- types/resources/call.d.ts | 16 ++++++++-------- types/resources/callFeedback.d.ts | 4 ++-- types/resources/conferences.d.ts | 4 ++-- types/resources/endpoints.d.ts | 6 +++--- types/resources/lookup.d.ts | 4 ++-- types/resources/media.d.ts | 2 +- types/resources/numbers.d.ts | 12 ++++++------ types/resources/phlo.d.ts | 8 ++++---- types/resources/phloMultipartyCall.d.ts | 4 ++-- types/resources/powerpacks.d.ts | 10 +++++----- types/resources/pricings.d.ts | 6 +++--- types/resources/recordings.d.ts | 4 ++-- types/rest/client.d.ts | 4 ++-- types/rest/request-test.d.ts | 2 +- types/rest/request.d.ts | 2 +- types/rest/utils.d.ts | 2 +- types/utils/jwt.d.ts | 2 +- types/utils/security.d.ts | 4 ++-- types/utils/v3Security.d.ts | 2 +- 23 files changed, 64 insertions(+), 62 deletions(-) diff --git a/lib/resources/messages.js b/lib/resources/messages.js index 58799b7..b7eaaa1 100644 --- a/lib/resources/messages.js +++ b/lib/resources/messages.js @@ -10,6 +10,8 @@ import { validate } from '../utils/common.js'; +import { type } from "os"; + const action = 'Message/'; const idField = 'messageUuid'; let actionKey = Symbol('api action'); diff --git a/types/base.d.ts b/types/base.d.ts index 6f598a8..1aaf772 100644 --- a/types/base.d.ts +++ b/types/base.d.ts @@ -1,11 +1,11 @@ export class PlivoGenericResponse { - constructor(params: any, idString: any); + constructor(params: object, idString: any); id: string; } export class PlivoResource { constructor(action: any, klass: any, idField: any, request: any); - update(params: any, id: string): Promise; - delete(params: any): Promise; + update(params: object, id: string): Promise; + delete(params: object): Promise; executeAction(task: string, method: string, params: {}, action: any): Promise; customexecuteAction(url: any, method?: string, params?: {}): Promise; customexecuteGetNumberAction(url: any, method?: string, params?: {}): any; @@ -14,6 +14,6 @@ export class PlivoResource { export class PlivoResourceInterface { constructor(action: any, klass: any, idField: any, request: any); get(id: string, params?: {}): Promise; - list(params: any): Promise; - create(params: any): Promise; + list(params: object): Promise; + create(params: object): Promise; } diff --git a/types/resources/accounts.d.ts b/types/resources/accounts.d.ts index a1a69bb..0ad6a79 100644 --- a/types/resources/accounts.d.ts +++ b/types/resources/accounts.d.ts @@ -66,8 +66,8 @@ export class Subaccount extends PlivoResource { * @promise {boolean} return true if subaccount deleted * @fail {Error} return Error */ - delete(cascade: any): Promise; - [clientKey]: any; + delete(cascade: boolean): Promise; + [clientKey]: symbol; } /** * Represents a Subaccount Interface @@ -113,7 +113,7 @@ export class SubaccountInterface extends PlivoResourceInterface { * @fail {Error} return Error */ delete(id: string, cascade: boolean): Promise; - [clientKey]: any; + [clientKey]: symbol; } /** * Represents a Account @@ -131,8 +131,8 @@ export class Account extends PlivoResource { * @fail {Error} return Error */ get(): Promise; - update(params: any): Promise; - [clientKey]: any; + update(params: object): Promise; + [clientKey]: symbol; } /** * Represents a Account Interface @@ -164,7 +164,7 @@ export class AccountInterface extends PlivoResourceInterface { city: string; address: string; }): Promise; - [clientKey]: any; + [clientKey]: symbol; } import { PlivoResource } from "../base"; declare const clientKey: unique symbol; diff --git a/types/resources/applications.d.ts b/types/resources/applications.d.ts index 053951f..fa5b5f3 100644 --- a/types/resources/applications.d.ts +++ b/types/resources/applications.d.ts @@ -57,7 +57,7 @@ export class ListAllApplicationResponse { export class Application extends PlivoResource { constructor(client: function, data?: {}); id: string; - [clientKey]: any; + [clientKey]: symbol; } /** * Represents a Application interface @@ -155,7 +155,7 @@ export class ApplicationInterface extends PlivoResourceInterface { cascade: boolean; newEndpointApplication: string; }): Promise; - [clientKey]: any; + [clientKey]: symbol; } import { PlivoResource } from "../base"; declare const clientKey: unique symbol; diff --git a/types/resources/call.d.ts b/types/resources/call.d.ts index 24995fa..4e77cdd 100644 --- a/types/resources/call.d.ts +++ b/types/resources/call.d.ts @@ -32,7 +32,7 @@ export class GetQueuedCallResponse { requestUuid: string; } export class GetLiveCallResponse { - constructor(params: any); + constructor(params: object); apiId: string; callStatus: string; callUuid: string; @@ -236,7 +236,7 @@ export class Call extends PlivoResource { * @fail {Error} returns Error */ cancel(): Promise < any > ; - [clientKey]: any; + [clientKey]: symbol; } /** * Represents a Call Interface @@ -393,23 +393,23 @@ export class CallInterface extends PlivoResourceInterface { * @fail {Error} returns Error */ cancel(id: string): Promise < any > ; - listLiveCalls(params: any): Promise < any > ; + listLiveCalls(params: object): Promise < any > ; getLiveCall(id: string): Promise < any > ; listQueuedCalls(): Promise < any > ; getQueuedCall(id: string): Promise < any > ; - [clientKey]: any; + [clientKey]: symbol; [liveCallInterfaceKey]: LiveCallInterface; [queuedCallInterfaceKey]: QueuedCallInterface; } export class LiveCallResource extends PlivoResource { constructor(client: function, data ? : {}); id: string; - [clientKey]: any; + [clientKey]: symbol; } export class QueuedCallResource extends PlivoResource { constructor(client: function, data ? : {}); id: string; - [clientKey]: any; + [clientKey]: symbol; } import { PlivoResource @@ -427,7 +427,7 @@ declare const liveCallInterfaceKey: unique symbol; */ declare class LiveCallInterface extends PlivoResourceInterface { constructor(client: function, data ? : {}); - [clientKey]: any; + [clientKey]: symbol; } declare const queuedCallInterfaceKey: unique symbol; /** @@ -441,6 +441,6 @@ declare class QueuedCallInterface extends PlivoResourceInterface { constructor(client: function, data ? : {}); get(id: string): Promise < GetQueuedCallResponse > ; list(): Promise < ListAllQueuedCalls > ; - [clientKey]: any; + [clientKey]: symbol; } export {}; \ No newline at end of file diff --git a/types/resources/callFeedback.d.ts b/types/resources/callFeedback.d.ts index 2b8df48..fc051b2 100644 --- a/types/resources/callFeedback.d.ts +++ b/types/resources/callFeedback.d.ts @@ -7,7 +7,7 @@ export class CallFeedbackResponse { export class CallFeedback extends PlivoResource { constructor(client: function, data?: {}); id: string; - [clientKey]: any; + [clientKey]: symbol; } /** * Represents a CallFeedback Interface @@ -18,7 +18,7 @@ export class CallFeedback extends PlivoResource { export class CallFeedbackInterface extends PlivoResourceInterface { constructor(client: function, data?: {}); create(callUUID: string, rating: string, issues?: never[], notes?: string): Promise; - [clientKey]: any; + [clientKey]: symbol; } import { PlivoResource } from "../base"; declare const clientKey: unique symbol; diff --git a/types/resources/conferences.d.ts b/types/resources/conferences.d.ts index 739355a..a80f36a 100644 --- a/types/resources/conferences.d.ts +++ b/types/resources/conferences.d.ts @@ -199,7 +199,7 @@ export class Conference extends PlivoResource { * @fail {Error} return Error */ stopRecording(): Promise; - [clientKey]: any; + [clientKey]: symbol; } /** * Represents a Conference Interface @@ -389,7 +389,7 @@ export class ConferenceInterface extends PlivoResourceInterface { * @fail {Error} return Error */ stopRecording(id: string): Promise; - [clientKey]: any; + [clientKey]: symbol; } import { PlivoResource } from "../base"; declare const clientKey: unique symbol; diff --git a/types/resources/endpoints.d.ts b/types/resources/endpoints.d.ts index bf8f063..a7e79d4 100644 --- a/types/resources/endpoints.d.ts +++ b/types/resources/endpoints.d.ts @@ -18,7 +18,7 @@ export class RetrieveEndpointResponse { username: string; } export class ListAllEndpointResponse { - constructor(params: any); + constructor(params: object); apiId: string; alias: string; application: string; @@ -66,7 +66,7 @@ export class Endpoint extends PlivoResource { * @fail {Error} return Error */ delete(): Promise; - [clientKey]: any; + [clientKey]: symbol; } /** * Represents a Endpoint Interface @@ -117,7 +117,7 @@ export class EndpointInterface extends PlivoResourceInterface { * @fail {Error} return Error */ delete(id: string): any; - [clientKey]: any; + [clientKey]: symbol; } import { PlivoResource } from "../base"; declare const clientKey: unique symbol; diff --git a/types/resources/lookup.d.ts b/types/resources/lookup.d.ts index 14c5831..84c282d 100644 --- a/types/resources/lookup.d.ts +++ b/types/resources/lookup.d.ts @@ -9,12 +9,12 @@ export class LookupResponse { } export class Number extends PlivoResource { constructor(client: function, data?: {}); - [clientKey]: any; + [clientKey]: symbol; } export class LookupInterface extends PlivoResourceInterface { constructor(client: function, data?: {}); get(number: string, type?: string): Promise; - [clientKey]: any; + [clientKey]: symbol; } import { PlivoResource } from "../base"; declare const clientKey: unique symbol; diff --git a/types/resources/media.d.ts b/types/resources/media.d.ts index a451af1..b812126 100644 --- a/types/resources/media.d.ts +++ b/types/resources/media.d.ts @@ -59,7 +59,7 @@ export class MediaInterface extends PlivoResourceInterface { * @fail {Error} returns Error */ list(params: object): Promise; - [clientKey]: any; + [clientKey]: symbol; } import { PlivoResource diff --git a/types/resources/numbers.d.ts b/types/resources/numbers.d.ts index c320cb8..d2ca408 100644 --- a/types/resources/numbers.d.ts +++ b/types/resources/numbers.d.ts @@ -26,7 +26,7 @@ export class PhoneNumber extends PlivoResource { * @fail {Error} return Error */ buy(appId: string): Promise < any > ; - [clientKey]: any; + [clientKey]: symbol; } /** * Represents a PhoneNumbers Interface @@ -45,7 +45,7 @@ export class PhoneNumberInterface extends PlivoResourceInterface { * @fail {Error} return Error */ buy(number: string, appId: string): Promise < BuyNumberResponse > ; - [clientKey]: any; + [clientKey]: symbol; } /** * Represents a Number @@ -63,7 +63,7 @@ export class NumberResource extends PlivoResource { * @fail {Error} return Error */ unrent(number: string): Promise < any > ; - [clientKey]: any; + [clientKey]: symbol; } /** * Represents a Numbers @@ -92,7 +92,7 @@ export class NumberInterface extends PlivoResourceInterface { * @promise {@link PlivoGenericResponse} return PlivoGenericResponse Object if success * @fail {Error} return Error */ - addOwnNumber(numbers: string, carrier: string, region: string, optionalParams: any): Promise < any > ; + addOwnNumber(numbers: string, carrier: string, region: string, optionalParams: object): Promise < any > ; /** * Add own number from carrier * @method @@ -101,7 +101,7 @@ export class NumberInterface extends PlivoResourceInterface { * @promise {@link PhoneNumberInterface} return PhoneNumbers Object if success * @fail {Error} return Error */ - search(countryISO: string, optionalParams: any): Promise < any > ; + search(countryISO: string, optionalParams: object): Promise < any > ; /** * Update Number * @method @@ -126,7 +126,7 @@ export class NumberInterface extends PlivoResourceInterface { * @fail {Error} return Error */ unrent(number: string): Promise < any > ; - [clientKey]: any; + [clientKey]: symbol; } import { PlivoResource diff --git a/types/resources/phlo.d.ts b/types/resources/phlo.d.ts index 3ddb7bc..e891e35 100644 --- a/types/resources/phlo.d.ts +++ b/types/resources/phlo.d.ts @@ -1,11 +1,11 @@ export class RunPHLOResponse { - constructor(params: any); + constructor(params: object); apiid: string; phloid: string; message: any; } export class RetrievePHLOResponse { - constructor(params: any); + constructor(params: object); apiid: string; phloid: string; name: any; @@ -28,7 +28,7 @@ export class Phlo extends PlivoResource { * @fail {Error} return Error */ run(params: object): Promise < RunPHLOResponse > ; - [clientKey]: any; + [clientKey]: symbol; } /** * Represents a Phlo Interface @@ -39,7 +39,7 @@ export class Phlo extends PlivoResource { export class PhloInterface extends PlivoResourceInterface { constructor(client: function, data?: {}); get(id: string): Promise; - [clientKey]: any; + [clientKey]: symbol; } import { PlivoResource diff --git a/types/resources/phloMultipartyCall.d.ts b/types/resources/phloMultipartyCall.d.ts index b3915fc..fb82e63 100644 --- a/types/resources/phloMultipartyCall.d.ts +++ b/types/resources/phloMultipartyCall.d.ts @@ -22,12 +22,12 @@ export class PhloMultiPartyCall extends PlivoResource { coldTransfer(triggerSource: any, to: any, role: any): Promise < UpdateMultipartyCallResponse > ; abortTransfer(memberAddress: any): Promise; update(action: any, triggerSource: any, to: any, role: any): Promise; - [clientKey]: any; + [clientKey]: symbol; } export class PhloMultiPartyCallInterface extends PlivoResourceInterface { constructor(client: function, data?: {}); get(phloId: string, id: string): Promise; - [clientKey]: any; + [clientKey]: symbol; } import { PlivoResource diff --git a/types/resources/powerpacks.d.ts b/types/resources/powerpacks.d.ts index 90520fb..701ad5d 100644 --- a/types/resources/powerpacks.d.ts +++ b/types/resources/powerpacks.d.ts @@ -5,7 +5,7 @@ export class ListAllNumbersResponse { objects: object; } export class CreatePowerpackResponse { - constructor(params: any); + constructor(params: object); apiId: string; applicationId: string; applicationType: string; @@ -63,7 +63,7 @@ export class RemoveTollFreeNumberResponse { response: string; } export class RemoveShortCodeResponse { - constructor(params: any); + constructor(params: object); apiid: string; response: string; } @@ -130,8 +130,8 @@ export class Powerpack extends PlivoResource { 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): any; - [clientKey]: any; + buy_add_number(params: object): Promise ; + [clientKey]: symbol; } export class NumberPool extends PlivoResource { constructor(client: function, data ? : {}); @@ -213,7 +213,7 @@ export class PowerpackInterface extends PlivoResourceInterface { application_type: string; application_id: string; }): Promise < UpdatePowerpackResponse > ; - [clientKey]: any; + [clientKey]: symbol; } import { PlivoResource diff --git a/types/resources/pricings.d.ts b/types/resources/pricings.d.ts index 5e5683b..084cf8d 100644 --- a/types/resources/pricings.d.ts +++ b/types/resources/pricings.d.ts @@ -5,7 +5,7 @@ * @param {object} [data] - data of call */ export class PricingResponse { - constructor(params: any); + constructor(params: object); apiId: string; country: string; countryCode: string; @@ -24,7 +24,7 @@ export class Pricing extends PlivoResource { * @fail {Error} return Error */ get(): Promise; - [clientKey]: any; + [clientKey]: symbol; } /** * Represents a Pricing Interface @@ -34,7 +34,7 @@ export class Pricing extends PlivoResource { */ export class PricingInterface extends PlivoResourceInterface { constructor(client: function, data?: {}); - [clientKey]: any; + [clientKey]: symbol; } import { PlivoResource } from "../base"; declare const clientKey: unique symbol; diff --git a/types/resources/recordings.d.ts b/types/resources/recordings.d.ts index b47f077..93967e1 100644 --- a/types/resources/recordings.d.ts +++ b/types/resources/recordings.d.ts @@ -37,7 +37,7 @@ export class ListRecordingResponse { export class Recording extends PlivoResource { constructor(client: function, data ? : {}); id: string; - [clientKey]: any; + [clientKey]: symbol; } /** * Represents a Recording Interface @@ -55,7 +55,7 @@ export class RecordingInterface extends PlivoResourceInterface { * @fail {Error} return Error */ delete(id: string): Promise < any > ; - [clientKey]: any; + [clientKey]: symbol; /** * Get recording by id * @method diff --git a/types/rest/client.d.ts b/types/rest/client.d.ts index 59c30c2..ab23647 100644 --- a/types/rest/client.d.ts +++ b/types/rest/client.d.ts @@ -4,7 +4,7 @@ * You can also pass in additional parameters accepted by the node requests module. */ export class Client { - constructor(authid: string, authToken: any, options?: any); + constructor(authid: string, authToken: string, options?: string); calls: CallInterface; accounts: AccountInterface; subaccounts: SubaccountInterface; @@ -28,7 +28,7 @@ export class Client { * You can also pass in additional parameters accepted by the node requests module. */ export class PhloClient { - constructor(authid: string, authToken: any, options: any); + constructor(authid: string, authToken: string, options?: string); phlo: (phloid: string) => Phlo; } import { CallInterface } from "../resources/call.js"; diff --git a/types/rest/request-test.d.ts b/types/rest/request-test.d.ts index 6093327..028039c 100644 --- a/types/rest/request-test.d.ts +++ b/types/rest/request-test.d.ts @@ -1 +1 @@ -export function Request(config: any): (method: any, action: any, params: any) => Promise; +export function Request(config: any): (method: any, action: any, params: object) => Promise; diff --git a/types/rest/request.d.ts b/types/rest/request.d.ts index 6093327..028039c 100644 --- a/types/rest/request.d.ts +++ b/types/rest/request.d.ts @@ -1 +1 @@ -export function Request(config: any): (method: any, action: any, params: any) => Promise; +export function Request(config: any): (method: any, action: any, params: object) => Promise; diff --git a/types/rest/utils.d.ts b/types/rest/utils.d.ts index bd0a981..ac52936 100644 --- a/types/rest/utils.d.ts +++ b/types/rest/utils.d.ts @@ -1,4 +1,4 @@ -export function camelCaseRequestWrapper(requestFunc: any): (method: any, action: any, params: any) => any; +export function camelCaseRequestWrapper(requestFunc: any): (method: any, action: any, params: object) => any; export function validateSpeakAttributes(content: any, voice: any): { success: boolean; msg?: undefined; diff --git a/types/utils/jwt.d.ts b/types/utils/jwt.d.ts index 5f54522..03d4ad2 100644 --- a/types/utils/jwt.d.ts +++ b/types/utils/jwt.d.ts @@ -1,4 +1,4 @@ -export function AccessToken(authid: string, authToken: any, username: any, validityOptions?: {}, uid?: any): void; +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; diff --git a/types/utils/security.d.ts b/types/utils/security.d.ts index 2755e7c..95c38e6 100644 --- a/types/utils/security.d.ts +++ b/types/utils/security.d.ts @@ -1,3 +1,3 @@ -export function computeOldSignature(authid: string, uri: any, params: any): any; -export function verifyOldSignature(authid: string, uri: any, params: any, signature: any): boolean; +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 index 79b13cb..cecdaeb 100644 --- a/types/utils/v3Security.d.ts +++ b/types/utils/v3Security.d.ts @@ -1 +1 @@ -export function validateV3Signature(method: any, uri: any, nonce: any, auth_token: any, v3_signature: any, params?: {}): boolean; +export function validateV3Signature(method:string, uri: string, nonce: string, auth_token: string, v3_signature: string, params?: {}): boolean; From 71e04635649947bd552e0cc90907be276b44e9ba Mon Sep 17 00:00:00 2001 From: huzaif Date: Wed, 6 Jan 2021 00:00:20 +0530 Subject: [PATCH 06/75] updated types --- lib/resources/numbers.js | 24 ++++++++++++++++++ types/resources/accounts.d.ts | 4 +-- types/resources/applications.d.ts | 2 +- types/resources/media.d.ts | 2 +- types/resources/messages.d.ts | 2 +- types/resources/numbers.d.ts | 33 +++++++++++++++++++++---- types/resources/phlo.d.ts | 6 ++--- types/resources/phloMultipartyCall.d.ts | 12 ++++----- types/resources/powerpacks.d.ts | 4 +-- types/rest/client-test.d.ts | 4 +-- 10 files changed, 70 insertions(+), 23 deletions(-) diff --git a/lib/resources/numbers.js b/lib/resources/numbers.js index 14c8152..5b0cc8b 100644 --- a/lib/resources/numbers.js +++ b/lib/resources/numbers.js @@ -22,6 +22,30 @@ export class BuyNumberResponse { } } +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 || {}; diff --git a/types/resources/accounts.d.ts b/types/resources/accounts.d.ts index 0ad6a79..fd613e7 100644 --- a/types/resources/accounts.d.ts +++ b/types/resources/accounts.d.ts @@ -103,7 +103,7 @@ export class SubaccountInterface extends PlivoResourceInterface { * @promise {Subaccount} return object of subaccount * @fail {Error} return Error */ - update(id: string, name: string, enabled: boolean): Promise; + update(id: string, name: string, enabled: boolean): Promise; /** * delete subaccount * @method @@ -163,7 +163,7 @@ export class AccountInterface extends PlivoResourceInterface { name: string; city: string; address: string; - }): Promise; + }): Promise; [clientKey]: symbol; } import { PlivoResource } from "../base"; diff --git a/types/resources/applications.d.ts b/types/resources/applications.d.ts index fa5b5f3..ed57fcd 100644 --- a/types/resources/applications.d.ts +++ b/types/resources/applications.d.ts @@ -140,7 +140,7 @@ export class ApplicationInterface extends PlivoResourceInterface { defaultEndpointApp: boolean; subaccount: string; logIncomingMessages: boolean; - }): Promise; + }): Promise; /** * delete Application * @method diff --git a/types/resources/media.d.ts b/types/resources/media.d.ts index b812126..8a025bf 100644 --- a/types/resources/media.d.ts +++ b/types/resources/media.d.ts @@ -42,7 +42,7 @@ export class MediaInterface extends PlivoResourceInterface { * @method * @fail {Error} return Error */ - upload(files: any): Promise; + upload(files: Array): Promise; /** * Get Media by given id * @method diff --git a/types/resources/messages.d.ts b/types/resources/messages.d.ts index 891058f..4a9ea8c 100644 --- a/types/resources/messages.d.ts +++ b/types/resources/messages.d.ts @@ -88,7 +88,7 @@ export class MessageInterface extends PlivoResourceInterface { type: string; url: string; method: string; - media_urls: any; + media_urls: Array; log: boolean; }): Promise < MessageResponse > ; /** diff --git a/types/resources/numbers.d.ts b/types/resources/numbers.d.ts index d2ca408..25c2c42 100644 --- a/types/resources/numbers.d.ts +++ b/types/resources/numbers.d.ts @@ -9,6 +9,29 @@ export class UpdateNumberResponse { 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: any; + restriction_text: any; + resource_uri: string; +} + /** * Represents a PhoneNumber * @constructor @@ -44,7 +67,7 @@ export class PhoneNumberInterface extends PlivoResourceInterface { * @promise {@link PlivoGenericResponse} return PlivoGenericResponse Object if success * @fail {Error} return Error */ - buy(number: string, appId: string): Promise < BuyNumberResponse > ; + buy(number: string, appId: string): Promise < any > ; [clientKey]: symbol; } /** @@ -81,7 +104,7 @@ export class NumberInterface extends PlivoResourceInterface { * @promise {@link PlivoGenericResponse} return PlivoGenericResponse Object if success * @fail {Error} return Error */ - buy(number: string, appId: string): Promise < any > ; + buy(number: string, appId: string): Promise < BuyNumberResponse > ; /** * Add own number from carrier * @method @@ -92,7 +115,7 @@ export class NumberInterface extends PlivoResourceInterface { * @promise {@link PlivoGenericResponse} return PlivoGenericResponse Object if success * @fail {Error} return Error */ - addOwnNumber(numbers: string, carrier: string, region: string, optionalParams: object): Promise < any > ; + addOwnNumber(numbers: string, carrier: string, region: string, optionalParams: object): Promise < UpdateNumberResponse > ; /** * Add own number from carrier * @method @@ -101,7 +124,7 @@ export class NumberInterface extends PlivoResourceInterface { * @promise {@link PhoneNumberInterface} return PhoneNumbers Object if success * @fail {Error} return Error */ - search(countryISO: string, optionalParams: object): Promise < any > ; + search(countryISO: string, optionalParams: object): Promise < SearchNumberResponse > ; /** * Update Number * @method @@ -117,7 +140,7 @@ export class NumberInterface extends PlivoResourceInterface { appId: string; subAccount: string; alias: string; - }): Promise < any > ; + }): Promise < UpdateNumberResponse > ; /** * Unrent Number * @method diff --git a/types/resources/phlo.d.ts b/types/resources/phlo.d.ts index e891e35..699905b 100644 --- a/types/resources/phlo.d.ts +++ b/types/resources/phlo.d.ts @@ -2,14 +2,14 @@ export class RunPHLOResponse { constructor(params: object); apiid: string; phloid: string; - message: any; + message: string; } export class RetrievePHLOResponse { constructor(params: object); apiid: string; phloid: string; - name: any; - createdOn: any; + name: string; + createdOn: string; } /** * Represents a Phlo diff --git a/types/resources/phloMultipartyCall.d.ts b/types/resources/phloMultipartyCall.d.ts index fb82e63..976907f 100644 --- a/types/resources/phloMultipartyCall.d.ts +++ b/types/resources/phloMultipartyCall.d.ts @@ -16,12 +16,12 @@ export class PhloMultiPartyCall extends PlivoResource { constructor(client: function, data ? : {}); action: string; client: function; - member: (memberAddress: any) => PhloMultiPartyCallMember; - call(triggerSource: any, to: any, role: any): Promise < any > ; - warmTransfer(triggerSource: any, to: any, role: any): Promise < UpdateMultipartyCallResponse > ; - coldTransfer(triggerSource: any, to: any, role: any): Promise < UpdateMultipartyCallResponse > ; - abortTransfer(memberAddress: any): Promise; - update(action: any, triggerSource: any, to: any, role: any): Promise; + 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 { diff --git a/types/resources/powerpacks.d.ts b/types/resources/powerpacks.d.ts index 701ad5d..cfa72bf 100644 --- a/types/resources/powerpacks.d.ts +++ b/types/resources/powerpacks.d.ts @@ -24,7 +24,7 @@ export class UpdatePowerpackResponse { applicationType: string; createdOn: string; localConnect: string; - name: string; + name: string; numberPool: string; stickySender: string; uuid: string; @@ -44,7 +44,7 @@ export class ListTollFreeResponse { export class AddNumberResponse { constructor(params: object); apiId: string; - accountPhoneNumberResource: string; + accountPhoneNumberResource: string; addedOn: string; countryIso2: string; number: string; diff --git a/types/rest/client-test.d.ts b/types/rest/client-test.d.ts index 15f2b17..6e73f73 100644 --- a/types/rest/client-test.d.ts +++ b/types/rest/client-test.d.ts @@ -1,5 +1,5 @@ export class Client { - constructor(authid: string, authToken: any, proxy: any); + constructor(authid: string, authToken: string, proxy: string); calls: CallInterface; accounts: AccountInterface; subAccounts: SubaccountInterface; @@ -20,7 +20,7 @@ export class Client { * You can also pass in additional parameters accepted by the node requests module. */ export class PhloClient { - constructor(authid: string, authToken: any, options: any); + constructor(authid: string, authToken: string, options: string); phlo: (phloid: string) => Phlo; } import { CallInterface } from "../resources/call.js"; From 035c7783e5bd84e4833db43b7a3b60b97daedf30 Mon Sep 17 00:00:00 2001 From: huzaif Date: Wed, 6 Jan 2021 15:57:51 +0530 Subject: [PATCH 07/75] updated types --- types/base.d.ts | 6 +++--- types/rest/request-test.d.ts | 2 +- types/rest/request.d.ts | 2 +- types/rest/utils.d.ts | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/types/base.d.ts b/types/base.d.ts index 1aaf772..6609e79 100644 --- a/types/base.d.ts +++ b/types/base.d.ts @@ -3,16 +3,16 @@ export class PlivoGenericResponse { id: string; } export class PlivoResource { - constructor(action: any, klass: any, idField: any, request: any); + constructor(action: string, klass: any, idField: string, request: any); update(params: object, id: string): Promise; delete(params: object): Promise; - executeAction(task: string, method: string, params: {}, action: any): Promise; + executeAction(task: string, method: string, params: {}, action: string): Promise; customexecuteAction(url: any, method?: string, params?: {}): Promise; customexecuteGetNumberAction(url: any, method?: string, params?: {}): any; getMetaResponse(url: any, method?: string, params?: {}): Promise; } export class PlivoResourceInterface { - constructor(action: any, klass: any, idField: any, request: any); + constructor(action: string, klass: any, idField: string, request: any); get(id: string, params?: {}): Promise; list(params: object): Promise; create(params: object): Promise; diff --git a/types/rest/request-test.d.ts b/types/rest/request-test.d.ts index 028039c..1f56632 100644 --- a/types/rest/request-test.d.ts +++ b/types/rest/request-test.d.ts @@ -1 +1 @@ -export function Request(config: any): (method: any, action: any, params: object) => Promise; +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 index 028039c..1f56632 100644 --- a/types/rest/request.d.ts +++ b/types/rest/request.d.ts @@ -1 +1 @@ -export function Request(config: any): (method: any, action: any, params: object) => Promise; +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 index ac52936..13c7262 100644 --- a/types/rest/utils.d.ts +++ b/types/rest/utils.d.ts @@ -1,4 +1,4 @@ -export function camelCaseRequestWrapper(requestFunc: any): (method: any, action: any, params: object) => any; +export function camelCaseRequestWrapper(requestFunc: any): (method: string, action: string, params: object) => any; export function validateSpeakAttributes(content: any, voice: any): { success: boolean; msg?: undefined; From bb0dc9924f59cc93b98ba540333ead372e66c2f9 Mon Sep 17 00:00:00 2001 From: huzaif Date: Wed, 6 Jan 2021 16:06:47 +0530 Subject: [PATCH 08/75] updated types --- lib/resources/messages.js | 3 --- types/base.d.ts | 4 ++-- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/lib/resources/messages.js b/lib/resources/messages.js index b7eaaa1..5788d21 100644 --- a/lib/resources/messages.js +++ b/lib/resources/messages.js @@ -1,7 +1,6 @@ import * as _ from "lodash"; import { - PlivoGenericResponse, PlivoResource, PlivoResourceInterface } from '../base'; @@ -10,8 +9,6 @@ import { validate } from '../utils/common.js'; -import { type } from "os"; - const action = 'Message/'; const idField = 'messageUuid'; let actionKey = Symbol('api action'); diff --git a/types/base.d.ts b/types/base.d.ts index 6609e79..ab17e9b 100644 --- a/types/base.d.ts +++ b/types/base.d.ts @@ -3,7 +3,7 @@ export class PlivoGenericResponse { id: string; } export class PlivoResource { - constructor(action: string, klass: any, idField: string, request: any); + 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; @@ -12,7 +12,7 @@ export class PlivoResource { getMetaResponse(url: any, method?: string, params?: {}): Promise; } export class PlivoResourceInterface { - constructor(action: string, klass: any, idField: string, request: any); + constructor(action: string, Klass: Symbol, idField: string, request: any); get(id: string, params?: {}): Promise; list(params: object): Promise; create(params: object): Promise; From 248fd4fbdaaf8f20953a9ac0de69d25eed3ad5cd Mon Sep 17 00:00:00 2001 From: huzaif Date: Wed, 6 Jan 2021 16:09:20 +0530 Subject: [PATCH 09/75] updated types --- types/resources/endpoints.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/resources/endpoints.d.ts b/types/resources/endpoints.d.ts index a7e79d4..da31b5a 100644 --- a/types/resources/endpoints.d.ts +++ b/types/resources/endpoints.d.ts @@ -108,7 +108,7 @@ export class EndpointInterface extends PlivoResourceInterface { * @promise {object} return {@link Endpoint} object if success * @fail {Error} return Error */ - update(id: string, params: object): any; + update(id: string, params: object): Promise; /** * delete Endpoint * @method From f40777f941c1ea05db04132c5ca7528a0b056f36 Mon Sep 17 00:00:00 2001 From: huzaif Date: Sun, 17 Jan 2021 21:41:53 +0530 Subject: [PATCH 10/75] updated xml in ts --- lib/utils/plivoxml.js | 2 +- types/resources/accounts.d.ts | 8 +- types/resources/applications.d.ts | 4 +- types/resources/call.d.ts | 12 +- types/resources/callFeedback.d.ts | 4 +- types/resources/conferences.d.ts | 4 +- types/resources/endpoints.d.ts | 4 +- types/resources/lookup.d.ts | 4 +- types/resources/media.d.ts | 4 +- types/resources/messages.d.ts | 4 +- types/resources/numbers.d.ts | 8 +- types/resources/phlo.d.ts | 6 +- types/resources/phloMultiPartyCallMember.d.ts | 8 +- types/resources/phloMultipartyCall.d.ts | 6 +- types/resources/powerpacks.d.ts | 12 +- types/resources/pricings.d.ts | 4 +- types/resources/recordings.d.ts | 4 +- types/rest/client.d.ts | 11 +- types/utils/plivoxml.d.ts | 179 ++++++++++++++++++ 19 files changed, 235 insertions(+), 53 deletions(-) create mode 100644 types/utils/plivoxml.d.ts diff --git a/lib/utils/plivoxml.js b/lib/utils/plivoxml.js index 002d668..577ce9f 100644 --- a/lib/utils/plivoxml.js +++ b/lib/utils/plivoxml.js @@ -741,4 +741,4 @@ function DTMF(Response) { this.valid_attributes = ['digits', 'async']; } -util.inherits(DTMF, Response); +util.inherits(DTMF, Response); \ No newline at end of file diff --git a/types/resources/accounts.d.ts b/types/resources/accounts.d.ts index fd613e7..796696a 100644 --- a/types/resources/accounts.d.ts +++ b/types/resources/accounts.d.ts @@ -48,7 +48,7 @@ export class GetSubAccountDetails { resourceUri: string; } export class Subaccount extends PlivoResource { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); id: string; /** * update subaccount @@ -76,7 +76,7 @@ export class Subaccount extends PlivoResource { * @param {object} [data] - data of call */ export class SubaccountInterface extends PlivoResourceInterface { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); /** * get subaccount by id * @method @@ -122,7 +122,7 @@ export class SubaccountInterface extends PlivoResourceInterface { * @param {object} [data] - data of call */ export class Account extends PlivoResource { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); id: string; /** * get account detail @@ -141,7 +141,7 @@ export class Account extends PlivoResource { * @param {object} [data] - data of call */ export class AccountInterface extends PlivoResourceInterface { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); /** * get account detail * @method diff --git a/types/resources/applications.d.ts b/types/resources/applications.d.ts index ed57fcd..4c2b0b1 100644 --- a/types/resources/applications.d.ts +++ b/types/resources/applications.d.ts @@ -55,7 +55,7 @@ export class ListAllApplicationResponse { subAccount: string; } export class Application extends PlivoResource { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); id: string; [clientKey]: symbol; } @@ -66,7 +66,7 @@ export class Application extends PlivoResource { * @param {object} [data] - data of call */ export class ApplicationInterface extends PlivoResourceInterface { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); /** * get application by given id * @method diff --git a/types/resources/call.d.ts b/types/resources/call.d.ts index 4e77cdd..a565095 100644 --- a/types/resources/call.d.ts +++ b/types/resources/call.d.ts @@ -118,7 +118,7 @@ export class RecordCallResponse { * @param {object} [data] - data of call */ export class Call extends PlivoResource { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); id: string; /** * hangup call @@ -245,7 +245,7 @@ export class Call extends PlivoResource { * @param {object} [data] - data of call */ export class CallInterface extends PlivoResourceInterface { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); /** * Get A Call Detail * @method @@ -402,12 +402,12 @@ export class CallInterface extends PlivoResourceInterface { [queuedCallInterfaceKey]: QueuedCallInterface; } export class LiveCallResource extends PlivoResource { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); id: string; [clientKey]: symbol; } export class QueuedCallResource extends PlivoResource { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); id: string; [clientKey]: symbol; } @@ -426,7 +426,7 @@ declare const liveCallInterfaceKey: unique symbol; * @param {object} [data] - data of call */ declare class LiveCallInterface extends PlivoResourceInterface { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); [clientKey]: symbol; } declare const queuedCallInterfaceKey: unique symbol; @@ -438,7 +438,7 @@ declare const queuedCallInterfaceKey: unique symbol; */ declare class QueuedCallInterface extends PlivoResourceInterface { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); get(id: string): Promise < GetQueuedCallResponse > ; list(): Promise < ListAllQueuedCalls > ; [clientKey]: symbol; diff --git a/types/resources/callFeedback.d.ts b/types/resources/callFeedback.d.ts index fc051b2..a662df3 100644 --- a/types/resources/callFeedback.d.ts +++ b/types/resources/callFeedback.d.ts @@ -5,7 +5,7 @@ export class CallFeedbackResponse { status: string; } export class CallFeedback extends PlivoResource { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); id: string; [clientKey]: symbol; } @@ -16,7 +16,7 @@ export class CallFeedback extends PlivoResource { * @param {object} [data] - data of call */ export class CallFeedbackInterface extends PlivoResourceInterface { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); create(callUUID: string, rating: string, issues?: never[], notes?: string): Promise; [clientKey]: symbol; } diff --git a/types/resources/conferences.d.ts b/types/resources/conferences.d.ts index a80f36a..c80e695 100644 --- a/types/resources/conferences.d.ts +++ b/types/resources/conferences.d.ts @@ -49,7 +49,7 @@ export class DeafMemberResponse { message: string; } export class Conference extends PlivoResource { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); id: string; /** * hangup conference @@ -208,7 +208,7 @@ export class Conference extends PlivoResource { * @param {object} [data] - data of call */ export class ConferenceInterface extends PlivoResourceInterface { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); /** * get conference by id diff --git a/types/resources/endpoints.d.ts b/types/resources/endpoints.d.ts index da31b5a..09ba026 100644 --- a/types/resources/endpoints.d.ts +++ b/types/resources/endpoints.d.ts @@ -45,7 +45,7 @@ export class CreateEndpointResponse { * @param {object} [data] - data of call */ export class Endpoint extends PlivoResource { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); id: string; /** * update Endpoint @@ -75,7 +75,7 @@ export class Endpoint extends PlivoResource { * @param {object} [data] - data of call */ export class EndpointInterface extends PlivoResourceInterface { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); /** * Get Endpoint by given id * @method diff --git a/types/resources/lookup.d.ts b/types/resources/lookup.d.ts index 84c282d..9d4fbcd 100644 --- a/types/resources/lookup.d.ts +++ b/types/resources/lookup.d.ts @@ -8,11 +8,11 @@ export class LookupResponse { resourceUri: string; } export class Number extends PlivoResource { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); [clientKey]: symbol; } export class LookupInterface extends PlivoResourceInterface { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); get(number: string, type?: string): Promise; [clientKey]: symbol; } diff --git a/types/resources/media.d.ts b/types/resources/media.d.ts index 8a025bf..fe251e5 100644 --- a/types/resources/media.d.ts +++ b/types/resources/media.d.ts @@ -26,7 +26,7 @@ export class ListMediaResponse { * @param {object} [data] - data of call */ export class Media extends PlivoResource { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); id: string; } /** @@ -36,7 +36,7 @@ export class Media extends PlivoResource { * @param {object} [data] - data of call */ export class MediaInterface extends PlivoResourceInterface { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); /** * Upload Media * @method diff --git a/types/resources/messages.d.ts b/types/resources/messages.d.ts index 4a9ea8c..6d6b37d 100644 --- a/types/resources/messages.d.ts +++ b/types/resources/messages.d.ts @@ -57,7 +57,7 @@ export class MMSMedia { * @param {object} [data] - data of call */ export class Message extends PlivoResource { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); id: string; listMedia(): Promise < any > ; } @@ -68,7 +68,7 @@ export class Message extends PlivoResource { * @param {object} [data] - data of call */ export class MessageInterface extends PlivoResourceInterface { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); /** * Send Message * @method diff --git a/types/resources/numbers.d.ts b/types/resources/numbers.d.ts index 25c2c42..c7dbb7d 100644 --- a/types/resources/numbers.d.ts +++ b/types/resources/numbers.d.ts @@ -39,7 +39,7 @@ export class SearchNumberResponse { * @param {object} [data] - data of call */ export class PhoneNumber extends PlivoResource { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); id: string; /** * Buy Phone Number @@ -59,7 +59,7 @@ export class PhoneNumber extends PlivoResource { * @param {string} [data.test] - test data */ export class PhoneNumberInterface extends PlivoResourceInterface { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); /** * Buy Phone Number * @method @@ -77,7 +77,7 @@ export class PhoneNumberInterface extends PlivoResourceInterface { * @param {object} [data] - data of call */ export class NumberResource extends PlivoResource { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); id: string; /** * Unrent Number @@ -95,7 +95,7 @@ export class NumberResource extends PlivoResource { * @param {object} [data] - data of call */ export class NumberInterface extends PlivoResourceInterface { - constructor(client: function); + constructor(client: Function); /** * Buy Phone Number * @method diff --git a/types/resources/phlo.d.ts b/types/resources/phlo.d.ts index 699905b..8bc5c26 100644 --- a/types/resources/phlo.d.ts +++ b/types/resources/phlo.d.ts @@ -18,8 +18,8 @@ export class RetrievePHLOResponse { * @param {object} [data] - data of phlo */ export class Phlo extends PlivoResource { - constructor(client: function, data ? : {}); - client: function; + constructor(client: Function, data ? : {}); + client: Function; multiPartyCall: (nodeid: string) => PhloMultiPartyCall; /** * run phlo @@ -37,7 +37,7 @@ export class Phlo extends PlivoResource { * @param {object} [data] - data of call */ export class PhloInterface extends PlivoResourceInterface { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); get(id: string): Promise; [clientKey]: symbol; } diff --git a/types/resources/phloMultiPartyCallMember.d.ts b/types/resources/phloMultiPartyCallMember.d.ts index 43fe788..73a7ded 100644 --- a/types/resources/phloMultiPartyCallMember.d.ts +++ b/types/resources/phloMultiPartyCallMember.d.ts @@ -10,9 +10,9 @@ export class UpdateMemberResponse { error: string; } export class PhloMultiPartyCallMember extends PlivoResource { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); action: string; - client: function; + client: Function; resumeCall(): Promise < any > ; voicemailDrop(): Promise < any > ; hangup(): Promise < any > ; @@ -21,9 +21,9 @@ export class PhloMultiPartyCallMember extends PlivoResource { update(action: object): Promise; } export class PhloMultiPartyCallMemberInterface extends PlivoResourceInterface { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); action: string; - client: function; + client: Function; get(phloId: string, nodeId: string, memberAddress: string): any; } import { diff --git a/types/resources/phloMultipartyCall.d.ts b/types/resources/phloMultipartyCall.d.ts index 976907f..b19dcea 100644 --- a/types/resources/phloMultipartyCall.d.ts +++ b/types/resources/phloMultipartyCall.d.ts @@ -13,9 +13,9 @@ export class RetrieveMultipartyCallResponse { createdOn: string; } export class PhloMultiPartyCall extends PlivoResource { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); action: string; - client: function; + client: Function; member: (memberAddress: string) => PhloMultiPartyCallMember; call(triggerSource: string, to: string, role: string): Promise < any > ; warmTransfer(triggerSource: string, to: string, role: string): Promise < UpdateMultipartyCallResponse > ; @@ -25,7 +25,7 @@ export class PhloMultiPartyCall extends PlivoResource { [clientKey]: symbol; } export class PhloMultiPartyCallInterface extends PlivoResourceInterface { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); get(phloId: string, id: string): Promise; [clientKey]: symbol; } diff --git a/types/resources/powerpacks.d.ts b/types/resources/powerpacks.d.ts index cfa72bf..1892aa3 100644 --- a/types/resources/powerpacks.d.ts +++ b/types/resources/powerpacks.d.ts @@ -113,7 +113,7 @@ export class RetrieveShortCodeResponse { * @param {object} [data] - data of call */ export class Powerpack extends PlivoResource { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); uuid: string; number_pool_id: string; number_pool: NumberPool; @@ -134,13 +134,13 @@ export class Powerpack extends PlivoResource { [clientKey]: symbol; } export class NumberPool extends PlivoResource { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); numbers: Numbers; shortcodes: Shortcode; tollfree: Tollfree; } export class Numbers extends PlivoResource { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); buy_add_number(params: object): any; list(params: object): Promise < any > ; count(params: object): Promise < any > ; @@ -150,14 +150,14 @@ export class Numbers extends PlivoResource { remove(number: string, unrent ? : boolean): Promise < any > ; } export class Shortcode extends PlivoResource { - constructor(client: function, data ? : {}); + 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 ? : {}); + constructor(client: Function, data ? : {}); number_pool_id: string; add(tollfree: string): Promise < any > ; remove(tollfree: string, unrent ? : boolean): Promise < any > ; @@ -171,7 +171,7 @@ export class Tollfree extends PlivoResource { * @param {object} [data] - data of call */ export class PowerpackInterface extends PlivoResourceInterface { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); /** * get Powerpack by given id * @method diff --git a/types/resources/pricings.d.ts b/types/resources/pricings.d.ts index 084cf8d..cbda073 100644 --- a/types/resources/pricings.d.ts +++ b/types/resources/pricings.d.ts @@ -16,7 +16,7 @@ export class PricingResponse { voice: object; } export class Pricing extends PlivoResource { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); /** * Get pricings by country * @method @@ -33,7 +33,7 @@ export class Pricing extends PlivoResource { * @param {object} [data] - data of call */ export class PricingInterface extends PlivoResourceInterface { - constructor(client: function, data?: {}); + constructor(client: Function, data?: {}); [clientKey]: symbol; } import { PlivoResource } from "../base"; diff --git a/types/resources/recordings.d.ts b/types/resources/recordings.d.ts index 93967e1..2cc6f4b 100644 --- a/types/resources/recordings.d.ts +++ b/types/resources/recordings.d.ts @@ -35,7 +35,7 @@ export class ListRecordingResponse { * @param {object} [data] - data of call */ export class Recording extends PlivoResource { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); id: string; [clientKey]: symbol; } @@ -46,7 +46,7 @@ export class Recording extends PlivoResource { * @param {object} [data] - data of call */ export class RecordingInterface extends PlivoResourceInterface { - constructor(client: function, data ? : {}); + constructor(client: Function, data ? : {}); /** * Delete recording by id * @method diff --git a/types/rest/client.d.ts b/types/rest/client.d.ts index ab23647..a49d75a 100644 --- a/types/rest/client.d.ts +++ b/types/rest/client.d.ts @@ -1,10 +1,13 @@ +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); + constructor(authId: string, authToken: string, options?: string); calls: CallInterface; accounts: AccountInterface; subaccounts: SubaccountInterface; @@ -28,8 +31,8 @@ export class Client { * 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; + constructor(authId: any, authToken: any, options: any); + phlo: (phloId: any) => Phlo; } import { CallInterface } from "../resources/call.js"; import { AccountInterface } from "../resources/accounts.js"; @@ -45,4 +48,4 @@ 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"; +import { Phlo } from "../resources/phlo.js"; \ No newline at end of file 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); +} From 0daf725a0ef0e15d02d5222ac91a97c71e1750c6 Mon Sep 17 00:00:00 2001 From: huzaif Date: Mon, 18 Jan 2021 09:50:25 +0530 Subject: [PATCH 11/75] updated types --- types/base.d.ts | 8 ++++---- types/resources/numbers.d.ts | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/types/base.d.ts b/types/base.d.ts index ab17e9b..b53c07b 100644 --- a/types/base.d.ts +++ b/types/base.d.ts @@ -1,5 +1,5 @@ export class PlivoGenericResponse { - constructor(params: object, idString: any); + constructor(params: object, idString: string); id: string; } export class PlivoResource { @@ -7,9 +7,9 @@ export class PlivoResource { update(params: object, id: string): Promise; delete(params: object): Promise; executeAction(task: string, method: string, params: {}, action: string): Promise; - customexecuteAction(url: any, method?: string, params?: {}): Promise; - customexecuteGetNumberAction(url: any, method?: string, params?: {}): any; - getMetaResponse(url: any, method?: string, params?: {}): 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); diff --git a/types/resources/numbers.d.ts b/types/resources/numbers.d.ts index c7dbb7d..19cceca 100644 --- a/types/resources/numbers.d.ts +++ b/types/resources/numbers.d.ts @@ -27,8 +27,8 @@ export class SearchNumberResponse { sms_rate: string; voice_enabled: boolean; voice_rate: string; - restriction: any; - restriction_text: any; + restriction: string; + restriction_text: string; resource_uri: string; } From d8aef3b63f0768ce8c2ebe0a8766dd633a025dbe Mon Sep 17 00:00:00 2001 From: huzaif Date: Tue, 19 Jan 2021 10:25:25 +0530 Subject: [PATCH 12/75] updated changelog --- CHANGELOG.md | 2 ++ package.json | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c59970..b633978 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ # Change Log +## [4.12.0](https://github.com/plivo/plivo-node/releases/tag/v4.11.0)(2020-10-30) +- Add Typescript support. ## [4.11.0](https://github.com/plivo/plivo-node/releases/tag/v4.11.0)(2020-10-30) - Change lookup API endpoint and response. diff --git a/package.json b/package.json index a3ef871..2c12110 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "plivo", - "version": "4.11.0", + "version": "4.12.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": [ From c78a835ed142402cb64a7f5babf95a6852c2d9fb Mon Sep 17 00:00:00 2001 From: nixonsam <37671608+nixonsam@users.noreply.github.com> Date: Tue, 19 Jan 2021 13:29:17 +0530 Subject: [PATCH 13/75] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b633978..82c5acc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## [4.12.0](https://github.com/plivo/plivo-node/releases/tag/v4.11.0)(2020-10-30) - Add Typescript support. + ## [4.11.0](https://github.com/plivo/plivo-node/releases/tag/v4.11.0)(2020-10-30) - Change lookup API endpoint and response. From add58030e19cbfaa0402afbc7299da9232a70217 Mon Sep 17 00:00:00 2001 From: nixonsam <37671608+nixonsam@users.noreply.github.com> Date: Tue, 19 Jan 2021 13:29:59 +0530 Subject: [PATCH 14/75] Update CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82c5acc..b6f32c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Change Log -## [4.12.0](https://github.com/plivo/plivo-node/releases/tag/v4.11.0)(2020-10-30) +## [4.12.0](https://github.com/plivo/plivo-node/releases/tag/v4.12.0)(2021-01-19) - Add Typescript support. ## [4.11.0](https://github.com/plivo/plivo-node/releases/tag/v4.11.0)(2020-10-30) From 77f4c2ebf63201e8d2da61c8f5a9c9abc6d8fb35 Mon Sep 17 00:00:00 2001 From: nixonsam <37671608+nixonsam@users.noreply.github.com> Date: Tue, 19 Jan 2021 13:37:40 +0530 Subject: [PATCH 15/75] Update package.json --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 2c12110..7cdcb2c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "plivo", - "version": "4.12.0", + "version": "4.13.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": [ From c4bbb143bc3e71c95a0509cf7160dfecb91f31a4 Mon Sep 17 00:00:00 2001 From: kalyan-plivo <49232630+kalyan-plivo@users.noreply.github.com> Date: Mon, 14 Dec 2020 13:58:32 +0530 Subject: [PATCH 16/75] testing the new got package --- lib/rest/client.js | 7 +- lib/rest/got.js | 222 +++++++++++++++++++++++++++++++++++++++++++++ package-lock.json | 213 ++++++++++++++++++++++++++++++++++++++++++- package.json | 1 + 4 files changed, 436 insertions(+), 7 deletions(-) create mode 100644 lib/rest/got.js diff --git a/lib/rest/client.js b/lib/rest/client.js index fb5874e..58195da 100644 --- a/lib/rest/client.js +++ b/lib/rest/client.js @@ -1,4 +1,5 @@ -import { Request } from "./request.js"; +// import { Request } from "./request.js"; +import { Got } from "./got.js"; import { camelCaseRequestWrapper } from "./utils"; import { name, version } from "../../package.json"; import { Phlo, PhloInterface } from "../resources/phlo"; @@ -67,7 +68,7 @@ export class Client { options ); - let client = camelCaseRequestWrapper(Request(options)); + let client = camelCaseRequestWrapper(Got(options)); this.calls = new CallInterface(client); this.accounts = new AccountInterface(client); @@ -125,7 +126,7 @@ export class PhloClient { options ); - let client = camelCaseRequestWrapper(Request(options)); + let client = camelCaseRequestWrapper(Got(options)); this.phlo = function(phloId) { let dd = new Phlo(client, { phloId: phloId, authId: authId }); diff --git a/lib/rest/got.js b/lib/rest/got.js new file mode 100644 index 0000000..3f4005e --- /dev/null +++ b/lib/rest/got.js @@ -0,0 +1,222 @@ +import got from 'got'; +import searchParams from 'searchParams'; +import * as Exceptions from '../utils/exceptions'; +import * as _ from "lodash"; + +export function Got(config) { + let auth = 'Basic ' + new Buffer(config.authId + ':' + config.authToken) + .toString('base64'); + + let headers = { + Authorization: auth, + 'User-Agent': config.userAgent, + 'Content-Type': 'application/json' + }; + + return (method, action, params) => { + if (typeof (params) != 'undefined' && typeof (params.file) != 'undefined') { + var 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; + } + var options = { + url: config.url + '/' + action, + method: method, + formData: params || '', + headers: headers, + json: {} + }; + 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.formData; + 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.formData !== '') { + let query = '?' + searchParams.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) => { + got(options, (error, response, body) => { + if (error) { + reject(error); + return; + } + + if(isVoiceReq === true){ + if (response.statusCode >= 500){ + options.url = apiVoiceUris[1] + config.authId + '/' + action; + if (method === 'GET' && options.formData !== '') { + let query = '?' + searchParams.stringify(params); + options.url += query; + } + got(options,(error, response) => { + if(error){ + reject(error); + return; + } + if(response.statusCode>=500){ + options.url = apiVoiceUris[2] + config.authId + '/' + action; + if (method === 'GET' && options.formData !== '') { + let query = '?' + searchParams.stringify(params); + options.url += query; + } + got(options, (error, response) => { + if(error){ + reject(error); + return; + } + const exceptionClass = { + 400: Exceptions.InvalidRequestError, + 401: Exceptions.AuthenticationError, + 404: Exceptions.ResourceNotFoundError, + 405: Exceptions.InvalidRequestError, + 500: Exceptions.ServerError, + } [response.statusCode] || Error; + + if (!_.inRange(response.statusCode, 200, 300)) { + body = body || response.body; + if (typeof body === 'object') { + reject(new exceptionClass(JSON.stringify(body))); + } else { + reject(new exceptionClass(body)); + } + } + // else { + let body = response.body; + let isObj = typeof _body === 'object' && _body !== null && !(_body instanceof Array) && !(_body instanceof Date) + if (isObj) { + _body['statusCode'] = response.statusCode; + } + resolve({ + response: response, + body: body + }); + // } + }) + } + else { + const exceptionClass = { + 400: Exceptions.InvalidRequestError, + 401: Exceptions.AuthenticationError, + 404: Exceptions.ResourceNotFoundError, + 405: Exceptions.InvalidRequestError, + 500: Exceptions.ServerError, + } [response.statusCode] || Error; + + if (!_.inRange(response.statusCode, 200, 300)) { + body = body || response.body; + if (typeof body === 'object') { + reject(new exceptionClass(JSON.stringify(body))); + } else { + reject(new exceptionClass(body)); + } + } + // else { + let body = response.body; + let isObj = typeof _body === 'object' && _body !== null && !(_body instanceof Array) && !(_body instanceof Date) + if (isObj) { + _body['statusCode'] = response.statusCode; + } + resolve({ + response: response, + body: body + }); + } + }) + } + else { + const exceptionClass = { + 400: Exceptions.InvalidRequestError, + 401: Exceptions.AuthenticationError, + 404: Exceptions.ResourceNotFoundError, + 405: Exceptions.InvalidRequestError, + 500: Exceptions.ServerError, + } [response.statusCode] || Error; + + if (!_.inRange(response.statusCode, 200, 300)) { + body = body || response.body; + if (typeof body === 'object') { + reject(new exceptionClass(JSON.stringify(body))); + } else { + reject(new exceptionClass(body)); + } + } + // else { + let body = response.body; + let isObj = typeof _body === 'object' && _body !== null && !(_body instanceof Array) && !(_body instanceof Date) + if (isObj) { + _body['statusCode'] = response.statusCode; + } + resolve({ + response: response, + body: body + }); + } + } + + else { + const exceptionClass = { + 400: Exceptions.InvalidRequestError, + 401: Exceptions.AuthenticationError, + 404: Exceptions.ResourceNotFoundError, + 405: Exceptions.InvalidRequestError, + 500: Exceptions.ServerError, + } [response.statusCode] || Error; + + if (!_.inRange(response.statusCode, 200, 300)) { + body = body || response.body; + if (typeof body === 'object') { + reject(new exceptionClass(JSON.stringify(body))); + } else { + reject(new exceptionClass(body)); + } + } + else { + let body = response.body; + let isObj = typeof _body === 'object' && _body !== null && !(_body instanceof Array) && !(_body instanceof Date) + if (isObj) { + _body['statusCode'] = response.statusCode; + } + resolve({ + response: response, + body: body + }); + } + } + }); + }); + }; +} diff --git a/package-lock.json b/package-lock.json index 347cb92..366195d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,9 +1,59 @@ { "name": "plivo", - "version": "4.1.2", + "version": "4.12.0", "lockfileVersion": 1, "requires": true, "dependencies": { + "@sindresorhus/is": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.0.0.tgz", + "integrity": "sha512-FyD2meJpDPjyNQejSjvnhpgI/azsQkA4lGbuu5BQZfjvJ9cbRZXzeWL2HceCekW4lixO9JPesIIQkSoLjeJHNQ==" + }, + "@szmarczak/http-timer": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.5.tgz", + "integrity": "sha512-PyRA9sm1Yayuj5OIoJ1hGt2YISX45w9WcFbh6ddT0Z/0yaFxOtGLInr4jUfU1EAFVs0Yfyfev4RNwBlUaHdlDQ==", + "requires": { + "defer-to-connect": "^2.0.0" + } + }, + "@types/cacheable-request": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.1.tgz", + "integrity": "sha512-ykFq2zmBGOCbpIXtoVbz4SKY5QriWPh3AjyU4G74RYbtt5yOc5OfaY75ftjg7mikMOla1CTGpX3lLbuJh8DTrQ==", + "requires": { + "@types/http-cache-semantics": "*", + "@types/keyv": "*", + "@types/node": "*", + "@types/responselike": "*" + } + }, + "@types/http-cache-semantics": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.0.0.tgz", + "integrity": "sha512-c3Xy026kOF7QOTn00hbIllV1dLR9hG9NkSrLQgCVs8NF6sBU+VGWjD3wLPhmh1TYAc7ugCFsvHYMN4VcBN1U1A==" + }, + "@types/keyv": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.1.tgz", + "integrity": "sha512-MPtoySlAZQ37VoLaPcTHCu1RWJ4llDkULYZIzOYxlhxBqYPB0RsRlmMU0R6tahtFe27mIdkHV+551ZWV4PLmVw==", + "requires": { + "@types/node": "*" + } + }, + "@types/node": { + "version": "14.14.13", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.14.13.tgz", + "integrity": "sha512-vbxr0VZ8exFMMAjCW8rJwaya0dMCDyYW2ZRdTyjtrCvJoENMpdUHOT/eTzvgyA5ZnqRZ/sI0NwqAxNHKYokLJQ==" + }, + "@types/responselike": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.0.tgz", + "integrity": "sha512-85Y2BjiufFzaMIlvJDvTTB8Fxl2xfLo4HgmHzVBz08w4wDePCTjYw66PdrolO0kzli3yam/YCgRufyo1DdQVTA==", + "requires": { + "@types/node": "*" + } + }, "abbrev": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.9.tgz", @@ -1037,6 +1087,25 @@ "unset-value": "^1.0.0" } }, + "cacheable-lookup": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz", + "integrity": "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==" + }, + "cacheable-request": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.1.tgz", + "integrity": "sha512-lt0mJ6YAnsrBErpTMWeu5kl/tg9xMAWjavYTN6VQXM1A/teBITuNcccXsCxF0tDQQJf9DfAaX5O4e0zp0KlfZw==", + "requires": { + "clone-response": "^1.0.2", + "get-stream": "^5.1.0", + "http-cache-semantics": "^4.0.0", + "keyv": "^4.0.0", + "lowercase-keys": "^2.0.0", + "normalize-url": "^4.1.0", + "responselike": "^2.0.0" + } + }, "caller-path": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/caller-path/-/caller-path-0.1.0.tgz", @@ -1120,6 +1189,14 @@ "integrity": "sha1-2jCcwmPfFZlMaIypAheco8fNfH4=", "dev": true }, + "clone-response": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.2.tgz", + "integrity": "sha1-0dyXOSAxTfZ/vrlCI7TuNQI56Ws=", + "requires": { + "mimic-response": "^1.0.0" + } + }, "clone-stats": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/clone-stats/-/clone-stats-0.0.1.tgz", @@ -1421,6 +1498,21 @@ "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=", "dev": true }, + "decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "requires": { + "mimic-response": "^3.1.0" + }, + "dependencies": { + "mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==" + } + } + }, "deep-is": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", @@ -1436,6 +1528,11 @@ "clone": "^1.0.2" } }, + "defer-to-connect": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-2.0.0.tgz", + "integrity": "sha512-bYL2d05vOSf1JEZNx5vSAtPuBMkX8K9EUutg7zlKvTqKXHt7RhWJFbmd7qakVuf13i+IkGmp6FwSsONOf6VYIg==" + }, "define-property": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz", @@ -2211,6 +2308,14 @@ "is-property": "^1.0.0" } }, + "get-stream": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", + "requires": { + "pump": "^3.0.0" + } + }, "get-value": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz", @@ -2433,6 +2538,24 @@ "sparkles": "^1.0.0" } }, + "got": { + "version": "11.8.1", + "resolved": "https://registry.npmjs.org/got/-/got-11.8.1.tgz", + "integrity": "sha512-9aYdZL+6nHmvJwHALLwKSUZ0hMwGaJGYv3hoPLPgnT8BoBXm1SjnZeky+91tfwJaDzun2s4RsBRy48IEYv2q2Q==", + "requires": { + "@sindresorhus/is": "^4.0.0", + "@szmarczak/http-timer": "^4.0.5", + "@types/cacheable-request": "^6.0.1", + "@types/responselike": "^1.0.0", + "cacheable-lookup": "^5.0.3", + "cacheable-request": "^7.0.1", + "decompress-response": "^6.0.0", + "http2-wrapper": "^1.0.0-beta.5.2", + "lowercase-keys": "^2.0.0", + "p-cancelable": "^2.0.0", + "responselike": "^2.0.0" + } + }, "graceful-fs": { "version": "4.1.15", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz", @@ -2981,6 +3104,11 @@ "parse-passwd": "^1.0.0" } }, + "http-cache-semantics": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.0.tgz", + "integrity": "sha512-carPklcUh7ROWRK7Cv27RPtdhYhUsela/ue5/jKzjegVvXDqM2ILE9Q2BGn9JZJh1g87cp56su/FgQSzcWS8cQ==" + }, "http-signature": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", @@ -2991,6 +3119,15 @@ "sshpk": "^1.7.0" } }, + "http2-wrapper": { + "version": "1.0.0-beta.5.2", + "resolved": "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-1.0.0-beta.5.2.tgz", + "integrity": "sha512-xYz9goEyBnC8XwXDTuC/MZ6t+MrKVQZOk4s7+PaDkwIsQd8IwqvM+0M6bA/2lvG8GHXcPdf+MejTUeO2LCPCeQ==", + "requires": { + "quick-lru": "^5.1.1", + "resolve-alpn": "^1.0.0" + } + }, "ignore": { "version": "3.3.10", "resolved": "https://registry.npmjs.org/ignore/-/ignore-3.3.10.tgz", @@ -3435,6 +3572,11 @@ "integrity": "sha1-RsP+yMGJKxKwgz25vHYiF226s0s=", "dev": true }, + "json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==" + }, "json-schema": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", @@ -3494,6 +3636,14 @@ "verror": "1.10.0" } }, + "keyv": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.0.3.tgz", + "integrity": "sha512-zdGa2TOpSZPq5mU6iowDARnMBZgtCqJ11dJROFi6tg6kTn4nuUdU09lFyLFSaHrWqpIJ+EBq4E8/Dc0Vx5vLdA==", + "requires": { + "json-buffer": "3.0.1" + } + }, "kind-of": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", @@ -3725,6 +3875,11 @@ "js-tokens": "^3.0.0 || ^4.0.0" } }, + "lowercase-keys": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz", + "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==" + }, "lru-cache": { "version": "2.7.3", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-2.7.3.tgz", @@ -3789,6 +3944,11 @@ "mime-db": "~1.37.0" } }, + "mimic-response": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", + "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==" + }, "minimatch": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", @@ -4029,6 +4189,11 @@ "abbrev": "1" } }, + "normalize-url": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-4.5.0.tgz", + "integrity": "sha512-2s47yzUxdexf1OhyRi4Em83iQk0aPvwTddtFz4hnSSw9dCEsLEGf6SwIO8ss/19S9iBb5sJaOuTvTGDeZI00BQ==" + }, "number-is-nan": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", @@ -4121,7 +4286,6 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", - "dev": true, "requires": { "wrappy": "1" } @@ -4193,6 +4357,11 @@ "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", "dev": true }, + "p-cancelable": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.0.0.tgz", + "integrity": "sha512-wvPXDmbMmu2ksjkB4Z3nZWTSkJEb9lqVdMaCKpZUGJG9TMiNp9XcbG3fn9fPKjem04fJMJnXoyFPk2FmgiaiNg==" + }, "parse-filepath": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/parse-filepath/-/parse-filepath-1.0.2.tgz", @@ -4366,6 +4535,25 @@ "resolved": "https://registry.npmjs.org/psl/-/psl-1.1.31.tgz", "integrity": "sha512-/6pt4+C+T+wZUieKR620OpzN/LlnNKuWjy1iFLQ/UG35JqHlR/89MP1d96dUfkf6Dne3TuLQzOYEYshJ+Hx8mw==" }, + "pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + }, + "dependencies": { + "end-of-stream": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", + "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", + "requires": { + "once": "^1.4.0" + } + } + } + }, "punycode": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", @@ -4381,6 +4569,11 @@ "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz", "integrity": "sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA=" }, + "quick-lru": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz", + "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==" + }, "readable-stream": { "version": "2.3.6", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", @@ -4582,6 +4775,11 @@ "path-parse": "^1.0.6" } }, + "resolve-alpn": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.0.0.tgz", + "integrity": "sha512-rTuiIEqFmGxne4IovivKSDzld2lWW9QCjqv80SYjPgf+gS35eaCAjaP54CCwGAwBtnCsvNLYtqxe1Nw+i6JEmA==" + }, "resolve-dir": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-1.0.1.tgz", @@ -4604,6 +4802,14 @@ "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=", "dev": true }, + "responselike": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.0.tgz", + "integrity": "sha512-xH48u3FTB9VsZw7R+vvgaKeLKzT6jOogbQhEe/jewwnZgzPcnyWui2Av6JpoYZF/91uueC+lqhWqeURw5/qhCw==", + "requires": { + "lowercase-keys": "^2.0.0" + } + }, "restore-cursor": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-1.0.1.tgz", @@ -5558,8 +5764,7 @@ "wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", - "dev": true + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "write": { "version": "0.2.1", diff --git a/package.json b/package.json index 7cdcb2c..ca3ef67 100644 --- a/package.json +++ b/package.json @@ -61,6 +61,7 @@ "@types/node": "^14.14.14", "base-64": "^0.1.0", "build-url": "^1.0.10", + "got": "^11.8.1", "jsonwebtoken": "^8.5.1", "lodash": "^4.17.4", "querystring": "^0.2.0", From b2181214342283ea62472aedead14400a477e006 Mon Sep 17 00:00:00 2001 From: kalyan-plivo <49232630+kalyan-plivo@users.noreply.github.com> Date: Mon, 14 Dec 2020 15:43:00 +0530 Subject: [PATCH 17/75] wip --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index ca3ef67..c6d705f 100644 --- a/package.json +++ b/package.json @@ -64,8 +64,8 @@ "got": "^11.8.1", "jsonwebtoken": "^8.5.1", "lodash": "^4.17.4", - "querystring": "^0.2.0", - "request": "^2.81.0", + // "querystring": "^0.2.0", + // "request": "^2.81.0", "uri-parser": "^1.0.0", "utf8": "^2.1.2", "xml2js": "^0.4.19", From 6322a306cea44c9fc2b0e3179a8b610992ba2a95 Mon Sep 17 00:00:00 2001 From: kalyan-plivo <49232630+kalyan-plivo@users.noreply.github.com> Date: Mon, 14 Dec 2020 15:44:36 +0530 Subject: [PATCH 18/75] wip --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index c6d705f..3b9acdd 100644 --- a/package.json +++ b/package.json @@ -64,7 +64,7 @@ "got": "^11.8.1", "jsonwebtoken": "^8.5.1", "lodash": "^4.17.4", - // "querystring": "^0.2.0", + "querystring": "^0.2.0", // "request": "^2.81.0", "uri-parser": "^1.0.0", "utf8": "^2.1.2", From b465b2c74718809430b0c8d5afcbbbf39de06202 Mon Sep 17 00:00:00 2001 From: kalyan-plivo <49232630+kalyan-plivo@users.noreply.github.com> Date: Mon, 14 Dec 2020 15:49:49 +0530 Subject: [PATCH 19/75] wip --- package.json | 2 -- 1 file changed, 2 deletions(-) diff --git a/package.json b/package.json index 3b9acdd..a51cc1a 100644 --- a/package.json +++ b/package.json @@ -64,8 +64,6 @@ "got": "^11.8.1", "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", From e2a581d259606da7feb1f2e2c9ab5b0b32ca38ed Mon Sep 17 00:00:00 2001 From: kalyan-plivo <49232630+kalyan-plivo@users.noreply.github.com> Date: Mon, 14 Dec 2020 16:27:16 +0530 Subject: [PATCH 20/75] changed the base url --- lib/rest/client.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/rest/client.js b/lib/rest/client.js index 58195da..48b5039 100644 --- a/lib/rest/client.js +++ b/lib/rest/client.js @@ -60,7 +60,7 @@ export class Client { authId: authId, authToken: authToken, version: "v1", - url: "https://api.plivo.com/v1/Account/" + authId, + url: "https://api.numbers.plivodev.com/v1/Account/" + authId, userAgent: `${"plivo-node"}/${version || "Unknown Version"} (Node: ${ process.version })` From 5fcecf83f2fc71ebd1c4a2b80c4e64fda119c874 Mon Sep 17 00:00:00 2001 From: kalyan-plivo <49232630+kalyan-plivo@users.noreply.github.com> Date: Mon, 14 Dec 2020 17:11:03 +0530 Subject: [PATCH 21/75] reverted the changes --- package-lock.json | 213 +--------------------------------------------- package.json | 5 +- 2 files changed, 7 insertions(+), 211 deletions(-) diff --git a/package-lock.json b/package-lock.json index 366195d..347cb92 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,59 +1,9 @@ { "name": "plivo", - "version": "4.12.0", + "version": "4.1.2", "lockfileVersion": 1, "requires": true, "dependencies": { - "@sindresorhus/is": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.0.0.tgz", - "integrity": "sha512-FyD2meJpDPjyNQejSjvnhpgI/azsQkA4lGbuu5BQZfjvJ9cbRZXzeWL2HceCekW4lixO9JPesIIQkSoLjeJHNQ==" - }, - "@szmarczak/http-timer": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.5.tgz", - "integrity": "sha512-PyRA9sm1Yayuj5OIoJ1hGt2YISX45w9WcFbh6ddT0Z/0yaFxOtGLInr4jUfU1EAFVs0Yfyfev4RNwBlUaHdlDQ==", - "requires": { - "defer-to-connect": "^2.0.0" - } - }, - "@types/cacheable-request": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.1.tgz", - "integrity": "sha512-ykFq2zmBGOCbpIXtoVbz4SKY5QriWPh3AjyU4G74RYbtt5yOc5OfaY75ftjg7mikMOla1CTGpX3lLbuJh8DTrQ==", - "requires": { - "@types/http-cache-semantics": "*", - "@types/keyv": "*", - "@types/node": "*", - "@types/responselike": "*" - } - }, - "@types/http-cache-semantics": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.0.0.tgz", - "integrity": "sha512-c3Xy026kOF7QOTn00hbIllV1dLR9hG9NkSrLQgCVs8NF6sBU+VGWjD3wLPhmh1TYAc7ugCFsvHYMN4VcBN1U1A==" - }, - "@types/keyv": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.1.tgz", - "integrity": "sha512-MPtoySlAZQ37VoLaPcTHCu1RWJ4llDkULYZIzOYxlhxBqYPB0RsRlmMU0R6tahtFe27mIdkHV+551ZWV4PLmVw==", - "requires": { - "@types/node": "*" - } - }, - "@types/node": { - "version": "14.14.13", - "resolved": "https://registry.npmjs.org/@types/node/-/node-14.14.13.tgz", - "integrity": "sha512-vbxr0VZ8exFMMAjCW8rJwaya0dMCDyYW2ZRdTyjtrCvJoENMpdUHOT/eTzvgyA5ZnqRZ/sI0NwqAxNHKYokLJQ==" - }, - "@types/responselike": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.0.tgz", - "integrity": "sha512-85Y2BjiufFzaMIlvJDvTTB8Fxl2xfLo4HgmHzVBz08w4wDePCTjYw66PdrolO0kzli3yam/YCgRufyo1DdQVTA==", - "requires": { - "@types/node": "*" - } - }, "abbrev": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.0.9.tgz", @@ -1087,25 +1037,6 @@ "unset-value": "^1.0.0" } }, - "cacheable-lookup": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz", - "integrity": "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==" - }, - "cacheable-request": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.1.tgz", - "integrity": "sha512-lt0mJ6YAnsrBErpTMWeu5kl/tg9xMAWjavYTN6VQXM1A/teBITuNcccXsCxF0tDQQJf9DfAaX5O4e0zp0KlfZw==", - "requires": { - "clone-response": "^1.0.2", - "get-stream": "^5.1.0", - "http-cache-semantics": "^4.0.0", - "keyv": "^4.0.0", - "lowercase-keys": "^2.0.0", - "normalize-url": "^4.1.0", - "responselike": "^2.0.0" - } - }, "caller-path": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/caller-path/-/caller-path-0.1.0.tgz", @@ -1189,14 +1120,6 @@ "integrity": "sha1-2jCcwmPfFZlMaIypAheco8fNfH4=", "dev": true }, - "clone-response": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.2.tgz", - "integrity": "sha1-0dyXOSAxTfZ/vrlCI7TuNQI56Ws=", - "requires": { - "mimic-response": "^1.0.0" - } - }, "clone-stats": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/clone-stats/-/clone-stats-0.0.1.tgz", @@ -1498,21 +1421,6 @@ "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=", "dev": true }, - "decompress-response": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", - "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", - "requires": { - "mimic-response": "^3.1.0" - }, - "dependencies": { - "mimic-response": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", - "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==" - } - } - }, "deep-is": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", @@ -1528,11 +1436,6 @@ "clone": "^1.0.2" } }, - "defer-to-connect": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-2.0.0.tgz", - "integrity": "sha512-bYL2d05vOSf1JEZNx5vSAtPuBMkX8K9EUutg7zlKvTqKXHt7RhWJFbmd7qakVuf13i+IkGmp6FwSsONOf6VYIg==" - }, "define-property": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz", @@ -2308,14 +2211,6 @@ "is-property": "^1.0.0" } }, - "get-stream": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", - "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", - "requires": { - "pump": "^3.0.0" - } - }, "get-value": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz", @@ -2538,24 +2433,6 @@ "sparkles": "^1.0.0" } }, - "got": { - "version": "11.8.1", - "resolved": "https://registry.npmjs.org/got/-/got-11.8.1.tgz", - "integrity": "sha512-9aYdZL+6nHmvJwHALLwKSUZ0hMwGaJGYv3hoPLPgnT8BoBXm1SjnZeky+91tfwJaDzun2s4RsBRy48IEYv2q2Q==", - "requires": { - "@sindresorhus/is": "^4.0.0", - "@szmarczak/http-timer": "^4.0.5", - "@types/cacheable-request": "^6.0.1", - "@types/responselike": "^1.0.0", - "cacheable-lookup": "^5.0.3", - "cacheable-request": "^7.0.1", - "decompress-response": "^6.0.0", - "http2-wrapper": "^1.0.0-beta.5.2", - "lowercase-keys": "^2.0.0", - "p-cancelable": "^2.0.0", - "responselike": "^2.0.0" - } - }, "graceful-fs": { "version": "4.1.15", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz", @@ -3104,11 +2981,6 @@ "parse-passwd": "^1.0.0" } }, - "http-cache-semantics": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.0.tgz", - "integrity": "sha512-carPklcUh7ROWRK7Cv27RPtdhYhUsela/ue5/jKzjegVvXDqM2ILE9Q2BGn9JZJh1g87cp56su/FgQSzcWS8cQ==" - }, "http-signature": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", @@ -3119,15 +2991,6 @@ "sshpk": "^1.7.0" } }, - "http2-wrapper": { - "version": "1.0.0-beta.5.2", - "resolved": "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-1.0.0-beta.5.2.tgz", - "integrity": "sha512-xYz9goEyBnC8XwXDTuC/MZ6t+MrKVQZOk4s7+PaDkwIsQd8IwqvM+0M6bA/2lvG8GHXcPdf+MejTUeO2LCPCeQ==", - "requires": { - "quick-lru": "^5.1.1", - "resolve-alpn": "^1.0.0" - } - }, "ignore": { "version": "3.3.10", "resolved": "https://registry.npmjs.org/ignore/-/ignore-3.3.10.tgz", @@ -3572,11 +3435,6 @@ "integrity": "sha1-RsP+yMGJKxKwgz25vHYiF226s0s=", "dev": true }, - "json-buffer": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", - "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==" - }, "json-schema": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", @@ -3636,14 +3494,6 @@ "verror": "1.10.0" } }, - "keyv": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.0.3.tgz", - "integrity": "sha512-zdGa2TOpSZPq5mU6iowDARnMBZgtCqJ11dJROFi6tg6kTn4nuUdU09lFyLFSaHrWqpIJ+EBq4E8/Dc0Vx5vLdA==", - "requires": { - "json-buffer": "3.0.1" - } - }, "kind-of": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", @@ -3875,11 +3725,6 @@ "js-tokens": "^3.0.0 || ^4.0.0" } }, - "lowercase-keys": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz", - "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==" - }, "lru-cache": { "version": "2.7.3", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-2.7.3.tgz", @@ -3944,11 +3789,6 @@ "mime-db": "~1.37.0" } }, - "mimic-response": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", - "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==" - }, "minimatch": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", @@ -4189,11 +4029,6 @@ "abbrev": "1" } }, - "normalize-url": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-4.5.0.tgz", - "integrity": "sha512-2s47yzUxdexf1OhyRi4Em83iQk0aPvwTddtFz4hnSSw9dCEsLEGf6SwIO8ss/19S9iBb5sJaOuTvTGDeZI00BQ==" - }, "number-is-nan": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", @@ -4286,6 +4121,7 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, "requires": { "wrappy": "1" } @@ -4357,11 +4193,6 @@ "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", "dev": true }, - "p-cancelable": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.0.0.tgz", - "integrity": "sha512-wvPXDmbMmu2ksjkB4Z3nZWTSkJEb9lqVdMaCKpZUGJG9TMiNp9XcbG3fn9fPKjem04fJMJnXoyFPk2FmgiaiNg==" - }, "parse-filepath": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/parse-filepath/-/parse-filepath-1.0.2.tgz", @@ -4535,25 +4366,6 @@ "resolved": "https://registry.npmjs.org/psl/-/psl-1.1.31.tgz", "integrity": "sha512-/6pt4+C+T+wZUieKR620OpzN/LlnNKuWjy1iFLQ/UG35JqHlR/89MP1d96dUfkf6Dne3TuLQzOYEYshJ+Hx8mw==" }, - "pump": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", - "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", - "requires": { - "end-of-stream": "^1.1.0", - "once": "^1.3.1" - }, - "dependencies": { - "end-of-stream": { - "version": "1.4.4", - "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", - "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", - "requires": { - "once": "^1.4.0" - } - } - } - }, "punycode": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", @@ -4569,11 +4381,6 @@ "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz", "integrity": "sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA=" }, - "quick-lru": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz", - "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==" - }, "readable-stream": { "version": "2.3.6", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", @@ -4775,11 +4582,6 @@ "path-parse": "^1.0.6" } }, - "resolve-alpn": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.0.0.tgz", - "integrity": "sha512-rTuiIEqFmGxne4IovivKSDzld2lWW9QCjqv80SYjPgf+gS35eaCAjaP54CCwGAwBtnCsvNLYtqxe1Nw+i6JEmA==" - }, "resolve-dir": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-1.0.1.tgz", @@ -4802,14 +4604,6 @@ "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=", "dev": true }, - "responselike": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.0.tgz", - "integrity": "sha512-xH48u3FTB9VsZw7R+vvgaKeLKzT6jOogbQhEe/jewwnZgzPcnyWui2Av6JpoYZF/91uueC+lqhWqeURw5/qhCw==", - "requires": { - "lowercase-keys": "^2.0.0" - } - }, "restore-cursor": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-1.0.1.tgz", @@ -5764,7 +5558,8 @@ "wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true }, "write": { "version": "0.2.1", diff --git a/package.json b/package.json index a51cc1a..6823ee3 100644 --- a/package.json +++ b/package.json @@ -61,12 +61,13 @@ "@types/node": "^14.14.14", "base-64": "^0.1.0", "build-url": "^1.0.10", - "got": "^11.8.1", "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", "xmlbuilder": "^9.0.1" } -} +} \ No newline at end of file From 3c46160209d589976d56fad151a0fd19194a14e2 Mon Sep 17 00:00:00 2001 From: kalyan-plivo <49232630+kalyan-plivo@users.noreply.github.com> Date: Mon, 14 Dec 2020 17:20:16 +0530 Subject: [PATCH 22/75] added the package --- package.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/package.json b/package.json index 6823ee3..d7dc1f7 100644 --- a/package.json +++ b/package.json @@ -61,10 +61,9 @@ "@types/node": "^14.14.14", "base-64": "^0.1.0", "build-url": "^1.0.10", + "got": "^11.8.1", "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", From 4aed1024ada2eb365bf672deb167c37cd8e4980c Mon Sep 17 00:00:00 2001 From: kalyan-plivo <49232630+kalyan-plivo@users.noreply.github.com> Date: Mon, 14 Dec 2020 21:52:57 +0530 Subject: [PATCH 23/75] wip --- package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index d7dc1f7..3ae972e 100644 --- a/package.json +++ b/package.json @@ -67,6 +67,7 @@ "uri-parser": "^1.0.0", "utf8": "^2.1.2", "xml2js": "^0.4.19", - "xmlbuilder": "^9.0.1" + "xmlbuilder": "^9.0.1", + "graceful-fs": "^4.2.4" } } \ No newline at end of file From 52102c92eb28816830394a950facdabb8f7154f0 Mon Sep 17 00:00:00 2001 From: kalyan-plivo <49232630+kalyan-plivo@users.noreply.github.com> Date: Mon, 14 Dec 2020 21:55:00 +0530 Subject: [PATCH 24/75] wip --- package.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/package.json b/package.json index 3ae972e..d7dc1f7 100644 --- a/package.json +++ b/package.json @@ -67,7 +67,6 @@ "uri-parser": "^1.0.0", "utf8": "^2.1.2", "xml2js": "^0.4.19", - "xmlbuilder": "^9.0.1", - "graceful-fs": "^4.2.4" + "xmlbuilder": "^9.0.1" } } \ No newline at end of file From 1848eeb011367450bf37c599b193fc7b740730c9 Mon Sep 17 00:00:00 2001 From: kalyan-plivo <49232630+kalyan-plivo@users.noreply.github.com> Date: Tue, 15 Dec 2020 10:18:53 +0530 Subject: [PATCH 25/75] WIP --- lib/rest/got.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/rest/got.js b/lib/rest/got.js index 3f4005e..51e5798 100644 --- a/lib/rest/got.js +++ b/lib/rest/got.js @@ -1,5 +1,5 @@ import got from 'got'; -import searchParams from 'searchParams'; +import queryString from 'querystring'; import * as Exceptions from '../utils/exceptions'; import * as _ from "lodash"; @@ -56,7 +56,7 @@ export function Got(config) { } if (method === 'GET' && options.formData !== '') { - let query = '?' + searchParams.stringify(params); + let query = '?' + queryString.stringify(params); options.url += query; } @@ -79,7 +79,7 @@ export function Got(config) { if (response.statusCode >= 500){ options.url = apiVoiceUris[1] + config.authId + '/' + action; if (method === 'GET' && options.formData !== '') { - let query = '?' + searchParams.stringify(params); + let query = '?' + queryString.stringify(params); options.url += query; } got(options,(error, response) => { @@ -90,7 +90,7 @@ export function Got(config) { if(response.statusCode>=500){ options.url = apiVoiceUris[2] + config.authId + '/' + action; if (method === 'GET' && options.formData !== '') { - let query = '?' + searchParams.stringify(params); + let query = '?' + queryString.stringify(params); options.url += query; } got(options, (error, response) => { From 97ebe4bc4627bf5c0c65f7a8934d750feeddf982 Mon Sep 17 00:00:00 2001 From: kalyan-plivo <49232630+kalyan-plivo@users.noreply.github.com> Date: Tue, 15 Dec 2020 10:19:42 +0530 Subject: [PATCH 26/75] wip --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index d7dc1f7..4f12f7b 100644 --- a/package.json +++ b/package.json @@ -62,6 +62,7 @@ "base-64": "^0.1.0", "build-url": "^1.0.10", "got": "^11.8.1", + "querystring": "^0.2.0", "jsonwebtoken": "^8.5.1", "lodash": "^4.17.4", "uri-parser": "^1.0.0", From 60b9cb1f47ea0544bd166f7715b7a00cf127400d Mon Sep 17 00:00:00 2001 From: kalyan-plivo <49232630+kalyan-plivo@users.noreply.github.com> Date: Wed, 16 Dec 2020 19:20:27 +0530 Subject: [PATCH 27/75] wip --- lib/base.js | 7 +- lib/resources/numbers.js | 2 +- lib/rest/axios.js | 222 +++++++++++++++++++++++++++++++++++++++ lib/rest/client.js | 12 ++- lib/rest/got.js | 3 +- package.json | 5 +- 6 files changed, 238 insertions(+), 13 deletions(-) create mode 100644 lib/rest/axios.js diff --git a/lib/base.js b/lib/base.js index 8049673..1048cbf 100644 --- a/lib/base.js +++ b/lib/base.js @@ -1,6 +1,5 @@ -import { - extend -} from './utils/common.js'; +import { extend } from './utils/common.js'; +import axios from 'axios'; let actionKey = Symbol('api action'); let klassKey = Symbol('constructor'); @@ -192,4 +191,4 @@ export class PlivoResourceInterface { }); } -} \ No newline at end of file +} diff --git a/lib/resources/numbers.js b/lib/resources/numbers.js index 5b0cc8b..8822b1c 100644 --- a/lib/resources/numbers.js +++ b/lib/resources/numbers.js @@ -345,4 +345,4 @@ export class NumberInterface extends PlivoResourceInterface { id: number }).unrent(number); } -} \ No newline at end of file +} diff --git a/lib/rest/axios.js b/lib/rest/axios.js new file mode 100644 index 0000000..a38901d --- /dev/null +++ b/lib/rest/axios.js @@ -0,0 +1,222 @@ +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' + }; + + return (method, action, params) => { + if (typeof (params) != 'undefined' && typeof (params.file) != 'undefined') { + var 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; + } + var options = { + url: config.url + '/' + action, + method: method, + formData: 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.formData; + 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.formData !== '') { + 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) => { + axios(options, (error, response, body) => { + if (error) { + reject(error); + return; + } + + if(isVoiceReq === true){ + if (response.statusCode >= 500){ + options.url = apiVoiceUris[1] + config.authId + '/' + action; + if (method === 'GET' && options.formData !== '') { + let query = '?' + queryString.stringify(params); + options.url += query; + } + axios(options,(error, response) => { + if(error){ + reject(error); + return; + } + if(response.statusCode>=500){ + options.url = apiVoiceUris[2] + config.authId + '/' + action; + if (method === 'GET' && options.formData !== '') { + let query = '?' + queryString.stringify(params); + options.url += query; + } + axios(options, (error, response) => { + if(error){ + reject(error); + return; + } + const exceptionClass = { + 400: Exceptions.InvalidRequestError, + 401: Exceptions.AuthenticationError, + 404: Exceptions.ResourceNotFoundError, + 405: Exceptions.InvalidRequestError, + 500: Exceptions.ServerError, + } [response.statusCode] || Error; + + if (!_.inRange(response.statusCode, 200, 300)) { + body = body || response.body; + if (typeof body === 'object') { + reject(new exceptionClass(JSON.stringify(body))); + } else { + reject(new exceptionClass(body)); + } + } + // else { + let body = response.body; + let isObj = typeof _body === 'object' && _body !== null && !(_body instanceof Array) && !(_body instanceof Date) + if (isObj) { + _body['statusCode'] = response.statusCode; + } + resolve({ + response: response, + body: body + }); + // } + }) + } + else { + const exceptionClass = { + 400: Exceptions.InvalidRequestError, + 401: Exceptions.AuthenticationError, + 404: Exceptions.ResourceNotFoundError, + 405: Exceptions.InvalidRequestError, + 500: Exceptions.ServerError, + } [response.statusCode] || Error; + + if (!_.inRange(response.statusCode, 200, 300)) { + body = body || response.body; + if (typeof body === 'object') { + reject(new exceptionClass(JSON.stringify(body))); + } else { + reject(new exceptionClass(body)); + } + } + // else { + let body = response.body; + let isObj = typeof _body === 'object' && _body !== null && !(_body instanceof Array) && !(_body instanceof Date) + if (isObj) { + _body['statusCode'] = response.statusCode; + } + resolve({ + response: response, + body: body + }); + } + }) + } + else { + const exceptionClass = { + 400: Exceptions.InvalidRequestError, + 401: Exceptions.AuthenticationError, + 404: Exceptions.ResourceNotFoundError, + 405: Exceptions.InvalidRequestError, + 500: Exceptions.ServerError, + } [response.statusCode] || Error; + + if (!_.inRange(response.statusCode, 200, 300)) { + body = body || response.body; + if (typeof body === 'object') { + reject(new exceptionClass(JSON.stringify(body))); + } else { + reject(new exceptionClass(body)); + } + } + // else { + let body = response.body; + let isObj = typeof _body === 'object' && _body !== null && !(_body instanceof Array) && !(_body instanceof Date) + if (isObj) { + _body['statusCode'] = response.statusCode; + } + resolve({ + response: response, + body: body + }); + } + } + + else { + const exceptionClass = { + 400: Exceptions.InvalidRequestError, + 401: Exceptions.AuthenticationError, + 404: Exceptions.ResourceNotFoundError, + 405: Exceptions.InvalidRequestError, + 500: Exceptions.ServerError, + } [response.statusCode] || Error; + + if (!_.inRange(response.statusCode, 200, 300)) { + body = body || response.body; + if (typeof body === 'object') { + reject(new exceptionClass(JSON.stringify(body))); + } else { + reject(new exceptionClass(body)); + } + } + else { + let body = response.body; + let isObj = typeof _body === 'object' && _body !== null && !(_body instanceof Array) && !(_body instanceof Date) + if (isObj) { + _body['statusCode'] = response.statusCode; + } + resolve({ + response: response, + body: body + }); + } + } + }); + }); + }; +} diff --git a/lib/rest/client.js b/lib/rest/client.js index 48b5039..8401ede 100644 --- a/lib/rest/client.js +++ b/lib/rest/client.js @@ -1,5 +1,5 @@ // import { Request } from "./request.js"; -import { Got } from "./got.js"; +import { Axios } from "./axios.js"; import { camelCaseRequestWrapper } from "./utils"; import { name, version } from "../../package.json"; import { Phlo, PhloInterface } from "../resources/phlo"; @@ -67,8 +67,12 @@ export class Client { }, options ); - - let client = camelCaseRequestWrapper(Got(options)); + console.log("testinsfsfsdjfdshfjhsldjfhjsdhfdsjhfjdsfhjsdahfsdahf") + console.log(typeof(options.url),"url") + console.log(options.userAgent,"useragent") + console.log(options.authId,"authid") + console.log(options.authToken,"authtoken") + let client = camelCaseRequestWrapper(Axios(options)); this.calls = new CallInterface(client); this.accounts = new AccountInterface(client); @@ -126,7 +130,7 @@ export class PhloClient { options ); - let client = camelCaseRequestWrapper(Got(options)); + let client = camelCaseRequestWrapper(Axios(options)); this.phlo = function(phloId) { let dd = new Phlo(client, { phloId: phloId, authId: authId }); diff --git a/lib/rest/got.js b/lib/rest/got.js index 51e5798..ab94563 100644 --- a/lib/rest/got.js +++ b/lib/rest/got.js @@ -29,8 +29,7 @@ export function Got(config) { url: config.url + '/' + action, method: method, formData: params || '', - headers: headers, - json: {} + headers: headers }; 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; diff --git a/package.json b/package.json index 4f12f7b..613e6d3 100644 --- a/package.json +++ b/package.json @@ -58,16 +58,17 @@ "test": "gulp" }, "dependencies": { - "@types/node": "^14.14.14", + "axios": "^0.19.2", "base-64": "^0.1.0", "build-url": "^1.0.10", "got": "^11.8.1", "querystring": "^0.2.0", "jsonwebtoken": "^8.5.1", "lodash": "^4.17.4", + "querystring": "^0.2.0", "uri-parser": "^1.0.0", "utf8": "^2.1.2", "xml2js": "^0.4.19", "xmlbuilder": "^9.0.1" } -} \ No newline at end of file +} From 2c606739840c8ff16e684697cae28f3b7fa7be7f Mon Sep 17 00:00:00 2001 From: kalyan-plivo <49232630+kalyan-plivo@users.noreply.github.com> Date: Thu, 17 Dec 2020 12:33:40 +0530 Subject: [PATCH 28/75] wip --- lib/rest/client.js | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/lib/rest/client.js b/lib/rest/client.js index 8401ede..3dac6fe 100644 --- a/lib/rest/client.js +++ b/lib/rest/client.js @@ -1,5 +1,6 @@ // import { Request } from "./request.js"; -import { Axios } from "./axios.js"; +// import { Axios } from "./axios.js"; +import { Got } from "./got.js"; import { camelCaseRequestWrapper } from "./utils"; import { name, version } from "../../package.json"; import { Phlo, PhloInterface } from "../resources/phlo"; @@ -60,19 +61,15 @@ export class Client { authId: authId, authToken: authToken, version: "v1", - url: "https://api.numbers.plivodev.com/v1/Account/" + authId, + url: "https://api.plivo.com/v1/Account/" + authId, userAgent: `${"plivo-node"}/${version || "Unknown Version"} (Node: ${ process.version })` }, options ); - console.log("testinsfsfsdjfdshfjhsldjfhjsdhfdsjhfjdsfhjsdahfsdahf") - console.log(typeof(options.url),"url") - console.log(options.userAgent,"useragent") - console.log(options.authId,"authid") - console.log(options.authToken,"authtoken") - let client = camelCaseRequestWrapper(Axios(options)); + console.log(options,"12311122222222222") + let client = camelCaseRequestWrapper(Got(options)); this.calls = new CallInterface(client); this.accounts = new AccountInterface(client); @@ -130,7 +127,7 @@ export class PhloClient { options ); - let client = camelCaseRequestWrapper(Axios(options)); + let client = camelCaseRequestWrapper(Got(options)); this.phlo = function(phloId) { let dd = new Phlo(client, { phloId: phloId, authId: authId }); From 8ac52d04a66e63aafe3a790cf3af76df3f189b18 Mon Sep 17 00:00:00 2001 From: kalyan-plivo <49232630+kalyan-plivo@users.noreply.github.com> Date: Thu, 17 Dec 2020 20:56:05 +0530 Subject: [PATCH 29/75] Axios integration is done --- lib/rest/axios.js | 92 +++++++++++++++++++++++++++------------------- lib/rest/client.js | 10 ++--- 2 files changed, 59 insertions(+), 43 deletions(-) diff --git a/lib/rest/axios.js b/lib/rest/axios.js index a38901d..af70693 100644 --- a/lib/rest/axios.js +++ b/lib/rest/axios.js @@ -69,45 +69,49 @@ export function Axios(config) { } return new Promise((resolve, reject) => { - axios(options, (error, response, body) => { - if (error) { - reject(error); - return; - } + // axios(options, (error, response, body) => { + axios(options).then(response => { + // if (error) { + // reject(error); + // return; + // } if(isVoiceReq === true){ - if (response.statusCode >= 500){ + if (response.status >= 500){ options.url = apiVoiceUris[1] + config.authId + '/' + action; if (method === 'GET' && options.formData !== '') { let query = '?' + queryString.stringify(params); options.url += query; } - axios(options,(error, response) => { - if(error){ - reject(error); - return; - } - if(response.statusCode>=500){ + // axios(options,(error, response) => { + axios(options).then(response => { + // if(error){ + // reject(error); + // return; + // } + if(response.status>=500){ options.url = apiVoiceUris[2] + config.authId + '/' + action; if (method === 'GET' && options.formData !== '') { let query = '?' + queryString.stringify(params); options.url += query; } - axios(options, (error, response) => { - if(error){ - reject(error); - return; - } + // axios(options, (error, response) => { + axios(options).then(response => { + // if(error){ + // reject(error); + // return; + // } const exceptionClass = { 400: Exceptions.InvalidRequestError, 401: Exceptions.AuthenticationError, 404: Exceptions.ResourceNotFoundError, 405: Exceptions.InvalidRequestError, 500: Exceptions.ServerError, - } [response.statusCode] || Error; + } [response.status] || Error; - if (!_.inRange(response.statusCode, 200, 300)) { - body = body || response.body; + if (!_.inRange(response.status, 200, 300)) { + // body = body || response.body; + let body = response.data; if (typeof body === 'object') { reject(new exceptionClass(JSON.stringify(body))); } else { @@ -115,10 +119,11 @@ export function Axios(config) { } } // else { - let body = response.body; + // let body = response.body; + let body = response.data; let isObj = typeof _body === 'object' && _body !== null && !(_body instanceof Array) && !(_body instanceof Date) if (isObj) { - _body['statusCode'] = response.statusCode; + _body['statusCode'] = response.status; } resolve({ response: response, @@ -134,10 +139,11 @@ export function Axios(config) { 404: Exceptions.ResourceNotFoundError, 405: Exceptions.InvalidRequestError, 500: Exceptions.ServerError, - } [response.statusCode] || Error; + } [response.status] || Error; - if (!_.inRange(response.statusCode, 200, 300)) { - body = body || response.body; + if (!_.inRange(response.status, 200, 300)) { + // body = body || response.body; + let body = response.data; if (typeof body === 'object') { reject(new exceptionClass(JSON.stringify(body))); } else { @@ -145,10 +151,11 @@ export function Axios(config) { } } // else { - let body = response.body; + // let body = response.body; + let body = response.data; let isObj = typeof _body === 'object' && _body !== null && !(_body instanceof Array) && !(_body instanceof Date) if (isObj) { - _body['statusCode'] = response.statusCode; + _body['statusCode'] = response.status; } resolve({ response: response, @@ -164,10 +171,11 @@ export function Axios(config) { 404: Exceptions.ResourceNotFoundError, 405: Exceptions.InvalidRequestError, 500: Exceptions.ServerError, - } [response.statusCode] || Error; + } [response.status] || Error; - if (!_.inRange(response.statusCode, 200, 300)) { - body = body || response.body; + if (!_.inRange(response.status, 200, 300)) { + // body = body || response.body; + let body = response.data; if (typeof body === 'object') { reject(new exceptionClass(JSON.stringify(body))); } else { @@ -175,10 +183,11 @@ export function Axios(config) { } } // else { - let body = response.body; + // let body = response.body; + let body = response.data; let isObj = typeof _body === 'object' && _body !== null && !(_body instanceof Array) && !(_body instanceof Date) if (isObj) { - _body['statusCode'] = response.statusCode; + _body['statusCode'] = response.status; } resolve({ response: response, @@ -194,10 +203,11 @@ export function Axios(config) { 404: Exceptions.ResourceNotFoundError, 405: Exceptions.InvalidRequestError, 500: Exceptions.ServerError, - } [response.statusCode] || Error; + } [response.status] || Error; - if (!_.inRange(response.statusCode, 200, 300)) { - body = body || response.body; + if (!_.inRange(response.status, 200, 300)) { + // body = body || response.body; + let body = response.data; if (typeof body === 'object') { reject(new exceptionClass(JSON.stringify(body))); } else { @@ -205,10 +215,11 @@ export function Axios(config) { } } else { - let body = response.body; + // let body = response.body; + let body = response.data; let isObj = typeof _body === 'object' && _body !== null && !(_body instanceof Array) && !(_body instanceof Date) if (isObj) { - _body['statusCode'] = response.statusCode; + _body['statusCode'] = response.status; } resolve({ response: response, @@ -216,7 +227,12 @@ export function Axios(config) { }); } } - }); + }) + .catch(function (error) { + // handle error + // console.log(error); + reject(error); + }) }); }; } diff --git a/lib/rest/client.js b/lib/rest/client.js index 3dac6fe..69225eb 100644 --- a/lib/rest/client.js +++ b/lib/rest/client.js @@ -1,6 +1,5 @@ // import { Request } from "./request.js"; -// import { Axios } from "./axios.js"; -import { Got } from "./got.js"; +import { Axios } from "./axios.js"; import { camelCaseRequestWrapper } from "./utils"; import { name, version } from "../../package.json"; import { Phlo, PhloInterface } from "../resources/phlo"; @@ -68,8 +67,8 @@ export class Client { }, options ); - console.log(options,"12311122222222222") - let client = camelCaseRequestWrapper(Got(options)); + let client = camelCaseRequestWrapper(Axios(options)); + // let client = camelCaseRequestWrapper(Request(options)); this.calls = new CallInterface(client); this.accounts = new AccountInterface(client); @@ -127,7 +126,8 @@ export class PhloClient { options ); - let client = camelCaseRequestWrapper(Got(options)); + let client = camelCaseRequestWrapper(Axios(options)); + // let client = camelCaseRequestWrapper(Request(options)); this.phlo = function(phloId) { let dd = new Phlo(client, { phloId: phloId, authId: authId }); From c523ffb7e33ac5057bf5fb73e0a68204b09233e4 Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Fri, 18 Dec 2020 20:25:08 +0530 Subject: [PATCH 30/75] Changed formdata to data in case of axios as dependency --- lib/rest/axios.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/rest/axios.js b/lib/rest/axios.js index af70693..958f698 100644 --- a/lib/rest/axios.js +++ b/lib/rest/axios.js @@ -28,7 +28,7 @@ export function Axios(config) { var options = { url: config.url + '/' + action, method: method, - formData: params || '', + data: params || '', headers: headers, json: true }; @@ -40,7 +40,7 @@ export function Axios(config) { delete params.is_call_insights_request; delete params.call_insights_base_url; delete params.call_insights_request_path; - delete options.formData; + delete options.data; options.json = params; } else if (params.hasOwnProperty('is_voice_request')){ @@ -55,7 +55,7 @@ export function Axios(config) { } } - if (method === 'GET' && options.formData !== '') { + if (method === 'GET' && options.data !== '') { let query = '?' + queryString.stringify(params); options.url += query; } @@ -79,7 +79,7 @@ export function Axios(config) { if(isVoiceReq === true){ if (response.status >= 500){ options.url = apiVoiceUris[1] + config.authId + '/' + action; - if (method === 'GET' && options.formData !== '') { + if (method === 'GET' && options.data !== '') { let query = '?' + queryString.stringify(params); options.url += query; } @@ -91,7 +91,7 @@ export function Axios(config) { // } if(response.status>=500){ options.url = apiVoiceUris[2] + config.authId + '/' + action; - if (method === 'GET' && options.formData !== '') { + if (method === 'GET' && options.data !== '') { let query = '?' + queryString.stringify(params); options.url += query; } @@ -232,7 +232,7 @@ export function Axios(config) { // handle error // console.log(error); reject(error); - }) + }) }); }; } From 1339b89e282a4e00f0d2ca30ba014336c00c14e0 Mon Sep 17 00:00:00 2001 From: kalyan-plivo <49232630+kalyan-plivo@users.noreply.github.com> Date: Sun, 20 Dec 2020 12:19:41 +0530 Subject: [PATCH 31/75] added the error --- lib/rest/axios.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/rest/axios.js b/lib/rest/axios.js index 958f698..e45439f 100644 --- a/lib/rest/axios.js +++ b/lib/rest/axios.js @@ -231,7 +231,7 @@ export function Axios(config) { .catch(function (error) { // handle error // console.log(error); - reject(error); + reject(error.stack); }) }); }; From 5d2868bdefc035ded18cf1d8d5e49b42855d19bd Mon Sep 17 00:00:00 2001 From: kalyan-plivo <49232630+kalyan-plivo@users.noreply.github.com> Date: Mon, 21 Dec 2020 17:47:03 +0530 Subject: [PATCH 32/75] added the some error logs --- lib/rest/axios.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/rest/axios.js b/lib/rest/axios.js index e45439f..ff0e121 100644 --- a/lib/rest/axios.js +++ b/lib/rest/axios.js @@ -231,7 +231,7 @@ export function Axios(config) { .catch(function (error) { // handle error // console.log(error); - reject(error.stack); + reject(error.stack + '\n' + JSON.stringify(error.response.data)); }) }); }; From b569c906780832b28e939bdc63b33469a026aac4 Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Tue, 22 Dec 2020 14:37:40 +0530 Subject: [PATCH 33/75] Added error logging for voice fallbacks --- lib/rest/axios.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/lib/rest/axios.js b/lib/rest/axios.js index ff0e121..9fe5676 100644 --- a/lib/rest/axios.js +++ b/lib/rest/axios.js @@ -131,6 +131,11 @@ export function Axios(config) { }); // } }) + .catch(function (error) { + // handle error + // console.log(error); + reject(error.stack + '\n' + JSON.stringify(error.response.data)); + }) } else { const exceptionClass = { @@ -163,6 +168,11 @@ export function Axios(config) { }); } }) + .catch(function (error) { + // handle error + // console.log(error); + reject(error.stack + '\n' + JSON.stringify(error.response.data)); + }) } else { const exceptionClass = { From 07106e961da2ba39ef7ca9a8a366708429bdd29c Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Mon, 28 Dec 2020 19:26:20 +0530 Subject: [PATCH 34/75] Added voice retry for axios library --- lib/resources/call.js | 2 +- lib/rest/axios.js | 190 +++++++++--------------------------------- 2 files changed, 42 insertions(+), 150 deletions(-) diff --git a/lib/resources/call.js b/lib/resources/call.js index 2b25bfe..a736e67 100644 --- a/lib/resources/call.js +++ b/lib/resources/call.js @@ -1031,4 +1031,4 @@ class QueuedCallInterface extends PlivoResourceInterface { }); }); } -} \ No newline at end of file +} diff --git a/lib/rest/axios.js b/lib/rest/axios.js index 9fe5676..1e27bea 100644 --- a/lib/rest/axios.js +++ b/lib/rest/axios.js @@ -13,6 +13,21 @@ export function Axios(config) { '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++ + return new Promise((resolve) => { + resolve(axios(config)) + }) + } + return Promise.reject(error) + }) + } + return (method, action, params) => { if (typeof (params) != 'undefined' && typeof (params.file) != 'undefined') { var files = [] @@ -69,112 +84,24 @@ export function Axios(config) { } return new Promise((resolve, reject) => { - // axios(options, (error, response, body) => { - axios(options).then(response => { - // if (error) { - // reject(error); - // return; - // } - - if(isVoiceReq === true){ - if (response.status >= 500){ - options.url = apiVoiceUris[1] + config.authId + '/' + action; - if (method === 'GET' && options.data !== '') { - let query = '?' + queryString.stringify(params); - options.url += query; - } - // axios(options,(error, response) => { - axios(options).then(response => { - // if(error){ - // reject(error); - // return; - // } - if(response.status>=500){ - options.url = apiVoiceUris[2] + config.authId + '/' + action; - if (method === 'GET' && options.data !== '') { - let query = '?' + queryString.stringify(params); - options.url += query; - } - // axios(options, (error, response) => { - axios(options).then(response => { - // if(error){ - // reject(error); - // return; - // } - 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)) { - // body = body || response.body; - let body = response.data; - if (typeof body === 'object') { - reject(new exceptionClass(JSON.stringify(body))); - } else { - reject(new exceptionClass(body)); - } - } - // else { - // let body = response.body; - 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) { - // handle error - // console.log(error); - reject(error.stack + '\n' + JSON.stringify(error.response.data)); - }) - } - else { - 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)) { - // body = body || response.body; - let body = response.data; - if (typeof body === 'object') { - reject(new exceptionClass(JSON.stringify(body))); - } else { - reject(new exceptionClass(body)); - } - } - // else { - // let body = response.body; - 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) { - // handle error - // console.log(error); - reject(error.stack + '\n' + JSON.stringify(error.response.data)); - }) - } - else { + if (isVoiceReq) { + retryWrapper(axios, {retryTime: 2}) + let retryAttempt; + for (retryAttempt = 0; retryAttempt < 3; retryAttempt++) { + options.url = apiVoiceUris[retryAttempt] + config.authId + '/' + action; + axios(options).then(response => { + 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, @@ -184,16 +111,15 @@ export function Axios(config) { } [response.status] || Error; if (!_.inRange(response.status, 200, 300)) { - // body = body || response.body; let body = response.data; if (typeof body === 'object') { reject(new exceptionClass(JSON.stringify(body))); - } else { + } + else { reject(new exceptionClass(body)); } } - // else { - // let body = response.body; + else { let body = response.data; let isObj = typeof _body === 'object' && _body !== null && !(_body instanceof Array) && !(_body instanceof Date) if (isObj) { @@ -204,45 +130,11 @@ export function Axios(config) { body: body }); } - } - - else { - 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)) { - // body = body || response.body; - let body = response.data; - if (typeof body === 'object') { - reject(new exceptionClass(JSON.stringify(body))); - } else { - reject(new exceptionClass(body)); - } - } - else { - // let body = response.body; - 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) { - // handle error - // console.log(error); - reject(error.stack + '\n' + JSON.stringify(error.response.data)); - }) + }) + .catch(function (error) { + reject(error.stack + '\n' + JSON.stringify(error.response.data)); + }) + } }); }; } From 4b968cd3b94c03b81bb245f3630a961be4dc0b62 Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Wed, 6 Jan 2021 11:18:24 +0530 Subject: [PATCH 35/75] remove commented lines --- lib/rest/client.js | 3 --- 1 file changed, 3 deletions(-) diff --git a/lib/rest/client.js b/lib/rest/client.js index 69225eb..be78627 100644 --- a/lib/rest/client.js +++ b/lib/rest/client.js @@ -1,4 +1,3 @@ -// import { Request } from "./request.js"; import { Axios } from "./axios.js"; import { camelCaseRequestWrapper } from "./utils"; import { name, version } from "../../package.json"; @@ -68,7 +67,6 @@ export class Client { options ); let client = camelCaseRequestWrapper(Axios(options)); - // let client = camelCaseRequestWrapper(Request(options)); this.calls = new CallInterface(client); this.accounts = new AccountInterface(client); @@ -127,7 +125,6 @@ export class PhloClient { ); let client = camelCaseRequestWrapper(Axios(options)); - // let client = camelCaseRequestWrapper(Request(options)); this.phlo = function(phloId) { let dd = new Phlo(client, { phloId: phloId, authId: authId }); From 53d5340dc4bade44723d8d480a6bb8aa8d4f8519 Mon Sep 17 00:00:00 2001 From: kalyan-plivo <49232630+kalyan-plivo@users.noreply.github.com> Date: Tue, 5 Jan 2021 12:55:07 +0530 Subject: [PATCH 36/75] removed the got js file --- lib/rest/got.js | 221 ------------------------------------------------ 1 file changed, 221 deletions(-) delete mode 100644 lib/rest/got.js diff --git a/lib/rest/got.js b/lib/rest/got.js deleted file mode 100644 index ab94563..0000000 --- a/lib/rest/got.js +++ /dev/null @@ -1,221 +0,0 @@ -import got from 'got'; -import queryString from 'querystring'; -import * as Exceptions from '../utils/exceptions'; -import * as _ from "lodash"; - -export function Got(config) { - let auth = 'Basic ' + new Buffer(config.authId + ':' + config.authToken) - .toString('base64'); - - let headers = { - Authorization: auth, - 'User-Agent': config.userAgent, - 'Content-Type': 'application/json' - }; - - return (method, action, params) => { - if (typeof (params) != 'undefined' && typeof (params.file) != 'undefined') { - var 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; - } - var options = { - url: config.url + '/' + action, - method: method, - formData: params || '', - headers: headers - }; - 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.formData; - 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.formData !== '') { - 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) => { - got(options, (error, response, body) => { - if (error) { - reject(error); - return; - } - - if(isVoiceReq === true){ - if (response.statusCode >= 500){ - options.url = apiVoiceUris[1] + config.authId + '/' + action; - if (method === 'GET' && options.formData !== '') { - let query = '?' + queryString.stringify(params); - options.url += query; - } - got(options,(error, response) => { - if(error){ - reject(error); - return; - } - if(response.statusCode>=500){ - options.url = apiVoiceUris[2] + config.authId + '/' + action; - if (method === 'GET' && options.formData !== '') { - let query = '?' + queryString.stringify(params); - options.url += query; - } - got(options, (error, response) => { - if(error){ - reject(error); - return; - } - const exceptionClass = { - 400: Exceptions.InvalidRequestError, - 401: Exceptions.AuthenticationError, - 404: Exceptions.ResourceNotFoundError, - 405: Exceptions.InvalidRequestError, - 500: Exceptions.ServerError, - } [response.statusCode] || Error; - - if (!_.inRange(response.statusCode, 200, 300)) { - body = body || response.body; - if (typeof body === 'object') { - reject(new exceptionClass(JSON.stringify(body))); - } else { - reject(new exceptionClass(body)); - } - } - // else { - let body = response.body; - let isObj = typeof _body === 'object' && _body !== null && !(_body instanceof Array) && !(_body instanceof Date) - if (isObj) { - _body['statusCode'] = response.statusCode; - } - resolve({ - response: response, - body: body - }); - // } - }) - } - else { - const exceptionClass = { - 400: Exceptions.InvalidRequestError, - 401: Exceptions.AuthenticationError, - 404: Exceptions.ResourceNotFoundError, - 405: Exceptions.InvalidRequestError, - 500: Exceptions.ServerError, - } [response.statusCode] || Error; - - if (!_.inRange(response.statusCode, 200, 300)) { - body = body || response.body; - if (typeof body === 'object') { - reject(new exceptionClass(JSON.stringify(body))); - } else { - reject(new exceptionClass(body)); - } - } - // else { - let body = response.body; - let isObj = typeof _body === 'object' && _body !== null && !(_body instanceof Array) && !(_body instanceof Date) - if (isObj) { - _body['statusCode'] = response.statusCode; - } - resolve({ - response: response, - body: body - }); - } - }) - } - else { - const exceptionClass = { - 400: Exceptions.InvalidRequestError, - 401: Exceptions.AuthenticationError, - 404: Exceptions.ResourceNotFoundError, - 405: Exceptions.InvalidRequestError, - 500: Exceptions.ServerError, - } [response.statusCode] || Error; - - if (!_.inRange(response.statusCode, 200, 300)) { - body = body || response.body; - if (typeof body === 'object') { - reject(new exceptionClass(JSON.stringify(body))); - } else { - reject(new exceptionClass(body)); - } - } - // else { - let body = response.body; - let isObj = typeof _body === 'object' && _body !== null && !(_body instanceof Array) && !(_body instanceof Date) - if (isObj) { - _body['statusCode'] = response.statusCode; - } - resolve({ - response: response, - body: body - }); - } - } - - else { - const exceptionClass = { - 400: Exceptions.InvalidRequestError, - 401: Exceptions.AuthenticationError, - 404: Exceptions.ResourceNotFoundError, - 405: Exceptions.InvalidRequestError, - 500: Exceptions.ServerError, - } [response.statusCode] || Error; - - if (!_.inRange(response.statusCode, 200, 300)) { - body = body || response.body; - if (typeof body === 'object') { - reject(new exceptionClass(JSON.stringify(body))); - } else { - reject(new exceptionClass(body)); - } - } - else { - let body = response.body; - let isObj = typeof _body === 'object' && _body !== null && !(_body instanceof Array) && !(_body instanceof Date) - if (isObj) { - _body['statusCode'] = response.statusCode; - } - resolve({ - response: response, - body: body - }); - } - } - }); - }); - }; -} From 25946cc682c56541425da66d093eb81fbc00e1ae Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Fri, 8 Jan 2021 16:13:34 +0530 Subject: [PATCH 37/75] Fixed review comments --- lib/rest/axios.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/rest/axios.js b/lib/rest/axios.js index 1e27bea..0b81ddb 100644 --- a/lib/rest/axios.js +++ b/lib/rest/axios.js @@ -17,11 +17,11 @@ export function Axios(config) { const max_time = options.retryTime; let counter = 0; axios.interceptors.response.use(null, (error) => { - const config = error.config + const config = error.config; if (counter < max_time && error.response.status >= 500) { - counter++ + counter++; return new Promise((resolve) => { - resolve(axios(config)) + resolve(axios(config)); }) } return Promise.reject(error) @@ -30,17 +30,17 @@ export function Axios(config) { return (method, action, params) => { if (typeof (params) != 'undefined' && typeof (params.file) != 'undefined') { - var files = [] + let files = []; if (Array.isArray(params.file)) { for (let index = 0; index < params.file.length; index++) { - files[index] = require('fs').createReadStream(params.file[index]) + files[index] = require('fs').createReadStream(params.file[index]); } } else { files[0] = require('fs').createReadStream(params.file); } params.file = files; } - var options = { + let options = { url: config.url + '/' + action, method: method, data: params || '', @@ -85,7 +85,7 @@ export function Axios(config) { return new Promise((resolve, reject) => { if (isVoiceReq) { - retryWrapper(axios, {retryTime: 2}) + retryWrapper(axios, {retryTime: 2}); let retryAttempt; for (retryAttempt = 0; retryAttempt < 3; retryAttempt++) { options.url = apiVoiceUris[retryAttempt] + config.authId + '/' + action; From 2ac90d455d380a1e42baaa5dfbb74f652ce569f8 Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Fri, 29 Jan 2021 12:53:07 +0530 Subject: [PATCH 38/75] Rebased code with master --- lib/base.js | 1 - lib/resources/call.js | 2 +- package.json | 3 +-- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/base.js b/lib/base.js index 1048cbf..3ed6040 100644 --- a/lib/base.js +++ b/lib/base.js @@ -1,5 +1,4 @@ import { extend } from './utils/common.js'; -import axios from 'axios'; let actionKey = Symbol('api action'); let klassKey = Symbol('constructor'); diff --git a/lib/resources/call.js b/lib/resources/call.js index a736e67..fc9a324 100644 --- a/lib/resources/call.js +++ b/lib/resources/call.js @@ -495,7 +495,7 @@ export class CallInterface extends PlivoResourceInterface { * @promise {object[]} returns list of Call Object * @fail {Error} returns Error */ - list(params) { + list(params = {}) { params.isVoiceRequest = 'true'; let client = this[clientKey]; diff --git a/package.json b/package.json index 613e6d3..0420afb 100644 --- a/package.json +++ b/package.json @@ -58,11 +58,10 @@ "test": "gulp" }, "dependencies": { + "@types/node": "^14.14.14", "axios": "^0.19.2", "base-64": "^0.1.0", "build-url": "^1.0.10", - "got": "^11.8.1", - "querystring": "^0.2.0", "jsonwebtoken": "^8.5.1", "lodash": "^4.17.4", "querystring": "^0.2.0", From 76fd2828d00ba9816d8125cff48bba3b0c984409 Mon Sep 17 00:00:00 2001 From: Nixon Date: Fri, 29 Jan 2021 13:13:55 +0530 Subject: [PATCH 39/75] bump version to 4.14.0 --- CHANGELOG.md | 3 +++ package.json | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 27cb77d..c23c7b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # Change Log +## [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. diff --git a/package.json b/package.json index 613e6d3..2ba34c4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "plivo", - "version": "4.13.0", + "version": "4.14.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": [ From 0ee63af66b7ef2b66f2f13e240226bd177b82fbe Mon Sep 17 00:00:00 2001 From: huzaif Date: Wed, 3 Feb 2021 10:51:59 +0530 Subject: [PATCH 40/75] TS Client fix --- types/rest/client.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/rest/client.d.ts b/types/rest/client.d.ts index a49d75a..ced5bb3 100644 --- a/types/rest/client.d.ts +++ b/types/rest/client.d.ts @@ -7,7 +7,7 @@ export function validateSignature(uri: string, nonce: string, signature: string, * You can also pass in additional parameters accepted by the node requests module. */ export class Client { - constructor(authId: string, authToken: string, options?: string); + constructor(authId?: string, authToken?: string, options?: string); calls: CallInterface; accounts: AccountInterface; subaccounts: SubaccountInterface; From 26d7762be2d6d52f4d2c597c78519a861627e565 Mon Sep 17 00:00:00 2001 From: huzaif Date: Wed, 3 Feb 2021 18:44:20 +0530 Subject: [PATCH 41/75] Fix Buy number --- lib/resources/numbers.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/resources/numbers.js b/lib/resources/numbers.js index 8822b1c..eae18c8 100644 --- a/lib/resources/numbers.js +++ b/lib/resources/numbers.js @@ -116,7 +116,7 @@ export class PhoneNumberInterface extends PlivoResourceInterface { let client = this[clientKey]; return new Promise((resolve, reject) => { - client('POST', action + number + '/', params) + client('POST', 'PhoneNumber/' + number + '/', params) .then(response => { resolve(new BuyNumberResponse(response.body, idField)); }) From 708c21cb27d2ec996acb10e886769f7228e50b3c Mon Sep 17 00:00:00 2001 From: huzaif Date: Tue, 9 Feb 2021 17:24:07 +0530 Subject: [PATCH 42/75] bump version to 4.14.1 --- CHANGELOG.md | 5 ++++- package.json | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c23c7b3..0f6f7c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,10 +1,13 @@ # Change Log +## [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. +- 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/package.json b/package.json index 9ff90b7..705d749 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "plivo", - "version": "4.14.0", + "version": "4.14.1", "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": [ From 03a2efa4f4a3d36103eb29b8bb9799558622b13a Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Wed, 17 Feb 2021 11:33:56 +0530 Subject: [PATCH 43/75] Fixed bug on multiple call placing during retries. --- lib/rest/axios.js | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/lib/rest/axios.js b/lib/rest/axios.js index 0b81ddb..5c3879a 100644 --- a/lib/rest/axios.js +++ b/lib/rest/axios.js @@ -20,6 +20,7 @@ export function Axios(config) { 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)); }) @@ -85,11 +86,26 @@ export function Axios(config) { return new Promise((resolve, reject) => { if (isVoiceReq) { - retryWrapper(axios, {retryTime: 2}); - let retryAttempt; - for (retryAttempt = 0; retryAttempt < 3; retryAttempt++) { - options.url = apiVoiceUris[retryAttempt] + config.authId + '/' + action; + 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 @@ -98,7 +114,6 @@ export function Axios(config) { .catch(function (error) { reject(error.stack+ "\r\n" + JSON.stringify(error.response.data)); }) - } } else { axios(options).then(response => { From 87e4b272cacb54ffae1ead2fb697a2d8f90301c6 Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Wed, 17 Feb 2021 16:19:59 +0530 Subject: [PATCH 44/75] Fixed bug on multiple call placing during retries. --- CHANGELOG.md | 3 +++ package.json | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f6f7c6..38c1534 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # Change Log +## [4.14.2](https://github.com/plivo/plivo-node/releases/tag/v4.14.1)(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. diff --git a/package.json b/package.json index 705d749..c4d3189 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "plivo", - "version": "4.14.1", + "version": "4.14.2", "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": [ From 2bc340bf778b43c5f02bd5bd4c9b10b87eb10380 Mon Sep 17 00:00:00 2001 From: huzaif Date: Wed, 17 Feb 2021 16:35:20 +0530 Subject: [PATCH 45/75] fix version tag --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 38c1534..1052162 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Change Log -## [4.14.2](https://github.com/plivo/plivo-node/releases/tag/v4.14.1)(2021-02-17) +## [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) From a6aea858a1949cd5ab0a617bbcb964c3cc8020a0 Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Tue, 16 Mar 2021 15:47:41 +0530 Subject: [PATCH 46/75] Fixed bug on call stop Recording API --- lib/resources/call.js | 9 +++++---- lib/resources/recordings.js | 6 ++++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/lib/resources/call.js b/lib/resources/call.js index fc9a324..e046eb7 100644 --- a/lib/resources/call.js +++ b/lib/resources/call.js @@ -232,7 +232,8 @@ export class Call extends PlivoResource { * @promise {object} return PlivoGenericResponse Object * @fail {Error} return Error */ - record(params) { + record(params= {}) { + params.isVoiceRequest = true; return this.startRecording(params); } @@ -262,7 +263,7 @@ export class Call extends PlivoResource { * @promise {object} return PlivoGenericResponse Object * @fail {Error} return Error */ - stopRecording(params) { + stopRecording(params= {}) { params.isVoiceRequest = 'true'; return super.executeAction(this.id + '/Record/', 'DELETE', params); } @@ -642,7 +643,7 @@ export class CallInterface extends PlivoResourceInterface { * @promise {object} returns PlivoGenericResponse Object * @fail {Error} returns Error */ - record(callUUID, optionalParams) { + record(callUUID, optionalParams = {}) { let errors = validate([{ field: 'call_uuid', value: callUUID, @@ -665,7 +666,7 @@ export class CallInterface extends PlivoResourceInterface { * @promise {object} returns PlivoGenericResponse Object * @fail {Error} returns Error */ - stopRecording(callUUID, optionalParams) { + stopRecording(callUUID, optionalParams= {}) { let errors = validate([{ field: 'call_uuid', value: callUUID, diff --git a/lib/resources/recordings.js b/lib/resources/recordings.js index 81dc158..f9294fe 100644 --- a/lib/resources/recordings.js +++ b/lib/resources/recordings.js @@ -73,9 +73,11 @@ export class Recording extends PlivoResource { * @fail {Error} return Error */ delete(id) { + let params = {}; + params.isVoiceRequest = 'true'; let client = this[clientKey]; return new Promise((resolve, reject) => { - client('DELETE', action + id + '/') + client('DELETE', action + id + '/', params) .then(() => { resolve(true); }) @@ -191,4 +193,4 @@ export class RecordingInterface extends PlivoResourceInterface { id: id }).delete(id); } -} \ No newline at end of file +} From 7ee53ba63848a060a54c02afa3d3fe6b858825d2 Mon Sep 17 00:00:00 2001 From: huzaif Date: Wed, 24 Mar 2021 17:46:56 +0530 Subject: [PATCH 47/75] Fixed Isvoicerequest within voice api --- lib/resources/applications.js | 3 +++ lib/resources/call.js | 19 ++++++++----------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/lib/resources/applications.js b/lib/resources/applications.js index d8895dd..7d653f5 100644 --- a/lib/resources/applications.js +++ b/lib/resources/applications.js @@ -143,6 +143,7 @@ export class Application extends PlivoResource { */ delete(params, id) { let client = this[clientKey]; + params.isVoiceRequest = 'true'; return new Promise((resolve, reject) => { client('DELETE', action + id + '/', params) .then(() => { @@ -205,6 +206,7 @@ export class ApplicationInterface extends PlivoResourceInterface { */ list(params = {}) { let client = this[clientKey]; + params.isVoiceRequest = true; return new Promise((resolve, reject) => { client('GET', action, params) .then(response => { @@ -258,6 +260,7 @@ export class ApplicationInterface extends PlivoResourceInterface { return errors; } params.app_name = appName; + params.isVoiceRequest = 'true'; let client = this[clientKey]; return new Promise((resolve, reject) => { console.log(action, params) diff --git a/lib/resources/call.js b/lib/resources/call.js index e046eb7..625c375 100644 --- a/lib/resources/call.js +++ b/lib/resources/call.js @@ -233,7 +233,7 @@ export class Call extends PlivoResource { * @fail {Error} return Error */ record(params= {}) { - params.isVoiceRequest = true; + params.isVoiceRequest = 'true'; return this.startRecording(params); } @@ -917,8 +917,7 @@ class LiveCallInterface extends PlivoResourceInterface { if (action !== '' && !id) { reject(new Error(this[idKey] + ' must be set')); } - client('GET', action + (id ? id + '/' : ''), { - status: 'live', + client('GET', action + (id ? id + '/?status=live' : '') , { isVoiceRequest: 'true' }) .then(response => { @@ -937,9 +936,9 @@ class LiveCallInterface extends PlivoResourceInterface { params = {} } params.status = 'live' - params.isVoiceRequest = 'true' + params.isVoiceRequest = 'true'; return new Promise((resolve, reject) => { - client('GET', action, params) + client('GET', action+'?status=live', params) .then(response => { let calls = []; response.body.calls.forEach(callUuid => { @@ -947,7 +946,7 @@ class LiveCallInterface extends PlivoResourceInterface { callUuid: callUuid })); }); - resolve(new ListAllLiveCallResponse(calls[0])); + resolve(calls); }) .catch(error => { reject(error); @@ -995,8 +994,7 @@ class QueuedCallInterface extends PlivoResourceInterface { reject(new Error(this[idKey] + ' must be set')); } - client('GET', action + (id ? id + '/' : ''), { - status: 'queued', + client('GET', action + (id ? id + '/?status=queued' : ''), { isVoiceRequest: 'true' }) .then(response => { @@ -1014,8 +1012,7 @@ class QueuedCallInterface extends PlivoResourceInterface { let client = this[clientKey]; return new Promise((resolve, reject) => { - client('GET', action, { - status: 'queued', + client('GET', action+'?status=queued', { isVoiceRequest: 'true' }) .then(response => { @@ -1025,7 +1022,7 @@ class QueuedCallInterface extends PlivoResourceInterface { callUuid: callUuid })); }); - resolve(new ListAllQueuedCalls(calls[0])); + resolve(calls); }) .catch(error => { reject(error); From 48a227bee1a48c9b196a826830c5f07cb407ae8b Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Fri, 26 Mar 2021 11:44:37 +0530 Subject: [PATCH 48/75] Updated SDK versioning --- CHANGELOG.md | 3 +++ package.json | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1052162..8a7c67c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # Change Log +## [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. diff --git a/package.json b/package.json index c4d3189..d8ff1dd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "plivo", - "version": "4.14.2", + "version": "4.14.3", "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": [ From 980634eb025bbcafb7611fd3fa1516cc4fefe82e Mon Sep 17 00:00:00 2001 From: gunjan01 Date: Thu, 11 Mar 2021 23:40:10 +0530 Subject: [PATCH 49/75] Integrate node apis for compliance --- examples/complianceApplications.js | 45 +++ examples/complianceDocumentTypes.js | 21 ++ examples/complianceDocuments.js | 34 +++ examples/complianceRequirements.js | 22 ++ examples/endUsers.js | 37 +++ lib/resources/complianceApplications.js | 281 +++++++++++++++++++ lib/resources/complianceDocumentTypes.js | 110 ++++++++ lib/resources/complianceDocuments.js | 262 +++++++++++++++++ lib/resources/complianceRequirements.js | 100 +++++++ lib/resources/endUsers.js | 254 +++++++++++++++++ lib/resources/numbers.js | 2 +- lib/rest/axios.js | 60 ++++ lib/rest/client.js | 10 + lib/rest/utils.js | 3 +- types/resources/complianceApplications.d.ts | 146 ++++++++++ types/resources/complianceDocumentTypes.d.ts | 65 +++++ types/resources/complianceDocuments.d.ts | 134 +++++++++ types/resources/complianceRequirements.d.ts | 58 ++++ types/resources/endUsers.d.ts | 131 +++++++++ types/rest/client.d.ts | 5 + 20 files changed, 1778 insertions(+), 2 deletions(-) create mode 100644 examples/complianceApplications.js create mode 100644 examples/complianceDocumentTypes.js create mode 100644 examples/complianceDocuments.js create mode 100644 examples/complianceRequirements.js create mode 100644 examples/endUsers.js create mode 100644 lib/resources/complianceApplications.js create mode 100644 lib/resources/complianceDocumentTypes.js create mode 100644 lib/resources/complianceDocuments.js create mode 100644 lib/resources/complianceRequirements.js create mode 100644 lib/resources/endUsers.js create mode 100644 types/resources/complianceApplications.d.ts create mode 100644 types/resources/complianceDocumentTypes.d.ts create mode 100644 types/resources/complianceDocuments.d.ts create mode 100644 types/resources/complianceRequirements.d.ts create mode 100644 types/resources/endUsers.d.ts 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/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..b50eddf --- /dev/null +++ b/lib/resources/complianceDocuments.js @@ -0,0 +1,262 @@ +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 => { + resolve(new CreateComplianceDocumentResponse(response.body, idField)); + }) + .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(); + } +} \ No newline at end of file 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/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/numbers.js b/lib/resources/numbers.js index eae18c8..ccaec8b 100644 --- a/lib/resources/numbers.js +++ b/lib/resources/numbers.js @@ -295,7 +295,7 @@ export class NumberInterface extends PlivoResourceInterface { let params = optionalParams || {}; params.country_iso = countryISO; - return new PhoneNumberInterface(this[clientKey]).list(countryISO, params); + return new PhoneNumberInterface(this[clientKey]).list(params); } /** diff --git a/lib/rest/axios.js b/lib/rest/axios.js index 5c3879a..d323f07 100644 --- a/lib/rest/axios.js +++ b/lib/rest/axios.js @@ -30,6 +30,65 @@ export function Axios(config) { } 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)) { @@ -41,6 +100,7 @@ export function Axios(config) { } params.file = files; } + let options = { url: config.url + '/' + action, method: method, diff --git a/lib/rest/client.js b/lib/rest/client.js index be78627..60a8fce 100644 --- a/lib/rest/client.js +++ b/lib/rest/client.js @@ -20,6 +20,11 @@ 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"; exports.Response = function() { return new Response(); @@ -82,6 +87,11 @@ 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); } toJSON() { diff --git a/lib/rest/utils.js b/lib/rest/utils.js index 1ece32a..a456cae 100644 --- a/lib/rest/utils.js +++ b/lib/rest/utils.js @@ -47,7 +47,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 => { 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/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/rest/client.d.ts b/types/rest/client.d.ts index ced5bb3..641839b 100644 --- a/types/rest/client.d.ts +++ b/types/rest/client.d.ts @@ -23,6 +23,11 @@ export class Client { recordings: RecordingInterface; callFeedback: CallFeedbackInterface; media: MediaInterface; + endUsers: EndUserInterface; + complianceDocumentTypes: ComplianceDocumentTypeInterface; + complianceDocuments: ComplianceDocumentInterface; + complianceRequirements: ComplianceRequirementInterface; + complianceApplications: ComplianceApplicationInterface; toJSON(...args: any[]): any; } /** From e5e6478204f5efef54c38306a66490f3896682a0 Mon Sep 17 00:00:00 2001 From: gunjan01 Date: Fri, 16 Apr 2021 18:13:45 +0530 Subject: [PATCH 50/75] Remove empty keys from compliance create response --- lib/resources/complianceDocuments.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/resources/complianceDocuments.js b/lib/resources/complianceDocuments.js index b50eddf..8235554 100644 --- a/lib/resources/complianceDocuments.js +++ b/lib/resources/complianceDocuments.js @@ -207,7 +207,9 @@ export class ComplianceDocumentInterface extends PlivoResourceInterface { params.multipart = true; client('POST', action, params) .then(response => { - resolve(new CreateComplianceDocumentResponse(response.body, idField)); + let object = new CreateComplianceDocumentResponse(response.body, idField); + Object.keys(object).forEach(key => object[key] === undefined && delete object[key]); + resolve(object); }) .catch(error => { reject(error); @@ -259,4 +261,4 @@ export class ComplianceDocumentInterface extends PlivoResourceInterface { id: id }).delete(); } -} \ No newline at end of file +} From 4a880c98f000efffb3bd225b02e9a040cbd59119 Mon Sep 17 00:00:00 2001 From: gunjan01 Date: Fri, 16 Apr 2021 18:36:39 +0530 Subject: [PATCH 51/75] Add new dependency for multipart requests --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index d8ff1dd..f27332f 100644 --- a/package.json +++ b/package.json @@ -62,6 +62,7 @@ "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", From cbf4617aa57a4787127b1d80bae7c9b7f0dc0732 Mon Sep 17 00:00:00 2001 From: gunjan01 Date: Fri, 16 Apr 2021 19:18:41 +0530 Subject: [PATCH 52/75] Add client tests --- lib/rest/client-test.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lib/rest/client-test.js b/lib/rest/client-test.js index b8bd8cc..bf709ed 100644 --- a/lib/rest/client-test.js +++ b/lib/rest/client-test.js @@ -90,6 +90,11 @@ 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); } } From e3e813a3706347899118fd45d63bbba6cc6786ae Mon Sep 17 00:00:00 2001 From: kalyan-plivo <49232630+kalyan-plivo@users.noreply.github.com> Date: Mon, 19 Apr 2021 11:08:30 +0530 Subject: [PATCH 53/75] bump version --- CHANGELOG.md | 4 ++++ package.json | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a7c67c..e9fa7fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Change Log +## [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. diff --git a/package.json b/package.json index f27332f..ddd9b7b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "plivo", - "version": "4.14.3", + "version": "4.15.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": [ From 957817f3057f608c22a26826ff46c70ad5a5673b Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Fri, 14 Aug 2020 16:54:31 +0530 Subject: [PATCH 54/75] XML changes for MPC along with UTs --- lib/rest/utils.js | 81 ++++++++++++++ lib/utils/plivoxml.js | 253 +++++++++++++++++++++++++++++++++++++++++- test/xml.js | 11 ++ 3 files changed, 341 insertions(+), 4 deletions(-) diff --git a/lib/rest/utils.js b/lib/rest/utils.js index a456cae..ae07f46 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; @@ -79,3 +81,82 @@ export function validateSpeakAttributes(content, voice) { } } +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') + } + } +} + +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 = paramName.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) === -1) || !(expectedValues.indexOf(paramValue) === -1)){ + return true; + } + else if (validUrl(paramName, paramValue)){ + return true; + } + else { + throw new InvalidRequestError(paramName + ' neither a valid URL nor in the expected values') + } +} diff --git a/lib/utils/plivoxml.js b/lib/utils/plivoxml.js index 577ce9f..d28595b 100644 --- a/lib/utils/plivoxml.js +++ b/lib/utils/plivoxml.js @@ -2,7 +2,6 @@ var qs = require('querystring'); var xmlBuilder = require('xmlbuilder'); var util = require('util'); var plivoUtils = require('./../rest/utils'); - import * as Exceptions from './exceptions'; var jsonStringifier = require('./jsonStrinfigier'); @@ -15,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); } @@ -440,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(); }, @@ -521,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,4 +968,22 @@ function DTMF(Response) { this.valid_attributes = ['digits', 'async']; } -util.inherits(DTMF, Response); \ No newline at end of file +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/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(); + }) }); From 326831d98cd4000f27549628d903c0fedff5f558 Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Wed, 26 Aug 2020 11:31:13 +0530 Subject: [PATCH 55/75] MPC API - Under Development --- lib/base.js | 15 + lib/resources/multiPartyCall.js | 559 ++++++++++++++++++++++++++++++++ lib/rest/client.js | 2 + lib/rest/utils.js | 127 +++++++- 4 files changed, 700 insertions(+), 3 deletions(-) create mode 100644 lib/resources/multiPartyCall.js diff --git a/lib/base.js b/lib/base.js index 3ed6040..e374e7c 100644 --- a/lib/base.js +++ b/lib/base.js @@ -4,6 +4,9 @@ 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) { @@ -123,6 +126,18 @@ export class PlivoResource { } } +// 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; +// } +// } + export class PlivoResourceInterface { constructor(action, klass, idField, request) { this[actionKey] = action; diff --git a/lib/resources/multiPartyCall.js b/lib/resources/multiPartyCall.js new file mode 100644 index 0000000..6099bac --- /dev/null +++ b/lib/resources/multiPartyCall.js @@ -0,0 +1,559 @@ +import {extend, validate} from '../utils/common.js'; +import {PlivoResource, PlivoResourceInterface} 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(){ + return super.executeAction(this.id, 'GET'); + } + + 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') + } + + if(params.role){ + 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){ + validRange('ringTimeout', params.ringTimeout, false, 15, 120) + } + else { + params.ringTimeout = 45 + } + + if(params.maxDuration){ + validRange('maxDuration', params.maxDuration, false, 300, 28800) + } + else { + params.maxDuration = 14400 + } + + if(params.maxParticipants){ + 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], 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], false) + } + else { + params.stayAlone = false + } + + if(params.coachMode){ + validParam('coachMode', params.coachMode, [Boolean], false) + } + else { + params.coachMode = true + } + + if(params.mute){ + validParam('mute', params.mute, [Boolean], false) + } + else { + params.mute = false + } + + if(params.hold){ + validParam('hold', params.hold, [Boolean], false) + } + else { + params.hold = false + } + + if(params.startMpcOnEnter){ + validParam('startMpcOnEnter', params.startMpcOnEnter, [Boolean], false) + } + else { + params.startMpcOnEnter = false + } + + if(params.endMpcOnExit){ + validParam('endMpcOnExit', params.endMpcOnExit, [Boolean], false) + } + else { + params.endMpcOnExit = false + } + + if(params.relayDTMFInputs){ + validParam('relayDTMFInputs', params.relayDTMFInputs, [Boolean], 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' + } + + return super.executeAction(this.id + '/Participant', 'POST', params) + } + + start(){ + return super.executeAction(this.id, 'POST', {'status' : 'active'}) + } + + stop(){ + return super.delete() + } + + 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' + } + + return super.executeAction(this.id + '/Record', 'POST', params) + } + + stopRecording(){ + return super.executeAction(this.id + '/Record', 'DELETE') + } + + pauseRecording(){ + return super.executeAction(this.id + '/Record/Pause', 'POST') + } + + resumeRecording(){ + return super.executeAction(this.id + '/Record/Resume', 'POST') + } + + listParticipants(params = {}){ + if(params.callUuid){ + validParam('callUuid', params.callUuid, [String], false) + } + + 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; +// } +// +// } + +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 MultiPartyCalls + * @method + * @param {object} params + * @param {string} [params.subAccount] + * @param {string} [params.friendlyName] + * @param {string} [params.status] + * @param {number} [params.terminationCauseCode] + * @param {Date} [params.end_time__gt] + * @param {Date} [params.end_time__gte] + * @param {Date} [params.end_time__lt] + * @param {Date} [params.end_time__lte] + * @param {Date} [params.creation_time__gt] + * @param {Date} [params.creation_time__gte] + * @param {Date} [params.creation_time__lt] + * @param {Date} [params.creation_time__lte] + * @param {number} [params.limit] + * @param {number} [params.offset] + */ + 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], 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) + } + + 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 = {}){ + let errors = validate([ + {field: 'friendly_name', value: params.friendlyName, validators: ['isString']} + ]); + if (errors) { + return errors; + } + 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) + } + + +} diff --git a/lib/rest/client.js b/lib/rest/client.js index 60a8fce..492c32d 100644 --- a/lib/rest/client.js +++ b/lib/rest/client.js @@ -25,6 +25,7 @@ import { ComplianceDocumentTypeInterface } from "../resources/complianceDocument 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(); @@ -92,6 +93,7 @@ export class Client { this.complianceDocuments = new ComplianceDocumentInterface(client); this.complianceRequirements = new ComplianceRequirementInterface(client); this.complianceApplications = new ComplianceApplicationInterface(client); + this.multiPartyCalls = new MultiPartyCallInterface(client); } toJSON() { diff --git a/lib/rest/utils.js b/lib/rest/utils.js index ae07f46..bf79ca9 100644 --- a/lib/rest/utils.js +++ b/lib/rest/utils.js @@ -81,6 +81,63 @@ 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; @@ -88,14 +145,15 @@ export function expectedValue(paramName, expectedValues, paramValue){ if(expectedValues.constructor === Array){ if(expectedValues.indexOf(paramValue) === -1){ - throw new InvalidRequestError(paramName + ': Expected one of ' + expectedValues + 'but received' + paramValue + 'instead'); + 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') + throw new InvalidRequestError(paramName + ': Expected ' + expectedValues + ' but received ' + paramValue + ' instead') } + return true; } } @@ -132,7 +190,7 @@ export function validUrl(paramName, paramValue, mandatory = false){ return true; } - let response = paramName.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g); + 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") } @@ -160,3 +218,66 @@ export function isOneAmongStringUrl(paramName, paramValue, mandatory = false, ex 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){ + 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") + } +} From 93c85714a9cda909909a73debd24fe3827f800f0 Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Wed, 26 Aug 2020 21:40:55 +0530 Subject: [PATCH 56/75] MPC API changes, TODO : Dev Testing --- lib/base.js | 46 +++++++++----- lib/resources/multiPartyCall.js | 105 ++++++++++++++++++++++++++------ 2 files changed, 117 insertions(+), 34 deletions(-) diff --git a/lib/base.js b/lib/base.js index e374e7c..29834c8 100644 --- a/lib/base.js +++ b/lib/base.js @@ -4,9 +4,9 @@ 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'); +let secondaryActionKey = Symbol('api action'); +let secondaryKlassKey = Symbol('constructor'); +let secondaryIdKey = Symbol('id filed'); export class PlivoGenericResponse { constructor(params, idString) { @@ -126,17 +126,35 @@ export class PlivoResource { } } -// 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; -// } -// } +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; + } + + 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 + '/' + secondaryAction + secondaryTask, params) + .then(response => { + resolve(new PlivoGenericResponse(response.body, secondaryIdField)); + }) + .catch(error => { + reject(error); + }); + }); + } +} export class PlivoResourceInterface { constructor(action, klass, idField, request) { diff --git a/lib/resources/multiPartyCall.js b/lib/resources/multiPartyCall.js index 6099bac..2eb71d8 100644 --- a/lib/resources/multiPartyCall.js +++ b/lib/resources/multiPartyCall.js @@ -1,5 +1,5 @@ import {extend, validate} from '../utils/common.js'; -import {PlivoResource, PlivoResourceInterface} from '../base'; +import {PlivoResource, PlivoResourceInterface, PlivoSecondaryResource} from '../base'; import { validSubAccount, validUrl, @@ -13,8 +13,8 @@ import { const clientKey = Symbol(); const action = 'MultiPartyCall/'; const idField = 'mpcUuid'; -// const secondaryAction = 'Participant/'; -// const secondaryIdField = 'participantUuid'; +const secondaryAction = 'Participant/'; +const secondaryIdField = 'participantUuid'; export class MPCError extends Error { } @@ -338,23 +338,47 @@ export class MultiPartyCall extends PlivoResource{ } } -// 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; -// } -// -// } +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], false) + } + + if(params.mute){ + validParam('mute', params.mute, [Boolean], false) + } + + if(params.hold){ + validParam('hold', params.hold, [Boolean], false) + } + + return super.executeAction(this.id, this.secondaryId, 'POST', params) + } + + kickParticipant(){ + return super.executeAction(this.id, this.secondaryId, 'DELETE') + } + + getParticipant(){ + return super.executeAction(this.id, this.secondaryId, 'GET') + } + +} export class MultiPartyCallInterface extends PlivoResourceInterface{ constructor(client, data = {}) { @@ -555,5 +579,46 @@ export class MultiPartyCallInterface extends PlivoResourceInterface{ return new MultiPartyCall(this[clientKey], {id: mpcId[0] + mpcId[1]}).listParticipants(params) } + updateParticipant(participantId, uuid= null, friendlyName = null, params){ + if(participantId){ + 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){ + if(participantId){ + 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){ + if(participantId){ + 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() + } } From b59e57cf9a8c7624905665a7481fff341324b25f Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Mon, 31 Aug 2020 16:01:14 +0530 Subject: [PATCH 57/75] Example Script --- example_script.js | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 example_script.js diff --git a/example_script.js b/example_script.js new file mode 100644 index 0000000..5c762a7 --- /dev/null +++ b/example_script.js @@ -0,0 +1,47 @@ +let plivo = require('./'); +var client = new plivo.Client('MAMDJMMTEZOWY0ZMQWM2', 'OTljNmVmOGVkNGZhNjJlOWIyMWM0ZDI0ZjQwZDdk'); + +// client.calls.create( "+919090909090", // from +// "sip:koushikqa119062465586783372208@phone-qa.voice.plivodev.com", // to +// "https://plivobin.non-prod.plivops.com/api/v1/Conference_test07.xml").then(function (response) { +// console.log(response); +// }, function (err) { +// console.error(err); +// }); + +// client.calls.transfer( +// "35283f77-a738-4d91-81dc-9f565e28d74c", {"legs": "aleg", "alegUrl": "https://www.google.com"}).then(function (response) { +// console.log(response); +// }, function (err) { +// console.error(err); +// }); + +// client.calls.sendDigits( +// "bfc3f1fd-d66b-42ab-88e4-9e82c8e2537f", // call uuid +// 123, // digits +// { +// 'leg': 'aleg' +// } +// ).then(function (response) { +// console.log(response); +// }, function (err) { +// console.error(err); +// }); + +// client.conferences.startRecording('FStestconference').then(function (response) { +// console.log(response); +// }, function (err) { +// console.error(err); +// }); + +client.multiPartyCalls.addParticipant({'friendlyName' : 'TestMPC', 'from' : '+919090909090', 'to': 'sip:koushikqa119062465586783372208@phone-qa.voice.plivodev.com'}).then(function (response) { + console.log(response); +}, function (err) { + console.error(err); +}); + +// client.multiPartyCalls.list().then(function (response) { +// console.log(response); +// }, function (err) { +// console.error(err); +// }); From f2f3ec5ba0f7b285219082685bae8d3de3ceb8c5 Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Tue, 1 Sep 2020 16:39:44 +0530 Subject: [PATCH 58/75] Reverted back to original --- example_script.js | 2 +- lib/resources/multiPartyCall.js | 29 ++++------------------------- 2 files changed, 5 insertions(+), 26 deletions(-) diff --git a/example_script.js b/example_script.js index 5c762a7..5b8483e 100644 --- a/example_script.js +++ b/example_script.js @@ -34,7 +34,7 @@ var client = new plivo.Client('MAMDJMMTEZOWY0ZMQWM2', 'OTljNmVmOGVkNGZhNjJlOWIyM // console.error(err); // }); -client.multiPartyCalls.addParticipant({'friendlyName' : 'TestMPC', 'from' : '+919090909090', 'to': 'sip:koushikqa119062465586783372208@phone-qa.voice.plivodev.com'}).then(function (response) { +client.multiPartyCalls.addParticipant('agent', {"friendlyName" : "TestMPC", 'from' : '+919090909090', 'to': 'sip:koushikqa119062465586783372208@phone-qa.voice.plivodev.com'}).then(function (response) { console.log(response); }, function (err) { console.error(err); diff --git a/lib/resources/multiPartyCall.js b/lib/resources/multiPartyCall.js index 2eb71d8..9a049ef 100644 --- a/lib/resources/multiPartyCall.js +++ b/lib/resources/multiPartyCall.js @@ -45,9 +45,7 @@ export class MultiPartyCall extends PlivoResource{ throw new MPCError('specify (from, to) when not adding an existing callUuid to multi party participant') } - if(params.role){ - validParam('role', params.role.toLowerCase(), [String], true, ['agent', 'supervisor', 'customer']) - } + validParam('role', params.role.toLowerCase(), [String], true, ['agent', 'supervisor', 'customer']) if(params.from){ validParam('from', params.from, [String], false) @@ -295,7 +293,7 @@ export class MultiPartyCall extends PlivoResource{ return super.delete() } - startRecording(params){ + startRecording(params){ if(params.fileFormat){ validParam('fileFormat', params.fileFormat, [String], false, ['mp3', 'wav']) } @@ -405,25 +403,6 @@ export class MultiPartyCallInterface extends PlivoResourceInterface{ return identifier; } - /** - * List MultiPartyCalls - * @method - * @param {object} params - * @param {string} [params.subAccount] - * @param {string} [params.friendlyName] - * @param {string} [params.status] - * @param {number} [params.terminationCauseCode] - * @param {Date} [params.end_time__gt] - * @param {Date} [params.end_time__gte] - * @param {Date} [params.end_time__lt] - * @param {Date} [params.end_time__lte] - * @param {Date} [params.creation_time__gt] - * @param {Date} [params.creation_time__gte] - * @param {Date} [params.creation_time__lt] - * @param {Date} [params.creation_time__lte] - * @param {number} [params.limit] - * @param {number} [params.offset] - */ list(params={}) { if(params.subAccount){ validSubAccount(params.subAccount); @@ -482,7 +461,7 @@ export class MultiPartyCallInterface extends PlivoResourceInterface{ return new MultiPartyCall(this[clientKey], {id: mpcId[0] + mpcId[1]}).get(); } - addParticipant(role, params = {}){ + addParticipant( role = 'agent', params = {}){ let errors = validate([ {field: 'friendly_name', value: params.friendlyName, validators: ['isString']} ]); @@ -495,10 +474,10 @@ export class MultiPartyCallInterface extends PlivoResourceInterface{ if(params.friendlyName){ validParam('friendlyName', params.friendlyName, [String], false) } + console.log(params.friendlyName); 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) } From 4db015960bba98949b75f2f96c396d3fcc92f6d1 Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Tue, 1 Sep 2020 16:50:11 +0530 Subject: [PATCH 59/75] Reverted back to original --- example_script.js | 2 +- lib/resources/multiPartyCall.js | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/example_script.js b/example_script.js index 5b8483e..4ec220a 100644 --- a/example_script.js +++ b/example_script.js @@ -34,7 +34,7 @@ var client = new plivo.Client('MAMDJMMTEZOWY0ZMQWM2', 'OTljNmVmOGVkNGZhNjJlOWIyM // console.error(err); // }); -client.multiPartyCalls.addParticipant('agent', {"friendlyName" : "TestMPC", 'from' : '+919090909090', 'to': 'sip:koushikqa119062465586783372208@phone-qa.voice.plivodev.com'}).then(function (response) { +client.multiPartyCalls.addParticipant('agent', {'friendlyName' : 'TestMPC', 'from' : '+919090909090', 'to': 'sip:koushikqa119062465586783372208@phone-qa.voice.plivodev.com'}).then(function (response) { console.log(response); }, function (err) { console.error(err); diff --git a/lib/resources/multiPartyCall.js b/lib/resources/multiPartyCall.js index 9a049ef..1911b04 100644 --- a/lib/resources/multiPartyCall.js +++ b/lib/resources/multiPartyCall.js @@ -478,6 +478,7 @@ export class MultiPartyCallInterface extends PlivoResourceInterface{ 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) } From 3e297f9ef3787b727cffaadd6fc34859d0e8b5d3 Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Tue, 8 Sep 2020 00:40:30 +0530 Subject: [PATCH 60/75] MPC API and XML changes - Dev completed --- example_script.js | 33 +++- lib/base.js | 2 +- lib/resources/multiPartyCall.js | 71 ++++---- lib/rest/client-test.js | 2 + lib/rest/request-test.js | 300 ++++++++++++++++++++++++++++++++ lib/rest/utils.js | 4 +- lib/utils/plivoxml.js | 58 +++--- test/multiPartyCalls.js | 95 ++++++++++ 8 files changed, 486 insertions(+), 79 deletions(-) create mode 100644 test/multiPartyCalls.js diff --git a/example_script.js b/example_script.js index 4ec220a..f71399d 100644 --- a/example_script.js +++ b/example_script.js @@ -2,12 +2,18 @@ let plivo = require('./'); var client = new plivo.Client('MAMDJMMTEZOWY0ZMQWM2', 'OTljNmVmOGVkNGZhNjJlOWIyMWM0ZDI0ZjQwZDdk'); // client.calls.create( "+919090909090", // from -// "sip:koushikqa119062465586783372208@phone-qa.voice.plivodev.com", // to +// "+918309866821", // to // "https://plivobin.non-prod.plivops.com/api/v1/Conference_test07.xml").then(function (response) { // console.log(response); // }, function (err) { // console.error(err); // }); +// +// client.conferences.get( "FStestconference").then(function (response) { +// console.log(response); +// }, function (err) { +// console.error(err); +// }); // client.calls.transfer( // "35283f77-a738-4d91-81dc-9f565e28d74c", {"legs": "aleg", "alegUrl": "https://www.google.com"}).then(function (response) { @@ -34,13 +40,24 @@ var client = new plivo.Client('MAMDJMMTEZOWY0ZMQWM2', 'OTljNmVmOGVkNGZhNjJlOWIyM // console.error(err); // }); -client.multiPartyCalls.addParticipant('agent', {'friendlyName' : 'TestMPC', 'from' : '+919090909090', 'to': 'sip:koushikqa119062465586783372208@phone-qa.voice.plivodev.com'}).then(function (response) { - console.log(response); -}, function (err) { - console.error(err); -}); - -// client.multiPartyCalls.list().then(function (response) { +// client.multiPartyCalls.stop('6172e321-284d-4159-8242-5f5e92933de5').then(function (response) { +// console.log(response); +// }, function (err) { +// console.error(err); +// }); + +// client.multiPartyCalls.kickParticipant(10, "6bed1e3a-e5da-4ffc-8ed5-84b0a3e0d75c", null).then(function (response) { +// console.log(response); +// }, function (err) { +// console.error(err); +// }); +// client.multiPartyCalls.get(null, 'TestMPC').then(function (response) { +// console.log(response); +// }, function (err) { +// console.error(err); +// }); + +// client.multiPartyCalls.get('6f84d47c-ee82-4172-a155-c6e22f87d874').then(function (response) { // console.log(response); // }, function (err) { // console.error(err); diff --git a/lib/base.js b/lib/base.js index 29834c8..d6ba0d7 100644 --- a/lib/base.js +++ b/lib/base.js @@ -145,7 +145,7 @@ export class PlivoSecondaryResource { let secondaryIdField = this[secondaryIdKey] return new Promise((resolve, reject) => { - client(method, action + task + '/' + secondaryAction + secondaryTask, params) + client(method, action + task + '/' + secondaryAction + secondaryTask + '/', params) .then(response => { resolve(new PlivoGenericResponse(response.body, secondaryIdField)); }) diff --git a/lib/resources/multiPartyCall.js b/lib/resources/multiPartyCall.js index 1911b04..bfe9816 100644 --- a/lib/resources/multiPartyCall.js +++ b/lib/resources/multiPartyCall.js @@ -185,10 +185,10 @@ export class MultiPartyCall extends PlivoResource{ } if(params.record){ - validParam('record', params.record, [Boolean], false) + validParam('record', params.record, [Boolean, String], false) } else { - params.record = false + params.record = 'false' } if(params.recordFileFormat){ @@ -206,52 +206,52 @@ export class MultiPartyCall extends PlivoResource{ } if(params.stayAlone){ - validParam('stayAlone', params.stayAlone, [Boolean], false) + validParam('stayAlone', params.stayAlone, [Boolean, String], false) } else { - params.stayAlone = false + params.stayAlone = 'false' } if(params.coachMode){ - validParam('coachMode', params.coachMode, [Boolean], false) + validParam('coachMode', params.coachMode, [Boolean, String], false) } else { - params.coachMode = true + params.coachMode = 'true' } if(params.mute){ - validParam('mute', params.mute, [Boolean], false) + validParam('mute', params.mute, [Boolean, String], false) } else { - params.mute = false + params.mute = 'false' } if(params.hold){ - validParam('hold', params.hold, [Boolean], false) + validParam('hold', params.hold, [Boolean, String], false) } else { - params.hold = false + params.hold = 'false' } if(params.startMpcOnEnter){ - validParam('startMpcOnEnter', params.startMpcOnEnter, [Boolean], false) + validParam('startMpcOnEnter', params.startMpcOnEnter, [Boolean, String], false) } else { - params.startMpcOnEnter = false + params.startMpcOnEnter = 'true' } if(params.endMpcOnExit){ - validParam('endMpcOnExit', params.endMpcOnExit, [Boolean], false) + validParam('endMpcOnExit', params.endMpcOnExit, [Boolean, String], false) } else { - params.endMpcOnExit = false + params.endMpcOnExit = 'false' } if(params.relayDTMFInputs){ - validParam('relayDTMFInputs', params.relayDTMFInputs, [Boolean], false) + validParam('relayDTMFInputs', params.relayDTMFInputs, [Boolean, String], false) } else { - params.relayDTMFInputs = false + params.relayDTMFInputs = 'false' } if(params.enterSound){ @@ -282,18 +282,18 @@ export class MultiPartyCall extends PlivoResource{ params.exitSoundMethod = 'GET' } - return super.executeAction(this.id + '/Participant', 'POST', params) + return super.executeAction(this.id + '/Participant/', 'POST', params) } start(){ - return super.executeAction(this.id, 'POST', {'status' : 'active'}) + return super.executeAction(this.id + '/', 'POST', {'status' : 'active'}) } stop(){ return super.delete() } - startRecording(params){ + startRecording(params = {}){ if(params.fileFormat){ validParam('fileFormat', params.fileFormat, [String], false, ['mp3', 'wav']) } @@ -312,19 +312,19 @@ export class MultiPartyCall extends PlivoResource{ params.statusCallbackMethod = 'POST' } - return super.executeAction(this.id + '/Record', 'POST', params) + return super.executeAction(this.id + '/Record/', 'POST', params) } stopRecording(){ - return super.executeAction(this.id + '/Record', 'DELETE') + return super.executeAction(this.id + '/Record/', 'DELETE') } pauseRecording(){ - return super.executeAction(this.id + '/Record/Pause', 'POST') + return super.executeAction(this.id + '/Record/Pause/', 'POST') } resumeRecording(){ - return super.executeAction(this.id + '/Record/Resume', 'POST') + return super.executeAction(this.id + '/Record/Resume/', 'POST') } listParticipants(params = {}){ @@ -332,7 +332,7 @@ export class MultiPartyCall extends PlivoResource{ validParam('callUuid', params.callUuid, [String], false) } - return super.executeAction(this.id + '/Participant', 'GET', params) + return super.executeAction(this.id + '/Participant/', 'GET', params) } } @@ -352,17 +352,17 @@ export class MultiPartyCallParticipant extends PlivoSecondaryResource{ this[clientKey] = client; } - updateParticipant(params){ + updateParticipant(params = {}){ if(params.coachMode){ - validParam('coachMode', params.coachMode, [Boolean], false) + validParam('coachMode', params.coachMode, [Boolean, String], false) } if(params.mute){ - validParam('mute', params.mute, [Boolean], false) + validParam('mute', params.mute, [Boolean, String], false) } if(params.hold){ - validParam('hold', params.hold, [Boolean], false) + validParam('hold', params.hold, [Boolean, String], false) } return super.executeAction(this.id, this.secondaryId, 'POST', params) @@ -414,7 +414,7 @@ export class MultiPartyCallInterface extends PlivoResourceInterface{ validParam('status', params.status.toLowerCase(), [String], false, ['initialized', 'active', 'ended']) } if(params.terminationCauseCode){ - validParam('terminationCauseCode', params.terminationCauseCode, [Number], false) + validParam('terminationCauseCode', params.terminationCauseCode, [Number, String], false) } if(params.end_time__gt){ validDateFormat('end_time__gt', params.end_time__gt, false) @@ -474,7 +474,6 @@ export class MultiPartyCallInterface extends PlivoResourceInterface{ if(params.friendlyName){ validParam('friendlyName', params.friendlyName, [String], false) } - console.log(params.friendlyName); let mpcId = this.makeMpcId(params.uuid, params.friendlyName) delete params.uuid delete params.friendlyName @@ -560,9 +559,7 @@ export class MultiPartyCallInterface extends PlivoResourceInterface{ } updateParticipant(participantId, uuid= null, friendlyName = null, params){ - if(participantId){ - validParam('participantId', participantId, [String, Number], true) - } + validParam('participantId', participantId, [String, Number], true) if(uuid){ validParam('uuid', uuid, [String], false) } @@ -574,9 +571,7 @@ export class MultiPartyCallInterface extends PlivoResourceInterface{ } kickParticipant(participantId, uuid = null, friendlyName = null){ - if(participantId){ - validParam('participantId', participantId, [String, Number], true) - } + validParam('participantId', participantId, [String, Number], true) if(uuid){ validParam('uuid', uuid, [String], false) } @@ -588,9 +583,7 @@ export class MultiPartyCallInterface extends PlivoResourceInterface{ } getParticipant(participantId, uuid = null, friendlyName = null){ - if(participantId){ - validParam('participantId', participantId, [String, Number], true) - } + validParam('participantId', participantId, [String, Number], true) if(uuid){ validParam('uuid', uuid, [String], false) } diff --git a/lib/rest/client-test.js b/lib/rest/client-test.js index bf709ed..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) { @@ -95,6 +96,7 @@ export class 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/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 bf79ca9..6add094 100644 --- a/lib/rest/utils.js +++ b/lib/rest/utils.js @@ -208,7 +208,7 @@ export function isOneAmongStringUrl(paramName, paramValue, mandatory = false, ex return true; } - if(!(expectedValues.indexOf(paramValue) === -1) || !(expectedValues.indexOf(paramValue) === -1)){ + if(!(expectedValues.indexOf(paramValue.toLowerCase()) === -1) || !(expectedValues.indexOf(paramValue.toUpperCase()) === -1)){ return true; } else if (validUrl(paramName, paramValue)){ @@ -228,7 +228,7 @@ export function validDateFormat(paramName, paramValue, mandatory = false){ return true; } - let response = paramValue.match(/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d{1-6})$/); + 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") } diff --git a/lib/utils/plivoxml.js b/lib/utils/plivoxml.js index d28595b..f6a30b3 100644 --- a/lib/utils/plivoxml.js +++ b/lib/utils/plivoxml.js @@ -481,188 +481,188 @@ Response.prototype = { 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + 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') + throw new PlivoXMLError('Invalid attribute value ' + attributes.customerHoldMusicUrl + ' for customerHoldMusicUrl') } return this.add(new MultiPartyCall(Response), body, attributes); }, 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/') + }) + }); +}) From 9b8d26db63c191435342ce5573ae01c03776499b Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Tue, 8 Sep 2020 00:50:36 +0530 Subject: [PATCH 61/75] Removed example test file and changed URL back to prod from QA url --- example_script.js | 64 ----------------------------------------------- 1 file changed, 64 deletions(-) delete mode 100644 example_script.js diff --git a/example_script.js b/example_script.js deleted file mode 100644 index f71399d..0000000 --- a/example_script.js +++ /dev/null @@ -1,64 +0,0 @@ -let plivo = require('./'); -var client = new plivo.Client('MAMDJMMTEZOWY0ZMQWM2', 'OTljNmVmOGVkNGZhNjJlOWIyMWM0ZDI0ZjQwZDdk'); - -// client.calls.create( "+919090909090", // from -// "+918309866821", // to -// "https://plivobin.non-prod.plivops.com/api/v1/Conference_test07.xml").then(function (response) { -// console.log(response); -// }, function (err) { -// console.error(err); -// }); -// -// client.conferences.get( "FStestconference").then(function (response) { -// console.log(response); -// }, function (err) { -// console.error(err); -// }); - -// client.calls.transfer( -// "35283f77-a738-4d91-81dc-9f565e28d74c", {"legs": "aleg", "alegUrl": "https://www.google.com"}).then(function (response) { -// console.log(response); -// }, function (err) { -// console.error(err); -// }); - -// client.calls.sendDigits( -// "bfc3f1fd-d66b-42ab-88e4-9e82c8e2537f", // call uuid -// 123, // digits -// { -// 'leg': 'aleg' -// } -// ).then(function (response) { -// console.log(response); -// }, function (err) { -// console.error(err); -// }); - -// client.conferences.startRecording('FStestconference').then(function (response) { -// console.log(response); -// }, function (err) { -// console.error(err); -// }); - -// client.multiPartyCalls.stop('6172e321-284d-4159-8242-5f5e92933de5').then(function (response) { -// console.log(response); -// }, function (err) { -// console.error(err); -// }); - -// client.multiPartyCalls.kickParticipant(10, "6bed1e3a-e5da-4ffc-8ed5-84b0a3e0d75c", null).then(function (response) { -// console.log(response); -// }, function (err) { -// console.error(err); -// }); -// client.multiPartyCalls.get(null, 'TestMPC').then(function (response) { -// console.log(response); -// }, function (err) { -// console.error(err); -// }); - -// client.multiPartyCalls.get('6f84d47c-ee82-4172-a155-c6e22f87d874').then(function (response) { -// console.log(response); -// }, function (err) { -// console.error(err); -// }); From 403c78168cdc92b8fec0cdf50903f7ff16aa899b Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Wed, 26 Aug 2020 11:31:13 +0530 Subject: [PATCH 62/75] MPC API - Under Development --- lib/rest/client.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/rest/client.js b/lib/rest/client.js index 492c32d..7e13eae 100644 --- a/lib/rest/client.js +++ b/lib/rest/client.js @@ -65,7 +65,7 @@ export class Client { authId: authId, authToken: authToken, version: "v1", - url: "https://api.plivo.com/v1/Account/" + authId, + url: "https://api-qa.voice.plivodev.com/v1/Account/" + authId, userAgent: `${"plivo-node"}/${version || "Unknown Version"} (Node: ${ process.version })` From 8bf07ad13c2985a9c0e8df7dbbc383c88e5bc726 Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Wed, 26 Aug 2020 21:40:55 +0530 Subject: [PATCH 63/75] MPC API changes, TODO : Dev Testing --- lib/resources/multiPartyCall.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/resources/multiPartyCall.js b/lib/resources/multiPartyCall.js index bfe9816..4a26f14 100644 --- a/lib/resources/multiPartyCall.js +++ b/lib/resources/multiPartyCall.js @@ -461,7 +461,7 @@ export class MultiPartyCallInterface extends PlivoResourceInterface{ return new MultiPartyCall(this[clientKey], {id: mpcId[0] + mpcId[1]}).get(); } - addParticipant( role = 'agent', params = {}){ + addParticipant(role, params = {}){ let errors = validate([ {field: 'friendly_name', value: params.friendlyName, validators: ['isString']} ]); From c4d27a67e699473584466ebf5abbe01e16147c1c Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Mon, 31 Aug 2020 16:01:14 +0530 Subject: [PATCH 64/75] Example Script --- example_script.js | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 example_script.js diff --git a/example_script.js b/example_script.js new file mode 100644 index 0000000..5c762a7 --- /dev/null +++ b/example_script.js @@ -0,0 +1,47 @@ +let plivo = require('./'); +var client = new plivo.Client('MAMDJMMTEZOWY0ZMQWM2', 'OTljNmVmOGVkNGZhNjJlOWIyMWM0ZDI0ZjQwZDdk'); + +// client.calls.create( "+919090909090", // from +// "sip:koushikqa119062465586783372208@phone-qa.voice.plivodev.com", // to +// "https://plivobin.non-prod.plivops.com/api/v1/Conference_test07.xml").then(function (response) { +// console.log(response); +// }, function (err) { +// console.error(err); +// }); + +// client.calls.transfer( +// "35283f77-a738-4d91-81dc-9f565e28d74c", {"legs": "aleg", "alegUrl": "https://www.google.com"}).then(function (response) { +// console.log(response); +// }, function (err) { +// console.error(err); +// }); + +// client.calls.sendDigits( +// "bfc3f1fd-d66b-42ab-88e4-9e82c8e2537f", // call uuid +// 123, // digits +// { +// 'leg': 'aleg' +// } +// ).then(function (response) { +// console.log(response); +// }, function (err) { +// console.error(err); +// }); + +// client.conferences.startRecording('FStestconference').then(function (response) { +// console.log(response); +// }, function (err) { +// console.error(err); +// }); + +client.multiPartyCalls.addParticipant({'friendlyName' : 'TestMPC', 'from' : '+919090909090', 'to': 'sip:koushikqa119062465586783372208@phone-qa.voice.plivodev.com'}).then(function (response) { + console.log(response); +}, function (err) { + console.error(err); +}); + +// client.multiPartyCalls.list().then(function (response) { +// console.log(response); +// }, function (err) { +// console.error(err); +// }); From a3b7ea4f301c3cf4ebf2be9285afa068873f8bec Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Tue, 1 Sep 2020 16:39:44 +0530 Subject: [PATCH 65/75] Reverted back to original --- example_script.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example_script.js b/example_script.js index 5c762a7..5b8483e 100644 --- a/example_script.js +++ b/example_script.js @@ -34,7 +34,7 @@ var client = new plivo.Client('MAMDJMMTEZOWY0ZMQWM2', 'OTljNmVmOGVkNGZhNjJlOWIyM // console.error(err); // }); -client.multiPartyCalls.addParticipant({'friendlyName' : 'TestMPC', 'from' : '+919090909090', 'to': 'sip:koushikqa119062465586783372208@phone-qa.voice.plivodev.com'}).then(function (response) { +client.multiPartyCalls.addParticipant('agent', {"friendlyName" : "TestMPC", 'from' : '+919090909090', 'to': 'sip:koushikqa119062465586783372208@phone-qa.voice.plivodev.com'}).then(function (response) { console.log(response); }, function (err) { console.error(err); From 29a4be9f3cb26db83fd56bbfdc63c25aa04d67ed Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Tue, 1 Sep 2020 16:50:11 +0530 Subject: [PATCH 66/75] Reverted back to original --- example_script.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example_script.js b/example_script.js index 5b8483e..4ec220a 100644 --- a/example_script.js +++ b/example_script.js @@ -34,7 +34,7 @@ var client = new plivo.Client('MAMDJMMTEZOWY0ZMQWM2', 'OTljNmVmOGVkNGZhNjJlOWIyM // console.error(err); // }); -client.multiPartyCalls.addParticipant('agent', {"friendlyName" : "TestMPC", 'from' : '+919090909090', 'to': 'sip:koushikqa119062465586783372208@phone-qa.voice.plivodev.com'}).then(function (response) { +client.multiPartyCalls.addParticipant('agent', {'friendlyName' : 'TestMPC', 'from' : '+919090909090', 'to': 'sip:koushikqa119062465586783372208@phone-qa.voice.plivodev.com'}).then(function (response) { console.log(response); }, function (err) { console.error(err); From ab352d5d0ea1abab0a53f6ee5c8e7e971abf4222 Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Tue, 8 Sep 2020 00:40:30 +0530 Subject: [PATCH 67/75] MPC API and XML changes - Dev completed --- example_script.js | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/example_script.js b/example_script.js index 4ec220a..f71399d 100644 --- a/example_script.js +++ b/example_script.js @@ -2,12 +2,18 @@ let plivo = require('./'); var client = new plivo.Client('MAMDJMMTEZOWY0ZMQWM2', 'OTljNmVmOGVkNGZhNjJlOWIyMWM0ZDI0ZjQwZDdk'); // client.calls.create( "+919090909090", // from -// "sip:koushikqa119062465586783372208@phone-qa.voice.plivodev.com", // to +// "+918309866821", // to // "https://plivobin.non-prod.plivops.com/api/v1/Conference_test07.xml").then(function (response) { // console.log(response); // }, function (err) { // console.error(err); // }); +// +// client.conferences.get( "FStestconference").then(function (response) { +// console.log(response); +// }, function (err) { +// console.error(err); +// }); // client.calls.transfer( // "35283f77-a738-4d91-81dc-9f565e28d74c", {"legs": "aleg", "alegUrl": "https://www.google.com"}).then(function (response) { @@ -34,13 +40,24 @@ var client = new plivo.Client('MAMDJMMTEZOWY0ZMQWM2', 'OTljNmVmOGVkNGZhNjJlOWIyM // console.error(err); // }); -client.multiPartyCalls.addParticipant('agent', {'friendlyName' : 'TestMPC', 'from' : '+919090909090', 'to': 'sip:koushikqa119062465586783372208@phone-qa.voice.plivodev.com'}).then(function (response) { - console.log(response); -}, function (err) { - console.error(err); -}); - -// client.multiPartyCalls.list().then(function (response) { +// client.multiPartyCalls.stop('6172e321-284d-4159-8242-5f5e92933de5').then(function (response) { +// console.log(response); +// }, function (err) { +// console.error(err); +// }); + +// client.multiPartyCalls.kickParticipant(10, "6bed1e3a-e5da-4ffc-8ed5-84b0a3e0d75c", null).then(function (response) { +// console.log(response); +// }, function (err) { +// console.error(err); +// }); +// client.multiPartyCalls.get(null, 'TestMPC').then(function (response) { +// console.log(response); +// }, function (err) { +// console.error(err); +// }); + +// client.multiPartyCalls.get('6f84d47c-ee82-4172-a155-c6e22f87d874').then(function (response) { // console.log(response); // }, function (err) { // console.error(err); From 9b2831d6f59bfc0e0c9fcb17555aa9d76068194c Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Tue, 8 Sep 2020 00:50:36 +0530 Subject: [PATCH 68/75] Removed example test file and changed URL back to prod from QA url --- example_script.js | 64 ---------------------------------------------- lib/rest/client.js | 2 +- 2 files changed, 1 insertion(+), 65 deletions(-) delete mode 100644 example_script.js diff --git a/example_script.js b/example_script.js deleted file mode 100644 index f71399d..0000000 --- a/example_script.js +++ /dev/null @@ -1,64 +0,0 @@ -let plivo = require('./'); -var client = new plivo.Client('MAMDJMMTEZOWY0ZMQWM2', 'OTljNmVmOGVkNGZhNjJlOWIyMWM0ZDI0ZjQwZDdk'); - -// client.calls.create( "+919090909090", // from -// "+918309866821", // to -// "https://plivobin.non-prod.plivops.com/api/v1/Conference_test07.xml").then(function (response) { -// console.log(response); -// }, function (err) { -// console.error(err); -// }); -// -// client.conferences.get( "FStestconference").then(function (response) { -// console.log(response); -// }, function (err) { -// console.error(err); -// }); - -// client.calls.transfer( -// "35283f77-a738-4d91-81dc-9f565e28d74c", {"legs": "aleg", "alegUrl": "https://www.google.com"}).then(function (response) { -// console.log(response); -// }, function (err) { -// console.error(err); -// }); - -// client.calls.sendDigits( -// "bfc3f1fd-d66b-42ab-88e4-9e82c8e2537f", // call uuid -// 123, // digits -// { -// 'leg': 'aleg' -// } -// ).then(function (response) { -// console.log(response); -// }, function (err) { -// console.error(err); -// }); - -// client.conferences.startRecording('FStestconference').then(function (response) { -// console.log(response); -// }, function (err) { -// console.error(err); -// }); - -// client.multiPartyCalls.stop('6172e321-284d-4159-8242-5f5e92933de5').then(function (response) { -// console.log(response); -// }, function (err) { -// console.error(err); -// }); - -// client.multiPartyCalls.kickParticipant(10, "6bed1e3a-e5da-4ffc-8ed5-84b0a3e0d75c", null).then(function (response) { -// console.log(response); -// }, function (err) { -// console.error(err); -// }); -// client.multiPartyCalls.get(null, 'TestMPC').then(function (response) { -// console.log(response); -// }, function (err) { -// console.error(err); -// }); - -// client.multiPartyCalls.get('6f84d47c-ee82-4172-a155-c6e22f87d874').then(function (response) { -// console.log(response); -// }, function (err) { -// console.error(err); -// }); diff --git a/lib/rest/client.js b/lib/rest/client.js index 7e13eae..492c32d 100644 --- a/lib/rest/client.js +++ b/lib/rest/client.js @@ -65,7 +65,7 @@ export class Client { authId: authId, authToken: authToken, version: "v1", - url: "https://api-qa.voice.plivodev.com/v1/Account/" + authId, + url: "https://api.plivo.com/v1/Account/" + authId, userAgent: `${"plivo-node"}/${version || "Unknown Version"} (Node: ${ process.version })` From e57a6bec3b52f4632ca34daad3e957d845ec0b7c Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Wed, 7 Oct 2020 16:40:55 +0530 Subject: [PATCH 69/75] Incorporated retry logic for MPC APIs and validated voice UTs --- lib/resources/applications.js | 2 +- lib/resources/multiPartyCall.js | 29 +++++++++++++++-------------- lib/rest/utils.js | 2 +- test/calls.js | 1 + 4 files changed, 18 insertions(+), 16 deletions(-) diff --git a/lib/resources/applications.js b/lib/resources/applications.js index 7d653f5..8f01b3a 100644 --- a/lib/resources/applications.js +++ b/lib/resources/applications.js @@ -327,4 +327,4 @@ export class ApplicationInterface extends PlivoResourceInterface { id: id }).delete(params, id); } -} \ No newline at end of file +} diff --git a/lib/resources/multiPartyCall.js b/lib/resources/multiPartyCall.js index 4a26f14..e122f13 100644 --- a/lib/resources/multiPartyCall.js +++ b/lib/resources/multiPartyCall.js @@ -30,8 +30,9 @@ export class MultiPartyCall extends PlivoResource{ this[clientKey] = client; } - get(){ - return super.executeAction(this.id, 'GET'); + get(params = {}){ + params.isVoiceRequest = 'true'; + return super.executeAction(this.id, 'GET', params); } addParticipant(params){ @@ -281,16 +282,16 @@ export class MultiPartyCall extends PlivoResource{ else { params.exitSoundMethod = 'GET' } - + params.isVoiceRequest = 'true'; return super.executeAction(this.id + '/Participant/', 'POST', params) } start(){ - return super.executeAction(this.id + '/', 'POST', {'status' : 'active'}) + return super.executeAction(this.id + '/', 'POST', {'status' : 'active', 'isVoiceRequest' : 'true'}) } stop(){ - return super.delete() + return super.delete({'isVoiceRequest' : 'true'}) } startRecording(params = {}){ @@ -311,27 +312,27 @@ export class MultiPartyCall extends PlivoResource{ else { params.statusCallbackMethod = 'POST' } - + params.isVoiceRequest = 'true'; return super.executeAction(this.id + '/Record/', 'POST', params) } stopRecording(){ - return super.executeAction(this.id + '/Record/', 'DELETE') + return super.executeAction(this.id + '/Record/', 'DELETE',{'isVoiceRequest' : 'true'}) } pauseRecording(){ - return super.executeAction(this.id + '/Record/Pause/', 'POST') + return super.executeAction(this.id + '/Record/Pause/', 'POST',{'isVoiceRequest' : 'true'}) } resumeRecording(){ - return super.executeAction(this.id + '/Record/Resume/', 'POST') + 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) } } @@ -364,16 +365,16 @@ export class MultiPartyCallParticipant extends PlivoSecondaryResource{ 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') + return super.executeAction(this.id, this.secondaryId, 'DELETE',{'isVoiceRequest' : 'true'}) } getParticipant(){ - return super.executeAction(this.id, this.secondaryId, 'GET') + return super.executeAction(this.id, this.secondaryId, 'GET',{'isVoiceRequest' : 'true'}) } } @@ -446,7 +447,7 @@ export class MultiPartyCallInterface extends PlivoResourceInterface{ if(params.offset){ validRange('offset', params.offset, false, 0) } - + params.isVoiceRequest = 'true'; return super.list(params); } diff --git a/lib/rest/utils.js b/lib/rest/utils.js index 6add094..49996bb 100644 --- a/lib/rest/utils.js +++ b/lib/rest/utils.js @@ -228,7 +228,7 @@ export function validDateFormat(paramName, paramValue, mandatory = false){ return true; } - let response = paramValue.match(/^\d{4}\-\d{2}\-\d{2} \d{2}:\d{2}:\d{2}(\.\d{1,6})?$/); + 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") } 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) From 1cfd02434a52cc53d9c6e4bdbe5c0203c7d85174 Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Wed, 7 Oct 2020 16:42:14 +0530 Subject: [PATCH 70/75] Updated CHANGELOG.md version --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e9fa7fd..c20b7c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # Change Log +## [5.0.0](https://github.com/plivo/plivo-node/releases/tag/v4.9.0)(2020-10-07) +- Add 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. From 0cd20c12e24d05485c9252afba54257fe22c7ce3 Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Wed, 4 Nov 2020 00:25:40 +0530 Subject: [PATCH 71/75] Updated changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c20b7c8..f5a7d59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Change Log -## [5.0.0](https://github.com/plivo/plivo-node/releases/tag/v4.9.0)(2020-10-07) +## [5.0.0](https://github.com/plivo/plivo-node/releases/tag/v5.0.0)(2020-11-03) - Add 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) From b6002f453845f435444e435cc49fe22704dafb61 Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Thu, 12 Nov 2020 18:38:57 +0530 Subject: [PATCH 72/75] Fixed ringTimeout not working bug --- lib/rest/utils.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/rest/utils.js b/lib/rest/utils.js index 49996bb..f58c3da 100644 --- a/lib/rest/utils.js +++ b/lib/rest/utils.js @@ -246,7 +246,7 @@ export function validRange(paramName, paramValue, mandatory = false, lowerBound return true; } - if(!expectedType(paramName, Number, paramValue)){ + if(!expectedType(paramName, [Number], paramValue)){ throw new InvalidRequestError(paramName + ": Expected an Integer but received " + paramValue.constructor + " instead") } From 454789324c2670127bc2688ebf44347767fbf206 Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Tue, 17 Nov 2020 10:59:50 +0530 Subject: [PATCH 73/75] Fixed error message bug --- lib/resources/multiPartyCall.js | 6 ------ 1 file changed, 6 deletions(-) diff --git a/lib/resources/multiPartyCall.js b/lib/resources/multiPartyCall.js index e122f13..1b84d9f 100644 --- a/lib/resources/multiPartyCall.js +++ b/lib/resources/multiPartyCall.js @@ -463,12 +463,6 @@ export class MultiPartyCallInterface extends PlivoResourceInterface{ } addParticipant(role, params = {}){ - let errors = validate([ - {field: 'friendly_name', value: params.friendlyName, validators: ['isString']} - ]); - if (errors) { - return errors; - } if(params.uuid){ validParam('uuid', params.uuid, [String], false) } From a6a7953132cad779b434e300d318bf9c5890de07 Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Thu, 19 Nov 2020 15:26:19 +0530 Subject: [PATCH 74/75] Fixed ringTimeout 0 error handling bug --- lib/resources/multiPartyCall.js | 6 +++--- lib/rest/utils.js | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/resources/multiPartyCall.js b/lib/resources/multiPartyCall.js index 1b84d9f..0ffe665 100644 --- a/lib/resources/multiPartyCall.js +++ b/lib/resources/multiPartyCall.js @@ -98,21 +98,21 @@ export class MultiPartyCall extends PlivoResource{ params.dialMusic = 'Real' } - if(params.ringTimeout){ + if(params.ringTimeout || params.ringTimeout === 0){ validRange('ringTimeout', params.ringTimeout, false, 15, 120) } else { params.ringTimeout = 45 } - if(params.maxDuration){ + if(params.maxDuration || params.maxDuration === 0){ validRange('maxDuration', params.maxDuration, false, 300, 28800) } else { params.maxDuration = 14400 } - if(params.maxParticipants){ + if(params.maxParticipants || params.maxParticipants === 0){ validRange('maxParticipants', params.maxParticipants, false, 2, 10) } else { diff --git a/lib/rest/utils.js b/lib/rest/utils.js index f58c3da..300fe5b 100644 --- a/lib/rest/utils.js +++ b/lib/rest/utils.js @@ -242,7 +242,7 @@ export function validRange(paramName, paramValue, mandatory = false, lowerBound throw new InvalidRequestError(paramName + " is a required parameter") } - if(!paramValue){ + if(!paramValue && paramValue !== 0){ return true; } From a65a44d29b6ff9ee2dcec9856ea034180a23e41e Mon Sep 17 00:00:00 2001 From: Koushik-Ayila Date: Mon, 19 Apr 2021 18:59:00 +0530 Subject: [PATCH 75/75] Added version bump up --- CHANGELOG.md | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f5a7d59..5c82c33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,7 @@ # Change Log -## [5.0.0](https://github.com/plivo/plivo-node/releases/tag/v5.0.0)(2020-11-03) -- Add SDK support for Voice MultiPartyCall APIs and XML +## [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. diff --git a/package.json b/package.json index ddd9b7b..7df55cd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "plivo", - "version": "4.15.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": [