Giter VIP home page Giter VIP logo

skrusty / asternet.ari Goto Github PK

View Code? Open in Web Editor NEW
88.0 24.0 49.0 4.39 MB

AsterNET.ARI is an incubation project and addition to the AsterNET framework for .NET. It allows you to develop against Stasis ARI for Asterisk using the .NET framework.

Home Page: http://www.xdev.net/projects/asternet-ari/

License: MIT License

C# 99.19% JavaScript 0.35% HTML 0.46% Smalltalk 0.01%
asterisk c-sharp ari stasis-ari

asternet.ari's People

Contributors

claudiuolteanu avatar ffloimair avatar pragmatrix avatar sebmurrayqi avatar seiggy avatar skrusty avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

asternet.ari's Issues

Adding custom headers to channel

When using OriginateWithId method, I pass the parameter variables as described in the article ("ARI Originate and SIP Headers").
In my case this dictionary:

new Dictionary<string, string>() 
{ {"SIPADDHEADER0", "custom-header-1:custom-value-1"}, {"SIPADDHEADER1", "custom-header-2:custom-value-2"} } 

JsonConvert serializes this into the format:
{"custom-header-1":"custom-value-1", "custom-header-2":"custom-value-2"}
But this format is not suitable, as documentation Asterisk ARI said:

The' variables ' key in the body object holds variable key/value pairs to set on the channel on creation. Other keys in the object body are interpreted as query parameters. Ex. { "endpoint": "SIP/Alice", "variables": { "CALLERID(name)": "Alice" } }

Necessary in the methods Originate and OriginateWithId instead of Dictionary<string, string> apply Dictionary<string, object> for serialize nested objects... How could have stated the problem, maybe there is a more rational decision... Please give me an example. Thank you.

Nuget package with .net standard support

I'm trying to add integration with asterisk using ARI into net.core 2.2 app. After installing version 1.2.1 of AsterNET.ARI nuget package I get the following warning
warning NU1701: Package 'AsterNET.ARI 1.2.1' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of the project target framework '.NETCoreApp,Version=v2.2'. This package may not be fully compatible with your project

There is a version of the nuget package with netstandard support in the source code, But I guess it's not published?
Can you publish the version with netstandard support? Probably, It would be useful not only for me. Please, tell if any help needed.

a problem with HangupAsync(AsterNET.ARI.SimpleTestApplicationAsync)

I downloaded your example(AsterNET.ARI.SimpleTestApplicationAsync)
Run it and click "#" , the phrase is not pronounced, and immediately goes off.
Log from asterisk:

- <SIP/201-000000af> Playing 'goodbye.ulaw' (language 'ru')
[2018-01-25 17:27:13] WARNING[22882][C-000000b8]: res_stasis_playback.c:277 playback_final_update: 1516890429.197: Playback failed for sound:goodbye"

But
case "*":
await sender.Channels.PlayAsync(e.Channel.Id, "sound:asterisk-friend");
await sender.Channels.PlayAsync(e.Channel.Id, "sound:goodbye");

work fine.

Asterisk 14.7.5.

Fast agi

I have created a extension at extension config for agi :
exten => 200,1,agi(agi://" + DEV_HOST + @"/customivr.agi)
exten => 200,2,Hangup()
I have created a script in agi bin by placing customerivr class code . But it is forwading the call to 200 and showing Agi status Successful but not playing any stream file .It is showing the events of AMI. Please reply me quick i few days left to complete my Final year project.

Code Generation should work out of the box.

Regenerating the code for the ARI Events and Actions does not work out of the box. Here are some issues I had:

I needed to change:

#>
        /// <param name="<#= param.SelectToken("name").Value<string>() #>"><#= param.SelectToken("description").Value<string>() #></param>
<#

into

#>      /// <param name="<#= param.SelectToken("name").Value<string>() #>"><#= param.SelectToken("description").Value<string>() #></param>
<#

to avoid two newlines (one before the param line, and the one after).

  • I think that the date in the header comment should be removed as long the code files are checked in to the repository, so that merge conflicts can be avoided.
  • In VS2015, the files are generated in a subdirectory Templates. It is not clear how these files should be distributed / copied back into the Asternet.ARI project in the directory structure below ARI_1_0. A script would be nice, or some kind of post build process in the code generation step.
  • The generated code uses tabs, but the rest of the code uses spaces.

Code Generation puts IEndpointsActions methods SendMessage and SendMessageToEndpoint into comments :)

How to add recipient to Conference

I create Conference with SimpleConf demo. I can join to conference when I dial in. But how to dial out from running conference and add call to running conference?

I try to dial with ariClient.Channels.Originate(). My mobile rings and after I answer I'm not in the conference.

What I'm missing?

WebSocket4Net needs to be updated

AsterNET.ARI uses WebSocket4Net 0.8, which contains a bug that prevents changing the state of the socket when the server drops the connection in an connection attempt. This could stall the connection process in AriClient (I could reproduce this problem with AsterNET.ARI before updating my fork):

kerryjiang/WebSocket4Net@3dddbb4

This problem has been fixed since the nuget package version 0.10.

Is a Stasis Dialplan actually required for Outbound call using ARI?

Hi,

I am new to Asterisk and have written a sample in Asternet.ARI app. The app facilitates the dialing of 2 outbound calls and allows DTMF to play/stop MOH.

All the docs I have found indicate that I HAVE to have a simple Stasis dialplan, in order to do the above. E.g.

exten => 1001,1,NoOp()
same => n,Answer()
same => n,Stasis(StasisTest)
same => n,hangup()

However, I am able to enter Stasis WITHOUT the above dialplan existing. I've pasted the pertinent portion of the code I'm using below.

static void Main()
{
    AriClient ActionClient = new AriClient(new StasisEndpoint("<IP>, 8088, "<username>", "<password>"), StasisTest);

    ActionClient.OnStasisStartEvent += c_OnStasisStartEvent;
    ActionClient.OnStasisEndEvent += c_OnStasisEndEvent;
    ActionClient.OnChannelDtmfReceivedEvent += ActionClientOnChannelDtmfReceivedEvent;

    ActionClient.Connect();
    Bridge SimpleBridge = ActionClient.Bridges.Create("mixing", Guid.NewGuid().ToString(), AppName); 

    ActionClient.Applications.Subscribe(AppName, "bridge:" + SimpleBridge.Id);
    Channel ch1 = ActionClient.Channels.Originate(strEndPoint1, null, null, null, null, "StasisTest");
    Channel ch2 = ActionClient.Channels.Originate(strEndPoint2, null, null, null, null, "StasisTest");
}
 static void c_OnStasisStartEvent(object sender, AsterNET.ARI.Models.StasisStartEvent e)
{
            // Answer channel
            ActionClient.Channels.Answer(e.Channel.Id);
        
            // Add channel to bridge
            ActionClient.Bridges.AddChannel(SimpleBridge.Id, e.Channel.Id, "participant");
}

I am trying to understand why one would require the Dialplan when I'm able to enter into Stasis without using a Dialplan. As I've explained, I'm a novice Asterisk user, so it's possible I'm overlooking some fundamental point.

Any info will be much appreciated.
Thank you

WebSocket4Net method not found

I created a new .NET console project. When I installed AsterNET.ARI from Nuget and tried to run the bridge sample, I got a runtime exception on ActionClient.Connect();.

Method not found: 'Void WebSocket4Net.WebSocket..ctor(System.String, System.String, System.Collections.Generic.List`1<System.Collections.Generic.KeyValuePair`2<System.String,System.String>>, System.Collections.Generic.List`1<System.Collections.Generic.KeyValuePair`2<System.String,System.String>>, System.String, System.String, WebSocket4Net.WebSocketVersion, System.Net.EndPoint)'.

What can be the problem? I tried this with a .NET 4.5 console project, AsterNET.ARI is the latest (1.2).

SimpleConf RemoveUser throwing exception

SimpleConf project RemoveUser method throws exception
"System.Net.Http.HttpRequestException: Response status code does not indicate success: 400 (Bad Request)."
when executing _client.Bridges.RemoveChannel(Confbridge.Id, channelId);

Can AsterNET work with Xamarin?

I really new to programming, sorry for silly question.

The description say that the package supports cross-platform development with Mono.

However, when I try to use it in my Xamarin Forms project, I get the following compiling errors.

Thank you for help

111

AsterNET.ARI not connecting to asterisk ARI consistently

I am trying to create an ARI based app using .net Core 2.1and asterisk 15 on an ubuntu 18.04 box.
I am connecting using the loopback interface with the following code:
Console.WriteLine("Creating connection:");
StasisEndpoint ARIStasisEP = new StasisEndpoint("127.0.0.1", 8088, "CareHawk", "chNTM");
Console.WriteLine(ARIStasisEP.AriEndPoint);
ActionClient = new AriClient(ARIStasisEP, "CareHawkNTM");

            // Hook into required events
            ActionClient.OnStasisStartEvent += NewPhoneConnected;
            ActionClient.OnStasisEndEvent += PhoneHangup;
            ActionClient.OnChannelDtmfReceivedEvent += DTMFReceived;
            ActionClient.OnConnectionStateChanged += StateChanged;
            Console.WriteLine("Succesfully created ARI.");

            ActionClient.Connect();
            Console.WriteLine("Connect to ARI attempt started.");

Occasionally I get the StateChanged function showing the state has changed to true and everything works fine.

But many more times I get no response after the ActionClient.Connect() and nothing shows in the asterisk about my ari app being connected.

the asterisk http.conf is:
;
; Asterisk Builtin mini-HTTP server
;
;
; Note about Asterisk documentation:
; If Asterisk was installed from a tarball, then the HTML documentation should
; be installed in the static-http/docs directory which is
; (/var/lib/asterisk/static-http/docs) on linux by default. If the Asterisk
; HTTP server is enabled in this file by setting the "enabled", "bindaddr",
; and "bindport" options, then you should be able to view the documentation
; remotely by browsing to:
; http://<server_ip>:/static/docs/index.html
;
[general]
;
; The name of the server, advertised in both the Server field in HTTP
; response message headers, as well as the

element in certain HTTP
; response message bodies. If not furnished here, "Asterisk/{version}" will be
; used as a default value for the Server header field and the
; element. Setting this property to a blank value will result in the omission
; of the Server header field from HTTP response message headers and the
; element from HTTP response message bodies.
;
servername=Asterisk
;
; Whether HTTP/HTTPS interface is enabled or not. Default is no.
; This also affects manager/rawman/mxml access (see manager.conf)
;
enabled=yes
;
; Address to bind to, both for HTTP and HTTPS. You MUST specify
; a bindaddr in order for the HTTP server to run. There is no
; default value.
;
bindaddr=0.0.0.0
;
; Port to bind to for HTTP sessions (default is 8088)
;
bindport=8088
;
;... (the rest is all comments

the asterisk ari file is:
[general]
enabled = yes ; When set to no, ARI support is disabled.
pretty = yes ; When set to yes, responses from ARI are
; ; formatted to be human readable.
allowed_origins = ws://127.0.0.1:8088
; ; Cross-Origin Resource Sharing. May be set to * to
; ; allow all origins.
;auth_realm = ; Realm to use for authentication. Defaults to Asterisk
; ; REST Interface.
;
; Default write timeout to set on websockets. This value may need to be adjusted
; for connections where Asterisk must write a substantial amount of data and the
; receiving clients are slow to process the received information. Value is in
; milliseconds; default is 100 ms.
;websocket_write_timeout = 100
;
; Display certain channel variables every time a channel-oriented
; event is emitted:
;
;channelvars = var1,var2,var3

;[username]
;type = user ; Specifies user configuration
;read_only = no ; When set to yes, user is only authorized for
; ; read-only requests.
;
;password = ; Crypted or plaintext password (see password_format).
;
; password_format may be set to plain (the default) or crypt. When set to crypt,
; crypt(3) is used to validate the password. A crypted password can be generated
; using mkpasswd -m sha-512.
;
; When set to plain, the password is in plaintext.
;
;password_format = plain
[CareHawk]
type = user
read_only = no
password = $6$7rbx86y2/xNrG4$evTgZNjGLzurw4cNsl99iHCOV3904otuEKQErbQMvTQBK6LxJn7P/AnAiKcNAJEy6/7xdlRuS/mm/rTSvFTHz1
password_format = crypt

I have other ARI apps written in node.js that work fine with same versions of Linux(Ubuntu) and Asterisk.

Any idea what I might be doing wrong?

The Middleware esposes only two states of the wbsocket connection

Hi there,

I was wondering why did you encapsulate the websocket connection states and why did you expose only two of them (Open and Closed) ? This can lead to some problems if someone wants to force socket's reconnection.

For example: if I want to use the autoreconnect feature and also to expose to the end user the possibility to manually reconnect the socket, then you can have an inconsintent state. If the state of the websocket is Connecting and the user tries to manually reconnect it, it will raise a WebSocket exception. ("The socket is connecting, cannot connect again!").

Thanks,
Claudiu

Nuget version published with 1.1.0

Hi guys,

Asternet ARI downloaded via Nuget contains a wrong dll reference (1.1.0 instead of 1.2.0) for .Net45.
So, when I try to connect there is an exception (WebSocket4Net constructor - missing method)

send fax using ARI

Hi,

i tried to send fax using AsterNET.ARI without any success.
Can we SendFax using AsterNET.ARI?
if yes how we do it?

RunSynchronously error

Try to use your code from repository. At example Sync method return error:

RunSynchronously may not be called on a task not bound to a delegate, such as the task returned from an asynchronous method.

If change code:

 public IRestCommandResult<T> ProcessRestCommand<T>(IRestCommand command) where T : new()
        {
            var cmd = (Command) command;
            var result = cmd.Client.Execute<T>(cmd.Request);
            result.RunSynchronously();

            var rtn = new CommandResult<T> {StatusCode = result.Result.StatusCode, Data = result.Result.Data};

            return rtn;
        }

        public IRestCommandResult ProcessRestCommand(IRestCommand command)
        {
            var cmd = (Command) command;
            var result = cmd.Client.Execute(cmd.Request);
            result.RunSynchronously();

            var rtn = new CommandResult {StatusCode = result.Result.StatusCode, RawData = result.Result.RawBytes};

            return rtn;
        }

To

public IRestCommandResult<T> ProcessRestCommand<T>(IRestCommand command) where T : new()
       {
           var cmd = (Command) command;
           var result = cmd.Client.Execute<T>(cmd.Request);
           result.Wait(new TimeSpan(0, 0, 0, 10));

           var rtn = new CommandResult<T> {StatusCode = result.Result.StatusCode, Data = result.Result.Data};

           return rtn;
       }

       public IRestCommandResult ProcessRestCommand(IRestCommand command)
       {
           var cmd = (Command) command;
           var result = cmd.Client.Execute(cmd.Request);
           result.Wait(new TimeSpan(0, 0, 0, 10));

           var rtn = new CommandResult {StatusCode = result.Result.StatusCode, RawData = result.Result.RawBytes};

           return rtn;
       }

start working normaly

Adding Channel Variable into a channels.originate

When i try to put in a channel variable it doesnt seem to make it to asterisk.

List<KeyValuePair<string,string>> bridgeID = new List<KeyValuePair<string,string>>(){
                    new KeyValuePair<string, string>("BRIDGEID", BRIDGEID)};

                    foreach(var element in bridgeID)
                    {
                        Console.WriteLine(element);
                    }

                    roboClient.Channels.Originate("SIP/200", "2011", "from-internal-custom", 6, null, null, null, null, bridgeID, newid, null);

How to click2dial?

I need to have a click to dial in our Net Core app, I tried below:

var _leg1 = _ari.Channels.Originate("PJSIP/1234", "908171234566", "from-internal", 1, null, "AppDial", null, "1234", 30, null, null, null, null);

Bridge _br = await _ari.Bridges.CreateAsync();
await _ari.Bridges.AddChannelAsync(_br.Id, _leg1.Id, "member");

it calls 1234 but it does not call 908171234566

please help

Consistantly get a 404 not found error when answering a channel

Any app compiled and run directly on the asterisk server, or remotely in visual studio, generates a 404 exception and aborts in the start event handler.

OS: Ubuntu 16.04.6 LTS
Mem: 2gb
Disk +20Gb free
Running in a VM on HyperV with 2 virtualised CPU Cores

Dotnet Info
image

CS Code is the test app sample available from this Repo

Build output
image

Asterisk Version:
image

Extension Setup:
image

ARI Setup:
image

Asterix HTTP setup:
image

Runtime output from ARI app:
image

Same Occurs in VS2019 (On core versions 2.0/2.1/2.2/3.0)
image

Wireshark Trace running while App test running shows:
image

This occurs no matter what code I write. As soon as an Answer is executed, everything ends with that 404

PlayAsync throwing exception

I am trying to run

await sender.Channels.PlayAsync(e.Channel.Id, "sound:custom/After-Lineup", null, null, null, e.Channel.Id);

in callback function OnStasisStartEvent

but everytime this line is executed following exception come and the music does not play. I have already check the sound file exist on correct path. Please guide me what the issue here? let me know if you need more info on this

2020-03-09 18:13:23,018 [8] ERROR Connector - c_OnStasisStartEventAsync|Exception:System.Net.Http.HttpRequestException: Response status code does not indicate success: 403 (Forbidden).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at RestSharp.Portable.HttpClient.Impl.Http.DefaultHttpResponseMessage.EnsureSuccessStatusCode()
   at RestSharp.Portable.RestClientBase.<ExecuteRequest>d__71.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at RestSharp.Portable.RestClientBase.<Execute>d__59`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at AsterNET.ARI.Middleware.Default.RestActionConsumer.<ProcessRestTaskCommand>d__5`1.MoveNext() in F:\Projects\Github\AsterNET.ARI\AsterNET.ARI\Middleware\Default\RESTActionConsumer.cs:line 0
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at AsterNET.ARI.ARIBaseAction.<ExecuteTask>d__5`1.MoveNext() in F:\Projects\Github\AsterNET.ARI\AsterNET.ARI\ARI_1_0\Actions\ARIBaseAction.cs:line 0
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at AsterNET.ARI.Actions.ChannelsActions.<PlayAsync>d__49.MoveNext() in F:\Projects\Github\AsterNET.ARI\AsterNET.ARI\ARI_1_0\Actions\ChannelsActions.cs:line 1588
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at vQubeConnector.vQubeAriConnector.<c_OnStasisStartEventAsync>d__11.MoveNext() in C:\Users\Zeeshan\Documents\GitHub\vQube\vQube\vQubeAriConnector.cs:line 76

403 Authentication Issue

Hi,

I'm getting the " The remote server returned an error: (403) Forbidden." WebException in the RestActionConsumer. Any idea how to overcome this ?

Thanks.

public IRestCommandResult<T> ProcessRestCommand<T>(IRestCommand command) where T : new()
    {
        var cmd = (Command) command;
        var result = cmd.Client.Execute<T>(cmd.Request); //here is where the exception occurs

        var rtn = new CommandResult<T> {StatusCode = result.StatusCode, Data = result.Data};

        return rtn;
    }

Not work send variables in Channels.Originate in Asterisk 13.8.2 (may be all 13.x)

In Asterisk 13.8.2 for create new channel variables send in BODY (not in URI) in JSON-format.

With using http://ari.asterisk.org/ - i set variables: {"variables":{"myvar":"zxcvzxcvxcv"}}
and all work fine;

But with code:
var per = new Dictionary<string, string>();
per.Add("myvar", "123456789");

Client.ClientIVR.Channels.Originate("Local/999@DialExtension", "s", "DialExtension", 1, variables: per, originator: e.Channel.Id);

Asterisk create channel BUT - without channels variables ((

References FUBAR

Created new VS 2019 Console App, Net Framework 4.5.2. Added AsterNet.ARI using NUGet.

Tried to run test code (Create StasisEndpoint then create/open ARIClient), get:

System.IO.FileLoadException: 'Could not load file or assembly 'WebSocket4Net, Version=0.15.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)'

Updated NewtonSoft.JSON, SuperSocket, WebSocket4Net via NUGet and tried again. Same result.

AsterNET.ARI - 1.2.1.0
FubarCoder.RestSharp.Portable.Core - 4.0.0.0
FubarCoder.RestSharp.Portable.Encodings - 4.0.0.0
FubarCoder.RestSharp.Portable.HttpClient - 4.0.0.0
Newtonsoft.Json - 12.0.0.0
SuperSocket.ClientEngine - 0.10.0.0
WebSocket4Net - 0.15.2.11

SimpleConf: Multiple conferences management

Hi,

In my app a user can set up a conference by completing a form in the web app UI which inserts the conference details into the local DB, like auto-incremented integers as conference Id's, callerId, Pin, startTime etc...

The SimpleConf Conference constructor has a Guid Id parameter that is generated on the spot each time a bridge is created?

My question is how can I link my set conference to the Stasis conference and add a caller into the correct conference in case of multiple conferences in the same time?

Thanks.
Dan

How to add recipient to Conference

I create Conference with SimpleConf demo. I can join to conference when I dial in. But how to dial out from running conference and add call to running conference?

I try to dial with ariClient.Channels.Originate(). My mobile rings and after I answer I'm not in the conference.

What I'm missing?

More a question that an issue

Hi Ben,

As I said in my email, I'm trying to create a conference app using your AsterNet.ARI project, but I have some unclarities/difficulties.
We have an external Asterisk server upgraded to version 13 to support the RESTful interface.
I've put the server/conference details into the app and it successfully connects: "Connection state is now true".

Q: It's not clear for me how can I create a dialplan application and test the app by dialing a number from my phone and receiving some kind of response, using AsterNet.ARI?

Thanks
Dan

Channel Not In Stasis Application

What am I missing here? Application always says -- Channel Not In Stasis Application

Here are the basics in my test:

DialerClient = new AriClient(new StasisEndpoint(endpoint, Convert.ToInt32(port), username, password), application);
DialerClient.Connect();
DialerClient.OnConnectionStateChanged += OnStateEvent;
DialerClient.OnStasisStartEvent += OnStartEvent;
DialerClient.OnStasisEndEvent += OnEndEvent;

** Events not shows

This is where it breaks:

var x = DialerClient.Channels.Originate("SIP/[email protected]", extension: "1000", app: application);
GlobalDialer.DialerClient.Channels.Ring(x.Id); -- Breaks here / With any event really

The channel is created, but when I look at the channel ids in the DialerClient there are none.
I thought that this was supposed to create the channel an register it in Stasis.
It never shows in Stasis. What could be going wrong?
What do I need to do to get the channel in the Stasis application?
Is the dial plan absolutely required?
If not can someone give me some example code for how it could be accomplished?

Thanks

Chris

How to update a call list in realtime?

I'm doing an application that shows a call list, I'm using "OnStasisStartEvent" and "OnStasisEndEvent", but it doesn't work. What else do I need to do?

Return the HttpStatusCode on each request

Hi there,

It would be useful if the framework will return the HTTP status code after you execute a HTTP request.

For example EventsActions::UserEvent method should return the IRestCommandResult from the execute method (or raise an exception).

Cheers,
Claudiu

Event ordering is not guaranteed.

Hi, I noticed that even though the events received from Asterisk do have an ordering guarantee (it's a concern in their design, for example see the fixed bugs here and here), the ordering is not guaranteed in the AriClient, because it dispatches the received events to the thread pool with Delegate.BeginInvoke().

One example is that a hangup event always must come before the stasis end event, and I can imagine other related issues, like the playback started and finished event, though I do not have much experience with ARI so far.

The WebSocket implementation does seem to guarantee the ordering, because there is always the .NET socket's IOCompletionCallback on the stack that is delivering the socket's data.

I don't see an elegant solution to this problem based on the current event handler based design of the AriClient. The only solution I can think of would be to provide a SynchronizationContext of a dedicated thread to dispatch the events to.

One alternative I can think of would require the following changes:

  • AriClient only maintains one properly ordered queue of events, probably including the connection state events.
  • Events can be dynamically dispatched to an object that implements interfaces of the particular method groups (channel, bridge, etc.). This way, clients can use the current thread or power up their own, then pull out one event after another from AriClient and dispatch the events to their object that implements their state machine.

Error switch doesn't work

Logic:

if ((int)response.StatusCode >= 200 && (int)response.StatusCode < 300)
                return;
            switch ((int)response.StatusCode)
            {
                case 400:
                    throw new AriException("Invalid reason for hangup provided", (int)response.StatusCode);
                case 404:
                    throw new AriException("Channel not found", (int)response.StatusCode);
                default:
                    // Unknown server response
                    throw new AriException(string.Format("Unknown response code {0} from ARI.", response.StatusCode), (int)response.StatusCode);
            }

and some similar code doesn't work it just throw exception if StatusCode not ok

Instructions

Is it possible to get instructions for SimpleConfAsync?
Simple 'How-To-Use' instructions.

Thanks in advance.

How use GetObject /UpdateObject ?

Centos 7
asterisk 16

I want use GetObject,UpdateObject to get /add a pjsip.but it's bad request
exp in Centos I use
$ curl -X PUT -H "Content-Type: application/json" -u asterisk:secret -d '{"fields": [ { "attribute": "auth_type", "value": "userpass"}, {"attribute": "username", "value": "alice"}, {"attribute": "password", "value": "secret" } ] }' https://localhost:8088/ari/asterisk/config/dynamic/res_pjsip/auth/alice

can add an auth,
but in asterNET.ARI, I like this to do ,but it's 400 (Bad request)

           ActionClient = new AriClient(new StasisEndpoint("192.168.137.211", 8088, "asterisk_ari", "123456"), AppName);

            var authDic = new Dictionary<string, string>();
              
            authDic.Add("auth_type", "userpass");
            authDic.Add("username", "alice");
            authDic.Add("password", "secret");
             ActionClient.Asterisk.UpdateObject("res_pjsip", "auth", "alice", authDic);

when alice is create by other way,it's sucess,but alice is not create ,it's return bad request

hope any help,tks

Having exception while trying to send notifications to SignalR connected clients based on DeviceStateChangeEvent

I'm trying to push notifications to clients who have connected to SignalR Hub based on related events are happening in PBX VOIP server.

I can get events using DeviceStateChangedEvent class from AsterNet using an event handler and want to push notification to clients related to their devices' state changes.

Also, SignalR connection is working as well and welcome message is showing on client web page.

But the problem is while sending notification by SendAsync method to caller client, my Hub goes to be disposed and below exception raised:

System.ObjectDisposedException: 'Cannot access a disposed object.
Object name: 'AgentHub'.'

Here is my Hub class.

using Microsoft.AspNetCore.SignalR;
using System;
using System.Threading.Tasks;
using AutoDialFinal.Models;
using AsterNET.ARI;
using AsterNET.ARI.Models;

namespace AutoDial.Hubs
{
    public class AgentHub : Hub
    {
        public AgentHub()
        {
            AriClient ActionClient;

            ActionClient = new AriClient(
                new StasisEndpoint("voip", 8088, "root", "password"),
                    "HelloWorld",
                    true);

            ActionClient.OnDeviceStateChangedEvent += ActionClientDeviceStateChangeEventAsync;

            ActionClient.Connect();

            void ActionClientDeviceStateChangeEventAsync(IAriClient sender, DeviceStateChangedEvent e)
            {
                var notification = new DeviceStateChangeNotification
                {
                    NotificationText = e.Device_state.Name + "'s state changed to " + e.Device_state.State,
                    SentAt = DateTime.Now.ToString()
                };

                SendNotificationToAgentAsync(notification);

            }
        }


        public override async Task OnConnectedAsync()
        {
            var notification = new DeviceStateChangeNotification
            {
                NotificationText = "Welcome!",
                SentAt = DateTime.Now.ToString()
            };

            await Clients.Caller.SendAsync(
                "ReceiveNotification",
                notification.NotificationText,
                notification.SentAt
            );

            await base.OnConnectedAsync();

        }

        public void SendNotificationToAgentAsync(DeviceStateChangeNotification notif)
        {
            Clients.Caller.SendAsync(
                "ReceiveNotification",
                notif.NotificationText,
                notif.SentAt
            );
        }
    }
}

Exception will raise in below method in ARIClient class while any device state change happening in PBX:

    private void _eventProducer_OnMessageReceived(object sender, MessageEventArgs e)
    {
        Debug.WriteLine(e.Message);
        // load the message
        var jsonMsg = (JObject)JToken.Parse(e.Message);
        var eventName = jsonMsg.SelectToken("type").Value<string>();
        var type = Type.GetType("AsterNET.ARI.Models." + eventName + "Event");
        var evnt =
            (type != null)
                ? (Event)JsonConvert.DeserializeObject(e.Message, type)
                : (Event)JsonConvert.DeserializeObject(e.Message, typeof(Event));

        lock (_syncRoot)
        {
            if (_dispatcher == null)
                return;

            _dispatcher.QueueAction(() =>
            {
                try
                {
                    FireEvent(evnt.Type, evnt, this);
                }
                catch(Exception ex)
                {

                    **// HERE IS WERE EXCEPTION IS RAISING**

                    // Handle any exceptions that were thrown by the invoked event handler
                    if (!UnhandledException(this, ex))
                    {
                        Console.WriteLine("The event listener " + evnt.Type.ToString() + " cause an exeption: " + ex.Message);
                    }
                }
            });
        }
    }

How do I fix this problem?
Thank you

Pass data from exteernal Stasis app to DialPlan

Hi,

I need to know if there's a way to pass data from an external Stasis app to a Dialplan. I'm using ...channel//continue

Scenario:

  • call from outside world is directed to an extension and dialplan in Asterisk
  • Dialplan Answers and places the channel into an external stasisapp
  • Stasis app performs some functionality then sends the channel back to dialplan
    (...channel//continue)

exten => 1001,1,NoOp(entering ${CONTEXT} as defined in extensions_custom.conf) same => n,Answer() same => n,Stasis(ZIN1,arg1) same => n,Hangup()

The data I wish to pass the dialplan could be char or numeric.

Thank you

Can an app have duplicate Stasis App Names which behave like instances?

I have an application with 5 threads, Each thread establishes an connection to Asterisk with the same Stasis App Name. I assumed that each connection creates an "instance" of the stasis app name. However, only the 1 thread gets messages from Channels that have been placed in that app.

I've checked the Asterisk logging, and it appears as if the Stasis App gets overwritten each time, as it's sharing the name of an existing app.

If possible, could someone elaborate on why this happens? I would have expected all the threads subscribing to the same app name to get duplicate events.

Please advise if you require any further info.

Thank you
Sue

How to solve Web4Socket Issue ?

Error Message "Could not load file or assembly 'WebSocket4Net, Version=0.14.1.0, Culture=neutral, PublicKeyToken=eb4e154b696bf72a' or one of its dependencies. The system cannot find the file specified"

Projects built on .NET full won't run due to WebSocket4Net error

Creating projects running on .NET core work perfectly, but to use speech synthesis I need to target the full .NET platform, as the speech synthesis assemblies are not yet available on core.

I've gone back in full .NET versions as far as I can without all the dependencies AsterNET uses, falling apart and the earliest version test is .NET v4.5.1

I have tested all the way up to v4.7.2 using both Visual Studio 2017 and Visual Studio 2019 (Release and Preview Builds) running as Admin and not as Admin.

In all cases, everything builds and references fine, but as soon as you try to run the app the following exception is thrown.

image

For reference, I've also performed recommended NuGet updates (Taking Websocket up to 0.15.12) and as well as reinstalling against different versions, have also test built from scratch.

Output seen in image is 100% consistent every time, have tested this on 2 different asterisk servers and same result.

originate example

Hi, This is more a request than an issue. I am new to asterisk and ari, I managed to get the examples up and runnning on a freepbx installation but I'm battling with making and outbound call "Originate".

Can you assist me with a simple example of dialing an internal extension from an internal extension using asternet.ari? I want to use this as a click to dial function not neccessarily from within a bridge.

Also, is asternet.ari recommended for outbound dialing or should I rather consider AMI for dialing?

Any help will be much appreciated.

Thanks,

Asternet softphone

I need to register my extensions to the asterisk using Asternet.ARI (like other softphone), then set events such as receiving call, registration for having conversation between clients connected to the asterisk(using Asternet).
dose Asternet.Ari support my need without using a third party softphone application like X-Lite?
I'm trying to implement Asternet to ASP Core web app and not willing to use libraries such as Sip.js...

No errors when read only

I recently re-installed Asterisk so I had to create a new ari user.

When trying to use this package to create a call it got stuck when creating a bridge and no error was thrown.

I later found wat was wrong, I forgot to set the read_only variable in my ari user to no.
I found this when testing ari with curl:

>curl -v -u username:password -X POST http://192.168.2.22:8088/ari/bridges
*   Trying 192.168.2.22...
* TCP_NODELAY set
* Connected to 192.168.2.22 (192.168.2.22) port 8088 (#0)
* Server auth using Basic with user 'username'
> POST /ari/bridges HTTP/1.1
> Host: 192.168.2.22:8088
> Authorization: Basic YXJpX2Nvbm5lY3Rvcjp0ZXN0bWU=
> User-Agent: curl/7.55.1
> Accept: */*
>
< HTTP/1.1 403 Forbidden
< Server: Asterisk/16.6.1
< Date: Mon, 29 Mar 2021 08:48:13 GMT
< Cache-Control: no-cache, no-store
< Content-type: application/json
< Content-Length: 38
<
{
  "message": "Write access denied"
}* Connection #0 to host 192.168.2.22 left intact

Could this package maybe throw an error when you are in read_oly mode and you are trying to update/create?
Thank you in advance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.