Example #1
0
        /// <summary>
        /// Try to end a particular call.
        /// </summary>
        /// <param name="callLegId">
        /// The call leg id.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public async Task TryDeleteCallAsync(string callLegId)
        {
            CallHandlers.TryGetValue(callLegId, out CallHandler handler);

            if (handler == null)
            {
                return;
            }

            try
            {
                await handler.Call.DeleteAsync().ConfigureAwait(false);

                graphLogger.Info("Delete call finished.");
            }
            catch (Exception ex)
            {
                graphLogger.Error(ex, $"Exception happened when delete the call {callLegId}");

                // in case the call deletion is failed, force remove the call in memory.
                Client.Calls().TryForceRemove(callLegId, out _);

                throw;
            }
        }
        public SampleObserver(IGraphLogger logger)
        {
            // Log unhandled exceptions.
            AppDomain.CurrentDomain.UnhandledException += (_, e) => logger.Error(e.ExceptionObject as Exception, $"Unhandled exception");
            TaskScheduler.UnobservedTaskException      += (_, e) => logger.Error(e.Exception, "Unobserved task exception");

            this.subscription = logger.Subscribe(this);
        }
Example #3
0
        /// <summary>
        /// Creates the video buffers from the provided h264 files.
        /// </summary>
        /// <param name="currentTick">The number of ticks that represent the current date and time.</param>
        /// <param name="videoFormats">The encoded video source formats.</param>
        /// <param name="replayed">If the video frame is being replayed.</param>
        /// <param name="logger">Graph logger.</param>
        /// <returns>The newly created list of <see cref="VideoMediaBuffer"/>.</returns>
        public static List <VideoMediaBuffer> CreateVideoMediaBuffers(
            long currentTick,
            List <VideoFormat> videoFormats,
            bool replayed,
            IGraphLogger logger)
        {
            List <VideoMediaBuffer> videoMediaBuffers = new List <VideoMediaBuffer>();

            try
            {
                foreach (var videoFormat in videoFormats)
                {
                    if (H264Frames.TryGetValue(videoFormat.GetId(), out List <H264Frame> h264Frames))
                    {
                        // create the videoBuffers
                        var packetSizeInMs = (long)((MsInOneSec / videoFormat.FrameRate) * TicksInOneMs);
                        var referenceTime  = currentTick;

                        if (replayed)
                        {
                            referenceTime += packetSizeInMs;
                        }

                        foreach (var h264Frame in h264Frames)
                        {
                            var    frameSize = h264Frame.Size;
                            byte[] buffer    = new byte[frameSize];
                            Marshal.Copy(h264Frame.Data, buffer, 0, (int)frameSize);
                            videoMediaBuffers.Add(new VideoSendBuffer(buffer, (uint)buffer.Length, videoFormat, referenceTime));
                            referenceTime += packetSizeInMs;
                        }
                    }
                    else
                    {
                        logger.Error($"h264FileReader not found for the videoFromat {videoFormat}");
                    }
                }

                logger.Info($"created {videoMediaBuffers.Count} VideoMediaBuffers");
                return(videoMediaBuffers);
            }
            catch (Exception ex)
            {
                logger.Error(ex, $"Failed to create the videoMediaBuffers with exception");
            }

            return(videoMediaBuffers);
        }
        /// <summary>
        /// Extension for Task to execute the task in background and log any exception.
        /// </summary>
        /// <param name="task">Task to execute and capture any exceptions.</param>
        /// <param name="logger">Graph logger.</param>
        /// <param name="description">Friendly description of the task for debugging purposes.</param>
        /// <param name="memberName">Calling function.</param>
        /// <param name="filePath">File name where code is located.</param>
        /// <param name="lineNumber">Line number where code is located.</param>
        /// <returns>
        /// A <see cref="Task" /> representing the asynchronous operation.
        /// </returns>
        public static async Task ForgetAndLogExceptionAsync(
            this Task task,
            IGraphLogger logger,
            string description = null,
            [CallerMemberName] string memberName = null,
            [CallerFilePath] string filePath     = null,
            [CallerLineNumber] int lineNumber    = 0)
        {
            try
            {
                await task.ConfigureAwait(false);

                logger?.Verbose(
                    $"Completed running task successfully: {description ?? string.Empty}",
                    memberName: memberName,
                    filePath: filePath,
                    lineNumber: lineNumber);
            }
            catch (Exception e)
            {
                // Log and absorb all exceptions here.
                logger?.Error(
                    e,
                    $"Caught an Exception running the task: {description ?? string.Empty}",
                    memberName: memberName,
                    filePath: filePath,
                    lineNumber: lineNumber);
            }
        }
        /// <summary>
        /// Boots this instance.
        /// </summary>
        public void Boot()
        {
            DotNetEnv.Env.Load(new DotNetEnv.Env.LoadOptions(parseVariables: false));

            var builder = new ConfigurationBuilder();

            // tell the builder to look for the appsettings.json file
            builder
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables();

            var configuration = builder.Build();

            ServiceCollection = new ServiceCollection();
            ServiceCollection.AddCoreServices(configuration);

            ServiceProvider = ServiceCollection.BuildServiceProvider();

            _logger = Resolve <IGraphLogger>();

            try
            {
                _settings = Resolve <IOptions <AzureSettings> >().Value;
                _settings.Initialize();
                Resolve <IEventPublisher>();
                _botService = Resolve <IBotService>();
            }
            catch (Exception e)
            {
                _logger.Error(e, "Unhandled exception in Boot()");
            }
        }
        /// <summary>
        /// Starts the server.
        /// </summary>
        public void StartServer()
        {
            try
            {
                _botService.Initialize();

                var callStartOptions = new StartOptions();

                foreach (var url in ((AzureSettings)_settings).CallControlListeningUrls)
                {
                    callStartOptions.Urls.Add(url);
                    _logger.Info("Listening on: {url}", url);
                }

                _callHttpServer = WebApp.Start(
                    callStartOptions,
                    (appBuilder) =>
                {
                    var startup = new HttpConfigurationInitializer();
                    startup.ConfigureSettings(appBuilder, _logger);
                });
            }
            catch (Exception e)
            {
                _logger.Error(e, "Unhandled exception in StartServer()");
                throw;
            }
        }
Example #7
0
#pragma warning disable AvoidAsyncVoid // Avoid async void
        /// <summary>
        /// Extension for Task to execute the task in background and log any exception.
        /// </summary>
        /// <param name="task">The task.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="description">The description.</param>
        /// <param name="memberName">Name of the member.</param>
        /// <param name="filePath">The file path.</param>
        /// <param name="lineNumber">The line number.</param>
        public static async void ForgetAndLogException(
            this Task task,
            IGraphLogger logger,
            string description = null,
            [CallerMemberName] string memberName = null,
            [CallerFilePath] string filePath     = null,
            [CallerLineNumber] int lineNumber    = 0)
        {
            try
            {
                await task.ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                description = string.IsNullOrWhiteSpace(description)
                    ? "Exception while executing task."
                    : description;

                logger.Error(
                    ex,
                    description,
                    memberName: memberName,
                    filePath: filePath,
                    lineNumber: lineNumber);
            }
        }
        /// <summary>
        /// Appends the audio buffer.
        /// </summary>
        /// <param name="buffer">The buffer.</param>
        /// <param name="participants">The participants.</param>
        public async Task AppendAudioBuffer(AudioMediaBuffer buffer, List <IParticipant> participants)
        {
            if (!_isRunning)
            {
                await _start();
            }

            try
            {
                await _buffer.SendAsync(new SerializableAudioMediaBuffer(buffer, participants), _tokenSource.Token).ConfigureAwait(false);
            }
            catch (TaskCanceledException e)
            {
                _buffer?.Complete();
                _logger.Error(e, "Cannot enqueue because queuing operation has been cancelled");
            }
        }
Example #9
0
 /// <summary>
 /// Extension for Task to execute the task in background and log any exception.
 /// </summary>
 /// <param name="task">Task to execute and capture any exceptions.</param>
 /// <param name="logger">Graph logger.</param>
 /// <param name="description">Friendly description of the task for debugging purposes.</param>
 /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
 public static async Task ForgetAndLogExceptionAsync(this Task task, IGraphLogger logger, string description = null)
 {
     try
     {
         await task.ConfigureAwait(false);
     }
     catch (Exception e)
     {
         // ignore
         logger.Error(e, $"Caught an Exception running the task: {description ?? string.Empty} {e.Message}\n StackTrace: {e.StackTrace}");
     }
 }
        public async Task <HttpResponseMessage> JoinCallAsync([FromBody] JoinCallBody joinCallBody)
        {
            try
            {
                var call = await _botService.JoinCallAsync(joinCallBody).ConfigureAwait(false);

                var callPath = $"/{HttpRouteConstants.CallRoute.Replace("{callLegId}", call.Id)}";
                var callUri  = $"{_settings.ServiceCname}{callPath}";
                _eventPublisher.Publish("JoinCall", $"Call.id = {call.Id}");

                var values = new JoinURLResponse()
                {
                    Call       = callUri,
                    CallId     = call.Id,
                    ScenarioId = call.ScenarioId
                };

                var serializer = new CommsSerializer(pretty: true);
                var json       = serializer.SerializeObject(values);
                var response   = this.Request.CreateResponse(HttpStatusCode.OK);
                response.Content = new StringContent(json, Encoding.UTF8, "application/json");
                return(response);
            }
            catch (ServiceException e)
            {
                HttpResponseMessage response = (int)e.StatusCode >= 300
                    ? this.Request.CreateResponse(e.StatusCode)
                    : this.Request.CreateResponse(HttpStatusCode.InternalServerError);

                if (e.ResponseHeaders != null)
                {
                    foreach (var responseHeader in e.ResponseHeaders)
                    {
                        response.Headers.TryAddWithoutValidation(responseHeader.Key, responseHeader.Value);
                    }
                }

                response.Content = new StringContent(e.ToString());
                return(response);
            }
            catch (Exception e)
            {
                _logger.Error(e, $"Received HTTP {this.Request.Method}, {this.Request.RequestUri}");
                HttpResponseMessage response = this.Request.CreateResponse(HttpStatusCode.InternalServerError);
                response.Content = new StringContent(e.Message);
                return(response);
            }
        }
        public async Task <IActionResult> JoinCallAsync([FromBody] JoinCallBody joinCallBody)
        {
            try
            {
                var call = await _botService.JoinCallAsync(joinCallBody).ConfigureAwait(false);

                var callPath = $"/{HttpRouteConstants.CallRoute.Replace("{callLegId}", call.Id)}";
                var callUri  = $"{_settings.ServiceCname}{callPath}";

                var values = new JoinURLResponse()
                {
                    Call       = callUri,
                    CallId     = call.Id,
                    ScenarioId = call.ScenarioId,
                    Logs       = callUri.Replace("/calls/", "/logs/")
                };

                var json = JsonConvert.SerializeObject(values);

                return(Ok(values));
            }
            catch (ServiceException e)
            {
                HttpResponseMessage response = (int)e.StatusCode >= 300
                    ? new HttpResponseMessage(e.StatusCode)
                    : new HttpResponseMessage(HttpStatusCode.InternalServerError);

                if (e.ResponseHeaders != null)
                {
                    foreach (var responseHeader in e.ResponseHeaders)
                    {
                        response.Headers.TryAddWithoutValidation(responseHeader.Key, responseHeader.Value);
                    }
                }

                response.Content = new StringContent(e.ToString());
                return(StatusCode(500, e.ToString()));
            }
            catch (Exception e)
            {
                _logger.Error(e, $"Received HTTP {this.Request.Method}, {this.Request.Path.Value}");
                return(StatusCode(500, e.Message));
            }
        }