Exemple #1
0
        public string Transfer()
        {
            // create a logger placeholder
            Logger logger = null;
            var    ncco   = string.Empty;

            try
            {
                logger = NexmoLogger.GetLogger("TransferCallLogger");
                logger.Open();

                using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    var value = reader.ReadToEndAsync();
                    logger.Log("Call transfered answer machine message request content: " + value.Result);

                    // Return NCCO with answer machine message
                    ncco = NexmoApi.AnswerMachineMessageNcco(logger, configuration);
                }
            }
            catch (Exception e)
            {
                logger.Log(Level.Exception, "Transfer Call Exception", e);
            }
            finally
            {
                logger.Close();
                logger.Deregister();
            }

            return(ncco);
        }
Exemple #2
0
        public IActionResult Alarm()
        {
            ViewData["From.FR"] = configuration["appSettings:Nexmo.Application.Number.From.FR"];
            ViewData["From.UK"] = configuration["appSettings:Nexmo.Application.Number.From.UK"];

            // create a logger placeholder
            Logger logger = null;

            try
            {
                logger = NexmoLogger.GetLogger("VoiceAlarmLogger");
                logger.Open();

                // Get an instance of the blob storage to store the phone number to connect to
                CloudBlobContainer container = Storage.GetCloudBlobContainer("vapi-connect-container");
                ViewData["feedback"]  = "Create a blob container if it does not exist: " + container.CreateIfNotExistsAsync().Result.ToString() + " \n";
                ViewData["feedback"] += "The storage container has been loaded successfully. \n";
                logger.Log(container.Name + " has been loaded successfully.");

                var blobUpload = Storage.UploadBlobAsync(container, logger, "{\"recipient\": \"\"}", "alarmAlert");
                ViewData["feedback"] += "The recipient's phone number has been reset successfully.";
                logger.Log("The recipient's phone number has been reset successfully.");
            }
            catch
            {
                ViewData["error"] = "The recipient's phone number could not be reset. Please try again.";
            }
            finally
            {
                logger.Close();
                logger.Deregister();
            }

            return(View());
        }
Exemple #3
0
        public string OnAnswer()
        {
            // create a logger placeholder
            Logger logger = null;
            string ncco   = String.Empty;

            try
            {
                logger = NexmoLogger.GetLogger("OnAnswerVoiceLogger");
                logger.Open();

                var queryString     = Request.QueryString.Value;
                var queryStringList = queryString.Split('&');

                var from     = queryStringList[1].Split('=')[1];
                var uuid     = queryStringList[3].Split('=')[1];
                var con_uuid = queryStringList[2].Split('=')[1];

                logger.Log("On Answer Input Query String: " + queryString);
                ncco = NexmoApi.CallWhisperTalkAction(logger, configuration);
            }
            catch (Exception e)
            {
                logger.Log(Level.Exception, e);
            }
            finally
            {
                logger.Close();
                logger.Deregister();
            }

            return(ncco);
        }
Exemple #4
0
        public string NexmoSMS()
        {
            // create a logger placeholder
            Logger logger        = null;
            var    inboundSMS    = new InboundSmsObject();
            var    messageResult = string.Empty;

            try
            {
                logger = NexmoLogger.GetLogger("MessagingSmsQueueLogger");
                logger.Open();

                var queue   = Storage.CreateQueue("chat", configuration, logger);
                var message = Storage.GetNextMessage(queue, logger);

                if (message != null)
                {
                    messageResult = message.AsString;
                    inboundSMS    = JsonConvert.DeserializeObject <InboundSmsObject>(message.AsString);
                }
            }
            catch (Exception e)
            {
                logger.Log(Level.Exception, e);
                return("Error");
            }

            return(messageResult);
        }
Exemple #5
0
        public HttpResponseMessage Inbound()
        {
            // create a logger placeholder
            Logger logger      = null;
            var    httpRequest = new HttpRequestMessage();

            try
            {
                logger = NexmoLogger.GetLogger("InboundMessagingLogger");
                logger.Open();

                using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    var value    = reader.ReadToEndAsync();
                    var fmObject = JsonConvert.DeserializeObject <FMRootObject>(value.Result);
                    logger.Log("Messaging Inbound body: " + JsonConvert.SerializeObject(fmObject, Formatting.Indented));
                }
            }
            catch (Exception e)
            {
                logger.Log(Level.Exception, e);
                return(httpRequest.CreateResponse(HttpStatusCode.InternalServerError));
            }
            finally
            {
                logger.Close();
                logger.Deregister();
            }

            return(httpRequest.CreateResponse(HttpStatusCode.OK));
        }
Exemple #6
0
        public HttpResponseMessage SmsStatus()
        {
            // create a logger placeholder
            Logger logger      = null;
            var    httpRequest = new HttpRequestMessage();

            try
            {
                logger = NexmoLogger.GetLogger("MessagingSmsStatusLogger");
                logger.Open();

                using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    var value = reader.ReadToEndAsync();
                    logger.Log("Messaging SMS Status update body: " + value.Result);

                    // Add status update to a queue
                    var queue = Storage.CreateQueue("smsstatus", configuration, logger);
                    Storage.InsertMessageInQueue(queue, value.Result, 120, logger);
                }
            }
            catch (Exception e)
            {
                logger.Log(Level.Exception, e);
                return(httpRequest.CreateResponse(System.Net.HttpStatusCode.InternalServerError));
            }
            finally
            {
                logger.Close();
                logger.Deregister();
            }

            return(httpRequest.CreateResponse(System.Net.HttpStatusCode.OK));
        }
Exemple #7
0
        public string InputIvrMachineDetection()
        {
            // create a logger placeholder
            Logger logger = null;
            string ncco   = String.Empty;

            try
            {
                logger = NexmoLogger.GetLogger("InputIvrMachineDetectionVoiceLogger");
                logger.Open();

                using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    var value            = reader.ReadToEndAsync();
                    var voiceInputObject = JsonConvert.DeserializeObject <VoiceInputObject>(value.Result);
                    logger.Log("Voice IVR Machine Detection Input body: " + JsonConvert.SerializeObject(voiceInputObject, Formatting.Indented));
                    ncco = NexmoApi.AnswerVoiceCallInputIvrMachineDetection(voiceInputObject, logger, configuration);
                }
            }
            catch (Exception e)
            {
                logger.Log(Level.Exception, e);
            }
            finally
            {
                logger.Close();
                logger.Deregister();
            }

            return(ncco);
        }
        public string StopRecordingSession()
        {
            // create a logger placeholder
            Logger logger = null;

            var value = string.Empty;
            var stopArchiveRequest = new StopArchiveRequest();

            var apiKey    = configuration["appSettings:OT.Api.Key"];
            var apiSecret = configuration["appSettings:OT.Api.Secret"];

            var openTok = new OpenTok(Convert.ToInt32(apiKey), apiSecret);

            try
            {
                logger = NexmoLogger.GetLogger("OTSessionArchivingLogger");
                logger.Open();

                // Get the session name out of the request body
                using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    value = reader.ReadToEndAsync().Result;
                    stopArchiveRequest = JsonConvert.DeserializeObject <StopArchiveRequest>(value);
                    logger.Log("OpenTok Session Recording end Request body: " + value);
                }

                // Get the archive ID from the session ID
                var blobName = "openTokArchives";
                CloudBlobContainer container    = Storage.GetCloudBlobContainer("opentok-container");
                string             archiveBlobs = Storage.GetBlob(blobName, "opentok-container");
                var archives = JsonConvert.DeserializeObject <List <OpenTokSDK.Archive> >(archiveBlobs);

                if (archives.Count > 0)
                {
                    stopArchiveRequest.archiveId = archives.Where(a => a.SessionId == stopArchiveRequest.sessionId).FirstOrDefault().Id;
                }
                else
                {
                    return("There is no archive for this session.");
                }

                // Start the recording
                var archive = openTok.StopArchive(stopArchiveRequest.archiveId.ToString());

                logger.Log("OpenTok Session archiving ended for session ID: " + archive.SessionId);
                logger.Log("OpenTok Session archiving ended with archive ID: " + archive.Id);

                var archiveId = archive.Id;
                return(archiveId.ToString());
            }
            catch (Exception e)
            {
                logger.Log("OpenTok Error ending archiving the session: " + e.Message);
                logger.Log("OpenTok Error ending archiving the session: " + e.StackTrace);

                return(e.Message);
            }
        }
Exemple #9
0
        public HttpResponseMessage SendSms()
        {
            // create a logger placeholder
            Logger logger      = null;
            var    httpRequest = new HttpRequestMessage();

            try
            {
                logger = NexmoLogger.GetLogger("MessagingSendSmsLogger");
                logger.Open();

                using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    var value         = reader.ReadToEndAsync();
                    var chatSmsObject = JsonConvert.DeserializeObject <ChatSmsObject>(value.Result);
                    logger.Log("Messaging Send SMS Chat body: " + JsonConvert.SerializeObject(chatSmsObject, Formatting.Indented));
                    logger.Log("Messaging Send SMS Chat - The text message entered is: " + chatSmsObject.Text);
                    logger.Log("Messaging Send SMS Chat - The text message recipient is: " + chatSmsObject.To);

                    if (!string.IsNullOrEmpty(chatSmsObject.Text))
                    {
                        var message = new MessagingModel()
                        {
                            Sender = configuration["appSettings:Nexmo.Application.Number.From.UK"],
                            Number = chatSmsObject.To,
                            Text   = chatSmsObject.Text
                        };

                        var smsResults = NexmoApi.SendSMS(message, configuration, "");
                        foreach (SMS.SMSResponseDetail responseDetail in smsResults.messages)
                        {
                            string messageDetails = "SMS sent successfully with messageId: " + responseDetail.message_id;
                            messageDetails += " \n to: " + responseDetail.to;
                            messageDetails += " \n at price: " + responseDetail.message_price;
                            messageDetails += " \n with status: " + responseDetail.status;
                            logger.Log(messageDetails);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                logger.Log(Level.Exception, e);
                return(httpRequest.CreateResponse(HttpStatusCode.InternalServerError));
            }
            finally
            {
                logger.Close();
                logger.Deregister();
            }

            return(httpRequest.CreateResponse(HttpStatusCode.OK));
        }
        public IActionResult Soft(ValidationModel validationModel)
        {
            if (ModelState.IsValid)
            {
                // create a logger
                Logger logger = NexmoLogger.GetLogger("SoftValidationLogger");;

                try
                {
                    if (logger == null)
                    {
                        logger = NexmoLogger.GetLogger("SoftValidationLogger");
                    }
                    logger.Open();

                    NumberInsightAdvancedResponse results = NexmoApi.AdvancedNumberInsightRequest(validationModel, configuration);
                    if (results.Status == "0" && results.NumberValidity == "valid")
                    {
                        logger.Log("Soft validation with NI advanced request successfully created with requestId: " + results.RequestId);
                        var responseObject = JsonConvert.SerializeObject(NexmoApi.GenerateAdvancedObject(results), Formatting.Indented);
                        ViewData["feedback"] = "Thanks " + validationModel.Name + ". We have checked your phone number and your account has been validated. More details: \n" + responseObject;
                    }
                    else if (results.NumberValidity != "valid")
                    {
                        logger.Log("Soft validation with NI advanced request failed with number validity: " + results.NumberValidity + " for requestId: " + results.RequestId);
                        ViewData["feedback"] = "Thanks " + validationModel.Name + ". Unfortunately it seems that the number you provided is invalid. Please try again with a different phone number.";
                    }
                    else
                    {
                        ViewData["error"] = "Your request could not be completed at this time. Please try again later.";
                        logger.Log(Level.Exception, "Response code: " + results.Status + " - Request could not be completed. Request ID: " + results.RequestId + " - Error Text: " + results.ErrorText);
                    }
                }
                catch (Exception e)
                {
                    logger.Log(Level.Exception, e);
                    ViewData["error"] = "There has been an issue dealing with your request. Please try again later.";
                }
                finally
                {
                    if (logger != null)
                    {
                        logger.Close();
                        logger.Deregister();
                    }
                }
            }

            return(View(validationModel));
        }
Exemple #11
0
        public string SendWAFile()
        {
            // create a logger placeholder
            Logger logger          = null;
            var    responseContent = string.Empty;

            try
            {
                logger = NexmoLogger.GetLogger("MessagingSendWAFileLogger");
                logger.Open();

                using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    var value        = reader.ReadToEndAsync();
                    var chatWAObject = JsonConvert.DeserializeObject <FileChatWAObject>(value.Result);
                    logger.Log("Messaging Send WA File Chat - The file message selecgted is: " + chatWAObject.path);

                    if (!string.IsNullOrEmpty(chatWAObject.path))
                    {
                        switch (chatWAObject.type)
                        {
                        case "image":
                            var response = NexmoApi.SendFileMessage(chatWAObject, logger, configuration);
                            responseContent = response.Content.ReadAsStringAsync().Result;
                            break;

                        case "file":
                            break;

                        case "audio":
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                logger.Log(Level.Exception, e);
            }
            finally
            {
                logger.Close();
                logger.Deregister();
            }

            return(responseContent);
        }
Exemple #12
0
        public string SendWA()
        {
            // create a logger placeholder
            Logger logger          = null;
            var    responseContent = string.Empty;

            try
            {
                logger = NexmoLogger.GetLogger("MessagingSendWALogger");
                logger.Open();

                using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    var value        = reader.ReadToEndAsync();
                    var chatWAObject = JsonConvert.DeserializeObject <ChatWAObject>(value.Result);
                    logger.Log("Messaging Send WA Chat body: " + JsonConvert.SerializeObject(chatWAObject, Formatting.Indented));
                    logger.Log("Messaging Send WA Chat - The text message entered is: " + chatWAObject.Text);
                    logger.Log("Messaging Send WA Chat - The text message recipient is: " + chatWAObject.To);

                    if (!string.IsNullOrEmpty(chatWAObject.Text))
                    {
                        var message = new MessagingModel()
                        {
                            Sender      = "447418342149",
                            Number      = chatWAObject.To,
                            Text        = chatWAObject.Text,
                            Type        = "WhatsApp",
                            ContentType = "text"
                        };

                        var response = NexmoApi.SendMessage(message, logger, configuration);
                        responseContent = response.Content.ReadAsStringAsync().Result;
                    }
                }
            }
            catch (Exception e)
            {
                logger.Log(Level.Exception, e);
            }
            finally
            {
                logger.Close();
                logger.Deregister();
            }

            return(responseContent);
        }
Exemple #13
0
        public HttpResponseMessage Status()
        {
            // create a logger placeholder
            Logger logger      = null;
            var    httpRequest = new HttpRequestMessage();

            try
            {
                logger = NexmoLogger.GetLogger("VoiceStatusLogger");
                logger.Open();

                using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    var value      = reader.ReadToEndAsync();
                    var callStatus = JsonConvert.DeserializeObject <CallStatus>(value.Result, new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore
                    });
                    logger.Log("Voice Status update body: " + JsonConvert.SerializeObject(callStatus, Formatting.Indented));

                    // Add status update to a queue
                    var queue = Storage.CreateQueue("voicestatus", configuration, logger);
                    Storage.InsertMessageInQueue(queue, value.Result, 120, logger);

                    if (callStatus.status == "machine")
                    {
                        // Transfer the call to the answer machine message
                        if (NexmoApi.TransferCall(logger, configuration))
                        {
                            return(httpRequest.CreateResponse(System.Net.HttpStatusCode.OK));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                logger.Log(Level.Exception, e);
                return(httpRequest.CreateResponse(System.Net.HttpStatusCode.InternalServerError));
            }
            finally
            {
                logger.Close();
                logger.Deregister();
            }

            return(httpRequest.CreateResponse(System.Net.HttpStatusCode.OK));
        }
        public string RecordSession()
        {
            // create a logger placeholder
            Logger logger = null;

            var value          = string.Empty;
            var archiveRequest = new ArchiveRequest();

            var apiKey    = configuration["appSettings:OT.Api.Key"];
            var apiSecret = configuration["appSettings:OT.Api.Secret"];

            var openTok = new OpenTok(Convert.ToInt32(apiKey), apiSecret);

            try
            {
                logger = NexmoLogger.GetLogger("OTSessionArchivingLogger");
                logger.Open();

                // Get the session name out of the request body
                using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    value          = reader.ReadToEndAsync().Result;
                    archiveRequest = JsonConvert.DeserializeObject <ArchiveRequest>(value);
                    logger.Log("OpenTok Session Recording Request body: " + value);
                }

                // Start the recording
                var archive = openTok.StartArchive(archiveRequest.sessionId);

                logger.Log("OpenTok Session archiving started for session ID: " + archiveRequest.sessionId);
                logger.Log("OpenTok Session archiving started with archive ID: " + archive.Id);
                logger.Log("OpenTok Session archiving started with parameters: " + JsonConvert.SerializeObject(archive, Formatting.Indented));

                // store the archive ID to be able to stop the recording later
                StoreArchiveID(logger, archive);

                var archiveId = archive.Id;
                return(archiveId.ToString());
            }
            catch (Exception e)
            {
                logger.Log("OpenTok Error starting archiving the session: " + e.Message);
                logger.Log("OpenTok Error starting archiving the session: " + e.StackTrace);

                return(e.Message);
            }
        }
Exemple #15
0
        public string Asr()
        {
            // create a logger placeholder
            Logger logger = null;
            string ncco   = String.Empty;

            try
            {
                logger = NexmoLogger.GetLogger("AsrVoiceLogger");
                logger.Open();

                using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    var value = reader.ReadToEndAsync();
                    logger.Log("ASR input raw request content: " + value.Result);
                    var asrInputObject = JsonConvert.DeserializeObject <AsrInputObject>(value.Result);
                    logger.Log("ASR input body: " + JsonConvert.SerializeObject(asrInputObject, Formatting.Indented));

                    var voiceInputObject = new VoiceInputObject()
                    {
                        Conversation_uuid = asrInputObject.conversation_uuid,
                        Uuid      = asrInputObject.uuid,
                        Dtmf      = "1",
                        Timed_out = true,
                        Timestamp = asrInputObject.timestamp
                    };
                    ncco = NexmoApi.AnswerVoiceCallInput(voiceInputObject, logger, configuration);
                }
            }
            catch (Exception e)
            {
                logger.Log(Level.Exception, "ASR Inbound Exception", e);
            }
            finally
            {
                logger.Close();
                logger.Deregister();
            }

            return(ncco);
        }
        public IActionResult Failover(FailoverModel failoverModel)
        {
            // create a logger
            Logger logger = NexmoLogger.GetLogger("FailoverLogger");

            logger.Open();

            if (ModelState.IsValid)
            {
                try
                {
                    // send the message with failover
                    if (NexmoApi.SendDispatchFailover(failoverModel, logger, configuration))
                    {
                        ViewData["feedback"] = "Your message has been sent successfully.";
                    }
                    else
                    {
                        ViewData["error"] = "We could not send your message. Please try again later";
                    }
                }
                catch (Exception e)
                {
                    logger.Log(Level.Exception, e);
                    ViewData["error"] = "There has been an issue dealing with your request. Please try again later.";
                }
                finally
                {
                    logger.Close();
                    logger.Deregister();
                }
            }
            else
            {
                logger.Log(Level.Warning, "Model State: " + ModelState.ValidationState);
                logger.Log(Level.Warning, "Model State Values: " + ModelState.Values);
            }

            return(View());
        }
Exemple #17
0
        public IActionResult Index(VoiceModel voiceModel)
        {
            ViewData["From.FR"] = configuration["appSettings:Nexmo.Application.Number.From.FR"];
            ViewData["From.UK"] = configuration["appSettings:Nexmo.Application.Number.From.UK"];

            if (ModelState.IsValid)
            {
                // create a logger placeholder
                Logger logger = null;

                try
                {
                    logger = NexmoLogger.GetLogger("TTSLogger");
                    logger.Open();

                    if (NexmoApi.MakeBasicTTSCall(voiceModel, logger, configuration))
                    {
                        ViewData["feedback"] = "Your phone call is starting now...";
                    }
                    else
                    {
                        ViewData["error"] = "Your request could not be connected at this time. Please try again later.";
                    }
                }
                catch (Exception e)
                {
                    logger.Log(Level.Exception, e);
                    ViewData["error"] = "There has been an issue dealing with your request. Please try again later.";
                }
                finally
                {
                    logger.Close();
                    logger.Deregister();
                }
            }

            return(View());
        }
Exemple #18
0
        public HttpResponseMessage WAInbound()
        {
            // create a logger placeholder
            Logger logger      = null;
            var    httpRequest = new HttpRequestMessage();

            try
            {
                logger = NexmoLogger.GetLogger("InboundMessagingLogger");
                logger.Open();

                using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    var value           = reader.ReadToEndAsync();
                    var waInboundObject = JsonConvert.DeserializeObject <InboundWAObject>(value.Result);
                    logger.Log("Messaging WA Inbound body: " + JsonConvert.SerializeObject(waInboundObject, Formatting.Indented));

                    // Add the message in a queue to be processed in the wa chat demo
                    var queue = Storage.CreateQueue("wachat", configuration, logger);
                    Storage.InsertMessageInQueue(queue, JsonConvert.SerializeObject(waInboundObject), 3000, logger);

                    logger.Log(Level.Warning, "Messaging SMS Inbound added to the queue: " + JsonConvert.SerializeObject(waInboundObject, Formatting.Indented));
                }
            }
            catch (Exception e)
            {
                logger.Log(Level.Exception, e);
                return(httpRequest.CreateResponse(HttpStatusCode.InternalServerError));
            }
            finally
            {
                logger.Close();
                logger.Deregister();
            }

            return(httpRequest.CreateResponse(HttpStatusCode.OK));
        }
        public HttpResponseMessage SessionMonitoring()
        {
            // create a logger placeholder
            Logger logger       = null;
            var    httpRequest  = new HttpRequestMessage();
            string sessionEvent = String.Empty;

            try
            {
                logger = NexmoLogger.GetLogger("SessionMonitoringLogger");
                logger.Open();

                using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    var value = reader.ReadToEndAsync();
                    sessionEvent = value.Result;
                    logger.Log("OpenTok Session Monitoring body: " + JsonConvert.SerializeObject(sessionEvent, Formatting.Indented));

                    // Add status update to a queue
                    var queue = Storage.CreateQueue("videomonitoring", configuration, logger);
                    Storage.InsertMessageInQueue(queue, sessionEvent, 120, logger);
                }
            }
            catch (Exception e)
            {
                logger.Log(Level.Exception, e);
                return(httpRequest.CreateResponse(System.Net.HttpStatusCode.InternalServerError));
            }
            finally
            {
                logger.Close();
                logger.Deregister();
            }

            return(httpRequest.CreateResponse(System.Net.HttpStatusCode.OK));
        }
        public string CreateSession()
        {
            // create a logger placeholder
            Logger logger = null;

            var httpRequest               = new HttpRequestMessage();
            var value                     = string.Empty;
            var blobName                  = "openTokSessions";
            var sessionName               = new SessionName();
            var sessionExist              = false;
            var clientSession             = new ClientSession();
            List <ClientSession> sessions = new List <ClientSession>();

            var apiKey    = configuration["appSettings:OT.Api.Key"];
            var apiSecret = configuration["appSettings:OT.Api.Secret"];

            var openTok = new OpenTok(Convert.ToInt32(apiKey), apiSecret);

            try
            {
                logger = NexmoLogger.GetLogger("OTSessionLogger");
                logger.Open();

                // Get the session name out of the request body
                using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    value       = reader.ReadToEndAsync().Result;
                    sessionName = JsonConvert.DeserializeObject <SessionName>(value);
                    logger.Log("OpenTok Session Creation Request body: " + value);
                }

                // Check if the session name already exists
                // Get an instance of the blob storage to store the session data
                CloudBlobContainer container = Storage.GetCloudBlobContainer("opentok-container");
                logger.Log("Blob container created if it does not exist: " + container.CreateIfNotExistsAsync().Result.ToString());

                string sessionBlobs = Storage.GetBlob(blobName, "opentok-container");
                if (sessionBlobs.StartsWith('['))
                {
                    sessions = JsonConvert.DeserializeObject <List <ClientSession> >(sessionBlobs);
                }
                else if (sessionBlobs.StartsWith('{'))
                {
                    sessions.Add(JsonConvert.DeserializeObject <ClientSession>(sessionBlobs));
                }

                if (sessions.Count > 0)
                {
                    foreach (ClientSession sessionBlob in sessions)
                    {
                        if (sessionBlob.Name == sessionName.Name)
                        {
                            sessionExist  = true;
                            clientSession = sessionBlob;

                            // Create an opentok token
                            clientSession.Token = openTok.GenerateToken(sessionBlob.Id);

                            var clientSessionJsonFormatted = JsonConvert.SerializeObject(clientSession, Formatting.Indented);
                            logger.Log("OpenTok Client Session already exist: " + clientSessionJsonFormatted);
                        }
                    }
                }

                if (!sessionExist)
                {
                    // Create an opentok session
                    var session = openTok.CreateSession("", MediaMode.ROUTED, ArchiveMode.MANUAL);

                    clientSession.ApiKey      = session.ApiKey.ToString();
                    clientSession.ApiSecret   = session.ApiSecret;
                    clientSession.ArchiveMode = session.ArchiveMode.ToString();
                    clientSession.Id          = session.Id;
                    clientSession.Location    = session.Location;
                    clientSession.MediaMode   = session.MediaMode.ToString();
                    clientSession.Name        = sessionName.Name;
                    // Create an opentok token
                    clientSession.Token = session.GenerateToken();

                    // Add the session to the blobs to be uploaded
                    sessions.Add(clientSession);

                    logger.Log("OpenTok Session created with session ID: " + session.Id);
                    logger.Log("OpenTok Session object: " + JsonConvert.SerializeObject(session, Formatting.Indented));
                    logger.Log("OpenTok Client Session Object generated with token: " + JsonConvert.SerializeObject(clientSession, Formatting.Indented));

                    NexmoApi.StoreOpenTokData("opentok-container", logger, JsonConvert.SerializeObject(sessions), blobName);
                }


                var clientSessionJson = JsonConvert.SerializeObject(clientSession);
                return(clientSessionJson);
            }
            catch (Exception e)
            {
                logger.Log("OpenTok Error creating a session: " + e.Message);
                logger.Log("OpenTok Error creating a session: " + e.StackTrace);

                return(e.Message);
            }
        }
        public IActionResult Index(RegistrationModel viewModel, string verifyAction)
        {
            if (ModelState.IsValid)
            {
                // create a logger
                Logger logger = NexmoLogger.GetLogger("RegistrationLogger");;

                try
                {
                    if (verifyAction == "Register")
                    {
                        if (logger == null)
                        {
                            logger = NexmoLogger.GetLogger("RegistrationLogger");
                        }
                        logger.Open();

                        if (string.IsNullOrEmpty(viewModel.PinCode) && viewModel.Workflow == "1")
                        {
                            var results = NexmoApi.SendVerifyRequest(viewModel, logger, configuration);
                            if (results.status == "0")
                            {
                                logger.Log("Verify request successfully created with requestId: " + results.request_id);
                                ViewData["feedback"]           = "Thanks " + viewModel.Name + ". We have sent a verification code to the number you provided.";
                                ViewData["requestId"]          = results.request_id;
                                ViewData["number"]             = viewModel.Number;
                                ViewData["model"]              = "0";
                                ViewData["RegistrationStatus"] = "started";
                            }
                            else if (results.status == "10")
                            {
                                ViewData["warning"] = "Please wait for the previous request to complete, then try again.";
                                logger.Log(Level.Warning, "Response code: " + results.status + " - Concurrent verifications to the same number are not allowed. Request ID: " + results.request_id);
                            }
                            else
                            {
                                ViewData["error"] = "Your request could not be created at this time. Please try again later.";
                                logger.Log(Level.Warning, "Response code: " + results.status + " - Request could not be completed. Request ID: " + results.request_id + " - Error Text: " + results.error_text);
                            }
                        }
                        else
                        {
                            // If a different workflow than the default has been selected but the PIN code is not generated in the UI
                            // then generate a random PIN
                            if (string.IsNullOrEmpty(viewModel.PinCode))
                            {
                                var    random = new Random();
                                string pin    = random.Next(0, 9).ToString();
                                pin += random.Next(0, 9).ToString();
                                pin += random.Next(0, 9).ToString();
                                pin += random.Next(0, 9).ToString();
                                pin += random.Next(0, 9).ToString();
                                pin += random.Next(0, 9).ToString();
                                pin += random.Next(0, 9).ToString();
                                pin += random.Next(0, 9).ToString();
                                pin += random.Next(0, 9).ToString();
                                pin += random.Next(0, 9).ToString();

                                viewModel.PinCode = pin;
                            }

                            var results  = NexmoApi.VerifyRequest(viewModel, logger, configuration);
                            var response = JsonConvert.DeserializeObject <VerifyResponse>(results);

                            if (response.status == "0")
                            {
                                logger.Log("Verify request successfully created with requestId: " + response.request_id);
                                ViewData["feedback"]           = "Thanks " + viewModel.Name + ". We have sent a verification code to the number you provided.";
                                ViewData["requestId"]          = response.request_id;
                                ViewData["number"]             = viewModel.Number;
                                ViewData["model"]              = "2";
                                ViewData["RegistrationStatus"] = "started";
                            }
                            else if (response.status == "10")
                            {
                                ViewData["warning"] = "Please wait for the previous request to complete, then try again.";
                                logger.Log(Level.Warning, "Response code: " + response.status + " - Concurrent verifications to the same number are not allowed. Request ID: " + response.request_id);
                            }
                            else
                            {
                                ViewData["error"] = "Your request could not be created at this time. Please try again later.";
                                logger.Log(Level.Warning, "Response code: " + response.status + " - Request could not be completed. Request ID: " + response.request_id + " - Error Text: " + response.error_text);
                            }
                        }
                    }
                    else if (verifyAction == "Check")
                    {
                        if (logger == null)
                        {
                            logger = NexmoLogger.GetLogger("RegistrationLogger");
                        }
                        logger.Open();

                        string pinCode   = viewModel.PinCode;
                        string requestId = viewModel.RequestId;
                        string number    = viewModel.Recipient;
                        var    results   = new NumberVerify.CheckResponse();

                        if (viewModel.Model == "2") // pay per request pricing model
                        {
                            results = NexmoApi.CheckVerify(viewModel, logger, configuration, requestId);
                        }
                        else
                        {
                            results = NexmoApi.CheckVerifyRequest(viewModel, logger, configuration, requestId);
                        }

                        // log the request response for future debugging
                        string response = "Response returned with status code: " + results.status;
                        response += " and error text: " + results.error_text;
                        response += " and price: " + results.price + " " + results.currency;
                        response += " and eventId: " + results.event_id;
                        logger.Log(response);

                        if (results.status == "0")
                        {
                            // provide feedback on the page
                            ViewData["feedback"] = "Your code has been successfully verified.";
                            logger.Log("PIN code: " + pinCode + " successfully verified. We have sent an confirmation message to the number provided.");
                            ViewData["RegistrationStatus"] = "completed";

                            // send confirmation message
                            var messagingModel = new MessagingModel()
                            {
                                Sender = viewModel.Name,
                                Number = viewModel.Number,
                                Text   = "Your account has been created successfully. You can access it here: http://dashboard.nexmo.com"
                            };
                            var smsResults = NexmoApi.SendSMS(messagingModel, configuration, "60");
                            foreach (SMS.SMSResponseDetail responseDetail in smsResults.messages)
                            {
                                string messageDetails = "SMS sent successfully with messageId: " + responseDetail.message_id;
                                messageDetails += " for Verify requestId: " + requestId;
                                messageDetails += " to: " + responseDetail.to;
                                messageDetails += " at price: " + responseDetail.message_price;
                                messageDetails += " with status: " + responseDetail.status;
                                logger.Log(messageDetails);
                            }
                        }
                        else
                        {
                            ViewData["warning"] = "Your code could not be verified. Please try again.";
                            logger.Log(Level.Warning, "The code could not be verified with status: " + results.status + " and message: " + results.error_text);
                            ViewData["RegistrationStatus"] = "started";
                        }
                    }
                }
                catch (Exception e)
                {
                    logger.Log(Level.Exception, e);
                    ViewData["error"] = "There has been an issue dealing with your request. Please try again later.";
                }
                finally
                {
                    if (logger != null)
                    {
                        logger.Close();
                        logger.Deregister();
                    }
                }
            }

            return(View(viewModel));
        }
        public IActionResult Index(MessagingModel messagingModel)
        {
            if (ModelState.IsValid)
            {
                // create a logger placeholder
                Logger logger = null;

                try
                {
                    logger = NexmoLogger.GetLogger("MessagingLogger");
                    logger.Open();

                    // TODO: Update the content type based on content send (e.g. video, audio, text, etc...)
                    messagingModel.ContentType = "text";

                    switch (messagingModel.Type)
                    {
                    case "WhatsApp":
                        messagingModel.TemplateName = "whatsapp:hsm:technology:nexmo:simplewelcome";
                        if (NexmoApi.SendMessage(messagingModel, logger, configuration).IsSuccessStatusCode)
                        {
                            ViewData["feedback"] = "Your " + messagingModel.Type + " message was sent succesfully.";
                        }
                        else
                        {
                            ViewData["error"] = "We could not send your " + messagingModel.Type + " message. Please try again later.";
                        }
                        break;

                    case "Viber":
                        break;

                    case "Facebook Messenger":
                        break;

                    default:
                        var smsResults = NexmoApi.SendSMS(messagingModel, configuration, "");
                        foreach (SMS.SMSResponseDetail responseDetail in smsResults.messages)
                        {
                            string messageDetails = "SMS sent successfully with messageId: " + responseDetail.message_id;
                            messageDetails += " \n to: " + responseDetail.to;
                            messageDetails += " \n at price: " + responseDetail.message_price;
                            messageDetails += " \n with status: " + responseDetail.status;
                            logger.Log(messageDetails);
                            ViewData["feedback"] = messageDetails;
                        }

                        break;
                    }
                }
                catch (Exception e)
                {
                    logger.Log(Level.Exception, e);
                    ViewData["error"] = "There has been an issue dealing with your request. Please try again later.";
                }
                finally
                {
                    logger.Close();
                    logger.Deregister();
                }
            }

            return(View());
        }
Exemple #23
0
        public HttpResponseMessage SmsInbound()
        {
            // create a logger placeholder
            Logger logger      = null;
            var    httpRequest = new HttpRequestMessage();

            try
            {
                logger = NexmoLogger.GetLogger("InboundMessagingSmsLogger");
                logger.Open();

                using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    var value       = reader.ReadToEndAsync();
                    var moSmsObject = JsonConvert.DeserializeObject <InboundSmsObject>(value.Result);
                    logger.Log("Messaging SMS Inbound body: " + JsonConvert.SerializeObject(moSmsObject, Formatting.Indented));
                    logger.Log("Messaging SMS Inbound - The text message entered is: " + moSmsObject.text);
                    logger.Log("Messaging SMS Inbound - The text message reciptient is: " + moSmsObject.to);

                    if (moSmsObject.to == configuration["appSettings:Nexmo.Application.Number.From.FR"] || moSmsObject.to == configuration["appSettings:Nexmo.Application.Number.From.UK"])
                    {
                        if (moSmsObject.text.ToLower().Trim() == "trigger")
                        {
                            VoiceModel voiceModel = new VoiceModel()
                            {
                                From = moSmsObject.to,
                                To   = moSmsObject.msisdn
                            };

                            var alertNcco = NexmoApi.MakeAlertTTSCall(voiceModel, logger, configuration);
                            if (alertNcco)
                            {
                                httpRequest.CreateResponse(HttpStatusCode.UnprocessableEntity);
                            }
                        }
                        else if (moSmsObject.text.ToLower().Trim() == "rob")
                        {
                            var result = NexmoApi.MakeIvrCallWithMachineDetection(moSmsObject.text, logger, configuration);
                        }
                        else if (moSmsObject.text.ToLower().Trim() == "mason")
                        {
                            var result = NexmoApi.MakeIvrCallWithMachineDetection(moSmsObject.text, logger, configuration);
                        }
                        else if (moSmsObject.text.ToLower().Trim() == "kaine")
                        {
                            var result = NexmoApi.MakeIvrCallWithMachineDetection(moSmsObject.text, logger, configuration);
                        }
                        else if (moSmsObject.text.ToLower().Trim() == "perry")
                        {
                            var result = NexmoApi.MakeIvrCallWithMachineDetection(moSmsObject.text, logger, configuration);
                        }
                        else if (moSmsObject.text.ToLower().Trim() == "jpc")
                        {
                            var result = NexmoApi.MakeIvrCallWithMachineDetection(moSmsObject.text, logger, configuration);
                        }
                        else
                        {
                            // Add the message in a queue to be processed in the chat demo
                            var queue = Storage.CreateQueue("chat", configuration, logger);
                            Storage.InsertMessageInQueue(queue, JsonConvert.SerializeObject(moSmsObject), 3000, logger);

                            logger.Log(Level.Warning, "Messaging SMS Inbound added to the queue: " + JsonConvert.SerializeObject(moSmsObject, Formatting.Indented));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                logger.Log(Level.Exception, e);
                return(httpRequest.CreateResponse(HttpStatusCode.InternalServerError));
            }
            finally
            {
                logger.Close();
                logger.Deregister();
            }

            return(httpRequest.CreateResponse(HttpStatusCode.OK));
        }
        public IActionResult Index(ValidationModel validationModel)
        {
            if (ModelState.IsValid)
            {
                // create a logger placeholder
                Logger logger = null;

                try
                {
                    logger = NexmoLogger.GetLogger("ValidationLogger");
                    logger.Open();

                    switch (validationModel.Version)
                    {
                    case "basic":
                        NumberInsightBasicResponse response = NexmoApi.BasicNumberInsightRequest(validationModel, configuration);

                        if (response.Status == "0")
                        {
                            var responseObject = JsonConvert.SerializeObject(NexmoApi.GenerateBasicObject(response), Formatting.Indented);
                            logger.Log("Request ID: " + response.RequestId + " has completed successfully with status code: " + response.Status + " and status text: " + response.StatusMessage);
                            ViewData["feedback"] = "Your request completed successfully. Please see below the response: \n" + responseObject;
                        }
                        break;

                    case "standard":
                        NumberInsightStandardResponse standardResponse = NexmoApi.StandardNumberInsightRequest(validationModel, configuration);

                        if (standardResponse.Status == "0")
                        {
                            var responseObject = JsonConvert.SerializeObject(NexmoApi.GenerateStandardObject(standardResponse), Formatting.Indented);
                            logger.Log("Request ID: " + standardResponse.RequestId + " has completed successfully with status code: " + standardResponse.Status + " and status text: " + standardResponse.StatusMessage);
                            ViewData["feedback"] = "Your request completed successfully. Please see below the response: \n" + responseObject;
                        }
                        break;

                    case "advanced":
                        NumberInsightAdvancedResponse advancedResponse = NexmoApi.AdvancedNumberInsightRequest(validationModel, configuration);

                        if (advancedResponse.Status == "0")
                        {
                            var responseObject = JsonConvert.SerializeObject(NexmoApi.GenerateAdvancedObject(advancedResponse), Formatting.Indented);
                            logger.Log("Request ID: " + advancedResponse.RequestId + " has completed successfully with status code: " + advancedResponse.Status + " and status text: " + advancedResponse.StatusMessage);
                            ViewData["feedback"] = "Your request completed successfully. Please see below the response: \n" + responseObject;
                        }
                        break;
                    }
                }
                catch (Exception e)
                {
                    logger.Log(Level.Exception, e);
                    ViewData["error"] = "There has been an issue dealing with your request. Please try again later.";
                }
                finally
                {
                    logger.Close();
                    logger.Deregister();
                }
            }

            return(View());
        }