Exemple #1
0
        private string BuildUrl(ApiCommand command, string value)
        {
            const string API_SEARCH_COMMAND = "search";
            const string API_GET_COMMAND    = "get";
            const string SEARCH_URL_PARAM   = "q";
            const string GET_URL_PARAM      = "rId";

            string url = URI_API;

            switch (command)
            {
            case ApiCommand.Search:
                url += String.Format($"{API_SEARCH_COMMAND}?{API_KEY_PARAM_NAME}={API_KEY}&{SEARCH_URL_PARAM}={value}");
                break;

            case ApiCommand.Get:
                url += String.Format($"{API_GET_COMMAND}?{API_KEY_PARAM_NAME}={API_KEY}&{GET_URL_PARAM}={value}");
                break;

            default:
                url += API_SEARCH_COMMAND;
                break;
            }

            return(url);
        }
 public bool Contains(ApiCommand message)
 {
     lock (_sync)
     {
         return(_cache.Contains(message.Endpoint.ToString()));
     }
 }
 public CommandBody(ApiCommand command, Guid aId = default, Guid bId = default, object data = null)
 {
     Command = command;
     AId     = aId;
     BId     = bId;
     Data    = data;
 }
Exemple #4
0
        public async Task <List <BindableItem> > ToggleItems(List <BindableItem> items)
        {
            var commands = new List <ApiCommand>();

            foreach (var bindableItem in items)
            {
                var command = new ApiCommand();
                if (bindableItem.Checked)
                {
                    command.Type = "item_complete";
                }
                else
                {
                    command.Type = "item_uncomplete";
                }
                command.Args = new CommandArguments {
                    Ids = new List <int> {
                        bindableItem.Id
                    }
                };
                commands.Add(command);
            }

            var syncData = await _webSyncService.RetrieveAllItemsAsync(commands);

            await UpdateDatabase(syncData);

            return(syncData.Items.Select(i => i.ToBindableItem()).ToList());
        }
 public void Add(ApiCommand message)
 {
     lock (_sync)
     {
         _cache.Set(message.Endpoint.ToString(), Guid.NewGuid(), DateTimeOffset.UtcNow.Add(message.CachePeriod));
     }
 }
Exemple #6
0
 static void Main(string[] args)
 {
     IApiCommand apiCommand = new ApiCommand();
     var         academy    = apiCommand.GetAcademy(new GetAcademyRequest()
     {
         AcademyId = 1
     });
 }
        /// <summary>
        /// Executes an api action.
        /// </summary>
        ///
        /// <param name="command">Api command.</param>
        /// <param name="parameters">Parameters format of an api command uri.</param>
        public static T ApiAction <T>(ApiCommand command, params object[] parameters)
        {
            var uri =
                ApiDictionary[command]
                .With(parameters);

            return(ApiAction <T>(uri));
        }
        /// <summary>
        ///
        /// </summary>
        ///
        /// <param name="command"></param>
        /// <param name="method"></param>
        /// <param name="extraParameters"></param>
        /// <param name="parameters"></param>
        public static T ApiAction <T>(ApiCommand command, HttpMethod method, Dictionary <string, object> extraParameters, params object[] parameters)
        {
            var uri =
                ApiDictionary[command]
                .UriAppendingParameters(extraParameters)
                .With(parameters);

            return(ApiAction <T>(uri, method));
        }
        /// <summary>
        /// Executes an api action.
        /// </summary>
        ///
        /// <param name="command">Api command;</param>
        /// <param name="extraParameters">Dictionnary of parameters to be passed in the api action uri.</param>
        public static T ApiAction <T>(ApiCommand command, Dictionary <string, object> extraParameters)
        {
            var uri =
                ApiDictionary[command]
                .UriAppendingParameters(extraParameters);


            return(ApiAction <T>(uri));
        }
        /// <summary>
        /// Executes an api action.
        /// </summary>
        ///
        /// <param name="command">Api command.</param>
        /// <param name="method">Http method. <seealso cref="HttpMethod"/>.</param>
        /// <param name="parameters">Parameters format of an api command uri.</param>
        public static T ApiAction <T>(ApiCommand command, HttpMethod method, params object[] parameters)
        {
            var uri =
                ApiDictionary[command]
                .With(parameters);

            bool requireAuthentication = command != ApiCommand.UserCredentialsFlow;

            return(ApiAction <T>(uri, method, requireAuthentication));
        }
        public async Task <ApiResponse> SendApiAsync(ApiCommand command,
                                                     IChannel context)
        {
            var asyncEvent = new CommandAsyncEvent(command);

            CommandAsyncEvents.Enqueue(asyncEvent);
            await context.WriteAndFlushAsync(command);

            return(await asyncEvent.Task as ApiResponse);
        }
        public async Task <ApiResponse> SendApiAsync(ApiCommand apiCommand)
        {
            if (!CanSend())
            {
                return(null);
            }
            var handler  = (InboundSessionHandler)Channel.Pipeline.Last();
            var response = await handler.SendApiAsync(apiCommand, Channel);

            return(response);
        }
        /// <summary>
        ///     SendApi().
        ///     It is used to send an api command to FreeSwitch.
        /// </summary>
        /// <param name="command"></param>
        /// <returns>ApiResponse response</returns>
        public async Task <ApiResponse> SendApi(ApiCommand command)
        {
            if (!Connected)
            {
                return(null);
            }
            // Send the command
            var event2 = EnqueueCommand(command);

            await SendAsync(command);

            return(await event2.Task as ApiResponse);
        }
Exemple #14
0
        public object Post([FromBody] ApiCommand command)
        {
            if (command != null && mCommandRepository.IsSupported(command))
            {
                //command.Context.ClientIpAddress = Request.HttpContext.GetFeature<IHttpConnectionFeature>( )?.RemoteIpAddress;

                var result = mCommandRepository.Invoke(command);

                return(result);
            }
            else
            {
                return(new { Message = string.Format("Command '{0}' is not supported.", command?.Name) });
            }
        }
Exemple #15
0
        public static async Task <ApiResponse> ExecuteCommand(ApiCommand command, string[] pars)
        {
            var response = new ApiResponse();

            ReqLog.Add(response);

            // Get command string from commsnd's attribute
            var apiAttr = command.GetAttribute <ApiCommandAttribute>();

            if (apiAttr.ParamCount != pars.Length)
            {
                response.ErrorMessage = "Ошибка формирования запроса к серверу.";
                return(response);
            }

            string url = API_URL;

            response.Request = url + string.Format(apiAttr.FormatString, pars);

            while (isBusy)
            {
                await Task.Delay(200);
            }

            try
            {
                isBusy = true;

                if (HttpClient == null)
                {
                    httpCookieHandler  = new NativeCookieHandler();
                    httpMessageHandler = new NativeMessageHandler(true, false, httpCookieHandler);
                    httpMessageHandler.ClientCertificateOptions = ClientCertificateOption.Automatic;
                    HttpClient = new HttpClient(httpMessageHandler, false);
                }

                try
                {
                    Debug.WriteLine("Request: {0}", response.Request);
                    var res = await HttpClient.GetAsync(response.Request).ConfigureAwait(false);

                    Debug.WriteLine("Read content");
                    response.Response = await res.Content.ReadAsStringAsync().ConfigureAwait(false);

                    //response.response = await httpClient.GetStringAsync(response.request);
                    Debug.WriteLine("Response: {0}", response.Response);
                    // Обработка напильником, блять!
                    //response.response = response.response.Replace("\"vUser\":[],", string.Empty);

                    if (string.IsNullOrEmpty(response.Response))
                    {
                        response.ErrorMessage = "Сервер не отвечает, попробуйте повторить позже";
                        return(response);
                    }
                    response.RequestDone = true;
                }
                catch (Exception e)
                {
                    response.BoolResult   = false;
                    response.ErrorMessage = "Ошибка отправки запроса на сервер " + Environment.NewLine + e.Message;
                    //GoogleAnalyticsHelper.SendException("MFService:ExecuteCommand " + e.Message, false);
                    return(response);
                }

                try
                {
                    long x = 0;
                    JsonConvert.PopulateObject(response.Response, response);
                    response.BoolResult = response?.Result?.ToUpper() == "TRUE" || response?.Result?.ToUpper() == "OK";
                    if (!response.BoolResult)
                    {
                        if (!string.IsNullOrEmpty(response.Error))
                        {
                            response.ErrorMessage = response.Error;
                        }
                        else if (string.IsNullOrEmpty(response.ErrorMessage))
                        {
                            response.ErrorMessage = "Запрос к серверу вернул отрицательный результат";
                        }
                    }
                    return(response);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                    response.BoolResult   = false;
                    response.ErrorMessage = "Ошибка при разборе ответа от сервера";
                    //GoogleAnalyticsHelper.SendException("MFService:ExecuteCommand " + e.Message, false);
                    return(response);
                }
            }
            finally
            {
                isBusy = false;
            }
        }
 public void Send(ApiCommand command, byte[] data)
 {
     Send((byte)command, data);
 }
 public void Send(ApiCommand command, object obj)
 {
     Send((byte)command, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(obj)));
 }
 public void Send(ApiCommand command)
 {
     Send((byte)command, new byte[0]);
 }
Exemple #19
0
        public static bool TryParseCommand(string RelativeUrl, string HttpMethod, out ApiCommand command, string beforeapi = null)
        {
            if (string.IsNullOrEmpty(beforeapi))
            {
                beforeapi = "_api";
            }
            command            = new ApiCommand();
            command.HttpMethod = HttpMethod;
            if (string.IsNullOrEmpty(RelativeUrl))
            {
                command = null;
                return(false);
            }
            int questionMarkIndex = RelativeUrl.IndexOf("?");

            if (questionMarkIndex > -1)
            {
                if (questionMarkIndex == 0)
                {
                    return(false);
                }
                else
                {
                    RelativeUrl = RelativeUrl.Substring(0, questionMarkIndex);
                }
            }
            RelativeUrl = RelativeUrl.Replace("\\", "/");

            RoutingState state = RoutingState.BeforeApi;

            string[] segments = RelativeUrl.Split('/');

            foreach (var item in segments)
            {
                if (string.IsNullOrEmpty(item))
                {
                    if (state == RoutingState.BeforeApi)
                    {
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    switch (state)
                    {
                    case RoutingState.BeforeApi:
                    {
                        if (item.ToLower() == beforeapi)
                        {
                            state = RoutingState.BeforeObject;
                            continue;
                        }
                        else
                        {
                            return(false);
                        }
                    }

                    case RoutingState.BeforeObject:


                        command.ObjectType = item;
                        state = RoutingState.AfterObject;
                        break;

                    case RoutingState.AfterObject:
                        command.Method = item;
                        state          = RoutingState.AfterCommand;
                        break;

                    case RoutingState.AfterCommand:
                        command.Value = item;
                        state         = RoutingState.AfterValue;
                        break;

                    case RoutingState.AfterValue:

                        if (command.Parameters.Count == 0)
                        {
                            command.Parameters.Add(command.Value);
                        }
                        command.Parameters.Add(item);
                        // return false;
                        break;

                    default:
                        break;
                    }
                }
            }

            if (state == RoutingState.BeforeObject || state == RoutingState.BeforeApi)
            {
                return(false);
            }
            else
            {
                if (string.IsNullOrEmpty(command.Method))
                {
                    command.Method = HttpMethod;
                }
                return(true);
            }
        }
        private static void Main(string[] args)
        {
            // Let us start the outboud server
            server              = new FreeSwitchServer();
            server.ClientReady += OnClientReady;

            server.Start(IPAddress.Parse("192.168.74.1"), ServerPort);
            Thread.Sleep(500);

            string evenlist = "BACKGROUND_JOB  CHANNEL_PROGRESS  CHANNEL_PROGRESS_MEDIA  CHANNEL_HANGUP_COMPLETE  CHANNEL_STATE SESSION_HEARTBEAT  CALL_UPDATE RECORD_STOP  CHANNEL_BRIDGE  CHANNEL_UNBRIDGE  CHANNEL_ANSWER  CHANNEL_ORIGINATE CHANNEL_EXECUTE  CHANNEL_EXECUTE_COMPLETE";

            client = new OutboundChannelSession(Address, Port, Password, evenlist);
            client.OnChannelProgressMedia += OnChannelProgressMedia;
            client.OnChannelState         += OnChannelState;
            bool connected = Connect().Result;

            if (connected)
            {
                Thread.Sleep(500);

                Log.Info("Connection Status {0}", client.Connected);
                Log.Info("Authentication Status {0}", client.Authenticated);

                var         command  = new ApiCommand("sofia profile external gwlist up");
                ApiResponse response = client.SendApi(command).Result;
                if (response == null)
                {
                    Log.Info("No gateways available");
                }
                else if (string.IsNullOrEmpty(response.Body))
                {
                    Log.Info("No gateways available");
                }
                else
                {
                    List <string> gws = response.Body.Split().ToList();
                    if (gws.Any())
                    {
                        var counter = 1;
                        foreach (var gw in gws)
                        {
                            Log.Info("Gateway no {0} : {1}", counter++, gw);
                        }
                    }
                }

                command  = new ApiCommand("sofia status");
                response = client.SendApi(command).Result;
                Log.Info("sofia status :\n");
                Log.Info("\n\n" + response.Body);

                // Let us make a call and handle it
                string       callCommand  = "{ignore_early_media=false,originate_timeout=120}sofia/gateway/smsghlocalsip/233247063817 &socket(192.168.74.1:10000 async full)";
                BgApiCommand bgapicommand = new BgApiCommand("originate", callCommand);
                Guid         jobId        = client.SendBgApi(bgapicommand).Result;
                Log.Info("Job Id {0}", jobId);

                Thread.Sleep(500);

                // EslLogLevels levels = EslLogLevels.INFO;
                // client.SetLogLevel(levels);

                // client.CloseAsync();

                //Thread.Sleep(500);
                //Log.Info("Connection Status {0}", client.Connected);
                //Log.Info("Authentication Status {0}", client.Authenticated);
            }

            Console.ReadKey();
        }
Exemple #21
0
 /// <summary>构造函数</summary>
 /// <param name="ip">IP</param>
 /// <param name="port">端口</param>
 /// <param name="cn">指令号</param>
 public CommandApi(string ip, Int32 port, ApiCommand cn)
 {
     IP   = ip;
     Port = port;
     CN   = cn;
 }