Inheritance: INotifyPropertyChanged, ISIPAsset
        public DialPlanDetailsControl(
            DetailsControlModesEnum mode, 
            SIPDialPlan dialPlan, 
            string owner,
            DialPlanUpdateDelegate dialPlanAdd, 
            DialPlanUpdateDelegate dialPlanUpdate, 
            ControlClosedDelegate closed)
        {
            InitializeComponent();

            m_detailsMode = mode;
            m_owner = owner;
            m_dialPlan = dialPlan;

            DialPlanAdd_External = dialPlanAdd;
            DialPlanUpdate_External = dialPlanUpdate;
            ControlClosed_External = closed;

            if (mode == DetailsControlModesEnum.Edit)
            {
                m_applyButton.Content = "Update";
                PopulateDataFields(m_dialPlan);
            }
            else
            {
                m_dialPlanIdCanvas.Visibility = Visibility.Collapsed;
                m_applyButton.Content = "Add";
            }
        }
        private void PopulateDataFields(SIPDialPlan dialPlan)
        {
            m_dialPlanId.Text = dialPlan.Id.ToString();
            m_dialPlanName.Text = dialPlan.DialPlanName;
            m_dialPlanTraceEmailAddress.Text = (dialPlan.TraceEmailAddress != null) ? dialPlan.TraceEmailAddress : String.Empty;
            m_dialPlanText.Text = dialPlan.DialPlanScript;

            if(dialPlan.ScriptType == SIPDialPlanScriptTypesEnum.Asterisk)
            {
                m_dialPlanTypeExtension.IsChecked = true;
            }
        }
 public DialPlanScriptContext(           
     SIPMonitorLogDelegate monitorLogDelegate,
     SIPTransport sipTransport,
     DialogueBridgeCreatedDelegate createBridge,
     SIPEndPoint outboundProxy,
     ISIPServerUserAgent sipServerUserAgent,
     SIPDialPlan dialPlan,
     List<SIPProvider> sipProviders,
     string traceDirectory,
     string callersNetworkId,
     Guid customerId)
     : base(monitorLogDelegate, sipTransport, createBridge, outboundProxy, sipServerUserAgent, dialPlan, sipProviders, traceDirectory, callersNetworkId, customerId)
 {
     ContextType = DialPlanContextsEnum.Script;
 }
 public DialPlanLineContext(
     SIPMonitorLogDelegate monitorLogDelegate,
     SIPTransport sipTransport,
     DialogueBridgeCreatedDelegate createBridge,
     SIPEndPoint outboundProxy,
     ISIPServerUserAgent sipServerUserAgent,
     SIPDialPlan dialPlan,
     List<SIPProvider> sipProviders,
     string traceDirectory,
     string callersNetworkId,
     Customer customer)
     : base(monitorLogDelegate, sipTransport, createBridge, outboundProxy, sipServerUserAgent, dialPlan, sipProviders, traceDirectory, callersNetworkId, customer, null, null)
 {
     ContextType = DialPlanContextsEnum.Line;
      string[] dialPlanEntries = dialPlan.DialPlanScript.Split(new char[] { '\n' });
      ParseDialPlan(dialPlanEntries);
 }
 private void DialPlansPanel_Add()
 {
     m_selectedDialPlan = null;
     m_addControl = new DialPlanDetailsControl(DetailsControlModesEnum.Add, m_selectedDialPlan, m_owner, AddDialPlan, null, DetailsControlClosed);
     m_dialPlansPanel.SetDetailsElement(m_addControl);
 }
        private List<ISIPClientUserAgent> m_uacWaitingForCallDetails = new List<ISIPClientUserAgent>(); // UACs can indicate they would like the call details when available.

        #endregion Fields

        #region Constructors

        public DialPlanContext(
            SIPMonitorLogDelegate monitorLogDelegate,
            SIPTransport sipTransport,
            DialogueBridgeCreatedDelegate createBridge,
            SIPEndPoint outboundProxy,
            ISIPServerUserAgent sipServerUserAgent,
            SIPDialPlan dialPlan,
            List<SIPProvider> sipProviders,
            string traceDirectory,
            string callersNetworkId,
            Guid customerId)
        {
            Log_External = monitorLogDelegate;
            CreateBridge_External = createBridge;
            m_sipTransport = sipTransport;
            m_outboundProxy = outboundProxy;
            m_sipServerUserAgent = sipServerUserAgent;
            m_dialPlan = dialPlan;
            m_sipProviders = sipProviders;
            m_traceDirectory = traceDirectory;
            CallersNetworkId = callersNetworkId;
            CustomerId = customerId;

            m_sipServerUserAgent.CallCancelled += ClientCallCancelled;
            m_sipServerUserAgent.NoRingTimeout += ClientCallNoRingTimeout;
            m_sipServerUserAgent.TransactionComplete += ClientTransactionRemoved;
            m_sipServerUserAgent.SetTraceDelegate(TransactionTraceMessage);
        }
 public abstract void AddDialPlanAsync(SIPDialPlan dialPlan);
        public SIPDialPlan UpdateDialPlan(SIPDialPlan dialPlan)
        {
            Customer customer = AuthoriseRequest();

            if (customer.AdminId != Customer.TOPLEVEL_ADMIN_ID && dialPlan.Owner != customer.CustomerUsername) {
                throw new ApplicationException("You are not authorised to update the Dial Plan.");
            }

            return DialPlanPersistor.Update(dialPlan);
        }
Example #9
0
            public void CommentOnLineTest()
            {
                Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

                string testDialPlan = @"
                    exten => 100,1,Switch(anonymous.invalid, password, [email protected]) ; Comment
                    exten => 101,1,Switch(""username"", ""password"", ""[email protected])
                ";

                SIPDialPlan dialPlan = new SIPDialPlan(null, null, null, testDialPlan, SIPDialPlanScriptTypesEnum.Asterisk);
                DialPlanLineContext dialPlanContext = new DialPlanLineContext(null, null, null, null, null, dialPlan, null, null, null);

                Console.WriteLine("dst=" + dialPlanContext.m_commands[0].Destination + ", data=" + dialPlanContext.m_commands[0].Data + ".");
                Console.WriteLine("dst=" + dialPlanContext.m_commands[1].Destination + ", data=" + dialPlanContext.m_commands[1].Data + ".");

                Assert.IsTrue(dialPlanContext.m_commands.Count == 2, "The dial plan was not correctly parsed.");
                Assert.IsTrue(dialPlanContext.m_commands[0].Command == "Switch", "The dial plan command was not correct.");
                Assert.IsTrue(dialPlanContext.m_commands[0].Data == "anonymous.invalid, password, [email protected]", "The dial plan data was not correct.");

                Console.WriteLine("---------------------------------");
            }
        private void Add()
        {
            if (m_dialPlanName.Text.Trim().Length == 0)
            {
                WriteStatusMessage(MessageLevelsEnum.Warn, "The Dial Plan Name cannot be empty.");
            }
            else
            {
                SIPDialPlanScriptTypesEnum scriptType = (m_dialPlanTypeRuby.IsChecked.Value) ? SIPDialPlanScriptTypesEnum.Ruby : SIPDialPlanScriptTypesEnum.Asterisk;

                string dialPlanText = (m_dialPlanText.Text != null) ? Regex.Replace(m_dialPlanText.Text.Trim(), "\r([^\n])", "\r\n${1}") : null;
                SIPDialPlan dialPlan = new SIPDialPlan(m_owner, m_dialPlanName.Text.Trim(), m_dialPlanTraceEmailAddress.Text.Trim(), dialPlanText, scriptType);

                WriteStatusMessage(MessageLevelsEnum.Info, "Adding Dial Plan please wait...");

                DialPlanAdd_External(dialPlan);
            }
        }
        private void DialPlansDataGrid_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            try
            {
                if (!m_dialPlansPanelRefreshInProgress && m_dialPlans != null && m_dialPlans.Count > 0)
                {
                    DataGrid dataGrid = (DataGrid)sender;
                    if (dataGrid.CurrentColumn.Header as string != "Delete")
                    {
                        SIPDialPlan dialPlan = (SIPDialPlan)m_dialPlansDataGrid.SelectedItem;

                        if (m_selectedDialPlan == null || m_selectedDialPlan != dialPlan)
                        {
                            m_selectedDialPlan = dialPlan;
                            m_editControl = new DialPlanDetailsControl(DetailsControlModesEnum.Edit, m_selectedDialPlan, m_owner, null, UpdateDialPlan, DetailsControlClosed);
                            m_dialPlansPanel.SetDetailsElement(m_editControl);
                        }
                    }
                }
            }
            catch (Exception excp)
            {
                LogActivityMessage_External(MessageLevelsEnum.Error, "Exception showing DialPlan details. " + excp.Message);
                m_selectedDialPlan = null;
            }
        }
Example #12
0
            public void SingleZMatchDialPlanTest()
            {
                Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

                string testDialPlan = "exten => _3Z.,1,Switch(anon, password, [email protected])";

                SIPDialPlan dialPlan = new SIPDialPlan(null, null, null, testDialPlan, SIPDialPlanScriptTypesEnum.Asterisk);
                SIPRequest request = new SIPRequest(SIPMethodsEnum.INVITE, SIPURI.ParseSIPURI("sip:[email protected]"));
                DialPlanLineContext dialPlanContext = new DialPlanLineContext(null, null, null, null, null, dialPlan, null, null, null);
                DialPlanCommand commandMatch = dialPlanContext.GetDialPlanMatch(request);

                Assert.IsNotNull(commandMatch, "The dial plan should have returned a match.");

                Console.WriteLine("---------------------------------");
            }
Example #13
0
            public void SimpleDialPlanTest()
            {
                Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

                string testDialPlan = @"
                    exten => 100,1,Switch(""anonymous.invalid"", ""password"", ""*****@*****.**"")
                    exten => 101,1,Switch(""username"", ""password"", ""*****@*****.**"")
                ";

                SIPDialPlan dialPlan = new SIPDialPlan(null, null, null, testDialPlan, SIPDialPlanScriptTypesEnum.Asterisk);
                DialPlanLineContext dialPlanContext = new DialPlanLineContext(null, null, null, null, null, dialPlan, null, null, null);

                Console.WriteLine("dst=" + dialPlanContext.m_commands[0].Destination + ", data=" + dialPlanContext.m_commands[0].Data + ".");
                Console.WriteLine("dst=" + dialPlanContext.m_commands[1].Destination + ", data=" + dialPlanContext.m_commands[1].Data + ".");

                Assert.IsTrue(dialPlanContext.m_commands.Count == 2, "The dial plan was not correctly parsed.");
                Assert.IsTrue(dialPlanContext.m_commands[0].Operation == DialPlanOpsEnum.Equals, "Command 1 oeration not correct.");
                Assert.IsTrue(dialPlanContext.m_commands[1].Operation == DialPlanOpsEnum.Equals, "Command 2 oeration not correct.");
                Assert.IsTrue(dialPlanContext.m_commands[0].Destination == "100", "Command 1 destination not correct.");
                Assert.IsTrue(dialPlanContext.m_commands[1].Destination == "101", "Command 2 destination not correct.");
                Assert.IsTrue(dialPlanContext.m_commands[0].Command == "Switch", "Command 1 command not correct.");
                Assert.IsTrue(dialPlanContext.m_commands[1].Command == "Switch", "Command 2 command not correct.");
                Assert.IsTrue(dialPlanContext.m_commands[0].Data == "\"anonymous.invalid\", \"password\", \"[email protected]\"", "Command 1 data not correct.");
                Assert.IsTrue(dialPlanContext.m_commands[1].Data == "\"username\", \"password\", \"[email protected]\"", "Command 2 data not correct.");

                Console.WriteLine("---------------------------------");
            }
Example #14
0
            public void RegexWithNoCommaMatchDialPlanTest()
            {
                Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

                string testDialPlan =
                    @"exten =~ \d{3},1,Switch(anon,,${dst}@sip.blueface.ie, ""sip switch"" <sip:[email protected]>, 194.213.29.100)";

                SIPDialPlan dialPlan = new SIPDialPlan(null, null, null, testDialPlan, SIPDialPlanScriptTypesEnum.Asterisk);
                SIPRequest request = new SIPRequest(SIPMethodsEnum.INVITE, SIPURI.ParseSIPURI("sip:[email protected]"));
                DialPlanLineContext dialPlanContext = new DialPlanLineContext(null, null, null, null, null, dialPlan, null, null, null);
                DialPlanCommand commandMatch = dialPlanContext.GetDialPlanMatch(request);

                Assert.IsNotNull(commandMatch, "The dial plan should have returned a match.");

                Console.WriteLine("---------------------------------");
            }
Example #15
0
            public void RegexWithCommaLoadDialPlanTest()
            {
                Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

                string testDialPlan =
                    "exten =~ /3d{4,6}/,1,Switch(anon,,${dst}@sip.blueface.ie, \"sip switch\" <sip:[email protected]>, 194.213.29.100)";

                SIPDialPlan dialPlan = new SIPDialPlan(null, null, null, testDialPlan, SIPDialPlanScriptTypesEnum.Asterisk);

                Assert.IsNotNull(dialPlan, "The dial plan could not be loaded.");

                Console.WriteLine("---------------------------------");
            }
Example #16
0
            public void NoMatchDialPlanTest()
            {
                Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

                string testDialPlan = @"
                    exten => _3100,1,Switch(anon, password, [email protected])
                    exten => _3300,1,Switch(anon, password, [email protected])
                    exten => _3000,1,Switch(anon, password, [email protected])
                ";

                SIPDialPlan dialPlan = new SIPDialPlan(null, null, null, testDialPlan, SIPDialPlanScriptTypesEnum.Asterisk);
                SIPRequest request = new SIPRequest(SIPMethodsEnum.INVITE, SIPURI.ParseSIPURI("sip:[email protected]"));
                DialPlanLineContext dialPlanContext = new DialPlanLineContext(null, null, null, null, null, dialPlan, null, null, null);
                DialPlanCommand commandMatch = dialPlanContext.GetDialPlanMatch(request);

                Assert.IsTrue(dialPlanContext.m_commands.Count == 3, "The dial plan was not correctly parsed.");
                Assert.IsNull(commandMatch, "The dial plan produced a match when it should not have.");

                Console.WriteLine("---------------------------------");
            }
Example #17
0
            public void DifferentOperatorsDialPlanTest()
            {
                Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

                string testDialPlan = @"
                    exten == 100,1,Switch(""anonymous.invalid"", ""password"", ""*****@*****.**"")
                    exten =~ 101,1,Switch(""username"", ""password"", ""*****@*****.**"")
                    exten = 103,1,Switch(""username"", ""password"", ""[email protected])
                ";

                SIPDialPlan dialPlan = new SIPDialPlan(null, null, null, testDialPlan, SIPDialPlanScriptTypesEnum.Asterisk);
                DialPlanLineContext dialPlanContext = new DialPlanLineContext(null, null, null, null, null, dialPlan, null, null, null);

                Assert.IsTrue(dialPlanContext.m_commands.Count == 3, "The dial plan was not correctly parsed.");
                Assert.IsTrue(dialPlanContext.m_commands[0].Operation == DialPlanOpsEnum.Equals, "Command 1 operation was incorrect.");
                Assert.IsTrue(dialPlanContext.m_commands[1].Operation == DialPlanOpsEnum.Regex, "Command 2 operation was incorrect.");
                Assert.IsTrue(dialPlanContext.m_commands[2].Operation == DialPlanOpsEnum.Equals, "Command 3 operation was incorrect.");

                Console.WriteLine("---------------------------------");
            }
 private void AddDialPlan(SIPDialPlan dialPlan)
 {
     m_persistor.AddDialPlanAsync(dialPlan);
 }
 private void UpdateDialPlan(SIPDialPlan dialPlan)
 {
     m_persistor.UpdateDialPlanAsync(dialPlan);
 }
        private bool GetDialPlanAndCustomer(string owner, string dialPlanName, ISIPServerUserAgent uas, out Customer customer, out SIPDialPlan dialPlan)
        {
            try
            {
                dialPlan = null;
                customer = m_customerPersistor.Get(c => c.CustomerUsername == owner);

                if (customer == null)
                {
                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Call rejected for customer " + owner + " as no matching account found.", null));
                    uas.Reject(SIPResponseStatusCodesEnum.DoesNotExistAnywhere, "No matching user was found", null);
                }
                else if (customer.Suspended)
                {
                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Call rejected for customer " + owner + " as account is suspended.", null));
                    uas.Reject(SIPResponseStatusCodesEnum.DoesNotExistAnywhere, "User account is suspended", null);
                }
                else if (dialPlanName.IsNullOrBlank() && uas.CallDirection == SIPCallDirection.Out)
                {
                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Call rejected for customer " + owner + " as no dialplan is configured for an " + uas.CallDirection + " call.", null));
                    uas.Reject(SIPResponseStatusCodesEnum.TemporarilyUnavailable, "SIP account missing dialplan setting", null);
                }
                else
                {
                    dialPlan = GetDialPlan_External(d => d.Owner == owner && d.DialPlanName == dialPlanName);
                    if (!IsDialPlanExecutionAllowed(dialPlan, customer))
                    {
                        Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Execution of dial plan " + dialPlanName + " was not processed as maximum execution count has been reached.", owner));
                        uas.Reject(SIPResponseStatusCodesEnum.TemporarilyUnavailable, "Dial plan execution exceeded maximum allowed", null);
                    }
                    else
                    {
                        if (m_dailyCallLimit == -1)
                        {
                            return true;
                        }
                        else
                        {
                            // Check whether the number of CDR's exceeds the daily call limit.
                            DateTime yesterday = DateTime.Now.AddDays(-1);
                            int cdrCount = m_sipCDRPersistor.Count(x => x.Owner == owner && x.Created > yesterday);
                            if (cdrCount >= m_dailyCallLimit)
                            {
                                Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Execution of call for " + owner + " was not processed as daily call limit reached.", owner));
                                uas.Reject(SIPResponseStatusCodesEnum.TemporarilyUnavailable, "Daily call limit reached", null);
                            }
                            else
                            {
                                return true;
                            }
                        }
                    }
                }

                return false;
            }
            catch (Exception excp)
            {
                logger.Error("Exception GetDialPlanAndCustomer. " + excp.Message);
                throw;
            }
        }
 private void DetailsControlClosed()
 {
     m_dialPlansPanel.CloseDetailsPane();
     m_selectedDialPlan = null;
 }
        public void CreateCustomer(Customer customer)
        {
            try {
                // Check whether the number of customers is within the allowed limit.
                if (m_newCustomersAllowedLimit != 0 && CRMCustomerPersistor.Count(null) >= m_newCustomersAllowedLimit) {
                    throw new ApplicationException("Sorry new account creations are currently disabled. Please monitor sipsorcery.wordpress.com for updates.");
                }
                else {
                    // Check whether the username is already taken.
                    customer.CustomerUsername = customer.CustomerUsername.ToLower();
                    Customer existingCustomer = CRMCustomerPersistor.Get(c => c.CustomerUsername == customer.CustomerUsername);
                    if (existingCustomer != null) {
                        throw new ApplicationException("The requested username is already in use please try a different one.");
                    }

                    // Check whether the email address is already taken.
                    customer.EmailAddress = customer.EmailAddress.ToLower();
                    existingCustomer = CRMCustomerPersistor.Get(c => c.EmailAddress == customer.EmailAddress);
                    if (existingCustomer != null) {
                        throw new ApplicationException("The email address is already associated with an account.");
                    }

                    string validationError = Customer.ValidateAndClean(customer);
                    if (validationError != null) {
                        throw new ApplicationException(validationError);
                    }

                    customer.MaxExecutionCount = Customer.DEFAULT_MAXIMUM_EXECUTION_COUNT;

                    CRMCustomerPersistor.Add(customer);
                    logger.Debug("New customer record added for " + customer.CustomerUsername + ".");

                    // Create a default dialplan.
                    SIPDialPlan defaultDialPlan = new SIPDialPlan(customer.CustomerUsername, "default", null, "sys.Log(\"hello world\")\n", SIPDialPlanScriptTypesEnum.Ruby);
                    DialPlanPersistor.Add(defaultDialPlan);
                    logger.Debug("Default dialplan added for " + customer.CustomerUsername + ".");

                    // Get default domain name.
                    string defaultDomain = SIPDomainManager.GetDomain("local", true);

                    // Create SIP account.
                    if (SIPAccountPersistor.Get(s => s.SIPUsername == customer.CustomerUsername && s.SIPDomain == defaultDomain) == null) {
                        SIPAccount sipAccount = new SIPAccount(customer.CustomerUsername, defaultDomain, customer.CustomerUsername, customer.CustomerPassword, "default");
                        SIPAccountPersistor.Add(sipAccount);
                        logger.Debug("SIP account " + sipAccount.SIPUsername + "@" + sipAccount.SIPDomain + " added for " + sipAccount.Owner + ".");
                    }
                    else {
                        int attempts = 0;
                        while (attempts < 10) {
                            string testUsername = customer.CustomerUsername + Crypto.GetRandomString(4);
                            if (SIPAccountPersistor.Get(s => s.SIPUsername == testUsername && s.SIPDomain == defaultDomain) == null) {
                                SIPAccount sipAccount = new SIPAccount(customer.CustomerUsername, defaultDomain, testUsername, customer.CustomerPassword, "default");
                                SIPAccountPersistor.Add(sipAccount);
                                logger.Debug("SIP account " + sipAccount.SIPUsername + "@" + sipAccount.SIPDomain + " added for " + sipAccount.Owner + ".");
                                break;
                            }
                            else {
                                attempts++;
                            }
                        }
                    }

                    logger.Debug("Sending new account confirmation email to " + customer.EmailAddress + ".");
                    Email.SendEmail(customer.EmailAddress, NEW_ACCOUNT_EMAIL_FROM_ADDRESS, NEW_ACCOUNT_EMAIL_SUBJECT, String.Format(NEW_ACCOUNT_EMAIL_BODY, customer.FirstName, customer.Id));
                }
            }
            catch (Exception excp) {
                logger.Error("Exception CreateNewCustomer. " + excp.Message);
                throw;
            }
        }
Example #23
0
        /// <summary>
        /// Processes the callback action that is initiated by the callmanager service. The callback method is typically initiated from
        /// a link on an authenticated web page and requires the user to be authenticated.
        /// </summary>
        /// <param name="username">The authenticated username of the user making the callback request.</param>
        /// <param name="dialString1">The first leg dial string of the callback.</param>
        /// <param name="dialString2">The second leg dial string of the callback.</param>
        /// <returns>A string that is returned to the user making the callmanager request that inidcates what action was taken.</returns>
        public string ProcessCallback(string username, string dialString1, string dialString2)
        {
            Customer customer = null;

            try
            {
                customer = m_customerPersistor.Get(c => c.CustomerUsername == username);

                if (customer == null)
                {
                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Callback rejected for " + username + " as no matching user.", null));
                    return "Sorry no matching user was found, the callback was not initiated.";
                }
                else if (customer.Suspended)
                {
                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Callback rejected for " + username + " as user account is suspended.", null));
                    return "Sorry your account is suspended.";
                }
                else if (customer.ServiceLevel == CustomerServiceLevels.PremiumPayReqd.ToString() || customer.ServiceLevel == CustomerServiceLevels.ProfessionalPayReqd.ToString() || customer.ServiceLevel == CustomerServiceLevels.SwitchboardPayReqd.ToString())
                {
                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Callback rejected for " + username + ", user account requires payment.", null));
                    return "Sorry your account requires payment.";
                }
                else
                {
                    UASInviteTransaction dummyTransaction = GetDummyWebCallbackTransaction("callback");
                    ISIPServerUserAgent uas = new SIPServerUserAgent(m_sipTransport, m_outboundProxy, username, SIPDomainManager.DEFAULT_LOCAL_DOMAIN, SIPCallDirection.Out, GetSIPAccount_External, null, Log_External, dummyTransaction);

                    string callbackScript =
                      "sys.Log(\"Callback dialString1=" + dialString1 + ", dialString2=" + dialString2 + ".\")\n" +
                      "sys.Callback(\"" + dialString1 + "\",\"" + dialString2 + "\", 0)\n";

                    SIPDialPlan callbackDialPlan = new SIPDialPlan(username, null, null, callbackScript, SIPDialPlanScriptTypesEnum.Ruby);
                    callbackDialPlan.Id = Guid.Empty; // Prevents the increment and decrement on the execution counts.
                    DialPlanScriptContext scriptContext = new DialPlanScriptContext(
                            Log_External,
                            m_sipTransport,
                            CreateDialogueBridge,
                            m_outboundProxy,
                            uas,
                            callbackDialPlan,
                            GetSIPProviders_External(p => p.Owner == username, null, 0, Int32.MaxValue),
                            null,
                            null,
                            customer,
                            null,
                            GetCanonicalDomain_External);
                    m_dialPlanEngine.Execute(scriptContext, uas, SIPCallDirection.Out, CreateDialogueBridge, this);

                    return null;
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPCallManager ProcessCallback. " + excp.Message);
                return "Sorry there was an unexpected error, the callback was not initiated.";
            }
        }
Example #24
0
            public void TestLoadOldDefaultDialPlanTest()
            {
                Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

                string testDialPlan =
                    "; Example extensions\n" +
                    "exten = 100,1,Switch(anon,,[email protected])\n" +
                    "exten == 101,1,Switch(anon,,[email protected])\n" +
                    "exten => _*1X.,1,Switch(user,pass,${EXTEN:2}@sip.blueface.ie)\n" +
                    "exten => _*2X.,1,Switch(anon,,${EXTEN:2}@fwd.pulver.com)\n";

                SIPDialPlan dialPlan = new SIPDialPlan(null, null, null, testDialPlan, SIPDialPlanScriptTypesEnum.Asterisk);

                Assert.IsNotNull(dialPlan, "The default dial plan could not be loaded.");

                Console.WriteLine("---------------------------------");
            }
        public SIPDialPlan AddDialPlan(SIPDialPlan dialPlan)
        {
            Customer customer = AuthoriseRequest();

            dialPlan.Owner = customer.CustomerUsername;

            if (customer.AdminId != Customer.TOPLEVEL_ADMIN_ID) {
                dialPlan.MaxExecutionCount = SIPDialPlan.DEFAULT_MAXIMUM_EXECUTION_COUNT;
            }

            return DialPlanPersistor.Add(dialPlan);
        }
Example #26
0
        private bool GetDialPlanAndCustomer(string owner, string dialPlanName, ISIPServerUserAgent uas, out Customer customer, out SIPDialPlan dialPlan)
        {
            try
            {
                dialPlan = null;
                customer = m_customerPersistor.Get(c => c.CustomerUsername == owner);

                if (customer == null)
                {
                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Call rejected for customer " + owner + " as no matching account found.", null));
                    uas.Reject(SIPResponseStatusCodesEnum.DoesNotExistAnywhere, "No matching user was found", null);
                }
                else if (customer.Suspended)
                {
                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Call rejected for customer " + owner + " as account is suspended.", null));
                    uas.Reject(SIPResponseStatusCodesEnum.DoesNotExistAnywhere, "User account is suspended", null);
                }
                else if (customer.ServiceLevel == CustomerServiceLevels.PremiumPayReqd.ToString() || customer.ServiceLevel == CustomerServiceLevels.ProfessionalPayReqd.ToString() || customer.ServiceLevel == CustomerServiceLevels.SwitchboardPayReqd.ToString())
                {
                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Call rejected for customer " + owner + " as payment is outstanding.", null));
                    uas.Reject(SIPResponseStatusCodesEnum.PaymentRequired, null, null);
                }
                else if (dialPlanName.IsNullOrBlank() && uas.CallDirection == SIPCallDirection.Out)
                {
                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Call rejected for customer " + owner + " as no dialplan is configured for an " + uas.CallDirection + " call.", null));
                    uas.Reject(SIPResponseStatusCodesEnum.TemporarilyUnavailable, "SIP account missing dialplan setting", null);
                }
                else
                {
                    if (dialPlanName.IsNullOrBlank())
                    {
                        // Incoming call with no dialplan.
                        return true;
                    }
                    else
                    {
                        dialPlan = GetDialPlan_External(d => d.Owner == owner && d.DialPlanName == dialPlanName);

                        if (dialPlan == null)
                        {
                            Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Call rejected, dialplan " + dialPlanName + " could not be found.", owner));
                            uas.Reject(SIPResponseStatusCodesEnum.InternalServerError, "Could not load dialplan " + dialPlanName, null);
                        }
                        else if (dialPlan != null && dialPlan.IsReadOnly)
                        {
                            Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Call rejected for read only dialplan " + dialPlanName + ". Upgrade to a Premium service to enable.", owner));
                            uas.Reject(SIPResponseStatusCodesEnum.PaymentRequired, "Dial plan is readonly, upgrade to Premium service", null);
                        }
                        else if (customer.ServiceLevel == CustomerServiceLevels.Free.ToString() && dialPlan.ScriptType == SIPDialPlanScriptTypesEnum.Asterisk)
                        {
                            Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Your service level does not permit the use of Asterisk dial plans.", owner));
                            uas.Reject(SIPResponseStatusCodesEnum.PaymentRequired, "Free plans cannot use Asterisk dial plans", null);
                        }
                        else if (!IsDialPlanExecutionAllowed(dialPlan, customer))
                        {
                            Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Execution of dial plan " + dialPlanName + " was not processed as maximum execution count has been reached.", owner));
                            uas.Reject(SIPResponseStatusCodesEnum.TemporarilyUnavailable, "Dial plan execution exceeded maximum allowed", null);
                        }
                        else
                        {
                            if (m_dailyCallLimit == -1)
                            {
                                return true;
                            }
                            else
                            {
                                // Check whether the number of CDR's exceeds the daily call limit.
                                DateTime yesterday = DateTime.Now.AddDays(-1);
                                int cdrCount = m_sipCDRPersistor.Count(x => x.Owner == owner && x.Created > yesterday);
                                if (cdrCount >= m_dailyCallLimit)
                                {
                                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Execution of call for " + owner + " was not processed as daily call limit reached.", owner));
                                    uas.Reject(SIPResponseStatusCodesEnum.TemporarilyUnavailable, "Daily call limit reached", null);
                                }
                                else
                                {
                                    return true;
                                }
                            }
                        }
                    }
                }

                return false;
            }
            catch (Exception excp)
            {
                logger.Error("Exception GetDialPlanAndCustomer. " + excp.Message);
                throw;
            }
        }
        public SIPDialPlan DeleteDialPlan(SIPDialPlan dialPlan)
        {
            Customer customer = AuthoriseRequest();

            if (customer.AdminId != Customer.TOPLEVEL_ADMIN_ID && dialPlan.Owner != customer.CustomerUsername) {
                throw new ApplicationException("You are not authorised to delete the Dial Plan.");
            }

            DialPlanPersistor.Delete(dialPlan);

            // Enables the caller to see which dialplan has been deleted.
            return dialPlan;
        }
Example #28
0
        private bool IsDialPlanExecutionAllowed(SIPDialPlan dialPlan, Customer customer)
        {
            try
            {
                /*int dialPlanExecutionCount = (dialPlan != null) ? dialPlan.ExecutionCount : 0;
                int dialPlanMaxExecutionCount = (dialPlan != null) ? dialPlan.MaxExecutionCount : 0;

                if (customer.ExecutionCount >= customer.MaxExecutionCount ||
                    (dialPlan != null && dialPlanExecutionCount >= dialPlanMaxExecutionCount))
                {
                    return false;
                }
                else
                {
                    return true;
                }*/

                //logger.Debug("IsDialPlanExecutionAllowed for " + customer.CustomerUsername + " and " + dialPlan.DialPlanName + ", count=" + dialPlan.ExecutionCount + ", max=" + dialPlan.MaxExecutionCount + ".");

                //return (customer.ExecutionCount < customer.MaxExecutionCount);

                int currentlyExecuting = m_dialPlanEngine.GetExecutionCountForUser(customer.CustomerUsername);
                return currentlyExecuting < customer.MaxExecutionCount;

                //if (dialPlan != null)
                //{
                //    return currentlyExecuting < customer.MaxExecutionCount && currentlyExecuting < dialPlan.MaxExecutionCount;
                //}
                //else
                //{
                //    return currentlyExecuting < customer.MaxExecutionCount;
                //}
            }
            catch (Exception excp)
            {
                logger.Error("Exception IsDialPlanExecutionAllowed. " + excp.Message);
                throw excp;
            }
        }
 public override void AddDialPlanAsync(SIPDialPlan dialPlan) {
     if (AddDialPlanComplete != null) {
         AddDialPlanComplete(new AddDialPlanCompletedEventArgs(new object[] { dialPlan }, null, false, null));
     }
 }
Example #30
0
        private void ProcessNewCall(ISIPServerUserAgent uas)
        {
            //bool wasExecutionCountIncremented = false;
            Customer customer = null;
            SIPDialPlan dialPlan = null;

            try
            {
                Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Call Manager processing new call on thread " + Thread.CurrentThread.Name + " for " + uas.CallRequest.Method + " to " + uas.CallRequest.URI.ToString() + ".", null));

                #region Do some pre-flight checks on the SIP account to determine if the call should be processed.

                if (uas.SIPAccount == null)
                {
                    if (uas.CallRequest.URI.User == DISPATCHER_SIPACCOUNT_NAME)
                    {
                        // This is a call from the monitoring system allow to proceed.
                    }
                    else if (uas.CallDirection == SIPCallDirection.Out)
                    {
                        Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "SIP account " + uas.CallRequest.Header.From.FromURI.ToParameterlessString() + " not found for outgoing call to " + uas.CallRequest.URI.ToString() + ".", null));
                        uas.Reject(SIPResponseStatusCodesEnum.Forbidden, null, null);
                        return;
                    }
                    else if (uas.CallDirection == SIPCallDirection.In)
                    {
                        Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "SIP account " + uas.CallRequest.URI.ToParameterlessString() + " not found for incoming call.", null));
                        uas.Reject(SIPResponseStatusCodesEnum.NotFound, null, null);
                        return;
                    }
                }
                else
                {
                    if (uas.SIPAccount.IsDisabled)
                    {
                        Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "SIP account " + uas.SIPAccount.SIPUsername + "@" + uas.SIPAccount.SIPDomain + " is disabled for " + uas.CallDirection + " call.", uas.SIPAccount.Owner));
                        uas.Reject(SIPResponseStatusCodesEnum.Forbidden, "SIP account disabled", null);
                        return;
                    }
                    else if (uas.SIPAccount.IsIncomingOnly && uas.CallDirection == SIPCallDirection.Out)
                    {
                        Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "SIP account " + uas.SIPAccount.SIPUsername + "@" + uas.SIPAccount.SIPDomain + " is not permitted to make outgoing calls", uas.SIPAccount.Owner));
                        uas.Reject(SIPResponseStatusCodesEnum.Forbidden, "SIP account not permitted to make outgoing calls", null);
                        return;
                    }
                }

                #endregion

                SIPURI callURI = (uas.CallRequest != null) ? uas.CallRequest.URI : null;
                SIPAccount sipAccount = uas.SIPAccount;

                if (uas.CallDirection == SIPCallDirection.In && callURI.User == DISPATCHER_SIPACCOUNT_NAME)
                {
                    uas.NoCDR();

                    #region Create a pseudo-dialplan to process the monitoring process call.

                    string pseudoScript =
                        //"sys.Log(\"Dispatcher Call.\")\n" +
                        "result = sys.DoesSIPAccountExist(\"" + DISPATCHER_SIPACCOUNT_NAME + "\")\n" + // Allows the test call to check the database connectivity.
                        //"sys.Log(\"DoesSIPAccountExist result=#{result}.\")\n" +
                        "sys.Respond(420, nil, \"DialPlanEngine-ExecutionCount: " + m_dialPlanEngine.ScriptCount + "\")\n";
                    SIPDialPlan dispatcherDialPlan = new SIPDialPlan(null, null, null, pseudoScript, SIPDialPlanScriptTypesEnum.Ruby);
                    dispatcherDialPlan.Id = Guid.Empty; // Prevents the increment and decrement on the execution counts.
                    DialPlanScriptContext scriptContext = new DialPlanScriptContext(
                            Log_External,
                            m_sipTransport,
                            CreateDialogueBridge,
                            m_outboundProxy,
                            uas,
                            dispatcherDialPlan,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null);
                    m_dialPlanEngine.Execute(scriptContext, uas, uas.CallDirection, null, this);

                    #endregion
                }
                else
                {
                    string dialPlanName = (uas.CallDirection == SIPCallDirection.Out) ? sipAccount.OutDialPlanName : sipAccount.InDialPlanName;
                    string owner = (uas.IsB2B) ? uas.SIPAccount.Owner : uas.Owner;

                    if (GetDialPlanAndCustomer(owner, dialPlanName, uas, out customer, out dialPlan))
                    {
                        //IncrementDialPlanExecutionCount(dialPlan, customer, originalExecutionCount + 1);
                        //IncrementCustomerExecutionCount(customer);
                        //wasExecutionCountIncremented = true;

                        if (dialPlan != null)
                        {
                            if (!uas.IsInvite && !dialPlan.AcceptNonInvite)
                            {
                                Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "A " + uas.CallRequest.Method + " was rejected for dialplan " + dialPlanName + " as it does not accept non-INVITE requests.", owner));
                                uas.Reject(SIPResponseStatusCodesEnum.MethodNotAllowed, "User has chosen not to accept request type", null);
                                return;
                            }
                            else
                            {
                                Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Using dialplan " + dialPlanName + " for " + uas.CallDirection + " call to " + callURI.ToString() + ".", owner));

                                if (dialPlan.ScriptType == SIPDialPlanScriptTypesEnum.Asterisk)
                                {
                                    DialPlanLineContext lineContext = new DialPlanLineContext(
                                        Log_External,
                                        m_sipTransport,
                                        CreateDialogueBridge,
                                        m_outboundProxy,
                                        uas,
                                        dialPlan,
                                        GetSIPProviders_External(p => p.Owner == owner, null, 0, Int32.MaxValue),
                                        m_traceDirectory,
                                        (uas.CallDirection == SIPCallDirection.Out) ? sipAccount.NetworkId : null,
                                        customer);
                                    //lineContext.DialPlanComplete += () => { DecrementCustomerExecutionCount(customer);} ;
                                    m_dialPlanEngine.Execute(lineContext, uas, uas.CallDirection, CreateDialogueBridge, this);
                                }
                                else
                                {
                                    dialPlan.AuthorisedApps = customer.AuthorisedApps + ";" + dialPlan.AuthorisedApps;
                                    DialPlanScriptContext scriptContext = new DialPlanScriptContext(
                                        Log_External,
                                        m_sipTransport,
                                        CreateDialogueBridge,
                                        m_outboundProxy,
                                        uas,
                                        dialPlan,
                                        GetSIPProviders_External(p => p.Owner == owner, null, 0, Int32.MaxValue),
                                        m_traceDirectory,
                                        (uas.CallDirection == SIPCallDirection.Out) ? sipAccount.NetworkId : null,
                                        customer,
                                        m_dialPlanEngine,
                                        GetCanonicalDomain_External);
                                    uas.SetDialPlanContextID(scriptContext.DialPlanContextID);
                                    //scriptContext.DialPlanComplete += () => { DecrementCustomerExecutionCount(customer);};
                                    m_dialPlanEngine.Execute(scriptContext, uas, uas.CallDirection, CreateDialogueBridge, this);
                                }
                            }
                        }
                        else if (uas.CallDirection == SIPCallDirection.In)
                        {
                            if (uas.IsB2B)
                            {
                                Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Dialplan could not be loaded for incoming B2B call to " + callURI.ToString() + ".", owner));
                                uas.Reject(SIPResponseStatusCodesEnum.InternalServerError, "Error loading incoming dial plan for B2B call", null);
                                //DecrementCustomerExecutionCount(customer);
                            }
                            else
                            {
                                Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "No dialplan specified for incoming call to " + sipAccount.SIPUsername + "@" + sipAccount.SIPDomain + ", registered bindings will be used.", owner));

                                // The SIP account has no dialplan for an incoming call therefore send to the SIP account's bindings.
                                List<SIPRegistrarBinding> bindings = GetSIPAccountBindings_External(b => b.SIPAccountId == sipAccount.Id, null, 0, MAX_FORWARD_BINDINGS);
                                if (bindings != null && bindings.Count > 0)
                                {
                                    // Create a pseudo-dialplan to process the incoming call.
                                    string pseudoScript = "sys.Dial(\"" + sipAccount.SIPUsername + "@" + sipAccount.SIPDomain + "\")\n";
                                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Forwarding incoming call for " + sipAccount.SIPUsername + "@" + sipAccount.SIPDomain + " to " + bindings.Count + " bindings.", owner));
                                    SIPDialPlan incomingDialPlan = new SIPDialPlan(sipAccount.Owner, null, null, pseudoScript, SIPDialPlanScriptTypesEnum.Ruby);
                                    incomingDialPlan.Id = Guid.Empty; // Prevents the increment and decrement on the execution counts.
                                    DialPlanScriptContext scriptContext = new DialPlanScriptContext(
                                            Log_External,
                                            m_sipTransport,
                                            CreateDialogueBridge,
                                            m_outboundProxy,
                                            uas,
                                            incomingDialPlan,
                                            null,
                                            m_traceDirectory,
                                            null,
                                            customer,
                                            null,
                                            GetCanonicalDomain_External);
                                    //scriptContext.DialPlanComplete += () => { DecrementCustomerExecutionCount(customer); };
                                    m_dialPlanEngine.Execute(scriptContext, uas, uas.CallDirection, CreateDialogueBridge, this);
                                }
                                else
                                {
                                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "No bindings available for " + sipAccount.SIPUsername + "@" + sipAccount.SIPDomain + " returning temporarily not available.", owner));
                                    uas.Reject(SIPResponseStatusCodesEnum.TemporarilyUnavailable, null, null);
                                    //DecrementDialPlanExecutionCount(null, customer.Id);
                                    //DecrementCustomerExecutionCount(customer);
                                }
                            }
                        }
                        else
                        {
                            // Couldn't load a dialplan for an outgoing call.
                            Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Dialplan could not be loaded for " + uas.CallDirection + " call to " + callURI.ToString() + ".", owner));
                            uas.Reject(SIPResponseStatusCodesEnum.InternalServerError, "Error loading dial plan", null);
                            //DecrementDialPlanExecutionCount(null, customer.Id);
                            //DecrementCustomerExecutionCount(customer);
                        }
                    }
                }
            }
            catch (Exception excp)
            {
                Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.Error, "Exception SIPCallManager ProcessNewCall. " + excp.Message, null));
                uas.Reject(SIPResponseStatusCodesEnum.InternalServerError, "Exception ProcessNewCall", null);

                //if (wasExecutionCountIncremented)
                //{
                //DecrementDialPlanExecutionCount(dialPlan, customer.Id);
                // DecrementCustomerExecutionCount(customer);
                //}
            }
        }