Exemplo n.º 1
0
        public void CreateCall()
        {
            CommunicationIdentityClient communicationIdentityClient = CreateInstrumentedCommunicationIdentityClient();
            var source           = communicationIdentityClient.CreateUser();
            var targets          = new[] { new PhoneNumberIdentifier(TestEnvironment.TargetPhoneNumber) };
            var createCallOption = new CreateCallOptions(
                new Uri(TestEnvironment.AppCallbackUrl),
                new[] { MediaType.Audio },
                new[] {
                EventSubscriptionType.ParticipantsUpdated,
                EventSubscriptionType.DtmfReceived
            });
            CallingServerClient callingServerClient = CreateInstrumentedCallingServerClient();

            Console.WriteLine("Performing CreateCallConnection operation");
            #region Snippet:Azure_Communication_Call_Tests_CreateCall
            var callConnection = callingServerClient.CreateCallConnection(
                //@@ source: new CommunicationUserIdentifier("<source-identifier>"), // Your Azure Communication Resource Guid Id used to make a Call
                //@@ targets: new List<CommunicationIdentifier>() { new PhoneNumberIdentifier("<targets-phone-number>") }, // E.164 formatted recipient phone number
                //@@ options: createCallOption // The options for creating a call.
                /*@@*/ source: source,
                /*@@*/ targets: targets,
                /*@@*/ options: createCallOption
                );
            Console.WriteLine($"Call connection id: {callConnection.Value.CallConnectionId}");
            #endregion Snippet:Azure_Communication_Call_Tests_CreateCall
        }
        public async Task RunCreatePlayCancelHangupScenarioTests()
        {
            CallingServerClient callingServerClient = CreateInstrumentedCallingServerClientWithConnectionString();
            var groupId = GetGroupId();

            try
            {
                // Establish a Call
                var callConnections = await CreateGroupCallOperation(callingServerClient, groupId, GetFromUserId(), GetToUserId(), TestEnvironment.AppCallbackUrl).ConfigureAwait(false);

                var serverCall = callingServerClient.InitializeServerCall(groupId);

                // Play Prompt Audio
                await SleepIfNotInPlaybackModeAsync().ConfigureAwait(false);
                await PlayAudioOperation(serverCall).ConfigureAwait(false);

                // Cancel Prompt Audio
                await SleepIfNotInPlaybackModeAsync().ConfigureAwait(false);
                await CancelAllMediaOperationsOperation(callConnections).ConfigureAwait(false);

                // Hang up the Call, there is one call leg in this test case, hangup the call will also delete the call as the result.
                await SleepIfNotInPlaybackModeAsync().ConfigureAwait(false);
                await CleanUpConnectionsAsync(callConnections).ConfigureAwait(false);
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine(ex.Message);
                Assert.Fail($"Unexpected error: {ex}");
            }
            catch (Exception ex)
            {
                Assert.Fail($"Unexpected error: {ex}");
            }
        }
        static async Task TransferRecording(EventGridEvent e, ILogger log)
        {
            var serverCallId = ExtractServerCallIDOrDie(e.Subject);
            var payload      = JsonConvert.DeserializeObject <RecordingFileStatusUpdatedPayload>(e.Data.ToString(), new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });

            var callingServerClient = new CallingServerClient(Settings.GetACSConnectionString());
            var storageClient       = new BlobStorage(log, Settings.GetRecordingStoreConnectionString(), Settings.GetRecordingStoreContainerName());

            var chunks         = payload.RecordingStorageInfo.RecordingChunks;
            var blobStorePaths = new List <string>();

            foreach (var chunk in chunks)
            {
                var name     = blobName(serverCallId, chunk);
                var inStream = callingServerClient.DownloadStreaming(new Uri(chunk.ContentLocation)).Value;
                if (await storageClient.UploadFileAsync(name, inStream))
                {
                    blobStorePaths.Add(name);
                    log.LogInformation($"Transferred {name}");
                }
            }
            log.LogInformation($"Uploaded {blobStorePaths.Count} chunks for {serverCallId}");
        }
 public CallRecordingController(IConfiguration configuration, ILogger <CallRecordingController> logger)
 {
     blobStorageConnectionString = configuration["BlobStorageConnectionString"];
     callbackUri         = configuration["CallbackUri"];
     containerName       = configuration["BlobContainerName"];
     callingServerClient = new CallingServerClient(configuration["ACSResourceConnectionString"]);
     Logger = logger;
 }
        public void JoinCall_Returns202Accepted(string serverCallId, CommunicationIdentifier source, JoinCallOptions joinCallOptions)
        {
            CallingServerClient callingServerClient = CreateMockCallingServerClient(202, CreateOrJoinCallPayload);

            var response = callingServerClient.JoinCall(serverCallId, source, joinCallOptions);

            Assert.AreEqual((int)HttpStatusCode.Accepted, response.GetRawResponse().Status);
            Assert.AreEqual("cad9df7b-f3ac-4c53-96f7-c76e7437b3c1", response.Value.CallConnectionId);
        }
        public void CreateCall_Returns404NotFound(CommunicationIdentifier source, IEnumerable <CommunicationIdentifier> targets, CreateCallOptions createCallOptions)
        {
            CallingServerClient callingServerClient = CreateMockCallingServerClient(404);

            RequestFailedException?ex = Assert.Throws <RequestFailedException>(() => callingServerClient.CreateCallConnection(source, targets, createCallOptions));

            Assert.NotNull(ex);
            Assert.AreEqual(ex?.Status, 404);
        }
        public void CreateCall_Returns201Created(CommunicationIdentifier source, IEnumerable <CommunicationIdentifier> targets, CreateCallOptions createCallOptions)
        {
            CallingServerClient callingServerClient = CreateMockCallingServerClient(201, CreateOrJoinCallPayload);

            var response = callingServerClient.CreateCallConnection(source, targets, createCallOptions);

            Assert.AreEqual((int)HttpStatusCode.Created, response.GetRawResponse().Status);
            Assert.AreEqual("cad9df7b-f3ac-4c53-96f7-c76e7437b3c1", response.Value.CallConnectionId);
        }
        public void JoinCall_Returns404NotFound(string serverCallId, CommunicationIdentifier source, JoinCallOptions joinCallOptions)
        {
            CallingServerClient callingServerClient = CreateMockCallingServerClient(404);

            RequestFailedException?ex = Assert.Throws <RequestFailedException>(() => callingServerClient.JoinCall(serverCallId, source, joinCallOptions));

            Assert.NotNull(ex);
            Assert.AreEqual(ex?.Status, 404);
        }
        public void JoinCallAsync_Returns404NotFound(string serverCallId, CommunicationIdentifier source, JoinCallOptions joinCallOptions)
        {
            CallingServerClient callingServerClient = CreateMockCallingServerClient(404);

            RequestFailedException?ex = Assert.ThrowsAsync <RequestFailedException>(async() => await callingServerClient.JoinCallAsync(serverCallId, source, joinCallOptions).ConfigureAwait(false));

            Assert.NotNull(ex);
            Assert.AreEqual(ex?.Status, 404);
        }
Exemplo n.º 10
0
        internal async Task <IEnumerable <CallConnection> > CreateGroupCallOperation(CallingServerClient callingServerClient, string groupId, string from, string to, string callBackUri)
        {
            CallConnection?fromCallConnection = null;
            CallConnection?toCallConnection   = null;

            try
            {
                CommunicationIdentifier fromParticipant = new CommunicationUserIdentifier(from);
                CommunicationIdentifier toParticipant   = new CommunicationUserIdentifier(to);

                JoinCallOptions fromCallOptions = new JoinCallOptions(
                    new Uri(callBackUri),
                    new MediaType[] { MediaType.Audio },
                    new EventSubscriptionType[] { EventSubscriptionType.ParticipantsUpdated });
                fromCallConnection = await callingServerClient.JoinCallAsync(groupId, fromParticipant, fromCallOptions).ConfigureAwait(false);

                SleepInTest(1000);
                Assert.IsFalse(string.IsNullOrWhiteSpace(fromCallConnection.CallConnectionId));

                JoinCallOptions joinCallOptions = new JoinCallOptions(
                    new Uri(callBackUri),
                    new MediaType[] { MediaType.Audio },
                    new EventSubscriptionType[] { EventSubscriptionType.ParticipantsUpdated });

                toCallConnection = await callingServerClient.JoinCallAsync(groupId, toParticipant, joinCallOptions).ConfigureAwait(false);

                SleepInTest(1000);
                Assert.IsFalse(string.IsNullOrWhiteSpace(toCallConnection.CallConnectionId));

                return(new CallConnection[] { fromCallConnection, toCallConnection });
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine(ex.Message);
                Assert.Fail($"Unexpected error: {ex}");
                throw;
            }
            catch (Exception ex)
            {
                Assert.Fail($"Unexpected error: {ex}");

                if (fromCallConnection != null)
                {
                    await fromCallConnection.HangupAsync().ConfigureAwait(false);
                }

                if (toCallConnection != null)
                {
                    await toCallConnection.HangupAsync().ConfigureAwait(false);
                }
                throw;
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Creates a <see cref="CallingServerClient" />
        /// </summary>
        /// <returns>The instrumented <see cref="CallingServerClient" />.</returns>
        protected CallingServerClient CreateInstrumentedCallingServerClient()
        {
            var connectionString = TestEnvironment.LiveTestStaticConnectionString;
            CallingServerClient callingServerClient = new CallingServerClient(connectionString, CreateServerCallingClientOptionsWithCorrelationVectorLogs());

            #region Snippet:Azure_Communication_ServerCalling_Tests_Samples_CreateServerCallingClient
            //@@var connectionString = "<connection_string>"; // Find your Communication Services resource in the Azure portal
            //@@CallingServerClient callingServerClient = new CallingServerClient(connectionString);
            #endregion Snippet:Azure_Communication_ServerCalling_Tests_Samples_CreateServerCallingClient

            return(InstrumentClient(callingServerClient));
        }
Exemplo n.º 12
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string requestBody = "";

            try
            {
                requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            }
            catch (ArgumentNullException)
            {
                return(new BadRequestObjectResult("null POST body"));
            }

            var request = JsonConvert.DeserializeObject <StartRecordingRequest>(requestBody, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });

            if (request == null)
            {
                return(new BadRequestObjectResult("malformed JSON"));
            }
            if (string.IsNullOrEmpty(request.ServerCallId))
            {
                return(new BadRequestObjectResult("`serverCallId` not set"));
            }

            var callingServerClient = new CallingServerClient(Settings.GetACSConnectionString());
            var serverCall          = callingServerClient.InitializeServerCall(request.ServerCallId);

            string recordingId = "";

            try
            {
                // We don't need status updates about an ongoing call, so we pass in a dummy callback URI.
                var startRecordingResult = await serverCall.StartRecordingAsync(new Uri("http://dummy.uri")).ConfigureAwait(false);

                recordingId = startRecordingResult.Value.RecordingId;
            }
            catch (RequestFailedException e)
            {
                log.LogWarning($"Failed to start recording for {request.ServerCallId}: {e}");
                return(new StatusCodeResult(e.Status));
            }

            log.LogInformation($"Started recording for {request.ServerCallId}: {recordingId}");

            return(new OkObjectResult(JsonConvert.SerializeObject(new StartRecordingResponse {
                RecordingId = recordingId
            })));
        }
        public async Task RunAllRecordingFunctionsScenarioTests(AuthMethod authMethod)
        {
            CallingServerClient callingServerClient = authMethod switch
            {
                AuthMethod.ConnectionString => CreateInstrumentedCallingServerClientWithConnectionString(),
                AuthMethod.TokenCredential => CreateInstrumentedCallingServerClientWithToken(),
                _ => throw new ArgumentOutOfRangeException(nameof(authMethod)),
            };

            var groupId = GetGroupId();

            try
            {
                // Establish a Call
                var callConnections = await CreateGroupCallOperation(callingServerClient, groupId, GetFromUserId(), GetToUserId(), TestEnvironment.AppCallbackUrl).ConfigureAwait(false);

                var serverCall = callingServerClient.InitializeServerCall(groupId);

                // Start Recording
                StartRecordingResult startCallRecordingResult = await serverCall.StartRecordingAsync(new Uri(TestEnvironment.AppCallbackUrl)).ConfigureAwait(false);

                var recordingId = startCallRecordingResult.RecordingId;
                await ValidateCallRecordingStateAsync(serverCall, recordingId, CallRecordingState.Active).ConfigureAwait(false);

                // Pause Recording
                await serverCall.PauseRecordingAsync(recordingId).ConfigureAwait(false);
                await ValidateCallRecordingStateAsync(serverCall, recordingId, CallRecordingState.Inactive).ConfigureAwait(false);

                // Resume Recording
                await serverCall.ResumeRecordingAsync(recordingId).ConfigureAwait(false);
                await ValidateCallRecordingStateAsync(serverCall, recordingId, CallRecordingState.Active).ConfigureAwait(false);

                // Stop Recording
                await serverCall.StopRecordingAsync(recordingId).ConfigureAwait(false);

                // Get Recording StateAsync
                Assert.ThrowsAsync <RequestFailedException>(async() => await serverCall.GetRecordingStateAsync(recordingId).ConfigureAwait(false));

                // Hang up the Call, there is one call leg in this test case, hangup the call will also delete the call as the result.
                await SleepIfNotInPlaybackModeAsync().ConfigureAwait(false);
                await CleanUpConnectionsAsync(callConnections).ConfigureAwait(false);
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine(ex.Message);
                Assert.Fail($"Unexpected error: {ex}");
            }
            catch (Exception ex)
            {
                Assert.Fail($"Unexpected error: {ex}");
            }
        }
Exemplo n.º 14
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string requestBody = "";

            try
            {
                requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            }
            catch (ArgumentNullException)
            {
                return(new BadRequestObjectResult("null POST body"));
            }

            var request = JsonConvert.DeserializeObject <StopRecordingRequest>(requestBody, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });

            if (request == null)
            {
                return(new BadRequestObjectResult("malformed JSON"));
            }
            if (string.IsNullOrEmpty(request.ServerCallId))
            {
                return(new BadRequestObjectResult("`serverCallId` not set"));
            }
            if (string.IsNullOrEmpty(request.RecordingId))
            {
                return(new BadRequestObjectResult("`recordingId` not set"));
            }

            var callingServerClient = new CallingServerClient(Settings.GetACSConnectionString());
            var serverCall          = callingServerClient.InitializeServerCall(request.ServerCallId);

            try
            {
                await serverCall.StopRecordingAsync(request.RecordingId).ConfigureAwait(false);
            }
            catch (RequestFailedException e)
            {
                log.LogWarning($"Failed to stop recording for ({request.ServerCallId}, {request.RecordingId}): {e}");
                return(new StatusCodeResult(e.Status));
            }

            log.LogInformation($"Stopped recording for {request.ServerCallId}: {request.RecordingId}");
            return(new OkResult());
        }
        public async Task RunCreateAddRemoveHangupScenarioTests()
        {
            if (SkipCallingServerInteractionLiveTests)
            {
                Assert.Ignore("Skip callingserver interaction live tests flag is on.");
            }

            CallingServerClient callingServerClient = CreateInstrumentedCallingServerClientWithConnectionString();
            var groupId = GetGroupId();

            try
            {
                // Establish a Call
                var callConnections = await CreateGroupCallOperation(callingServerClient, groupId, GetFromUserId(), GetToUserId(), TestEnvironment.AppCallbackUrl).ConfigureAwait(false);

                var serverCall = callingServerClient.InitializeServerCall(groupId);

                // Add Participant
                await SleepIfNotInPlaybackModeAsync().ConfigureAwait(false);

                var participantId = await AddParticipantOperation(serverCall).ConfigureAwait(false);

                // Remove Participant
                await SleepIfNotInPlaybackModeAsync().ConfigureAwait(false);
                await RemoveParticipantOperation(serverCall, participantId).ConfigureAwait(false);

                // Hang up the Call, there is one call leg in this test case, hangup the call will also delete the call as the result.
                await SleepIfNotInPlaybackModeAsync().ConfigureAwait(false);
                await CleanUpConnectionsAsync(callConnections).ConfigureAwait(false);
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine(ex.Message);
                Assert.Fail($"Unexpected error: {ex}");
            }
            catch (Exception ex)
            {
                Assert.Fail($"Unexpected error: {ex}");
            }
        }
        /// <summary>
        /// Creates a <see cref="CallingServerClient" />.
        /// </summary>
        /// <returns>The instrumented <see cref="CallingServerClient"/>.</returns>
        protected CallingServerClient CreateInstrumentedCallingServerClientWithToken()
        {
            Uri             endpoint = TestEnvironment.LiveTestStaticEndpoint;
            TokenCredential tokenCredential;

            if (Mode == RecordedTestMode.Playback)
            {
                tokenCredential = new MockCredential();
            }
            else
            {
                tokenCredential = new DefaultAzureCredential();
                #region Snippet:Azure_Communication_CallingServer_Tests_Samples_CreateCallingServerClientWithToken
                //@@ var endpoint = new Uri("https://my-resource.communication.azure.com");
                //@@ TokenCredential tokenCredential = new DefaultAzureCredential();
                //@@ var client = new CallingServerClient(endpoint, tokenCredential);
                #endregion Snippet:Azure_Communication_CallingServer_Tests_Samples_CreateCallingServerClientWithToken
            }

            CallingServerClient client = new CallingServerClient(endpoint, tokenCredential, CreateServerCallingClientOptionsWithCorrelationVectorLogs());
            return(InstrumentClient(client));
        }
Exemplo n.º 17
0
        public async Task RunCreateAddRemoveHangupScenarioTests()
        {
            if (SkipCallingServerInteractionLiveTests)
            {
                Assert.Ignore("Skip callingserver interaction live tests flag is on.");
            }

            CallingServerClient client = CreateInstrumentedCallingServerClient();

            try
            {
                // Establish a call
                var callConnection = await CreateCallConnectionOperation(client).ConfigureAwait(false);

                // Add Participant
                await SleepIfNotInPlaybackModeAsync().ConfigureAwait(false);

                var participantId = await AddParticipantOperation(callConnection).ConfigureAwait(false);

                // Remove Participant
                await SleepIfNotInPlaybackModeAsync().ConfigureAwait(false);
                await RemoveParticipantOperation(callConnection, participantId).ConfigureAwait(false);

                // Hang up the Call, there is one call leg in this test case, hangup the call will also delete the call as the result.
                await SleepIfNotInPlaybackModeAsync().ConfigureAwait(false);
                await HangupOperation(callConnection).ConfigureAwait(false);
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine(ex.Message);
                Assert.Fail($"Unexpected error: {ex}");
            }
            catch (Exception ex)
            {
                Assert.Fail($"Unexpected error: {ex}");
            }
        }
Exemplo n.º 18
0
        public async Task RunCreatePlayCancelHangupScenarioTests()
        {
            if (SkipCallingServerInteractionLiveTests)
            {
                Assert.Ignore("Skip callingserver interaction live tests flag is on.");
            }

            CallingServerClient client = CreateInstrumentedCallingServerClient();

            try
            {
                // Establish a Call
                var callConnection = await CreateCallConnectionOperation(client).ConfigureAwait(false);

                // Play Prompt Audio
                await SleepIfNotInPlaybackModeAsync().ConfigureAwait(false);
                await PlayAudioOperation(callConnection).ConfigureAwait(false);

                // Cancel Prompt Audio
                await SleepIfNotInPlaybackModeAsync().ConfigureAwait(false);
                await CancelAllMediaOperationsOperation(callConnection).ConfigureAwait(false);

                // Hang up the Call, there is one call leg in this test case, hangup the call will also delete the call as the result.
                await SleepIfNotInPlaybackModeAsync().ConfigureAwait(false);
                await HangupOperation(callConnection).ConfigureAwait(false);
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine(ex.Message);
                Assert.Fail($"Unexpected error: {ex}");
            }
            catch (Exception ex)
            {
                Assert.Fail($"Unexpected error: {ex}");
            }
        }
Exemplo n.º 19
0
        internal async Task <Response <CallConnection> > CreateCallConnectionOperation(CallingServerClient client)
        {
            CommunicationIdentityClient communicationIdentityClient = CreateInstrumentedCommunicationIdentityClient();
            var source = await CreateUserAsync(communicationIdentityClient).ConfigureAwait(false);

            var targets          = new[] { new PhoneNumberIdentifier(TestEnvironment.TargetPhoneNumber) };
            var createCallOption = new CreateCallOptions(
                new Uri(TestEnvironment.AppCallbackUrl),
                new[] { MediaType.Audio },
                new[] { EventSubscriptionType.ParticipantsUpdated, EventSubscriptionType.DtmfReceived });

            createCallOption.AlternateCallerId = new PhoneNumberIdentifier(TestEnvironment.SourcePhoneNumber);

            Console.WriteLine("Performing CreateCall operation");

            var callConnection = await client.CreateCallConnectionAsync(source : source, targets : targets, options : createCallOption).ConfigureAwait(false);

            Console.WriteLine("Call initiated with Call connection id: {0}", callConnection.Value.CallConnectionId);

            Assert.IsFalse(string.IsNullOrWhiteSpace(callConnection.Value.CallConnectionId));
            return(callConnection);
        }
 public OutboundCallReminder(CallConfiguration callConfiguration)
 {
     this.callConfiguration = callConfiguration;
     callClient             = new CallingServerClient(this.callConfiguration.ConnectionString);
 }
 public Phonecall(string callbackUrl)
 {
     connectionString = Environment.GetEnvironmentVariable("Connectionstring");
     callClient       = new CallingServerClient(connectionString);
     appCallbackUrl   = callbackUrl;
 }