diff --git a/CallAutomation_LobbyCall_Sample/README.md b/CallAutomation_LobbyCall_Sample/README.md new file mode 100644 index 0000000..8491db3 --- /dev/null +++ b/CallAutomation_LobbyCall_Sample/README.md @@ -0,0 +1,163 @@ +|page_type| languages |products +|---|---------------------------------------|---| +|sample|
Java
|
azureazure-communication-services
| + +# Call Automation - Lobby Call Sample + +This sample demonstrates how to utilize the Call Automation SDK to implement a Lobby Call scenario. Users join a lobby call and remain on hold until an user in the target call confirms their participation. Once approved, Call Automation (bot) automatically connects the lobby users to the designated target call. +The sample uses a client application (java script sample) available in [Web Client Quickstart](https://github.com/Azure-Samples/communication-services-javascript-quickstarts/tree/users/v-kuppu/LobbyCallConfirmSample). + +## Features + +- **Lobby Call Management**: Automatically answer incoming calls and place them in a lobby +- **Text-to-Speech**: Play waiting messages to lobby participants using Azure Cognitive Services +- **Participant Management**: Move participants between lobby and target calls +- **WebSocket Support**: Real-time communication for call state updates +- **Event-Driven Architecture**: Handle Call Automation events via webhooks +- **Dev Tunnel Integration**: Easy development with Azure Dev Tunnels for webhook delivery + +# Design + +![Lobby Call Support](./resources/Lobby_Call_Support_Scenario.jpg) + + +## Prerequisites + +- Java 17 or later +- Maven 3.6 or later +- Azure Communication Services resource +- Azure Cognitive Services resource (for text-to-speech) +- Azure Dev Tunnels CLI (for local development) + +## Setup and Configuration + +### 1. Setup Azure Dev Tunnel + +[Azure DevTunnels](https://learn.microsoft.com/en-us/azure/developer/dev-tunnels/overview) enables you to expose your local development server to the internet for webhook delivery. + +```bash +# Create a new dev tunnel +devtunnel create --allow-anonymous + +# Create a port mapping for the application +devtunnel port create -p 8443 + +# Start the tunnel +devtunnel host +``` + +Copy the HTTPS URL provided by dev tunnel (e.g., `https://abc123-8443.inc1.devtunnels.ms`) for use in configuration. + +### 2. Build and Run the Application + +Navigate to the project directory and run: + +```bash +# Compile the application +mvn compile + +# Build the package +mvn package + +# Run the application +mvn spring-boot:run +``` + +Alternative execution method: +```bash +mvn exec:java +``` + +The application will start on port 8443 and be accessible at: +- **Local**: http://localhost:8443/swagger-ui/index.html +- **Dev Tunnel**: https://your-tunnel-url/swagger-ui/index.html + +### 3. Configure Application Settings + +Use the Swagger UI to configure the application via the `/api/setConfiguration` endpoint: + +**Required Configuration Parameters:** + +1. **`acsConnectionString`**: Your Azure Communication Services connection string + - Format: `endpoint=https://your-acs-resource.communication.azure.com/;accesskey=your-access-key` + +2. **`cognitiveServiceEndpoint`**: Azure Cognitive Services endpoint for text-to-speech + - Format: `https://your-cognitive-service.cognitiveservices.azure.com/` + +3. **`callbackUriHost`**: Your application's base URL for webhook callbacks + - Local: `http://localhost:8443` + - Dev Tunnel: `https://your-tunnel-url` (without trailing slash) + +4. **`pmaEndpoint`**: Azure Communication Services endpoint + - Format: `https://your-acs-resource.communication.azure.com` + +5. **`acsGeneratedId`**: Communication user ID for receiving lobby calls + - Generate using ACS Identity SDK or Azure portal + +6. **`webSocketToken`**: Unique token for WebSocket endpoint security + - Use any unique string (e.g., UUID or custom token) + +## API Endpoints + +The application provides the following REST endpoints: + +### Core Endpoints +- **`POST /api/setConfiguration`** - Configure application settings +- **`POST /api/lobbyCallEventHandler`** - EventGrid webhook for incoming calls +- **`POST /api/callbacks`** - Call Automation event callbacks +- **`POST /targetCallToAcsUser`** - Create a target call to an ACS user +- **`GET /getParticipants`** - List participants in the lobby call +- **`GET /terminateCalls`** - Terminate all active calls + +### WebSocket Endpoint +- **`/ws/{webSocketToken}`** - Real-time communication endpoint + +## Usage Flow + +1. **Configure the application** using `/api/setConfiguration` +2. **Set up EventGrid webhook** to point to `/api/lobbyCallEventHandler` +3. **Create a target call** using `/targetCallToAcsUser` with an ACS user ID +4. **Incoming calls** are automatically answered and placed in lobby +5. **Lobby participants** hear a waiting message via text-to-speech +6. **Participants are automatically moved** to the target call after the message completes + +## Development Features + +### Environment Variables +Configure dev tunnel support using environment variables: +- `DEVTUNNEL_URL`: Your dev tunnel URL +- `DEVTUNNEL_ENABLED`: Set to `true` to enable dev tunnel features + +### WebSocket Integration +The application includes WebSocket support for real-time updates. WebSocket endpoints are dynamically configured based on the `webSocketToken` parameter. + +### Dynamic Server Configuration +The Swagger UI automatically detects and displays available servers (local and dev tunnel) based on your configuration. + +## Technology Stack + +- **Spring Boot 3.0.6** - Web framework +- **Azure Communication Services Call Automation SDK** - Call management +- **Azure EventGrid** - Event handling +- **WebSocket** - Real-time communication +- **SpringDoc OpenAPI** - API documentation +- **Maven** - Build tool +- **Java 17** - Runtime environment + +## Troubleshooting + +### Common Issues + +1. **Dev Tunnel 502 Errors**: Ensure your application is running on port 8443 before starting the tunnel +2. **Webhook Delivery Failures**: Verify your `callbackUriHost` matches your dev tunnel URL exactly +3. **Audio Issues**: Confirm your Cognitive Services endpoint is correctly configured +4. **Connection Issues**: Check that your ACS connection string is valid and has the required permissions + +### Logs and Monitoring +The application provides detailed logging for all call events and operations. Check the console output for debugging information. + +## Additional Resources + +- [Azure Communication Services Documentation](https://docs.microsoft.com/en-us/azure/communication-services/) +- [Call Automation SDK Reference](https://docs.microsoft.com/en-us/azure/communication-services/concepts/call-automation/) +- [Azure Dev Tunnels Documentation](https://learn.microsoft.com/en-us/azure/developer/dev-tunnels/) diff --git a/CallAutomation_LobbyCall_Sample/pom.xml b/CallAutomation_LobbyCall_Sample/pom.xml new file mode 100644 index 0000000..318ea02 --- /dev/null +++ b/CallAutomation_LobbyCall_Sample/pom.xml @@ -0,0 +1,195 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 3.0.6 + + + + com.communication.callautomation + CallAutomation_LobbyCallSample + 1.0-SNAPSHOT + + CallAutomation_LobbyCallSample + CallAutomation Sample application for instructional usage + + + 17 + 17 + UTF-8 + 1.18.26 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-websocket + + + org.springframework.boot + spring-boot-starter-test + test + + + com.vaadin.external.google + android-json + + + + + com.microsoft.azure + applicationinsights-spring-boot-starter + 2.6.4 + + + junit + junit + 4.13.2 + test + + + com.azure + azure-core + 1.42.0 + + + com.azure + azure-identity + 1.10.4 + + + com.azure + azure-communication-identity + 1.5.0 + + + com.azure + azure-communication-callautomation + 1.6.0-beta.1 + + + com.azure + azure-messaging-eventgrid + 4.16.0 + + + com.azure + azure-communication-common + 1.5.0-beta.1 + + + org.projectlombok + lombok + provided + ${lombok.version} + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.springframework.boot + spring-boot-autoconfigure-processor + true + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + 2.0.0 + + + org.json + json + 20231013 + + + + + azure-sdk-for-java + https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-java/maven/v1 + + true + + + true + + + + + + + + maven-clean-plugin + 3.2.0 + + + maven-resources-plugin + 3.3.1 + + + maven-compiler-plugin + 3.11.0 + + + maven-surefire-plugin + 3.1.0 + + + maven-jar-plugin + 3.3.0 + + + maven-deploy-plugin + 3.1.1 + + + maven-site-plugin + 3.12.1 + + + maven-project-info-reports-plugin + 3.4.3 + + + org.codehaus.mojo + exec-maven-plugin + 3.1.0 + + + + java + + + + + com.communication.callautomation.Main + + + + + + + org.springframework.boot + spring-boot-maven-plugin + 3.2.5 + + + + repackage + + + + + + + \ No newline at end of file diff --git a/CallAutomation_LobbyCall_Sample/resources/Lobby_Call_Support_Scenario.jpg b/CallAutomation_LobbyCall_Sample/resources/Lobby_Call_Support_Scenario.jpg new file mode 100644 index 0000000..92225d4 Binary files /dev/null and b/CallAutomation_LobbyCall_Sample/resources/Lobby_Call_Support_Scenario.jpg differ diff --git a/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/ConfigurationRequest.java b/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/ConfigurationRequest.java new file mode 100644 index 0000000..4814912 --- /dev/null +++ b/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/ConfigurationRequest.java @@ -0,0 +1,31 @@ +package com.communication.callautomation; + +import lombok.Getter; +import org.springframework.boot.context.properties.ConfigurationProperties; + + +@ConfigurationProperties(prefix = "acs") +@Getter +public class ConfigurationRequest { + private String acsConnectionString; + private String cognitiveServiceEndpoint; + private String callbackUriHost; + private String acsGeneratedIdForTargetCallSender; + + // Getters and Setters + public void setAcsConnectionString(String acsConnectionString) { + this.acsConnectionString = acsConnectionString; + } + + public void setCognitiveServiceEndpoint(String cognitiveServiceEndpoint) { + this.cognitiveServiceEndpoint = cognitiveServiceEndpoint; + } + + public void setCallbackUriHost(String callbackUriHost) { + this.callbackUriHost = callbackUriHost; + } + + public void setAcsGeneratedIdForTargetCallSender(String acsGeneratedIdForTargetCallSender) { + this.acsGeneratedIdForTargetCallSender = acsGeneratedIdForTargetCallSender; + } +} diff --git a/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/CorsConfig.java b/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/CorsConfig.java new file mode 100644 index 0000000..82a2fb1 --- /dev/null +++ b/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/CorsConfig.java @@ -0,0 +1,25 @@ +package com.communication.callautomation; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.lang.NonNull; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class CorsConfig { + + @Bean + public WebMvcConfigurer corsConfigurer() { + return new WebMvcConfigurer() { + @Override + public void addCorsMappings(@NonNull CorsRegistry registry) { + registry.addMapping("/**") // Allow all endpoints + .allowedOrigins("*") // Allow all origins + .allowedMethods("*") // Allow all HTTP methods + .allowedHeaders("*") // Allow all headers + .allowCredentials(false); // Disable credentials for security + } + }; + } +} \ No newline at end of file diff --git a/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/LobbyWebSocketHandler.java b/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/LobbyWebSocketHandler.java new file mode 100644 index 0000000..db1f25b --- /dev/null +++ b/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/LobbyWebSocketHandler.java @@ -0,0 +1,55 @@ +package com.communication.callautomation; + +import org.springframework.lang.NonNull; +import org.springframework.stereotype.Component; +import org.springframework.web.socket.TextMessage; +import org.springframework.web.socket.WebSocketSession; +import org.springframework.web.socket.handler.TextWebSocketHandler; + +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Component +public class LobbyWebSocketHandler extends TextWebSocketHandler { + private final List sessions = new ArrayList<>(); + private static final Logger log = LoggerFactory.getLogger(LobbyWebSocketHandler.class); + + // Reference to ProgramSample for handling messages + private ProgramSample programSample; + + public void setProgramSample(ProgramSample programSample) { + this.programSample = programSample; + } + + @Override + public void afterConnectionEstablished(@NonNull WebSocketSession session) { + sessions.add(session); + log.info("WebSocket connection established: " + session.getId()); + } + + @Override + protected void handleTextMessage(@NonNull WebSocketSession session, @NonNull TextMessage message) throws Exception { + log.info("Received WebSocket message: " + message.getPayload()); + + // Delegate to ProgramSample if available + if (programSample != null) { + programSample.handleWebSocketMessage(session, message); + } else { + log.warn("ProgramSample not available, cannot process message"); + } + } + + @Override + public void handleTransportError(@NonNull WebSocketSession session, @NonNull Throwable exception) throws Exception { + log.error("WebSocket transport error: " + exception.getMessage()); + } + + @Override + public void afterConnectionClosed(@NonNull WebSocketSession session, @NonNull org.springframework.web.socket.CloseStatus status) throws Exception { + sessions.remove(session); + log.info("WebSocket connection closed: " + session.getId()); + } +} diff --git a/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/Main.java b/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/Main.java new file mode 100644 index 0000000..85a3ed8 --- /dev/null +++ b/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/Main.java @@ -0,0 +1,13 @@ +package com.communication.callautomation; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; + +@SpringBootApplication +@EnableConfigurationProperties(value = ConfigurationRequest.class) +public class Main { + public static void main(String[] args) { + SpringApplication.run(Main.class, args); + } +} \ No newline at end of file diff --git a/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/OpenApiConfig.java b/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/OpenApiConfig.java new file mode 100644 index 0000000..6f53aa7 --- /dev/null +++ b/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/OpenApiConfig.java @@ -0,0 +1,68 @@ +package com.communication.callautomation; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.servers.Server; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.StringUtils; + +import java.util.List; +import java.util.ArrayList; + +@Configuration +public class OpenApiConfig { + + @Value("${devtunnel.url:}") + private String devTunnelUrl; + + @Value("${devtunnel.enabled:false}") + private boolean devTunnelEnabled; + + @Value("${server.port:8443}") + private int serverPort; + + @Bean + public OpenAPI customOpenAPI() { + List servers = new ArrayList<>(); + + // Local server + Server localServer = new Server(); + localServer.setUrl("http://localhost:" + serverPort); + localServer.setDescription("Local Server (HTTP on port " + serverPort + ")"); + servers.add(localServer); + + // Dev Tunnel server (only if configured) + if (devTunnelEnabled && StringUtils.hasText(devTunnelUrl)) { + Server devTunnelServer = new Server(); + devTunnelServer.setUrl(devTunnelUrl); + devTunnelServer.setDescription("Dev Tunnel Server (HTTPS via tunnel)"); + servers.add(devTunnelServer); + } + + String description = buildDescription(); + + return new OpenAPI() + .info(new Info() + .title("Call Automation Lobby Call Sample API") + .description(description) + .version("1.0.0")) + .servers(servers); + } + + private String buildDescription() { + StringBuilder desc = new StringBuilder(); + desc.append("Azure Communication Services Call Automation API for managing lobby calls.\n"); + desc.append("**🚀 Server Access Information:**\n"); + desc.append("- **Local**: [http://localhost:").append(serverPort).append("/swagger-ui/index.html](http://localhost:").append(serverPort).append("/swagger-ui/index.html)\n"); + + if (devTunnelEnabled && StringUtils.hasText(devTunnelUrl)) { + desc.append("- **Dev Tunnel**: [").append(devTunnelUrl).append("/swagger-ui/index.html](").append(devTunnelUrl).append("/swagger-ui/index.html)\n"); + } else { + desc.append("- **Dev Tunnel**: Not configured (set DEVTUNNEL_URL environment variable)\n"); + } + + return desc.toString(); + } +} diff --git a/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/ProgramSample.java b/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/ProgramSample.java new file mode 100644 index 0000000..7b76f43 --- /dev/null +++ b/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/ProgramSample.java @@ -0,0 +1,455 @@ +package com.communication.callautomation; + +import com.azure.communication.callautomation.CallAutomationClient; +import com.azure.communication.callautomation.CallAutomationClientBuilder; +import com.azure.communication.callautomation.CallAutomationEventParser; +import com.azure.communication.callautomation.CallConnection; +import com.azure.communication.callautomation.CallMedia; +import com.azure.communication.callautomation.models.*; +import com.azure.communication.callautomation.models.events.*; +import com.azure.messaging.eventgrid.EventGridEvent; +import com.azure.messaging.eventgrid.SystemEventNames; +import com.azure.messaging.eventgrid.systemevents.SubscriptionValidationEventData; +import com.azure.messaging.eventgrid.systemevents.SubscriptionValidationResponse; +import com.azure.communication.common.CommunicationIdentifier; +import com.azure.communication.common.CommunicationUserIdentifier; +import com.azure.communication.common.PhoneNumberIdentifier; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; + +import io.swagger.v3.oas.annotations.tags.Tag; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.json.JSONObject; + +import org.springframework.web.bind.annotation.*; +import org.springframework.web.socket.TextMessage; +import org.springframework.web.socket.WebSocketSession; +import org.springframework.http.*; +import org.springframework.beans.factory.annotation.Autowired; +import jakarta.annotation.PostConstruct; +import java.net.URI; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.Comparator; + +@RestController +public class ProgramSample { + + private CallAutomationClient acsClient; + private static final Logger log = LoggerFactory.getLogger(ProgramSample.class); + + @Autowired + private LobbyWebSocketHandler lobbyWebSocketHandler; + + // Configuration state variables + private ConfigurationRequest configuration = new ConfigurationRequest(); + private String acsConnectionString = ""; + private String cognitiveServiceEndpoint = ""; + private String callbackUriHost = ""; + private String acsGeneratedIdForTargetCallSender = ""; + private String acsGeneratedIdForTargetCallReceiver = ""; + private String acsGeneratedIdForLobbyCallReceiver = ""; + + private String textToPlayToLobbyUser = "You are currently in a lobby call, we will notify the admin that you are waiting."; + private String confirmMessageToTargetCall = "A user is waiting in lobby, do you want to add the lobby user to your call?"; + + private String lobbyCallConnectionId = ""; + private String targetCallConnectionId = ""; + private String lobbyCallerId = ""; + + @PostConstruct + public void init() { + // Set up the connection between ProgramSample and LobbyWebSocketHandler + if (lobbyWebSocketHandler != null) { + lobbyWebSocketHandler.setProgramSample(this); + } + } + + // Method to handle WebSocket messages (called by LobbyWebSocketHandler) + public void handleWebSocketMessage(WebSocketSession session, TextMessage message) { + String jsResponse = message.getPayload(); + log.info("Received from JS: " + jsResponse); + + if ("yes".equalsIgnoreCase(jsResponse.trim())) { + log.info("TODO: Move Participant"); + try { + log.info( + "\n~~~~~~~~~~~~ /api/callbacks ~~~~~~~~~~~~\n" + + "Move Participant operation started..\n" + + "Source Caller Id: " + lobbyCallerId + "\n" + + "Source Connection Id: " + lobbyCallConnectionId + "\n" + + "Target Connection Id: " + targetCallConnectionId + "\n" + ); + + CallConnection targetConnection = acsClient.getCallConnection(targetCallConnectionId); + // CallConnection sourceConnection = client.getCallConnection(lobbyConnectionId.get()); + + CommunicationIdentifier participantToMove; + if (lobbyCallerId.startsWith("+")) { + participantToMove = new PhoneNumberIdentifier(lobbyCallerId); + } else if (lobbyCallerId.startsWith("8:acs")) { + participantToMove = new CommunicationUserIdentifier(lobbyCallerId); + } else { + log.error("Invalid participant identifier"); + return; + } + + targetConnection.moveParticipants(java.util.Collections.singletonList(participantToMove), lobbyCallConnectionId); + // If no exception is thrown, the operation is considered successful + log.info("Move Participants operation completed successfully."); + } catch (Exception ex) { + log.info("Error in manual move participants operation: " + ex.getMessage()); + } + } + } + + private ResponseEntity handleSubscriptionValidation(final BinaryData eventData) { + try { + log.info("Received Subscription Validation Event from Incoming Call API endpoint"); + SubscriptionValidationEventData subscriptioneventData = eventData + .toObject(SubscriptionValidationEventData.class); + SubscriptionValidationResponse responseData = new SubscriptionValidationResponse(); + responseData.setValidationResponse(subscriptioneventData.getValidationCode()); + + return ResponseEntity.ok().body(responseData); + } catch (Exception e) { + log.error("Error at subscription validation event {} {}", + e.getMessage(), + e.getCause()); + + return ResponseEntity.internalServerError().build(); + } + } + + private ResponseEntity handleIncomingCall(final BinaryData eventData) { + log.info("Incoming call received"); + JSONObject data = new JSONObject(eventData.toString()); + String callbackUri = URI.create(callbackUriHost + "/api/callbacks").toString(); + + String fromCallerId = data.getJSONObject("from").getString("rawId"); + String toCallerId = data.getJSONObject("to").getString("rawId"); + log.info("Incoming call from: {}, to: {}", fromCallerId, toCallerId); + String incomingCallContext = data.getString("incomingCallContext"); + log.info("Incoming Call Context: " + incomingCallContext); + + // Lobby Call: Answer + if (toCallerId.contains(acsGeneratedIdForTargetCallSender)) { + StringBuilder msgLog = new StringBuilder(); + try { + AnswerCallOptions options = new AnswerCallOptions(incomingCallContext, callbackUri); + options.setOperationContext("LobbyCall"); + CallIntelligenceOptions intelligenceOptions = new CallIntelligenceOptions(); + intelligenceOptions.setCognitiveServicesEndpoint(cognitiveServiceEndpoint); + options.setCallIntelligenceOptions(intelligenceOptions); + + AnswerCallResult answerCallResult = acsClient.answerCallWithResponse(options, Context.NONE).getValue(); + lobbyCallConnectionId = answerCallResult.getCallConnection().getCallProperties().getCallConnectionId(); + + msgLog.append("User Call(Inbound) Answered by Call Automation.\n") + .append("From Caller Raw Id: ").append(fromCallerId).append("\n") + .append("To Caller Raw Id: ").append(toCallerId).append("\n") + .append("Lobby Call Connection Id: ").append(lobbyCallConnectionId).append("\n") + .append("Correlation Id: ").append(answerCallResult.getCallConnection().getCallProperties().getCorrelationId()).append("\n") + .append("Lobby Call answered successfully.\n"); + log.info(msgLog.toString()); + + return ResponseEntity.ok().build(); + } catch (Exception ex) { + msgLog.append("Error answering call: ").append(ex.getMessage()).append("\n"); + log.info(msgLog.toString()); + + return ResponseEntity.internalServerError().body(msgLog.toString()); + } + } + + return ResponseEntity.ok().build(); + } + + @Tag(name = "STEP 00. Call Automation Events", description = "Configure Event Grid webhook to point to /api/lobbyCallEventHandler endpoint") + @PostMapping("/api/lobbyCallEventHandler") + public ResponseEntity lobbyCallEventHandler(@RequestBody final String reqBody) { + log.info("Lobby call event received"); + List events = EventGridEvent.fromString(reqBody); + var response = ResponseEntity.ok().build(); + + for (EventGridEvent eventGridEvent : events) { + if (eventGridEvent.getEventType().equals(SystemEventNames.EVENT_GRID_SUBSCRIPTION_VALIDATION)) { + response = handleSubscriptionValidation(eventGridEvent.getData()); + } else if (eventGridEvent.getEventType().equals(SystemEventNames.COMMUNICATION_INCOMING_CALL)) { + response = handleIncomingCall(eventGridEvent.getData()); + } + } + + return response; + } + + @Tag(name = "STEP 00. Call Automation Events", description = "Call Back Events") + @PostMapping("/api/callbacks") + public ResponseEntity callbackEvents(@RequestBody final String reqBody) { + StringBuilder msgLog = new StringBuilder(); + try { + List events = CallAutomationEventParser.parseEvents(reqBody); + for (CallAutomationEventBase event : events) { + String callConnectionId = event.getCallConnectionId(); + log.info( + "Received call event callConnectionID: {}, serverCallId: {}, CorrelationId: {}, eventType: {}", + callConnectionId, + event.getServerCallId(), + event.getCorrelationId(), + event.getClass().getSimpleName()); + + // Parse the event using the Azure SDK's parser if available + // For illustration, we use eventType string matching + if (event instanceof CallConnected) { + String operationContext = ((CallConnected) event).getOperationContext(); + String correlationId = ((CallConnected) event).getCorrelationId(); + + log.info("~~~~~~~~~~~~ /api/callbacks ~~~~~~~~~~~~ "); + log.info("Received callConnected.CallConnectionId : " + callConnectionId); + + if ("LobbyCall".equals(operationContext)) { + msgLog.append("~~~~~~~~~~~~ /api/callbacks ~~~~~~~~~~~~ \n") + .append("Received call event : ").append(event.getClass()).append("\n") + .append("Lobby Call Connection Id: ").append(callConnectionId).append("\n") + .append("Correlation Id: ").append(correlationId).append("\n"); + + // Record lobby caller id and connection id + CallConnection lobbyCallConnection = acsClient.getCallConnection(callConnectionId); + CallConnectionProperties callConnectionProperties = lobbyCallConnection.getCallProperties(); + lobbyCallerId = callConnectionProperties.getSource().getRawId(); + lobbyCallConnectionId = callConnectionProperties.getCallConnectionId(); + log.info("Lobby Caller Id: " + lobbyCallerId); + log.info("Lobby Connection Id: " + lobbyCallConnectionId); + + // Play lobby waiting message + CallMedia callMedia = lobbyCallConnection.getCallMedia(); + TextSource textSource = new TextSource().setText("You are currently in a lobby call, we will notify the admin that you are waiting."); + textSource.setVoiceName("en-US-NancyNeural"); + CommunicationUserIdentifier playTo = new CommunicationUserIdentifier(lobbyCallerId); + callMedia.play(textSource, List.of(playTo)); + } + } else if (event instanceof PlayCompleted) { + msgLog.append("~~~~~~~~~~~~ /api/callbacks ~~~~~~~~~~~~ \n") + .append("Received event: ").append(event.getClass()).append("\n"); + + // Notify Target Call user via websocket + // In Java/Spring, you would use a WebSocket messaging template or similar + // For now, just log the message + String confirmMessageToTargetCall = "Target Call user has been notified that the lobby call is connected."; + msgLog.append("Target Call notified with message: ").append(confirmMessageToTargetCall).append("\n"); + log.info("Target Call notified with message: " + confirmMessageToTargetCall); + return ResponseEntity.ok("Target Call notified with message: " + confirmMessageToTargetCall); + // } else if (event instanceof MoveParticipantsSucceeded) { + // String correlationId = event.getCorrelationId(); + // msgLog.append("~~~~~~~~~~~~ /api/callbacks ~~~~~~~~~~~~ \n") + // .append("Received event: ").append(event.getClass()).append("\n") + // .append("Call Connection Id: ").append(callConnectionId).append("\n") + // .append("Correlation Id: ").append(correlationId).append("\n"); + } + else if (event instanceof CallDisconnected) { + msgLog.append("~~~~~~~~~~~~ /api/callbacks ~~~~~~~~~~~~ \n") + .append("Received event: ").append(event.getClass()).append("\n") + .append("Call Connection Id: ").append(callConnectionId).append("\n"); + } + } + } catch (Exception ex) { + msgLog.append("Error processing event: ").append(ex.getMessage()).append("\n"); + } + log.info(msgLog.toString()); + return ResponseEntity.ok(msgLog.toString()); + } + + @Tag(name = "STEP 01. Set Configuration", description = "Assign the global variables for the Call Automation sample") + @PostMapping("/api/setConfiguration") + public ResponseEntity setConfiguration(@RequestBody ConfigurationRequest configurationRequest) { + try { + // Reset variables + acsConnectionString = ""; + cognitiveServiceEndpoint = ""; + callbackUriHost = ""; + acsGeneratedIdForTargetCallSender = ""; + + lobbyCallConnectionId = ""; + lobbyCallerId = ""; + + if (configurationRequest != null) { + configuration.setAcsConnectionString( + Optional.ofNullable(configurationRequest.getAcsConnectionString()) + .filter(s -> !s.isEmpty()) + .orElseThrow(() -> new IllegalArgumentException("AcsConnectionString is required")) + ); + configuration.setCognitiveServiceEndpoint( + Optional.ofNullable(configurationRequest.getCognitiveServiceEndpoint()) + .filter(s -> !s.isEmpty()) + .orElseThrow(() -> new IllegalArgumentException("CognitiveServiceEndpoint is required")) + ); + configuration.setCallbackUriHost( + Optional.ofNullable(configurationRequest.getCallbackUriHost()) + .filter(s -> !s.isEmpty()) + .orElseThrow(() -> new IllegalArgumentException("CallbackUriHost is required")) + ); + configuration.setAcsGeneratedIdForTargetCallSender( + Optional.ofNullable(configurationRequest.getAcsGeneratedIdForTargetCallSender()) + .filter(s -> !s.isEmpty()) + .orElseThrow(() -> new IllegalArgumentException("AcsGeneratedId is required")) + ); + } + + // Assign to global variables + acsConnectionString = configuration.getAcsConnectionString(); + cognitiveServiceEndpoint = configuration.getCognitiveServiceEndpoint(); + callbackUriHost = configuration.getCallbackUriHost(); + acsGeneratedIdForTargetCallSender = configuration.getAcsGeneratedIdForTargetCallSender(); + + acsClient = initClient(acsConnectionString); + + log.info("Initialized call automation client."); + return ResponseEntity.ok("Configuration set successfully. Initialized call automation client."); + } catch (Exception e) { + log.error("Error configuring: {}", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to configure call automation client."); + } + } + + @Tag(name = "STEP 02. Target Call To ACSUser", description = "Make a call to ACS User by using this endpoint") + @PostMapping("/targetCallToAcsUser") + public ResponseEntity createTargetCall(@RequestParam String acsTarget) { + StringBuilder msgLog = new StringBuilder(); + msgLog.append("\n~~~~~~~~~~~~ /TargetCall(Create) ~~~~~~~~~~~~\n"); + + try { + URI callbackUri = new URI(callbackUriHost + "/api/callbacks"); + CommunicationUserIdentifier targetUser = new CommunicationUserIdentifier(acsTarget); + CallInvite callInvite = new CallInvite(targetUser); + CreateCallOptions createCallOptions = new CreateCallOptions(callInvite, callbackUri.toString()); + CallIntelligenceOptions intelligenceOptions = new CallIntelligenceOptions(); + intelligenceOptions.setCognitiveServicesEndpoint(cognitiveServiceEndpoint); + createCallOptions.setCallIntelligenceOptions(intelligenceOptions); + + CreateCallResult createCallResult = acsClient.createCall(callInvite, callbackUri.toString()); + targetCallConnectionId = createCallResult.getCallConnectionProperties().getCallConnectionId(); + + msgLog.append("TargetCall:\n") + .append("-----------\n") + .append("From: Call Automation\n") + .append("To: ").append(acsTarget).append("\n") + .append("Target Call Connection Id: ").append(targetCallConnectionId).append("\n") + .append("Correlation Id: ") + .append(createCallResult.getCallConnectionProperties().getCorrelationId()).append("\n"); + + log.info(msgLog.toString()); + return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).body(msgLog.toString()); + } catch (Exception ex) { + msgLog.append("Error creating call: ").append(ex.getMessage()).append("\n"); + log.error(msgLog.toString()); + return ResponseEntity.status(500).contentType(MediaType.TEXT_PLAIN).body(msgLog.toString()); + } + } + + @Tag(name = "STEP 03. Get Call Participants", description = "Get call participants for the lobby call connection by using this endpoint") + @GetMapping("/getParticipants") + public ResponseEntity getParticipants() { + StringBuilder msgLog = new StringBuilder(); + msgLog.append("\n~~~~~~~~~~~~ /GetParticipants/").append(targetCallConnectionId).append(" ~~~~~~~~~~~~\n"); + + try { + CallConnection callConnection = acsClient.getCallConnection(targetCallConnectionId); + PagedIterable participantsResult = callConnection.listParticipants(); + List participants = participantsResult.stream().collect(Collectors.toList()); + + // Map and sort participants: phone numbers first, then ACS users + List participantInfo = participants.stream() + .map(p -> { + CommunicationIdentifier id = p.getIdentifier(); + String type = id.getClass().getSimpleName(); + String rawId = id.getRawId(); + String phoneNumber = (id instanceof PhoneNumberIdentifier) ? ((PhoneNumberIdentifier) id).getPhoneNumber() : null; + String acsUserId = (id instanceof CommunicationUserIdentifier) ? ((CommunicationUserIdentifier) id).getId() : null; + + if (acsUserId == null || acsUserId.isBlank()) { + return String.format("%s - RawId: %s, Phone: %s", type, rawId, phoneNumber); + } else { + return String.format("%s - RawId: %s", type, acsUserId); + } + }) + .sorted(Comparator.comparing(info -> info.contains("Phone:") ? "" : "z")) // phone numbers first + .collect(Collectors.toList()); + + if (participantInfo.isEmpty()) { + return ResponseEntity.status(404).body( + String.format("{\"Message\":\"No participants found for the specified call connection.\",\"CallConnectionId\":\"%s\"}", lobbyCallConnectionId) + ); + } else { + msgLog.append("\nNo of Participants: ").append(participantInfo.size()) + .append("\nParticipants: \n-------------\n"); + for (int i = 0; i < participantInfo.size(); i++) { + msgLog.append(i + 1).append(". ").append(participantInfo.get(i)).append("\n"); + } + log.info(msgLog.toString()); + return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).body(msgLog.toString()); + } + } catch (Exception ex) { + log.error("Error getting participants for call " + targetCallConnectionId + ": " + ex.getMessage()); + return ResponseEntity.badRequest().body( + String.format("{\"Error\":\"%s\",\"CallConnectionId\":\"%s\"}", ex.getMessage(), targetCallConnectionId) + ); + } + } + + @Tag(name = "STEP 04. Terminate Calls", description = "Terminate all Calls created so far by using this endpoint") + @GetMapping("/terminateCalls") + public ResponseEntity terminateCalls() { + try { + CallConnection callConnection = getCallConnection(acsClient, lobbyCallConnectionId); + callConnection.hangUpWithResponse(true, Context.NONE); + } catch (Exception e) { + log.warn("Could not hang up lobby call: {}", e.getMessage()); + } + try { + CallConnection callConnection = getCallConnection(acsClient, targetCallConnectionId); + callConnection.hangUpWithResponse(true, Context.NONE); + } catch (Exception e) { + log.warn("Could not hang up target call: {}", e.getMessage()); + } + lobbyCallConnectionId = ""; + targetCallConnectionId = ""; + lobbyCallerId = ""; + return ResponseEntity.ok("Terminated all calls"); + } + + // 🔄 Shared Methods + private CallConnection getCallConnection(CallAutomationClient client, String callConnectionId) { + if (callConnectionId == null || callConnectionId.isEmpty()) { + throw new IllegalArgumentException("Call connection id is empty"); + } + return client.getCallConnection(callConnectionId); + } + + private CallAutomationClient initClient(String connectionString) { + try { + if (connectionString == null || connectionString.trim().isEmpty()) { + log.error("ACS Connection String is null or empty"); + return null; + } + + log.info("Initializing Call Automation Client with connection string length: {}", connectionString.length()); + + var client = new CallAutomationClientBuilder() + .connectionString(connectionString) + .buildClient(); + + log.info("Call Automation Client initialized successfully."); + return client; + } catch (NullPointerException e) { + log.error("Please verify if Application config is properly set up"); + return null; + } catch (Exception e) { + log.error("Error occurred when initializing Call Automation Client: {} {}", e.getMessage(), e.getCause()); + return null; + } + } +} diff --git a/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/WebSocketConfig.java b/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/WebSocketConfig.java new file mode 100644 index 0000000..2611fb8 --- /dev/null +++ b/CallAutomation_LobbyCall_Sample/src/main/java/com/communication/callautomation/WebSocketConfig.java @@ -0,0 +1,22 @@ +package com.communication.callautomation; + +import org.springframework.context.annotation.Configuration; +import org.springframework.lang.NonNull; +import org.springframework.web.socket.config.annotation.EnableWebSocket; +import org.springframework.web.socket.config.annotation.WebSocketConfigurer; +import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; +import org.springframework.beans.factory.annotation.Autowired; + +@Configuration +@EnableWebSocket +public class WebSocketConfig implements WebSocketConfigurer { + + @Autowired + private LobbyWebSocketHandler lobbyWebSocketHandler; + + @Override + public void registerWebSocketHandlers(@NonNull WebSocketHandlerRegistry registry) { + // Initial registration with default token + registry.addHandler(lobbyWebSocketHandler, "/ws").setAllowedOrigins("*"); + } +} \ No newline at end of file diff --git a/CallAutomation_LobbyCall_Sample/src/main/resources/application.yml b/CallAutomation_LobbyCall_Sample/src/main/resources/application.yml new file mode 100644 index 0000000..4dc1e2f --- /dev/null +++ b/CallAutomation_LobbyCall_Sample/src/main/resources/application.yml @@ -0,0 +1,44 @@ +spring: + application: + name: CallAutomation_LobbyCallSample + +springdoc: + swagger-ui: + tagsSorter: alpha + operationsSorter: alpha + tryItOutEnabled: true + supportedSubmitMethods: ["get", "post", "put", "delete", "patch"] + showCommonExtensions: false + showExtensions: false + api-docs: + enabled: true + show-actuator: false + +server: + port: 8443 # Primary port - accepts both HTTP and HTTPS + ssl: + enabled: false # Disable SSL to allow HTTP requests from dev tunnels + # Forward headers for reverse proxy support (dev tunnels) + forward-headers-strategy: framework + # Tomcat configuration for reverse proxy and dev tunnels + tomcat: + remoteip: + remote-ip-header: x-forwarded-for + protocol-header: x-forwarded-proto + protocol-header-https-value: https + +# Dev tunnel configuration +devtunnel: + url: # Set via environment variable or leave empty for local only + enabled: true # Set to true when using dev tunnels + +applicationinsights: + connection-string: "" + +acs: + acsConnectionString: "" + cognitiveServiceEndpoint: "" + callbackUriHost: "" + pmaEndpoint: "" + acsGeneratedId: "" + webSocketToken: "" \ No newline at end of file diff --git a/CallAutomation_LobbyCall_Sample/src/main/resources/keystore.p12 b/CallAutomation_LobbyCall_Sample/src/main/resources/keystore.p12 new file mode 100644 index 0000000..e324cc6 Binary files /dev/null and b/CallAutomation_LobbyCall_Sample/src/main/resources/keystore.p12 differ