Skip to content

Commit e708b83

Browse files
authored
Merge pull request #22 from samagra-comms/main
Outbound Controller
2 parents badb7d4 + 16b4c62 commit e708b83

File tree

6 files changed

+78
-25
lines changed

6 files changed

+78
-25
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
"test:e2e": "jest --config ./test/jest-e2e.json"
2121
},
2222
"dependencies": {
23+
"@nestjs/axios": "^3.0.1",
2324
"@nestjs/common": "^10.0.0",
2425
"@nestjs/config": "^3.1.1",
2526
"@nestjs/core": "^10.0.0",

src/message/controllers/outbound/outbound.controller.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,16 @@ export class OutboundMessageController {
88

99
@Post()
1010
async handleIncomingXMessage(@Body() orchestratorRequest: XMessage): Promise<any> {
11-
// await this.outboundService.handleOrchestratorResponse(orchestratorRequest)
11+
12+
if (orchestratorRequest.from.bot) {
13+
if ( 'botMobileNumber' in orchestratorRequest.from.meta) {
14+
const botMobileNumber = orchestratorRequest.from.meta.botMobileNumber as string
15+
const credentials = await this.outboundService.getAdapterCredentials(botMobileNumber)
16+
await this.outboundService.handleOrchestratorResponse(orchestratorRequest, credentials)
17+
}
18+
}
19+
20+
1221
}
1322

1423
}

src/message/message.module.ts

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,11 @@ import { GupshupWhatsappInboundService } from './services/inbound/gupshup.whatsa
44
import { ConfigModule } from '@nestjs/config';
55
import { OutboundService } from './services/outbound/outbound.service';
66
import { CredentialService } from './services/credentials/credentials.service';
7+
import { OutboundMessageController } from './controllers/outbound/outbound.controller';
78

89
@Module({
9-
imports: [ConfigModule.forRoot()],
10-
controllers: [GupshupWhatsappInboundController],
11-
providers: [
12-
GupshupWhatsappInboundService,
13-
OutboundService,
14-
CredentialService
15-
],
10+
imports: [ConfigModule.forRoot()],
11+
controllers: [GupshupWhatsappInboundController, OutboundMessageController],
12+
providers: [GupshupWhatsappInboundService, OutboundService, CredentialService]
1613
})
17-
export class MessageModule {}
14+
export class MessageModule {}

src/message/services/inbound/gupshup.whatsapp.service.ts

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
11
import { Injectable, Logger } from '@nestjs/common';
2-
import {
3-
GSWhatsAppMessage,
4-
convertMessageToXMsg,
5-
convertXMessageToMsg,
6-
gupshupWhatsappAdapterServiceConfig
7-
} from '@samagra-x/gupshup-whatsapp-adapter';
2+
import { GSWhatsAppMessage, convertMessageToXMsg } from '@samagra-x/gupshup-whatsapp-adapter';
83
import { ConfigService } from '@nestjs/config';
94
import axios from 'axios';
105
import { v4 as uuid4 } from 'uuid';
@@ -83,23 +78,33 @@ export class GupshupWhatsappInboundService {
8378
}
8479
}
8580

86-
const xMessagePayload = await convertMessageToXMsg(whatsappMessage);
81+
const xMessagePayload: XMessage = await convertMessageToXMsg(whatsappMessage);
82+
if (xMessagePayload.messageType != MessageType.TEXT) {
83+
throw new Error("Media Type Not Supported");
84+
}
85+
86+
this.logger.log("Converted Message:", xMessagePayload)
8787
xMessagePayload.from.userID = uuid4();
8888
xMessagePayload.to.userID = uuid4();
8989
xMessagePayload.messageId.Id = uuid4();
9090

91+
xMessagePayload.to.bot = true;
92+
xMessagePayload.to.meta = xMessagePayload.to.meta || new Map<string, string>();
93+
xMessagePayload.to.meta.set('botMobileNumber', whatsappMessage.waNumber);
94+
console.log(xMessagePayload)
95+
9196
const orchestratorServiceUrl = this.configService.get<string>('ORCHESTRATOR_API_ENDPOINT');
9297
const resp = await axios.post(orchestratorServiceUrl, xMessagePayload, {
9398
headers: {
9499
'Content-Type': 'application/json'
95100
}
96101
});
97-
98-
const xResponse = this.convertApiResponseToXMessage(resp.data, whatsappMessage.mobile.substring(2));
99-
this.logger.log("OrchestratorResponse", xResponse)
100-
const sentResp = await this.outboundService.handleOrchestratorResponse(xResponse, adapterCredentials);
101-
this.logger.log("OutboundResponse",sentResp)
102+
this.logger.log('OrchestratorResponse', resp)
102103
} catch (error) {
104+
let errorText = 'Something went wrong. Please try again later'
105+
if ( error == 'Error: Media Type Not Supported') {
106+
errorText = `Sorry, I can only respond to text-based questions at the moment. Please type your question using regular text characters, and I'll be happy to help!\n\nThank you for your understanding!`
107+
}
103108
const errorResponse = this.convertApiResponseToXMessage(
104109
{
105110
adapterId: '7b0cf232-38a2-4f9b-8070-9b988ff94c2c',
@@ -110,12 +115,12 @@ export class GupshupWhatsappInboundService {
110115
providerURI: 'gupshup',
111116
timestamp: Date.now(),
112117
messageState: MessageState.REPLIED,
113-
payload: { text: 'Something went wrong. Please try again later.' }
118+
payload: { text: errorText }
114119
},
115120
whatsappMessage.mobile.substring(2)
116121
);
117122
const sentResp = await this.outboundService.handleOrchestratorResponse(errorResponse, adapterCredentials);
118-
this.logger.log("OutboundErrorResponse",sentResp)
123+
this.logger.log('OutboundErrorResponse', error);
119124
}
120125
}
121126
}

src/message/services/outbound/outbound.service.ts

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,52 @@ import { CredentialService } from '../credentials/credentials.service';
77

88
@Injectable()
99
export class OutboundService {
10-
constructor(private configService: ConfigService) {}
10+
constructor(
11+
private configService: ConfigService,
12+
private readonly credentialService: CredentialService
13+
) {}
1114
private readonly logger = new Logger(OutboundService.name);
1215

16+
async getAdapterCredentials(number: string) {
17+
console.log(number)
18+
if (number.endsWith('88')) {
19+
const vaultResponse = await this.credentialService.getCredentialsFromVault(
20+
this.configService.get<string>('VAULT_SERVICE_URL'),
21+
'/admin/secret/gupshupWhatsappVariable',
22+
{
23+
ownerId: '8f7ee860-0163-4229-9d2a-01cef53145ba',
24+
ownerOrgId: 'org1',
25+
'admin-token': this.configService.get<string>('VAULT_SERVICE_TOKEN')
26+
}
27+
);
28+
29+
const credentials = vaultResponse['result']['gupshupWhatsappVariable'];
30+
return credentials;
31+
} else if (number.endsWith("87")) {
32+
const vaultResponse = await this.credentialService.getCredentialsFromVault(
33+
this.configService.get<string>('VAULT_SERVICE_URL'),
34+
'/admin/secret/gupshupWhatsappVariable2',
35+
{
36+
ownerId: '8f7ee860-0163-4229-9d2a-01cef53145ba',
37+
ownerOrgId: 'org1',
38+
'admin-token': this.configService.get<string>('VAULT_SERVICE_TOKEN')
39+
}
40+
);
41+
42+
const credentials = vaultResponse['result']['gupshupWhatsappVariable2'];
43+
return credentials;
44+
} else {
45+
throw new Error("unknown whatsapp number")
46+
}
47+
}
48+
1349
async handleOrchestratorResponse(orchestratorRequest: XMessage, credentials) {
1450
gupshupWhatsappAdapterServiceConfig.setConfig({
1551
adapterCredentials: credentials
1652
});
1753
const adapterResponse = await convertXMessageToMsg(orchestratorRequest);
1854
if (adapterResponse.messageState == MessageState.NOT_SENT) {
19-
throw new Error("Message Not Sent")
55+
throw new Error('Message Not Sent');
2056
}
2157
}
2258
}

yarn.lock

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -790,6 +790,11 @@
790790
resolved "https://registry.yarnpkg.com/@lukeed/csprng/-/csprng-1.1.0.tgz#1e3e4bd05c1cc7a0b2ddbd8a03f39f6e4b5e6cfe"
791791
integrity sha512-Z7C/xXCiGWsg0KuKsHTKJxbWhpI3Vs5GwLfOean7MGyVFGqdRgBbAjOCh6u4bbjPc/8MJ2pZmK/0DLdCbivLDA==
792792

793+
"@nestjs/axios@^3.0.1":
794+
version "3.0.1"
795+
resolved "https://registry.yarnpkg.com/@nestjs/axios/-/axios-3.0.1.tgz#b006f81dd54a49def92cfaf9a8970434567e75ce"
796+
integrity sha512-VlOZhAGDmOoFdsmewn8AyClAdGpKXQQaY1+3PGB+g6ceurGIdTxZgRX3VXc1T6Zs60PedWjg3A82TDOB05mrzQ==
797+
793798
"@nestjs/cli@^10.0.0":
794799
version "10.2.1"
795800
resolved "https://registry.yarnpkg.com/@nestjs/cli/-/cli-10.2.1.tgz#a1d32c28e188f0fb4c3f54235c55745de4c6dd7f"

0 commit comments

Comments
 (0)