예제 #1
0
 /// <summary>
 ///  Makes adjustments to path based on whether the path is relative or not
 /// </summary>
 /// <param name="path"></param>
 /// <param name="queryParams"></param>
 /// <param name="authenticator"></param>
 /// <returns></returns>
 public string MakeUrl(string path, Values queryParams = null, Authenticator authenticator = null)
 {
     if (path.StartsWith("http:", StringComparison.InvariantCultureIgnoreCase) ||
         path.StartsWith("https:", StringComparison.InvariantCultureIgnoreCase))
     {
         return(SdkUtils.AddQueryParams(path, queryParams));
     }
     // TODO I don't think authenticator is needed here any more?
     return(SdkUtils.AddQueryParams($"{BaseUrl}{path}", queryParams));
 }
예제 #2
0
        public override string ToString()
        {
            var sb = new StringBuilder();

            foreach (var item in this)
            {
                sb.Append(SdkUtils.EncodeParam(item));
                sb.Append(Delimiter);
            }

            // remove last delimiter
            if (Count > 1)
            {
                sb.Remove(sb.Length - Delimiter.Length, Delimiter.Length);
            }

            return(sb.ToString());
        }
예제 #3
0
        public static SdkResponse <TSuccess, TError> ParseResponse <TSuccess, TError>(IRawResponse response)
            where TSuccess : class where TError : class
        {
            if (response.Body is Exception)
            {
                return(new SdkResponse <TSuccess, TError> {
                    Error = response.Body as TError
                });
            }

            switch (SdkUtils.ResponseMode(response.ContentType))
            {
            case ResponseMode.Binary:
                return(new SdkResponse <TSuccess, TError> {
                    Value = response.Body as TSuccess
                });

            case ResponseMode.String:
                if (response.ContentType.StartsWith("application/json"))
                {
                    return(new SdkResponse <TSuccess, TError>
                    {
                        Value = JsonConvert.DeserializeObject <TSuccess>(response.Body.ToString())
                    });
                }
                else
                {
                    return(new SdkResponse <TSuccess, TError> {
                        Value = response.Body.ToString() as TSuccess
                    });
                }

            case ResponseMode.Unknown:
                return(new SdkResponse <TSuccess, TError>
                {
                    Error = JsonConvert.DeserializeObject <TError>(response.Body.ToString())
                });

            default:
                throw new ArgumentOutOfRangeException($"Unrecognized Content Type {response.ContentType}");
            }
        }
예제 #4
0
        public async Task <IRawResponse> RawRequest(
            HttpMethod method,
            string path,
            Values queryParams          = null,
            object body                 = null,
            Authenticator authenticator = null,
            ITransportSettings options  = null
            )
        {
            var url     = MakeUrl(path, queryParams, authenticator);
            var request = new HttpRequestMessage(method,
                                                 url);

            request.Headers.Add(Constants.LookerAppiId, _settings.AgentTag);
            if (body != null)
            {
                if (body is string)
                {
                    request.Content = new StringContent(
                        body.ToString(),
                        Encoding.UTF8,
                        "application/x-www-form-urlencoded");
                }
                else
                {
                    request.Content =
                        new StringContent(
                            JsonSerializer.Serialize(body, new JsonSerializerOptions {
                        IgnoreNullValues = true
                    }),
                            Encoding.UTF8,
                            "application/json");
                }
            }

            if (authenticator != null)
            {
                request = await authenticator(request);
            }
            RawResponse         result   = new RawResponse();
            HttpResponseMessage response = null;

            try
            {
                response = await _client.SendAsync(request);

                result = InitRawResponse(response);
                // if (response.IsSuccessStatusCode)
                await using var stream = await response.Content.ReadAsStreamAsync();

                // Simple content conversion here to make body easily readable in consumers
                switch (SdkUtils.ResponseMode(result.ContentType))
                {
                case ResponseMode.Binary:
                    result.Body = SdkUtils.StreamToByteArray(stream);
                    break;

                case ResponseMode.String:
                    using (var sr = new StreamReader(stream))
                    {
                        result.Body = await sr.ReadToEndAsync();
                    }

                    break;

                case ResponseMode.Unknown:
                    result.Body = SdkUtils.StreamToByteArray(stream);
                    break;

                default:
                    throw new ArgumentOutOfRangeException($"Unrecognized Content Type {result.ContentType}");
                }
            }
            catch (Exception e)
            {
                result      = InitRawResponse(response);
                result.Body = e;
            }

            return(result);
        }
예제 #5
0
        private async Task <object> _login(string sudoId = null)
        {
            await SudoLogout();

            if (sudoId != SudoId)
            {
                SudoId = sudoId;
            }

            if (!_authToken.IsActive())
            {
                Reset();
                // only retain client API3 credentials for the lifetime of the login request
                var section  = Settings.ReadConfig();
                var clientId = section["client_id"].ToString();
                var secret   = section["client_secret"].ToString();
                if (clientId.IsNullOrEmpty() || secret.IsNullOrEmpty())
                {
                    throw new SdkError("API3 credentials client_id and/or client_secret are not set");
                }

                var body     = $"client_id={SdkUtils.EncodeParam(clientId)}&client_secret={SdkUtils.EncodeParam(secret)}";
                var apiToken = await Ok(Transport.Request <AccessToken, Exception>(
                                            HttpMethod.Post,
                                            $"{_apiPath}/login",
                                            null,
                                            body
                                            ));

                this._authToken.SetToken(apiToken);
            }

            if (sudoId.IsNullOrEmpty())
            {
                return(this.ActiveToken);
            }
            // Now that API user is logged in, login as the Sudo user
            var token = this.ActiveToken;

            async Task <HttpRequestMessage> Auth(HttpRequestMessage request)
            {
                if (token.access_token.IsFull())
                {
                    request.Headers.Authorization = new AuthenticationHeaderValue(
                        Constants.Bearer, token.access_token);
                }

                return(await Task.FromResult(request));
            }

            var sudoPath  = $"{_apiPath}/login/{SdkUtils.EncodeParam(sudoId)}";
            var sudoToken = await Ok(Transport.Request <AccessToken, Exception>(
                                         HttpMethod.Post,
                                         sudoPath,
                                         null,
                                         null,
                                         Auth
                                         ));

            _sudoToken.SetToken(sudoToken);
            return(ActiveToken);
        }
예제 #6
0
 protected Task <TSuccess> Ok <TSuccess, TError>(Task <SdkResponse <TSuccess, TError> > task) where TSuccess : class
     where TError : Exception
 {
     return(SdkUtils.Ok(task));
 }