예제 #1
0
        internal static User GetWhoAmI(IEnumerable <FluxCookie> cookies, SDKMetadata sdkMetadata)
        {
            if (cookies == null)
            {
                return(null);
            }

            var authCookie = cookies.FirstOrDefault(el => el.CookieName == FluxApiData.CookiesAuthName);

            if (authCookie == null)
            {
                return(null);
            }

            User user    = null;
            var  request = HttpWebClientHelper.CreateRequest(sdkMetadata, FluxApiData.WhoAmIUrl, cookies.ToList());

            request.Method = "GET";
            using (var response = HttpWebClientHelper.GetResponse(request))
            {
                user = DataSerializer.Deserialize <User>(StreamUtils.GetDecompressedResponseStream(response));
            }

            user.SdkMetadata = sdkMetadata;
            user.Cookies     = cookies.ToList();

            return(user);
        }
예제 #2
0
        /// <summary>Update list of projects for the current user. </summary>
        /// <exception cref="Exceptions.ConnectionFailureException">Throws if network connection is down.</exception>
        /// <exception cref="Exceptions.UnathorizedException">Throws if provided cookies were obsolete.</exception>
        /// <exception cref="Exceptions.ServerUnavailableException">Throws if Flux server is down.</exception>
        /// <exception cref="Exceptions.InternalSDKException">Throws for unhandled SDK exceptions.</exception>
        public void UpdateProjects()
        {
            var projectList = new List <Project>();
            var request     = HttpWebClientHelper.CreateRequest(SdkMetadata, FluxApiData.ProjectsUrl, Cookies);

            request.Method = "GET";
            request.Headers.Add("user", Id);
            try
            {
                using (var response = HttpWebClientHelper.GetResponse(request))
                {
                    projectList = DataSerializer.Deserialize <List <Project> >(StreamUtils.GetDecompressedResponseStream(response));
                }
            }
            catch (Exceptions.FluxException ex)
            {
                log.Error(ex);
                throw;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw new Exceptions.InternalSDKException(ex.Message);
            }

            Projects = projectList;
        }
예제 #3
0
        /// <summary>Convert brep to specified format.</summary>
        /// <param name="content">Brep to convert (base64 encoded string).</param>
        /// <param name="sourceFormat">Source format of brep.</param>
        /// <param name="targetFormat">Target format of brep</param>
        /// <returns>Converted brep (base64 encoded string).</returns>
        /// <exception cref="Exceptions.ConnectionFailureException">Throws if network connection is down.</exception>
        /// <exception cref="Exceptions.UnathorizedException">Throws if provided cookies were obsolete.</exception>
        /// <exception cref="Exceptions.ServerUnavailableException">Throws if Flux server is down.</exception>
        /// <exception cref="Exceptions.InternalSDKException">Throws for unhandled SDK exceptions.</exception>
        public string ConvertBrep(string content, string sourceFormat, string targetFormat)
        {
            if (string.IsNullOrEmpty(content))
            {
                return(null);
            }

            #region Create object wrapper for brep

            var brep = new BrepToConvert.SceneObject.BrepPrimitive();
            brep.Primitive = "brep";
            brep.Format    = sourceFormat;
            brep.Content   = content;

            var entities = new BrepToConvert.SceneObject.EntitiesObject();
            entities.Brep = brep;

            BrepToConvert.SceneObject scene = new BrepToConvert.SceneObject();
            scene.Entities = entities;
            var initObj = new BrepToConvert.SceneObject.OperationObj();
            initObj.Name = "result";
            initObj.Op   = new string[] { "repr", targetFormat, "brep@1" };

            scene.Operations = new object[] { initObj };

            var brepToConvert = new BrepToConvert();
            brepToConvert.Scene = scene;

            #endregion

            var request = WriteBrepToRequest(brepToConvert);

            try
            {
                using (var response = HttpWebClientHelper.GetResponse(request))
                {
                    dynamic responseJson     = DataSerializer.DynamicDeserialize(StreamUtils.GetDecompressedResponseStream(response));
                    dynamic convertedContent = responseJson.Output.Results.value.result.content;
                    if (convertedContent != null)
                    {
                        object contentStr = convertedContent;
                        return(contentStr.ToString());
                    }
                }
            }
            catch (Exceptions.FluxException ex)
            {
                log.Error(ex);
                throw;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw new Exceptions.InternalSDKException(ex.Message);
            }

            return(null);
        }
예제 #4
0
        public static string GetResponseString(HttpWebResponse response)
        {
            string responseStr = string.Empty;

            if (response != null)
            {
                using (var stream = StreamUtils.GetDecompressedResponseStream(response))
                {
                    var reader = new StreamReader(stream);
                    responseStr = reader.ReadToEnd();
                }
            }

            return(responseStr);
        }
예제 #5
0
        /// <summary>Create new project.</summary>
        /// <param name="projectName">name of the new project.</param>
        /// <returns>Porject instance if project was created successully.</returns>
        /// <exception cref="Exceptions.FluxException">Throws for internal SDK exceptions (Network is down, etc.).</exception>
        /// <exception cref="Exceptions.InternalSDKException">Throws for unhandled SDK exceptions.</exception>
        public async Task <Project> CreateNewProjectAsync(string projectName)
        {
            Project newProject = null;
            var     request    = HttpWebClientHelper.CreateRequest(SdkMetadata, FluxApiData.ProjectsUrl, Cookies);

            request.Method = "POST";

            try
            {
                string formParams = string.Format("user={0}&name={1}&app={2}", Uri.EscapeDataString(Id), Uri.EscapeDataString(projectName), Uri.EscapeDataString("blank"));
                byte[] bytes      = Encoding.ASCII.GetBytes(formParams);
                request.ContentLength = bytes.Length;
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(bytes, 0, bytes.Length);
                }

                using (var response = await HttpWebClientHelper.GetResponseAsync(request))
                {
                    newProject = DataSerializer.Deserialize <Project>(StreamUtils.GetDecompressedResponseStream(response));
                    if (newProject != null)
                    {
                        newProject.Cookies     = Cookies;
                        newProject.SdkMetadata = SdkMetadata;
                    }

                    if (projects != null)
                    {
                        projects.Add(newProject);
                    }
                }
            }
            catch (Exceptions.FluxException ex)
            {
                log.Error(ex);
                throw;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw new Exceptions.InternalSDKException(ex.Message);
            }

            return(newProject);
        }
예제 #6
0
        internal void ObtainToken(Uri uri)
        {
            try
            {
                var code            = HttpUtility.ParseQueryString(uri.Query).Get("code");
                var fluxToken       = HttpUtility.ParseQueryString(uri.Query).Get("flux_token");
                var returnedStateId = HttpUtility.ParseQueryString(uri.Query).Get("state");

                //we MUST verify state
                if (string.IsNullOrEmpty(returnedStateId) || returnedStateId != stateId.ToString())
                {
                    throw new Exceptions.AuthorizationFailedException("State uuids don't match.");
                }

                //requesting access_token
                var request = HttpWebClientHelper.CreateRequest(sdkMetadata, FluxApiData.TokenUrl, null);
                request.Method      = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                var authStr      = sdkMetadata.ClientInfo.ClientId + ":" + clientSecret;
                var authStrBytes = Encoding.UTF8.GetBytes(authStr);
                request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authStrBytes);

                string formParams = string.Format("client_id={0}&code={1}&grant_type=authorization_code&redirect_uri={2}",
                                                  Uri.EscapeDataString(sdkMetadata.ClientInfo.ClientId),
                                                  Uri.EscapeDataString(code),
                                                  Uri.EscapeUriString(RedirectUrl));

                byte[] bytes = Encoding.ASCII.GetBytes(formParams);
                request.ContentLength = bytes.Length;
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(bytes, 0, bytes.Length);
                }

                using (var response = HttpWebClientHelper.GetResponse(request))
                {
                    var token = DataSerializer.Deserialize <Token>(StreamUtils.GetDecompressedResponseStream(response));

                    if (token != null && !string.IsNullOrEmpty(token.AccessToken) && !string.IsNullOrEmpty(fluxToken) && !string.IsNullOrEmpty(token.IdToken))
                    {
                        //verify nonce uuid
                        JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(token.IdToken);
                        var returnedNonceId = jwtSecurityToken.Payload.Nonce;
                        if (string.IsNullOrEmpty(returnedNonceId) || returnedNonceId != nonceId.ToString())
                        {
                            throw new Exceptions.AuthorizationFailedException("Nonce uuids don't match.");
                        }

                        token.FluxToken = fluxToken;
                        Init(token);

                        var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Flux\fluxData.bin");
                        if (!string.IsNullOrEmpty(AccessToken) && !string.IsNullOrEmpty(FluxToken))
                        {
                            var cookies  = new List <FluxCookie>();
                            var authCook = new FluxCookie()
                            {
                                CookieName   = "auth",
                                CookieValue  = Uri.UnescapeDataString(AccessToken),
                                CookieDomain = sdkMetadata.BaseUri.Host
                            };
                            cookies.Add(authCook);

                            var fluxCook = new FluxCookie()
                            {
                                CookieName   = "flux_token",
                                CookieValue  = Uri.UnescapeDataString(FluxToken),
                                CookieDomain = sdkMetadata.BaseUri.Host
                            };
                            cookies.Add(fluxCook);

                            Utils.StoreOICCookies(path, cookies, sdkMetadata.ClientInfo.ClientId);
                        }
                    }
                    else
                    {
                        log.Debug("Unable to receive token.");
                        throw new Exceptions.AuthorizationFailedException(
                                  "Authentication has been failed. See log for more details.");
                    }
                }
            }
            catch (Exceptions.AuthorizationFailedException)
            {
                throw;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw new Exceptions.AuthorizationFailedException(ex.Message);
            }
        }
예제 #7
0
        private static void HandleWebException(WebException ex)
        {
            var httpResponse = (HttpWebResponse)ex.Response;

            if (httpResponse == null)
            {
                if (ex.Status == WebExceptionStatus.Timeout || ex.Status == WebExceptionStatus.NameResolutionFailure ||
                    ex.Status == WebExceptionStatus.ConnectFailure)
                {
                    throw new Exceptions.ConnectionFailureException(ex);
                }
                else
                {
                    throw ex;
                }
            }

            if (ex.Status == WebExceptionStatus.ProtocolError)
            {
                var content = new StreamReader(StreamUtils.GetDecompressedResponseStream(httpResponse)).ReadToEnd();
                log.Error(content);
                log.Error("Unable to get data from server. Server returns {0}", httpResponse.StatusCode);

                switch (httpResponse.StatusCode)
                {
                case 0:
                    break;

                case HttpStatusCode.NoContent:
                    break;                        //204 return null for empty response

                case HttpStatusCode.Unauthorized: //401
                {
                    throw new Exceptions.UnathorizedException();
                }

                case HttpStatusCode.Forbidden:     //403
                {
                    throw new Exceptions.ForbiddenException();
                }

                case HttpStatusCode.NotFound:     //404
                {
                    throw new Exceptions.NotFoundException();
                }

                case HttpStatusCode.ServiceUnavailable:     //503
                case HttpStatusCode.InternalServerError:    //500
                {
                    throw new Exceptions.ServerUnavailableException(ex, (int)httpResponse.StatusCode);
                }

                case HttpStatusCode.RequestTimeout:     //408
                {
                    throw new Exceptions.ConnectionFailureException(ex, (int)httpResponse.StatusCode);
                }

                default:     // other errors
                {
                    throw ex;
                }
                }

                log.Error(httpResponse.StatusDescription);
            }
        }